A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Run the full game in the ink-style 3D world (#1)
Sandro Maglione065f995a1e1d
diff --git a/.gitignore b/.gitignoreindex 16f8e39..3acec73 100644--- a/.gitignore+++ b/.gitignore@@ -4,3 +4,4 @@ dist.env.env.*snapshots/+output/inkline-3d/diff --git a/DEVELOPMENT.md b/DEVELOPMENT.mdindex 6d28616..2efc556 100644--- a/DEVELOPMENT.md+++ b/DEVELOPMENT.md@@ -4,7 +4,8 @@Inkline Town is a TypeScript game. The simulation runs on the[bevy-ts](https://github.com/SandroMaglione/bevy-ts) ECS at a fixed step and-knows nothing of the page; [Pixi](https://pixijs.com) draws it; saving is+knows nothing of the page; [Three.js](https://threejs.org) draws the 3D world;+Pixi renders the original menu thumbnails; saving iswritten with [Effect](https://effect.website).```sh@@ -13,11 +14,40 @@ pnpm dev --host --port 5232pnpm typecheckpnpm test # model-based tests: random mayors, rules that must always hold; and savingpnpm check # every way a term can end, ends it+pnpm check:browser # the actual 3D game: placement, picking, saves, populated towns and phone layoutpnpm balance # a bot plays terms headless and reports the pressure```Before pushing, run `pnpm typecheck`, `pnpm test`, and `pnpm check`.+## The playable 3D game++Open [`/`](http://localhost:5232/) with the dev server running. The existing+simulation, town panels, economy, charter, history, reckoning and save format+drive the approved 3D models. Drag to pan; right-drag or choose **Rotate** to+turn and tilt. Scroll to zoom. Q/E turn, arrow keys pan, Home resets, and+the camera toolbar provides the same controls. On touch screens, two fingers+pan and pinch to zoom; twisting them rotates. Road/home tools still drag to+build; camera gestures never place anything.++`src/render3d/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,+preserves entity IDs for picking, varies costumes per instance, and bounds+the cache of unused animation/construction states. Loading or founding a+town clears and rebuilds the presentation from the saved world.++`pnpm check:browser` uses an isolated Chromium browser and the running dev+server. It can use installed Brave/Chrome or `BROWSER_EXECUTABLE_PATH`; otherwise+install Chromium with `pnpm exec playwright install chromium`. `GAME_BASE_URL`+overrides the local URL. It generates a reproducible 20-minute bot save,+loads it through the real UI, and writes screenshots and measurements to+`output/inkline-3d/game-check/`. `GAME_SAVE_PATH` can supply another save.+Phone viewport and simulated touch checks do not replace physical-device testing.+++## The art galleryWith `pnpm dev` running, [`/gallery.html`](http://localhost:5232/gallery.html)@@ -28,6 +58,71 @@ around, ctrl + wheel (or pinch) to zoom. `?sheet` lays the same drawings outas the labelled sheet the README's pictures come from. The gallery is notpart of the build.+## The 3D art study++With `pnpm dev` running, [`/asset-lab.html`](http://localhost:5232/asset-lab.html)+compares the complete world catalogue with the actual drawings from+`art.ts`. Choose a collection or search by name. Drag to rotate; the rotation+and elevation controls also work with a keyboard. The original view uses a+30-degree orthographic camera with the game's 64×32 projection.++| Collection | Models | Coverage |+| --- | ---: | --- |+| Buildings | 16 | Every building kind, with its roof, topper and yard |+| Homes | 8 | Both tiers in all four roof palettes |+| Land | 19 | Three tree shapes at three growth stages, stone and ore in both resource states, four crop stages, roads and water |+| People | 27 | Carriers, settlers, citizens, market and chapel walkers, all six hats and the sixteen reference-gallery residents |+| Cargo and vehicles | 69 | Eleven distinct goods and labelled crates; empty handcart/barrow and small/full loads of each good; the approved mixed goods plate |+| Construction and effects | 10 | Empty/supplied sites, frame/walls, problem sign, smoke and four placement/reach outlines |++The 149 entries cover object families and representative seeded variants.+Continuous growth, construction progress, walk poses and colours can be+generated; this is not a list of every possible random seed. Page icons+remain the game's original 2D UI art.++++`pnpm assets:build` exports 149 GLBs and editable geometry descriptions,+a manifest, and two standalone viewers to `output/inkline-3d/`:+`inkline-3d-study.html` and `inkline-3d-map.html`. It reimports every GLB and+checks geometry and unlit materials. The viewers work without a dev server;+their optional web fonts use the network. The game build remains separate.++- `src/asset-lab/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.+- `renderer.ts`: Three.js adapter, material batching, depth-tested ink,+ continuous curved outlines and silhouette hulls. GLB uses ordinary meshes+ and unlit materials so the ink survives import into another renderer.+- `main.ts`: original drawing comparisons, collection/search UI and downloads.++The art viewer uses fixed poses; the playable game animates them from live+state. The Three.js adapter does not establish compatibility with the private+PixiJS 3D beta. Rear facades and rounded volumes interpret surfaces the original+drawing does not show. GLB edge antialiasing can differ from the live viewer.++### The complete 3D review map++Open [`/map-lab.html`](http://localhost:5232/map-lab.html) to see every catalogue+model on one island. Drag to pan, right-drag or choose Rotate to orbit, and+scroll or pinch to zoom. The toolbar also controls zoom, rotation and tilt.+WASD or arrow keys pan; Q/E rotate; Home restores the original view.+Double-click the ground to focus the camera there.++++District shortcuts focus the town, workshops, homes, people, cargo yard or+forest. Inspect selects any of the 149 models and links to its original+drawing comparison. Eight additional people walk along the street using two+procedural poses; pause them for review. Smoke and the problem sign face+the camera so they stay readable when the map turns.++Map faces and strokes are batched by material. Tests check catalogue+coverage, valid geometry and the presence of every model on the map.+This tests presentation and camera controls; it runs no town simulation.+The walking preview does not export skeletal animation.+## Opening a bot's town in the browser`pnpm balance -- --snapshot <minute>` writes each seed's town at that minute@@ -52,6 +147,7 @@ That is how the README's screenshots of grown towns were made.(seasons, the crown, approval, the end of the term, history).- `src/present.ts`: per-frame interaction, panel, and view sync.- `src/art.ts`: all drawing: buildings and their yards, homes, the land, roads, carts, and figures.+- `src/render3d/`: live world renderer, model instances, camera and map input.- `src/townsfolk.ts`: residents out walking, for looking at only: not simulated, not saved.- `src/icons.ts`: the page's line-drawn icons.- `src/gallery.ts`: the dev-only art gallery (see above).diff --git a/README.md b/README.mdindex bebd136..8e192ea 100644--- a/README.md+++ b/README.md@@ -8,7 +8,8 @@ your time runs out. Or watch it go bankrupt, revolt, or empty out.Inkline Town plays like a small Anno in a small box. Every building, cart, and-person is drawn live in thin isometric line art, every map is new, and every+person is drawn live in thin 3D line art. Pan, zoom and rotate the island;+every map is new, and everyterm ends with a verdict and the story of how you got there.## A new charter, a new landdiff --git a/asset-lab.html b/asset-lab.htmlnew file mode 100644index 0000000..26f6485--- /dev/null+++ b/asset-lab.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Inkline Town · 3D art study</title>+ </head>+ <body>+ <main id="lab"></main>+ <script type="module" src="/src/asset-lab/main.ts"></script>+ </body>+</html>diff --git a/docs/how-to-play.md b/docs/how-to-play.mdindex 9284e2b..c8d0b18 100644--- a/docs/how-to-play.md+++ b/docs/how-to-play.md@@ -9,8 +9,12 @@ town, the levers you hold, how a term ends, and how the town works underneath.| | ||---|---|-| drag | pan the map |-| mouse wheel, pinch | zoom |+| drag, arrow keys | pan the map (road/home tools drag to build) |+| right-drag, or drag with **Rotate** selected | rotate and tilt the 3D map |+| **Q**, **E** | rotate left/right |+| mouse wheel, **+** / **−** | zoom |+| two fingers | pan, pinch to zoom, twist to rotate |+| **Home**, camera reset button | restore the original view || **S** | select: click a building or a home to see what it does || **R** | road: drag to lay one || **H** | homes: drag to lay a row along a road |diff --git a/docs/screenshots/3d-art-study.webp b/docs/screenshots/3d-art-study.webpnew file mode 100644index 0000000..17a98abBinary files /dev/null and b/docs/screenshots/3d-art-study.webp differdiff --git a/docs/screenshots/3d-catalogue.webp b/docs/screenshots/3d-catalogue.webpnew file mode 100644index 0000000..801a758Binary files /dev/null and b/docs/screenshots/3d-catalogue.webp differdiff --git a/docs/screenshots/3d-comparisons.webp b/docs/screenshots/3d-comparisons.webpnew file mode 100644index 0000000..fb151fdBinary files /dev/null and b/docs/screenshots/3d-comparisons.webp differdiff --git a/docs/screenshots/3d-map-cargo.webp b/docs/screenshots/3d-map-cargo.webpnew file mode 100644index 0000000..57157e5Binary files /dev/null and b/docs/screenshots/3d-map-cargo.webp differdiff --git a/docs/screenshots/3d-map-complete.webp b/docs/screenshots/3d-map-complete.webpnew file mode 100644index 0000000..7eee198Binary files /dev/null and b/docs/screenshots/3d-map-complete.webp differdiff --git a/docs/screenshots/3d-map-people.webp b/docs/screenshots/3d-map-people.webpnew file mode 100644index 0000000..16e42e9Binary files /dev/null and b/docs/screenshots/3d-map-people.webp differdiff --git a/docs/screenshots/3d-map-town.webp b/docs/screenshots/3d-map-town.webpnew file mode 100644index 0000000..7ce313bBinary files /dev/null and b/docs/screenshots/3d-map-town.webp differdiff --git a/docs/screenshots/game-3d-phone.png b/docs/screenshots/game-3d-phone.pngnew file mode 100644index 0000000..fbaa44fBinary files /dev/null and b/docs/screenshots/game-3d-phone.png differdiff --git a/docs/screenshots/game-3d-rotated.png b/docs/screenshots/game-3d-rotated.pngnew file mode 100644index 0000000..35fa2f3Binary files /dev/null and b/docs/screenshots/game-3d-rotated.png differdiff --git a/docs/screenshots/game-3d.png b/docs/screenshots/game-3d.pngnew file mode 100644index 0000000..439324aBinary files /dev/null and b/docs/screenshots/game-3d.png differdiff --git a/index.html b/index.htmlindex ae9f063..7b52a2b 100644--- a/index.html+++ b/index.html@@ -3,7 +3,8 @@<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />- <title>Town</title>+ <title>Inkline Town</title>+ <link rel="icon" href="/favicon.svg" type="image/svg+xml" /><link rel="stylesheet" href="/src/factory.css" /></head><body>diff --git a/map-lab.html b/map-lab.htmlnew file mode 100644index 0000000..45ff3bc--- /dev/null+++ b/map-lab.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Inkline Town · 3D map test</title>+ </head>+ <body>+ <main id="map-lab"></main>+ <script type="module" src="/src/map-lab/main.ts"></script>+ </body>+</html>diff --git a/package.json b/package.jsonindex bc10fb8..052dbbf 100644--- a/package.json+++ b/package.json@@ -6,9 +6,11 @@"scripts": {"dev": "vite","build": "vite build",+ "assets:build": "node scripts/ink-assets.ts","typecheck": "tsc -p tsconfig.json --pretty false","balance": "node scripts/balance.ts","check": "node scripts/check.ts",+ "check:browser": "node scripts/check-browser.ts","test": "node --test \"test/*.test.ts\"","release": "pnpm --dir deploy release"},@@ -19,10 +21,13 @@"@typeonce/bevy-ts-pixi": "^0.5.0","@typeonce/bevy-ts-render": "^0.5.0","effect": "4.0.3",- "pixi.js": "^8.22.0"+ "pixi.js": "^8.22.0",+ "three": "^0.186.1"},"devDependencies": {"@types/node": "25.5.0",+ "@types/three": "^0.186.0",+ "playwright": "^1.64.0","typescript": "7.0.2","vite": "8.3.1"}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 067948a..4954eb7 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -29,10 +29,19 @@ importers:pixi.js:specifier: ^8.22.0version: 8.22.0+ three:+ specifier: ^0.186.1+ version: 0.186.1devDependencies:'@types/node':specifier: 25.5.0version: 25.5.0+ '@types/three':+ specifier: ^0.186.0+ version: 0.186.0+ playwright:+ specifier: ^1.64.0+ version: 1.64.0typescript:specifier: 7.0.2version: 7.0.2@@ -42,6 +51,9 @@ importers:packages:+ '@dimforge/[email protected]':+ resolution: {integrity: sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==}+'@oxc-project/[email protected]':resolution: {integrity: sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw==}@@ -141,6 +153,9 @@ packages:'@rolldown/[email protected]':resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}+ '@tweenjs/[email protected]':+ resolution: {integrity: sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==}+'@typeonce/[email protected]':resolution: {integrity: sha512-69IcRugcpq0bfd809RtmuZbJ/11zrcTTJyJ0o5kDDTQWY7RtqNUm1layTTbBqnJYl8rkMXP0Qzzu2Pcypz/2pA==}engines: {node: '>=20'}@@ -172,6 +187,15 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-mxYSBpDC+D0pLfSP6sW4WZTcT+nrtmZcimMqnVmy36Hte3XpeYSrvgg4TRdaM1GemGog1AWzI5qL2VoIfMXbJQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==}+'@typescript/[email protected]':resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==}engines: {node: '>=16.20.0'}@@ -321,6 +345,9 @@ packages:picomatch:optional: true+ resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==}+resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}@@ -405,6 +432,9 @@ packages:resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==}engines: {node: '>= 12.0.0'}+ resolution: {integrity: sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==}+resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}@@ -423,6 +453,16 @@ packages:resolution: {integrity: sha512-QbTANHMZ751MIjLiLSUSM8a7LNMWwMIf0KbRCqlW+SPS9hNLfSVS+cl1O2SEp9g1K/wyLzj/OJHv+1TUfiPr/w==}+ resolution: {integrity: sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==}+ engines: {node: '>=20'}+ hasBin: true++ resolution: {integrity: sha512-kVzTnYFYEyQ9RGzBjNCd2+yEqWmVbxl3AHPynv3qQ6JTjv4a+kwRcnqQwIpuP3NnrnIrE/Q6wWAIAvMfIE2/Yg==}+ engines: {node: '>=20'}+ hasBin: true+resolution: {integrity: sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==}engines: {node: ^10 || ^12 || >=14}@@ -436,6 +476,9 @@ packages:resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==}+resolution: {integrity: sha512-w/Te7uMUVeH0CR8vZIjr+XiN41V+30lkDdK+NRIDCUYKKuL9VcmaUEmaPISuwGhLlrTGh5yu18lENtR9axSxYw==}engines: {node: '>=12'}@@ -497,6 +540,8 @@ packages:snapshots:+ '@dimforge/[email protected]': {}+'@oxc-project/[email protected]': {}'@pixi/[email protected]': {}@@ -548,6 +593,8 @@ snapshots:'@rolldown/[email protected]': {}+ '@tweenjs/[email protected]': {}+'@typeonce/[email protected]([email protected])':dependencies:'@typeonce/bevy-ts': 0.5.0([email protected])@@ -582,6 +629,19 @@ snapshots:dependencies:undici-types: 7.18.2+ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ '@dimforge/rapier3d-compat': 0.12.0+ '@tweenjs/tween.js': 23.1.3+ '@types/stats.js': 0.17.4+ '@types/webxr': 0.5.24+ fflate: 0.8.3+ meshoptimizer: 1.1.1++ '@types/[email protected]': {}+'@typescript/[email protected]':optional: true@@ -658,6 +718,8 @@ snapshots:optionalDependencies:picomatch: 4.0.7+ [email protected]: {}+optional: true@@ -718,6 +780,8 @@ snapshots:lightningcss-win32-arm64-msvc: 1.33.0lightningcss-win32-x64-msvc: 1.33.0+ [email protected]: {}+@@ -739,6 +803,12 @@ snapshots:parse-svg-path: 0.2.0tiny-lru: 11.4.7+ [email protected]: {}++ dependencies:+ playwright-core: 1.64.0+dependencies:nanoid: 3.3.20@@ -768,6 +838,8 @@ snapshots:+ [email protected]: {}+diff --git a/public/favicon.svg b/public/favicon.svgnew file mode 100644index 0000000..d61f6f5--- /dev/null+++ b/public/favicon.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" class="icon " width="32" height="32" viewBox="0 0 16 16" aria-hidden="true" stroke="#3d4943" stroke-width="1.2" stroke-linejoin="round" stroke-linecap="round"><path d="M2.5 14.5v-7h11v7z" fill="#f5f6f2"/><path d="M5 9.5h1.5v2H5zM9.5 9.5H11v2H9.5z" fill="#f3dca6" stroke-width="1"/><path d="M7 14.5v-3h2v3" fill="none" stroke-width="1"/><path d="M8 7.5V1.5" fill="none"/><path d="M8 1.8l3.5 1.2L8 4.2z" fill="#c4523f" stroke-width="1"/></svg>diff --git a/scripts/check-browser.ts b/scripts/check-browser.tsnew file mode 100644index 0000000..5e35a79--- /dev/null+++ b/scripts/check-browser.ts@@ -0,0 +1,190 @@+/** End-to-end checks against the real local game, in an isolated browser.+ * Start pnpm dev first. BROWSER_EXECUTABLE_PATH selects an installed browser;+ * otherwise use Playwright Chromium (pnpm exec playwright install chromium).+ */+import assert from "node:assert/strict"+import { existsSync } from "node:fs"+import { mkdir,readFile,writeFile } from "node:fs/promises"+import { execFileSync } from "node:child_process"+import { chromium } from "playwright"+import type { UiValue } from "../src/ui.ts"+import type { GameScene } from "../src/render3d/scene.ts"+import type { Snapshot } from "../src/sim/headless.ts"++declare global {+ interface Window {+ town:{ui:UiValue;view:GameScene;advance:(seconds:number)=>void;runtime:{snapshot:()=>Snapshot}}+ }+}+const executable=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,...(executable?{executablePath:executable}:{})})+const page=await browser.newPage({viewport:{width:1440,height:1000},deviceScaleFactor:1})+const errors:Array<string>=[]+page.on("pageerror",e=>errors.push(e.message))+page.on("console",m=>{if(m.type()==="error")errors.push(m.text())})+const output="output/inkline-3d/game-check"+await mkdir(output,{recursive:true})+const facts:Record<string,unknown>={}+const frames=async()=>page.waitForFunction(()=>window.town?.view.stats().frames>3)+const snapshot=()=>page.evaluate(()=>window.town.runtime.snapshot())+const entities=async(kind:string)=>(await snapshot()).entities.filter(e=>kind in e.components)+const point=async(x:number,y:number,z=0)=>page.evaluate(([x,y,z])=>window.town.view.project(x!,y!,z!),[x,y,z])+const clickGrid=async(x:number,y:number,z=0)=>{const p=await point(x,y,z);await page.mouse.click(p.x,p.y)}+const dragGrid=async(a:[number,number],b:[number,number])=>{const p=await point(...a),q=await point(...b);await page.mouse.move(p.x,p.y);await page.mouse.down();await page.mouse.move(q.x,q.y,{steps:8});await page.mouse.up()}+const tool=async(name:string)=>page.locator(".toolbar button").filter({hasText:new RegExp("^"+name)}).click()+const capture=async(name:string)=>{+ const frame=await page.evaluate(()=>window.town.view.stats().frames)+ await page.waitForFunction(f=>window.town.view.stats().frames>f+20,frame)+ await page.screenshot({path:`${output}/${name}.png`})+ const data=await page.evaluate(()=>window.town.view.capture())+ await writeFile(`${output}/${name}.webp`,Buffer.from(data.split(",")[1]!,"base64"))+}+try {+ await page.goto(process.env.GAME_BASE_URL??"http://127.0.0.1:5232")+ await page.waitForFunction(()=>window.town)+ await page.getByRole("button",{name:"small",exact:true}).click()+ await page.getByRole("button",{name:"Found the town",exact:true}).click()+ await page.waitForFunction(()=>!window.town.ui.founding)+ await page.locator(".toolbar .pause").click()+ const hall=(await entities("Town/TownHall"))[0]!,tile=hall.components["Town/Tile"]+ await page.getByRole("button",{name:"Rotate map right",exact:true}).click()+ await clickGrid(tile.x+1.5,tile.y+1.5,48)+ await page.waitForFunction(id=>window.town.ui.selected===id,hall.id)+ assert.equal((await page.evaluate(()=>window.town.ui.panel))?.type,"building")+ facts.rotatedSelection=true+ await tool("road")+ await dragGrid([tile.x+5.5,tile.y+1.5],[tile.x+8.5,tile.y+1.5])+ await page.waitForFunction(([x,y])=>[6,7,8].every(dx=>window.town.runtime.snapshot().entities.some(e=>e.components["Town/Road"]&&e.components["Town/Tile"].x===x!+dx&&e.components["Town/Tile"].y===y!+1)),[tile.x,tile.y])+ facts.rotatedRoadDrag=true+ await tool("homes")+ await dragGrid([tile.x+5.5,tile.y+2.5],[tile.x+8.5,tile.y+2.5])+ await page.waitForFunction(()=>window.town.runtime.snapshot().entities.filter(e=>e.components["Town/House"]).length===4)+ facts.rotatedHomeDrag=true+ await tool("build")+ await page.locator(".panel .option").filter({has:page.locator(".name",{hasText:"lumberjack"})}).click()+ await clickGrid(tile.x+7,tile.y)+ await page.waitForFunction(()=>window.town.runtime.snapshot().entities.some(e=>e.components["Town/Building"]?.kind==="lumberjack"))+ const lumber=(await entities("Town/Building")).find(e=>e.components["Town/Building"].kind==="lumberjack")!+ assert.deepEqual(lumber.components["Town/Tile"],{x:tile.x+6,y:tile.y-1,size:2})+ facts.rotatedBuildingPlacement=true+ await capture("construction")+ await page.evaluate(()=>window.town.advance(90))+ await page.waitForFunction(()=>window.town.ui.stats!.settlers>0)+ assert.ok((await entities("Town/House")).some(e=>!("Town/Site" in e.components)))+ facts.liveConstruction=true+ await tool("select")+ await page.getByRole("button",{name:"Rotate map right",exact:true}).click()+ const lt=lumber.components["Town/Tile"]+ await clickGrid(lt.x+1,lt.y+1,16)+ await page.waitForFunction(id=>window.town.ui.selected===id,lumber.id)+ const pauseWork=page.getByRole("button",{name:"Pause work",exact:true})+ await pauseWork.click()+ await page.waitForFunction(id=>!!window.town.runtime.snapshot().entities.find(e=>e.id===id)?.components["Town/Paused"],lumber.id)+ await page.getByRole("button",{name:"Resume work",exact:true}).click()+ await page.waitForFunction(id=>!("Town/Paused" in window.town.runtime.snapshot().entities.find(e=>e.id===id)!.components),lumber.id)+ facts.buildingPauseResume=true+ await page.locator(".panel .close").click()+ await page.getByRole("button",{name:"save",exact:true}).click()+ const saved=await page.evaluate(()=>JSON.parse(localStorage.getItem("inkline-town/save/manual")!))+ await tool("bulldoze")+ await clickGrid(lt.x+1,lt.y+1,16)+ await page.waitForFunction(id=>!window.town.runtime.snapshot().entities.some(e=>e.id===id),lumber.id)+ facts.rotatedBulldozing=true+ await page.getByRole("button",{name:"load",exact:true}).click()+ await page.getByRole("button",{name:"Load without saving",exact:true}).click()+ await page.waitForFunction(id=>window.town.runtime.snapshot().entities.some(e=>e.id===id),lumber.id)+ await page.waitForFunction(()=>window.town.view.stats().nodes>0)+ assert.deepEqual(await snapshot(),saved.world)+ facts.saveLoadUnchangedFormat=true+ const restoredNodes=await page.evaluate(()=>window.town.view.stats().nodes)+ const renderableCount=(await snapshot()).entities.filter(e=>["Town/Building","Town/House","Town/Tree","Town/Rock","Town/Field","Town/Figure"].some(c=>c in e.components)).length+ assert.ok(restoredNodes>=renderableCount,`Restored ${restoredNodes} nodes for ${renderableCount} renderable entities`)+ facts.restoreRebuildsScene=true+ await capture("live-town")+ await page.getByRole("button",{name:"new town",exact:true}).click()+ await page.getByRole("button",{name:"Choose new land without saving",exact:true}).click()+ await page.getByRole("button",{name:"large",exact:true}).click()+ await page.getByRole("button",{name:"rich",exact:true}).click()+ await page.getByRole("button",{name:"Found the town",exact:true}).click()+ await page.waitForFunction(()=>!window.town.ui.founding&&window.town.ui.stats?.charter.size==="large")+ assert.equal((await entities("Town/House")).length,0)+ assert.equal((await entities("Town/TownHall")).length,1)+ await page.locator(".toolbar .pause").click()+ await page.waitForFunction(()=>window.town.view.stats().frames>20)+ facts.newTownClearsOldScene=true+ facts.largeIsland=await page.evaluate(()=>window.town.view.stats())+ await capture("large-island")+ const fixture=process.env.GAME_SAVE_PATH??`${output}/fixture/large-rich-24757-20min.json`+ if (!existsSync(fixture)) execFileSync(process.execPath,["scripts/balance.ts","--seeds","1","--from","3","--size","large","--land","rich","--term","45","--snapshot","20","--out",`${output}/fixture`],{stdio:"pipe"})+ const grown=JSON.parse(await readFile(fixture,"utf8"))+ await page.evaluate(save=>{+ localStorage.removeItem("inkline-town/save/auto")+ localStorage.setItem("inkline-town/save/manual",JSON.stringify({...save,savedAt:Date.now()}))+ },grown)+ await page.getByRole("button",{name:"load",exact:true}).click()+ await page.getByRole("button",{name:"Load without saving",exact:true}).click()+ await page.waitForFunction(()=>window.town.ui.stats!.settlers>100)+ assert.deepEqual(await snapshot(),grown.world)+ const settledFrame=await page.evaluate(()=>window.town.view.stats().frames)+ await page.waitForFunction(start=>window.town.view.stats().frames>start+60,settledFrame)+ facts.populatedTown=await page.evaluate(()=>window.town.view.stats())+ assert.ok((await entities("Town/Figure")).length>0,"Live simulated carriers must render")+ const grownHall=(await entities("Town/TownHall"))[0]!,ht=grownHall.components["Town/Tile"]+ await page.evaluate(([x,y])=>window.town.view.focus(x!,y!),[ht.x+1.5,ht.y+1.5])+ await capture("populated-town")+ for (let angle=0;angle<8;angle++) {+ await page.getByRole("button",{name:"Rotate map right",exact:true}).click()+ await clickGrid(ht.x+1.5,ht.y+1.5,48)+ await page.waitForFunction(id=>window.town.ui.selected===id,grownHall.id)+ await page.locator(".panel .close").click()+ }+ facts.selectionAllEightAngles=true+ await page.getByRole("button",{name:"Rotate map right",exact:true}).click()+ await capture("populated-rotated")+ await page.getByRole("button",{name:"4×",exact:true}).click()+ const before=await snapshot()+ const positions=await page.evaluate(()=>[...window.town.view.nodes].filter(n=>n.constructor.name==="WalkerView").map(n=>n.group.position.toArray()))+ await page.waitForFunction(t=>window.town.runtime.snapshot().resources["Town/Time"].tick>t+30,before.resources["Town/Time"].tick)+ await page.locator(".toolbar .pause").click()+ const paused=await snapshot(),pf=await page.evaluate(()=>window.town.view.stats().frames)+ await page.waitForFunction(f=>window.town.view.stats().frames>f+10,pf)+ assert.equal((await snapshot()).resources["Town/Time"].tick,paused.resources["Town/Time"].tick)+ assert.notDeepEqual(await page.evaluate(()=>[...window.town.view.nodes].filter(n=>n.constructor.name==="WalkerView").map(n=>n.group.position.toArray())),positions)+ facts.speedAndPause=true+ facts.liveWalkerMovement=true+ await page.setViewportSize({width:390,height:844})+ await page.getByRole("button",{name:"Reset camera",exact:true}).click()+ await page.getByRole("button",{name:"Rotate map left",exact:true}).click()+ await page.getByRole("button",{name:"Zoom in",exact:true}).click()+ assert.equal(await page.evaluate(()=>[...document.querySelectorAll(".camera-controls,.toolbar,.system,.hud")].some(e=>{const r=e.getBoundingClientRect();return r.left<0||r.right>innerWidth+1})),false)+ facts.phoneViewport=true+ await tool("homes")+ const touch=await page.context().newCDPSession(page),beforeTouch=await snapshot(),cameraBefore=await page.evaluate(()=>window.town.view.stats())+ await touch.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{x:130,y:380,id:1}]})+ await touch.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{x:130,y:380,id:1},{x:230,y:420,id:2}]})+ await touch.send("Input.dispatchTouchEvent",{type:"touchMove",touchPoints:[{x:100,y:350,id:1},{x:290,y:460,id:2}]})+ await touch.send("Input.dispatchTouchEvent",{type:"touchEnd",touchPoints:[]})+ const tf=await page.evaluate(()=>window.town.view.stats().frames)+ await page.waitForFunction(f=>window.town.view.stats().frames>f+5,tf)+ assert.deepEqual(await snapshot(),beforeTouch,"Pinching a build tool must never commit an edit")+ const cameraAfter=await page.evaluate(()=>window.town.view.stats())+ assert.ok(cameraAfter.zoom>cameraBefore.zoom)+ assert.notEqual(cameraAfter.heading,cameraBefore.heading)+ facts.touchPinchRotateDoesNotBuild=true+ await tool("select")+ await page.getByRole("button",{name:"Reset camera",exact:true}).click()+ await capture("phone")+ // A saved term that has ended still opens the existing reckoning UI.+ const ended=structuredClone(grown)+ ended.world.resources["Town/Fate"]={...ended.world.resources["Town/Fate"],state:"over",reason:"The term has ended.",at:ended.world.resources["Town/Time"].tick}+ await page.evaluate(save=>localStorage.setItem("inkline-town/save/manual",JSON.stringify({...save,savedAt:Date.now()})),ended)+ await page.getByRole("button",{name:"load",exact:true}).click()+ await page.getByRole("button",{name:"Load without saving",exact:true}).click()+ await page.getByRole("button",{name:"Found a new town",exact:true}).waitFor({state:"visible"})+ assert.equal(await page.evaluate(()=>window.town.ui.stats!.fate.state),"over")+ facts.reckoning=true+ assert.deepEqual(errors,[])+ await writeFile(`${output}/results.json`,JSON.stringify(facts,null,2))+ console.log(JSON.stringify(facts,null,2))+}catch(error){await page.screenshot({path:`${output}/failure.png`});console.error({errors,facts});throw error}+finally{await browser.close()}diff --git a/scripts/ink-assets.ts b/scripts/ink-assets.tsnew file mode 100644index 0000000..94b89f2--- /dev/null+++ b/scripts/ink-assets.ts@@ -0,0 +1,87 @@+import { mkdir, readFile, writeFile } from "node:fs/promises"+import path from "node:path"+import { build } from "vite"+import { inkAssets } from "../src/asset-lab/assets.ts"+import * as THREE from "three"+import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"+import { exportAsset } from "../src/asset-lab/renderer.ts"++// GLTFExporter uses the browser's FileReader to assemble binary buffers.+// There are no textures here; only readAsArrayBuffer is needed in Node.+class BinaryReader {+ result: ArrayBuffer | null = null+ onloadend: (() => void) | null = null+ readAsArrayBuffer(blob: Blob) {+ void blob.arrayBuffer().then((buffer) => {+ this.result = buffer+ this.onloadend?.()+ })+ }+}+if (typeof globalThis.FileReader === "undefined") Object.assign(globalThis, { FileReader: BinaryReader })++const output = path.resolve("output/inkline-3d")+await mkdir(path.join(output, "models"), { recursive: true })+const manifest = []+const loader = new GLTFLoader()+for (const asset of inkAssets) {+ const glb = await exportAsset(asset)+ await writeFile(path.join(output, "models", `${asset.id}.glb`), new Uint8Array(glb))+ await writeFile(path.join(output, "models", `${asset.id}.json`), JSON.stringify(asset, null, 2))+ const imported = await loader.parseAsync(glb, "")+ let meshes = 0,+ vertices = 0+ imported.scene.traverse((object) => {+ if (!(object instanceof THREE.Mesh)) return+ meshes+++ const position = object.geometry.getAttribute("position")+ if (!position?.count) throw new Error(`${asset.id}: empty imported mesh`)+ vertices += position.count+ for (const n of position.array) if (!Number.isFinite(n)) throw new Error(`${asset.id}: invalid imported coordinate`)+ const materials = Array.isArray(object.material) ? object.material : [object.material]+ for (const material of materials) {+ if (!(material instanceof THREE.MeshBasicMaterial)) throw new Error(`${asset.id}: ink material lost its unlit shading`)+ material.dispose()+ }+ object.geometry.dispose()+ })+ if (!meshes) throw new Error(`${asset.id}: no imported meshes`)+ manifest.push({+ id: asset.id,+ title: asset.title,+ category: asset.category,+ glb: `models/${asset.id}.glb`,+ geometry: `models/${asset.id}.json`,+ bytes: glb.byteLength,+ meshes,+ vertices+ })+ console.log(`${asset.id}: ${(glb.byteLength / 1024).toFixed(1)} KB`)+}++await writeFile(path.join(output, "manifest.json"), JSON.stringify({ models: manifest.length, assets: manifest }, null, 2))+for (const [input, directory, filename] of [+ ["asset-lab.html", "viewer", "inkline-3d-study.html"],+ ["map-lab.html", "map-viewer", "inkline-3d-map.html"]+]) {+ await build({+ configFile: false,+ base: "./",+ build: {+ outDir: path.join(output, directory!),+ cssCodeSplit: false,+ rolldownOptions: { input: input!, output: { codeSplitting: false } }+ }+ })+ let html = await readFile(path.join(output, directory!, input!), "utf8")+ const script = html.match(/<script[^>]*src="([^"]+)"[^>]*><\/script>/)+ const style = html.match(/<link[^>]*href="([^"]+\.css)"[^>]*>/)+ if (!script || !style) throw new Error("Could not locate viewer bundle")+ const javascript = await readFile(path.resolve(output, directory!, script[1]!), "utf8")+ const css = await readFile(path.resolve(output, directory!, style[1]!), "utf8")+ html = html.replace(script[0], () => `<script type="module">${javascript.replace(/<\/script/gi, "<\\/script")}</script>`)+ html = html.replace(style[0], () => `<style>${css}</style>`).replace(/<link[^>]*rel="modulepreload"[^>]*>/g, "")+ await writeFile(path.join(output, filename!), html)+ console.log(`Standalone viewer: ${path.join(output, filename!)}`)+}+console.log(`Verified ${manifest.length} GLB exports by reimporting their geometry and unlit materials.`)diff --git a/src/art.ts b/src/art.tsindex 17a87dc..232bef0 100644--- a/src/art.ts+++ b/src/art.ts@@ -1437,7 +1437,7 @@ const cartLog = (g: Graphics, u: number, v: number, d: Point, c: number, half: nconst wicker = { top: 0xc9a46a, left: 0xe3c592, right: 0xd2b07a }/** What is on a cart, `z` px up: each good its own way, more of it for a bigger load. */-const drawCargo = (g: Graphics, u: number, v: number, d: Point, good: GoodId, count: number, z: number) => {+export const drawCargo = (g: Graphics, u: number, v: number, d: Point, good: GoodId, count: number, z: number) => {const n = count >= 4 ? 3 : count >= 2 ? 2 : 1const p = cartPoint(u, v, d)switch (good) {diff --git a/src/asset-lab/assets.ts b/src/asset-lab/assets.tsnew file mode 100644index 0000000..0f289b8--- /dev/null+++ b/src/asset-lab/assets.ts@@ -0,0 +1,148 @@+/** Portable polygon-and-stroke assets. Floor coordinates remain in cells;+ * heights remain in the original drawing's pixels. No renderer types here. */+import { kindIds, goodIds } from "../content.ts"+import { makeBuilding } from "./buildings.ts"+import { house } from "./homes.ts"+import { U } from "../iso.ts"+import { makeTree, makeRock, makeField, makeRoadPatch, makeWater } from "./land.ts"+import { personCatalogue, makeCarrier, makeGoods, makeCrate } from "./people.ts"+import { makeSite, makeConstruction, makeMarker, makeSmoke, makePlot } from "./construction.ts"++import { Drawing, mix, pale, square, sides, palette, type InkAsset, type Vertex } from "./primitives.ts"+export * from "./primitives.ts"++export { house } from "./homes.ts"++function firTree() {+ const hash = (x: number, y: number) => {+ let h = (x * 374761393 + y * 668265263) >>> 0+ h = Math.imul(h ^ (h >>> 13), 1274126177) >>> 0+ return ((h ^ (h >>> 16)) >>> 0) / 4294967296+ }+ const h2 = hash(17, 7),+ h3 = hash(101, 3),+ size = 0.85 + h2 * 0.3,+ ox = Math.round((h3 - 0.5) * 12),+ oy = Math.round((h2 - 0.5) * 5)+ const u = ox / 64 + oy / 32,+ v = -ox / 64 + oy / 32,+ trunk = Math.round(6 * size),+ tiers = h2 < 0.5 ? 2 : 3,+ step = (24 * size) / (tiers + 1)+ const d = new Drawing(+ "fir",+ "Fir tree",+ "A sculpted volume with the original stepped silhouette and two leaf colours. The canopy has real depth."+ )+ d.face(+ Array.from({ length: 40 }, (_, i): Vertex => {+ const t = (i * Math.PI) / 20,+ x = ox + 3 * size + 9 * size * Math.cos(t),+ y = oy + 3.5 * size * Math.sin(t)+ return [x / 64 + y / 32, -x / 64 + y / 32, -0.02]+ }),+ 0xe3e6de,+ 0+ )+ d.line(+ [+ [u, v, 0],+ [u, v, trunk]+ ],+ 1.5,+ 0x6b5a45+ )+ for (let i = 0; i < tiers; i++) {+ const w = (8 * size * (1 - i * 0.22)) / 64,+ depth = w,+ z = trunk - 2 + i * step+ // A sloped lower rim gives the canopy full depth while preserving its+ // shallow drawn notch at the original camera angle.+ const lift = depth * 32 - 1.5 * size+ const ring: Array<Vertex> = [+ [u - depth, v - depth, z - lift],+ [u + w, v - w, z],+ [u + depth, v + depth, z + lift],+ [u - w, v + w, z]+ ]+ const light = h3 < 0.5 ? 0xd9e5d7 : 0xd3e0d3,+ shade = h3 < 0.5 ? 0xb3c7b4 : 0xa9bfab+ for (let j = 0; j < 4; j++) d.face([ring[j]!, ring[(j + 1) % 4]!, [u, v, z + 2 * step]], j >= 2 ? light : shade, 0)+ d.face(ring, shade, 0)+ d.line([...ring, ring[0]!], 1.5)+ // Outer contours only; a wireframe would add an unwanted central seam.+ for (const f of d.asset.faces.slice(-5)) f.contour = i + 1+ }+ return d.asset+}++function props() {+ const d = new Drawing("goods", "Goods & crates", "The same labelled wood crates, plank stacks and stone blocks, completed on all sides.")+ d.plate(2)+ d.crate(0.35, 0.3, 0, 0x2f8c87, 3 * U, 12)+ d.crate(-0.15, 0.3, 0, 0x8a58a8, 3 * U, 12)+ d.crate(0.1, 0.3, 12, 0xd27a34, 3 * U, 12)+ for (let i = 0; i < 3; i++) d.box(0.3, -0.4, 1.1 * U, 3 * U, i * 2.5, 2.5, 0xf0c59a, 0xe2a873, 0xd2945c, 1)+ d.box(-0.4, -0.35, 1.2 * U, 1.2 * U, 0, 5, 0xeeefea, 0xdcded7, 0xc9ccc4)+ return d.asset+}++const approvedAssets: Array<InkAsset> = [+ house(1),+ house(2),+ makeBuilding("townhall"),+ makeBuilding("mill"),+ makeBuilding("market"),+ props(),+ firTree()+]++const baseFir = approvedAssets.find((asset) => asset.id === "fir")!+baseFir.category = "land"+baseFir.reference = { type: "tree", x: 0, y: 0, grown: 1 }+baseFir.footprint = 1+for (const face of baseFir.faces) if (face.contour) face.contourWidth = 1.5+approvedAssets.find((asset) => asset.id === "goods")!.category = "cargo"+approvedAssets.find((asset) => asset.id === "goods")!.footprint = 2+const additional: Array<InkAsset> = []+for (const kind of kindIds) if (!approvedAssets.some((asset) => asset.id === kind)) additional.push(makeBuilding(kind))+const names = ["terracotta", "slate", "thatch", "moss"]+for (const tier of [1, 2] as const)+ for (let i = 0; i < 4; i++) {+ if ((tier === 1 && i === 0) || (tier === 2 && i === 1)) continue+ const asset = house(tier, i / 4 + 0.03, `${tier === 1 ? "cottage" : "citizen"}-${names[i]}`)+ asset.title = `${tier === 1 ? "Cottage" : "Citizen home"} · ${names[i]}`+ additional.push(asset)+ }+for (const type of ["fir", "broadleaf", "poplar"] as const)+ for (const grown of [0.3, 0.6, 1]) {+ if (type === "fir" && grown === 1) continue+ additional.push(makeTree(type, grown, `${type}-${grown === 1 ? "grown" : grown >= 0.5 ? "young" : "sapling"}`))+ }+for (const ore of [false, true]) for (const full of [false, true]) additional.push(makeRock(ore, full))+for (const stage of [0, 1, 2, 3] as const) additional.push(makeField(stage))+additional.push(makeRoadPatch(), makeWater(), ...personCatalogue())+for (const barrow of [false, true]) {+ additional.push(makeCarrier(null, barrow))+ for (const good of goodIds) for (const count of [1, 4]) additional.push(makeCarrier(good, barrow, count))+}+for (const good of goodIds) additional.push(makeGoods(good), makeCrate(good))+additional.push(+ makeSite(0),+ makeSite(1),+ makeConstruction("warehouse", 0.3),+ makeConstruction("warehouse", 0.65),+ makeMarker(),+ makeSmoke(),+ ...["hover", "picked", "blocked", "reach"].map((look) => makePlot(look as "hover" | "picked" | "blocked" | "reach"))+)+export const inkAssets: ReadonlyArray<InkAsset> = [...approvedAssets, ...additional]+export const assetById = new Map(inkAssets.map((asset) => [asset.id, asset]))+export const assetCategoryTitles = {+ buildings: "Buildings",+ homes: "Homes",+ land: "Land",+ people: "People",+ cargo: "Cargo & vehicles",+ construction: "Construction & effects"+} as constdiff --git a/src/asset-lab/buildings.ts b/src/asset-lab/buildings.tsnew file mode 100644index 0000000..9e97f16--- /dev/null+++ b/src/asset-lab/buildings.ts@@ -0,0 +1,517 @@+import { kinds, type KindId } from "../content.ts"+import { U } from "../iso.ts"+import { Drawing, palette, pale, square, sides, type Vertex, type Side } from "./primitives.ts"++const dresses: Record<KindId, { accent: number; roof?: number; glass?: number }> = {+ townhall: { accent: 0x8a58a8, glass: 0xf3dca6 },+ warehouse: { accent: 0x8a58a8 },+ lumberjack: { accent: 0x8a6a45, roof: 0x8a6a45 },+ forester: { accent: 0x6e8f36, roof: 0x6e8f36 },+ quarry: { accent: 0x8f9891 },+ mine: { accent: 0x5a6479, glass: 0xd5dae4 },+ fishery: { accent: 0x2f8c87, roof: 0x2f8c87 },+ sawmill: { accent: 0xd27a34 },+ smithy: { accent: 0xb04a39, glass: 0xf3dca6 },+ farm: { accent: 0xd6ae2e, roof: 0xc4523f },+ mill: { accent: 0xc9b48a, roof: 0x8a6a45 },+ bakery: { accent: 0xc4523f, glass: 0xf3dca6 },+ sheep: { accent: 0xb5654a, roof: 0xb5654a },+ weaver: { accent: 0x8a58a8 },+ market: { accent: 0x3d6db5 },+ chapel: { accent: 0x3d6db5, glass: 0xc9d6ee }+}++export interface BuildingOptions {+ doors?: Partial<Record<Side, boolean>>+ fit?: number+ open?: number+ plate?: boolean+ motion?: boolean+}+export function makeBuilding(id: KindId, options: BuildingOptions = {}) {+ const fit = options.fit ?? 1+ const kind = kinds[id],+ a = kind.half * U,+ H = kind.roof === "gable" ? 20 : kind.stories * 32,+ p = (kind.size * 8 - 1) * U+ const accent = dresses[id].accent+ const glass = dresses[id].glass ?? palette.glass+ const d = new Drawing(+ id,+ kind.title,+ id === "mill"+ ? "The lattice sails sit on a real upright plane. Flour sacks remain softly rounded."+ : id === "market"+ ? "Striped canopy, coloured goods crates and roof flag, all built as geometry."+ : id === "townhall"+ ? "Two storeys, clock faces, violet trim, three skylights and a red flag. Original dimensions throughout."+ : "Original footprint, palette and yard details, with complete walls and roof geometry."+ )+ d.asset.category = "buildings"+ d.asset.reference = { type: "building", kind: id }+ d.asset.footprint = kind.size+ if (options.plate !== false) d.plate(kind.size)+ d.box(0, 0, a, a, 0, H)+ for (const side of sides) {+ const door = options.doors ? !!options.doors[side] : side === "right" || side === "left"+ const pt = (s: number, z: number) => d.wall(side, a, s, z, 0.007)+ if (kind.stories === 2) d.line([pt(-a, 32), pt(a, 32)], 1, palette.ink, 0.7)+ if (kind.roof === "flat" && fit > 0.3) {+ d.face([pt(-a, H - 3), pt(a, H - 3), pt(a, H), pt(-a, H)], pale(accent, 0.35), 0)+ d.line([pt(-a, H - 3), pt(a, H - 3)], 1, palette.ink, 0.6)+ }+ const positions = door ? (a >= 12 * U ? [-(a - 3 * U), a - 3 * U] : []) : [-Math.round(a / U / 2) * U, Math.round(a / U / 2) * U]+ if (kind.roof === "flat" && fit > 0.4)+ for (let floor = 0; floor < kind.stories; floor++)+ for (const s of positions) {+ if (id === "chapel") {+ const z = floor * 32 + 9,+ w = 1 / 16,+ p = (along: number, height: number) => d.wall(side, a, along, height)+ d.face([p(s - w, z), p(s + w, z), p(s + w, z + 11), p(s, z + 14), p(s - w, z + 11)], glass, 1)+ d.line([p(s - w - 0.5 / 16, z), p(s + w + 0.5 / 16, z)])+ } else d.window(side, a, s, floor * 32 + 12, 8, glass, true)+ }+ if (door && fit > 0.15)+ d.door(side, a, Math.max(2, Math.round(Math.min(16, H - 8) * fit)), 5 * U, 6 * U, 3 * U, accent, true, options.open ?? 0)+ if (kind.roof === "gable" && !door && fit > 0.4) d.window(side, a, 0, 6)+ if (id === "townhall" && fit > 0.8) d.circle(side, a, 50, 5)+ }+ if (id === "mill") {+ if (fit > 0) d.pyramid(a, H, 16 * fit, pale(0x8a6a45, 0.7), pale(0x8a6a45, 0.52))+ if (options.motion !== false && fit > 0.6) drawSails(d, a, H, 1.2)+ // Sacks are complete faceted solids, rather than a fixed screen drawing.+ const c = (a + p) / 2+ for (const [u, v] of [+ [c - U, c + U],+ [c + 1.5 * U, c - U],+ [c + 0.5 * U, c + 2.5 * U]+ ])+ d.sack(u!, v!)+ } else if (kind.roof === "gable") {+ const roof = dresses[id].roof ?? 0x8a6a45+ if(fit>0)d.gable(a, H, 14 * fit, "x", pale(roof, 0.7), pale(roof, 0.52), false)+ for (const side of ["right", "left"] as const) {+ for (const seam of (options.doors?.[side] ?? true) ? [-(a - 4 * U), a - 4 * U] : [0])+ d.line([d.wall(side, a, seam, 0), d.wall(side, a, seam, H)], 1, palette.ink, 0.5)+ }+ for (const side of ["backRight", "backLeft"] as const) {+ d.line([d.wall(side, a, 0, 0), d.wall(side, a, 0, H)], 1, palette.ink, 0.5)+ }+ } else if (fit > 0.4) {+ const pitch = (2 * a) / kind.bays+ for (let row = 0; row < kind.bays; row++)+ for (let col = 0; col < kind.bays; col++) {+ if (+ (kind.topper === "flag" && row === 0 && col === kind.bays - 1) ||+ (["chimney", "cupola", "crates"].includes(kind.topper) && row === 0 && col === 0)+ )+ continue+ const u = -a + pitch * (col + 0.5),+ v = -a + pitch * (row + 0.5),+ pane = square(u, v, (kind.window / 2) * U, H + 0.035)+ d.face(pane, glass)+ d.line([pane[0]!, pane[2]!], 1, palette.ink, 0.25)+ }+ if (kind.topper === "flag") {+ const u = -a + pitch * (kind.bays - 0.5),+ v = -a + pitch * 0.5+ d.line(+ [+ [u, v, H],+ [u, v, H + 24]+ ],+ 1.5+ )+ // A flag hanging in a vertical world plane, matching the original at 45°.+ const delta = 11 / 64+ if (options.motion !== false)+ d.face(+ [+ [u, v, H + 24],+ [u - delta, v + delta, H + 24 - 6],+ [u, v, H + 16]+ ],+ id === "townhall" ? 0xc4523f : 0x3d6db5,+ 1+ )+ }+ }+ if (id === "market" && fit > 0.75) {+ const c = (a + p) / 2,+ u0 = c - 1.2 * U,+ u1 = c + 1.2 * U,+ v0 = -a - 2.5 * U,+ v1 = -a + 4.5 * U+ for (const [u, v] of [+ [u0, v0],+ [u1, v0],+ [u0, v1],+ [u1, v1]+ ])+ d.line(+ [+ [u!, v!, 0],+ [u!, v!, 11]+ ],+ 1.5+ )+ d.box(c, (v0 + v1) / 2, 1.2 * U, (v1 - v0) / 2, 0, 4, 0xe9c48a, 0xd5a86c, 0xc79a5b)+ for (let i = 0; i < 5; i++) {+ const s = v0 + ((v1 - v0) * i) / 5,+ e = v0 + ((v1 - v0) * (i + 1)) / 5+ d.face(+ [+ [u0, s, 12],+ [u0, e, 12],+ [u1 + U, e, 9],+ [u1 + U, s, 9]+ ],+ i % 2 === 0 ? 0xc4523f : 0xf7f3ea+ )+ }+ d.crate(-a - 2 * U, c, 0, 0x2f8c87)+ d.crate(-a + 1.5 * U, c, 0, 0xc4523f)+ d.crate(-a - 0.2 * U, c, 5, 0x8a58a8)+ }+ finishBuilding(d, id, a, p, H, fit)+ return d.asset+}++function finishBuilding(d: Drawing, id: KindId, a: number, p: number, H: number, fit = 1) {+ const kind = kinds[id],+ c = (a + p) / 2,+ pitch = (2 * a) / kind.bays,+ u = -a + pitch * 0.5,+ v = -a + pitch * 0.5+ if (kind.topper === "chimney" && fit > 0) {+ d.box(u, v, 2 * U, 2 * U, H, 24 * fit)+ d.face(square(u, v, 1.5 * U, H + 24 * fit + 0.035), 0x8b938c, 0)+ } else if (kind.topper === "cupola" && fit > 0) {+ const half = 3 * U,+ top = H + 10 * fit,+ base = square(u, v, half, top)+ d.box(u, v, half, half, H, 10 * fit)+ for (const side of ["right", "left"] as const) {+ const pts = (along: number, z: number): Vertex =>+ side === "right" ? [u + half + 0.003, v + along, z] : [u + along, v + half + 0.003, z]+ d.line([pts(-U, top - 7), pts(U, top - 7), pts(U, top - 2), pts(-U, top - 2), pts(-U, top - 7)])+ }+ for (let i = 0; i < 4; i++) d.face([base[i]!, base[(i + 1) % 4]!, [u, v, top + 8]], pale(0x3d6db5, i >= 2 ? 0.7 : 0.52))+ d.line(+ [+ [u, v, top + 8],+ [u, v, top + 15]+ ],+ 1.5+ )+ d.line(+ [+ [u - 2.5 / 64, v + 2.5 / 64, top + 13],+ [u + 2.5 / 64, v - 2.5 / 64, top + 13]+ ],+ 1.5+ )+ } else if (kind.topper === "crates" && fit > 0.5) {+ d.crate(u, v, H, 0xd27a34, 3 * U, 12)+ d.crate(u + 7 * U, v, H, 0x2f8c87, 3 * U, 12)+ d.crate(u + 3 * U, v, H + 12, 0x8a58a8, 3 * U, 12)+ }+ const post = (x: number, y: number, h: number) =>+ d.line(+ [+ [x, y, 0],+ [x, y, h]+ ],+ 1.5+ )+ const bush = (x: number, y: number, r: number, shade = 0xc6d4b2, light = 0xe4ecd6) =>+ d.ellipsoid(x, y, r, r / 45.2548, r / 45.2548, r * 0.866, shade, 1, light)+ const pyramid = (x: number, y: number, half: number, z: number, rise: number, color: number) => {+ const base = square(x, y, half, z)+ for (let i = 0; i < 4; i++) d.face([base[i]!, base[(i + 1) % 4]!, [x, y, z + rise]], pale(color, i >= 2 ? 0.7 : 0.52))+ }+ if (fit <= 0.75) return+ switch (id) {+ case "warehouse":+ d.crate(c, c - 1.5 * U, 0, 0x2f8c87, 1.6 * U, 6)+ d.crate(c, c + 1.5 * U, 0, 0xd27a34, 1.6 * U, 6)+ d.cylinder(c, -a - 2 * U, 1.5 * U, 0, 8, 0xc79a5b, 0xe9c48a, 1.5)+ break+ case "lumberjack": {+ for (const [du, z] of [+ [-1.6, 0],+ [0, 0],+ [1.6, 0],+ [-0.8, 2.6],+ [0.8, 2.6]+ ])+ d.log("v", c + du! * U, a + 0.5 * U, p - 0.5 * U, z!, 1.6, 0xb08a5e, 0xe9d2a8)+ const y = -a - 1.5 * U+ d.cylinder(c, y, 1.3 * U, 0, 3, 0xb08a5e, 0xe9d2a8, 1.5)+ d.line(+ [+ [c, y, 3],+ [c + 0.05, y, 10]+ ],+ 1.5,+ 0x7d6140+ )+ d.box(c + 0.075, y, U, U, 8, 3, 0xb3b9b0, 0x8f9891, 0x7b847d, 1)+ break+ }+ case "forester":+ for (const [x, y, s] of [+ [c, c, 0.8],+ [c, -a - 2 * U, 0.6],+ [-a - 2 * U, c, 0.55]+ ]) {+ d.cylinder(x!, y!, 1.2 * U, 0, 3, 0xd5a86c, 0x7d6140, 1.5)+ d.fir(x!, y!, 3, s!, 2)+ }+ break+ case "quarry": {+ for (const [x, y, z] of [+ [c - U, c - U, 0],+ [c + 1.2 * U, c - 0.8 * U, 0],+ [c - 0.5 * U, c + 1.4 * U, 0],+ [c, c, 5]+ ])+ d.box(x!, y!, 1.2 * U, 1.2 * U, z!, 5, 0xeeefea, 0xdcded7, 0xc9ccc4)+ const y = -a - 2.5 * U+ d.line(+ [+ [c - 1.5 * U, y, 0],+ [c, y, 16],+ [c + 1.5 * U, y, 0]+ ],+ 1.5+ )+ d.line([+ [c, y, 16],+ [c, y, 8]+ ])+ d.box(c, y, U, U, 4, 4, 0xeeefea, 0xdcded7, 0xc9ccc4)+ break+ }+ case "mine": {+ for (const du of [-1, 1])+ d.line(+ [+ [c + du * U, a + 0.5 * U, 0],+ [c + du * U, p - 0.2 * U, 0]+ ],+ 1,+ palette.ink,+ 0.6+ )+ d.box(c, c, 1.6 * U, 2 * U, 2, 5, 0x6c7488, 0xd5dae4, 0xbcc3d1)+ for (const [du, dv] of [+ [-0.8, -0.5],+ [0.7, 0.5],+ [0, 0]+ ])+ d.ellipsoid(c + du! * U, c + dv! * U, 7.5, 0.035, 0.035, 1.5, 0x5a6479, 0.75)+ for (const dv of [-1.2, 1.2]) d.cylinder(c + 1.6 * U, c + dv * U, 0.026, 0, 3, palette.ink, palette.ink, 0.75)+ pyramid(c, -a - 2 * U, 3 * U, 0, 6, 0x5a6479)+ break+ }+ case "fishery": {+ d.cylinder(c, c, 1.5 * U, 0, 7, 0xc79a5b, 0x9fc9c4, 1.5)+ const y0 = -a - 4 * U,+ y1 = -a + 3 * U+ post(c, y0, 11)+ post(c, y1, 11)+ d.line([+ [c, y0, 11],+ [c, y1, 11]+ ])+ for (let i = 1; i <= 3; i++) {+ const y = y0 + ((y1 - y0) * i) / 4+ d.line([+ [c, y, 11],+ [c, y, 9]+ ])+ d.ellipsoid(c, y, 6, 0.028, 0.045, 3, 0x2f8c87, 1)+ d.face(+ [+ [c, y - 0.04, 4],+ [c, y + 0.04, 4],+ [c, y, 3]+ ],+ 0x2f8c87,+ 1+ )+ }+ break+ }+ case "sawmill":+ for (let i = 0; i < 3; i++) d.box(c, -a + 1.5 * U, 1.1 * U, 3 * U, i * 2.5, 2.5, 0xf0c59a, 0xe2a873, 0xd2945c, 1)+ d.log("u", c, -a - 3 * U, -a + 4 * U, 0, 2, 0xb08a5e, 0xe9d2a8)+ break+ case "smithy":+ d.cylinder(c, c, U, 0, 3, 0xb08a5e, 0xe9d2a8, 1.5)+ d.box(c, c, 0.6 * U, 1.4 * U, 3, 3, 0x6d7671, 0x5a625e, 0x4b524e)+ pyramid(c, -a - 2 * U, 2.5 * U, 0, 5, 0x3d4943)+ break+ case "farm":+ d.cylinder(c + U, -a - 3 * U, 3.5 * U, 0, 28, 0xeeeae0, pale(0xc4523f, 0.6), 1.5)+ {+ const start = d.asset.faces.length,+ x = c + U,+ y = -a - 3 * U,+ ring = Array.from({ length: 24 }, (_, i): Vertex => [+ x + Math.cos((i / 24) * Math.PI * 2) * 3.5 * U,+ y + Math.sin((i / 24) * Math.PI * 2) * 3.5 * U,+ 28+ ])+ for (let i = 0; i < 24; i++) d.face([ring[i]!, ring[(i + 1) % 24]!, [x, y, 37]], pale(0xc4523f, 0.6), 0)+ d.face([...ring].reverse(), pale(0xc4523f, 0.6), 0)+ d.volume(start, 1.5)+ d.line([...ring, ring[0]!], 1.5)+ }+ for (const [y, z] of [+ [c - 2.5 * U, 0],+ [c + 2.5 * U, 0],+ [c, 5]+ ])+ d.log("u", y!, a + 2 * U, a + 7 * U, z!, 3, 0xe9cf7c, 0xf3e3a8)+ break+ case "bakery": {+ d.sack(c, -a - U)+ d.sack(c, -a + 2 * U)+ post(c, c, 12)+ const p = (x: number, z: number): Vertex => [c + x / 64, c - x / 64, z]+ d.face([p(-4, 11), p(4, 11), p(4, 17), p(-4, 17)], 0xfaf3e3, 1)+ d.ellipsoid(c + 0.015, c + 0.015, 14, 0.05, 0.05, 1.3, 0xc4523f, 0.75)+ break+ }+ case "sheep": {+ const s = a + U,+ e = p - U+ for (const [x, y] of [+ [s, s],+ [s, e],+ [e, s],+ [e, e]+ ])+ post(x!, y!, 6)+ for (const z of [2.5, 5.5])+ d.line([+ [s, s, z],+ [s, e, z],+ [e, e, z],+ [e, s, z],+ [s, s, z]+ ])+ for (const [x, y, facing] of [+ [s + 3 * U, s + 4 * U, 1],+ [s + 6 * U, s + 2.5 * U, -1],+ [s + 5.5 * U, s + 6.5 * U, 1]+ ]) {+ for (const du of [-0.04, 0.04])+ for (const dv of [-0.025, 0.025])+ d.line(+ [+ [x! + du, y! + dv, 0],+ [x! + du, y! + dv, 3]+ ],+ 1+ )+ d.ellipsoid(x!, y!, 4.5, 0.085, 0.06, 2.2, 0xf8f8f4, 1)+ d.ellipsoid(x! + facing! * 0.1, y!, 5.5, 0.032, 0.032, 1.4, palette.ink, 0)+ }+ d.cylinder(c, -a - 3 * U, 2 * U, 0, 5, 0xe9cf7c, 0xf3e3a8, 1.5)+ break+ }+ case "weaver": {+ const y0 = -a - 2.5 * U,+ y1 = -a + 5 * U+ post(c, y0, 11)+ post(c, y1, 11)+ d.line([+ [c, y0, 11],+ [c, y1, 11]+ ])+ for (const [i, color] of [0x8a58a8, 0xd6ae2e, 0x3d6db5].entries()) {+ const s = y0 + ((y1 - y0) / 3) * i + 0.4 * U,+ e = y0 + ((y1 - y0) / 3) * (i + 1) - 0.4 * U+ d.face(+ [+ [c, s, 10.5],+ [c, e, 10.5],+ [c, e, 4 + (i % 2)],+ [c, s, 4 + (i % 2)]+ ],+ color+ )+ }+ d.sack(c, c, 0, 0xeceee8)+ break+ }+ case "chapel":+ bush(c, c, 4.5)+ bush(c, -a - U, 4, 0xbccfa8, 0xdde8cf)+ bush(-a - U, c, 4, 0xccd5ae, 0xe8ecd2)+ break+ }+}++function drawSails(d: Drawing, a: number, H: number, wave: number) {+ const out = a + 3 * U,+ hubZ = H - 6+ d.line(+ [+ [a, 0, hubZ],+ [out, 0, hubZ]+ ],+ 1.5+ )+ const upright = (s: number, t: number): Vertex => [out, (s / Math.sqrt(5)) * U, hubZ + t]+ for (let i = 0; i < 4; i++) {+ const turn = wave * 0.6 + (i * Math.PI) / 2,+ c = Math.cos(turn),+ s = Math.sin(turn)+ const along = (r: number, w: number) => upright(c * r - s * w, s * r + c * w)+ d.line([along(0, 0), along(26, 0)], 1.5)+ d.face([along(8, 0.5), along(26, 0.5), along(26, 6), along(8, 6)], 0xf6f1e4, 1)+ for (const r of [14, 20]) d.line([along(r, 0.5), along(r, 6)], 1, palette.ink, 0.6)+ d.line([along(8, 3.2), along(26, 3.2)], 1, palette.ink, 0.4)+ }+ d.face(+ Array.from({ length: 24 }, (_, i): Vertex => {+ const [u, v, z] = upright(Math.cos((i * Math.PI) / 12) * 2.2, Math.sin((i * Math.PI) / 12) * 2.2)+ return [u + 0.006, v, z]+ }),+ palette.roof,+ 1+ )+}+export function makeSails() {+ const d = new Drawing("mill-sails", "Mill sails", "")+ const a = kinds.mill.half * U,+ H = kinds.mill.stories * 32+ drawSails(d, a, H, 1.2)+ const shift = ([u, v, z]: Vertex): Vertex => [u - a - 3 * U, v, z - H + 6]+ d.asset.faces.forEach((f) => {+ f.points = f.points.map(shift)+ })+ d.asset.strokes.forEach((s) => {+ s.points = s.points.map(shift)+ })+ return d.asset+}+export function makeFlag(id: KindId) {+ const d = new Drawing("flag-" + id, "Flag", ""),+ delta = 11 / 64+ d.face(+ [+ [0, 0, 0],+ [-delta, delta, -6],+ [0, 0, -8]+ ],+ id === "townhall" ? 0xc4523f : 0x3d6db5,+ 1+ )+ return d.asset+}diff --git a/src/asset-lab/construction.ts b/src/asset-lab/construction.tsnew file mode 100644index 0000000..055ef13--- /dev/null+++ b/src/asset-lab/construction.ts@@ -0,0 +1,138 @@+import { Drawing, palette, square, type Vertex } from "./primitives.ts"+import { buildStages } from "../art.ts"+import { kinds, type KindId } from "../content.ts"+import { U } from "../iso.ts"++export function makeSite(share: number, size = 2) {+ const d = new Drawing(+ `site-${share === 0 ? "empty" : "supplied"}`,+ share === 0 ? "Marked construction site" : "Supplied construction site",+ "Stakes, ropes and incoming materials, using the original site proportions."+ )+ d.asset.category = "construction"+ d.asset.reference = { type: "site", share }+ d.asset.footprint = size+ const p = (size * 8 - 1) * U,+ s = p - U+ d.plate(size)+ d.line([...square(0, 0, s, 6), [-s, -s, 6]], 1, palette.ink, 0.45)+ for (const [u, v] of [+ [-s, -s],+ [s, -s],+ [s, s],+ [-s, s]+ ])+ d.line(+ [+ [u!, v!, 0],+ [u!, v!, 7]+ ],+ 1.5+ )+ const spots = [+ [s - 3 * U, s - 3 * U, 0],+ [s - 3 * U, s - 8 * U, 0],+ [s - 3 * U, s - 5.5 * U, 5]+ ]+ for (let i = 0; i < Math.min(3, Math.ceil(share * 3)); i++) {+ const [u, v, z] = spots[i]!+ d.crate(u!, v!, z!, 0x8f9891, 2 * U, 5)+ }+ return d.asset+}+export function makeConstruction(kindId: KindId, progress: number) {+ const kind = kinds[kindId],+ a = kind.half * U,+ H = kind.roof === "gable" ? 20 : kind.stories * 32,+ stage = buildStages(progress)+ const d = new Drawing(+ `build-${kindId}-${progress}`,+ `${kind.title} · ${progress < 0.5 ? "frame" : "walls"}`,+ "The same construction timing and frame/wall dimensions as the 2D drawing."+ )+ d.asset.category = "construction"+ d.asset.reference = { type: "building", kind: kindId, build: progress }+ d.asset.footprint = kind.size+ d.plate(kind.size)+ if (stage.frame > 0 && stage.walls < 1) {+ const top = Math.round(H * stage.frame)+ d.line([...square(0, 0, a, top), [-a, -a, top]], 1)+ for (const [u, v] of [+ [-a, -a],+ [a, -a],+ [a, a],+ [-a, a]+ ])+ d.line(+ [+ [u!, v!, 0],+ [u!, v!, top]+ ],+ 1+ )+ }+ if (stage.walls > 0) d.box(0, 0, a, a, 0, Math.round(H * stage.walls))+ return d.asset+}+export function makeMarker() {+ const d = new Drawing("problem-marker", "Problem marker", "The original red exclamation mark, as a thin world-space sign.")+ d.asset.category = "construction"+ d.asset.reference = { type: "none" }+ d.asset.footprint = 1+ const p = (x: number, z: number): Vertex => [x / 64, -x / 64, z]+ d.face([p(-7.5, 0), p(7.5, 0), p(7.5, 15), p(-7.5, 15)], 0xf6f7f3, 1, 0xc4523f)+ d.face([p(-1, 6), p(1, 6), p(1, 12), p(-1, 12)], 0xc4523f, 0)+ d.face([p(-1, 3), p(1, 3), p(1, 5), p(-1, 5)], 0xc4523f, 0)+ return d.asset+}+export function makeSmoke() {+ const d = new Drawing("smoke", "Chimney smoke", "The original fine smoke rings, on upright planes above the chimney.")+ d.asset.category = "construction"+ d.asset.reference = { type: "none" }+ d.asset.footprint = 1+ for (const t of [0.1, 0.4, 0.7]) {+ const r = 4 + t * 7,+ dx = Math.sin(t * 5) * 1.5,+ h = t * 34+ const ring = Array.from({ length: 25 }, (_, i): Vertex => [+ (dx + Math.cos((i / 24) * Math.PI * 2) * r) / 64,+ -(dx + Math.cos((i / 24) * Math.PI * 2) * r) / 64,+ h + Math.sin((i / 24) * Math.PI * 2) * r+ ])+ d.line(ring, 1, palette.ink, (1 - t) * 0.55)+ }+ return d.asset+}+export function makePlot(look: "hover" | "picked" | "blocked" | "reach") {+ const d = new Drawing(`plot-${look}`, `Plot · ${look}`, "Ground-space placement and reach outlines, preserving the original ink colours.")+ d.asset.category = "construction"+ d.asset.reference = { type: "plot", look }+ d.asset.footprint = 2+ const color = look === "blocked" ? 0xc4523f : look === "picked" ? 0x3d6db5 : palette.ink+ d.line(+ [...square(0, 0, 1, 0.05), [-1, -1, 0.05]],+ look === "picked" || look === "blocked" ? 1.5 : 1,+ color,+ look === "hover" ? 0.35 : look === "reach" ? 0.45 : 0.85+ )+ if (look === "picked" || look === "blocked")+ for (const [u, v] of [+ [-1, -1],+ [1, -1],+ [1, 1],+ [-1, 1]+ ]) {+ d.line(+ [+ [u! * 0.75, v!, 0.06],+ [u! + Math.sign(u!) * U, v!, 0.06],+ [u!, v! + Math.sign(v!) * U, 0.06],+ [u!, v! * 0.75, 0.06]+ ],+ 1.5,+ color,+ 0.9+ )+ }+ return d.asset+}diff --git a/src/asset-lab/homes.ts b/src/asset-lab/homes.tsnew file mode 100644index 0000000..310a9a0--- /dev/null+++ b/src/asset-lab/homes.ts@@ -0,0 +1,47 @@+import { home } from "../content.ts"+import { homeVariant } from "../art.ts"+import { U } from "../iso.ts"+import { Drawing, palette, sides, type Side } from "./primitives.ts"++export function house(+ tier: 1 | 2,+ variantN = tier === 1 ? 0.03 : 0.28,+ id = tier === 1 ? "cottage" : "citizen",+ options: { doors?: Partial<Record<Side, boolean>>; fit?: number; plate?: boolean } = {}+) {+ const fit = options.fit ?? 1+ const d = new Drawing(+ id,+ tier === 1 ? "Settler cottage" : "Citizen home",+ "Original roof palette, footprint, chimney, windows and awnings. Rear walls completed for rotation."+ )+ const variant = homeVariant(variantN)+ const a = (home.half + (tier === 2 ? 1 : 0)) * U,+ H = home.tiers[tier].height+ d.asset.category = "homes"+ d.asset.reference = { type: "house", tier, variant: variantN }+ d.asset.footprint = 1+ if (options.plate !== false) d.plate(1)+ d.box(0, 0, a, a, 0, H)+ for (const side of sides) {+ const door = options.doors ? !!options.doors[side] : side === "right"+ if (tier === 2) d.line([d.wall(side, a, -a, 13), d.wall(side, a, a, 13)], 1, palette.ink, 0.7)+ if (door && fit > 0.15) d.door(side, a, Math.max(2, 9 * fit), 2 * U, 3 * U, 2 * U, variant.roof.shade)+ for (const floor of fit > 0.4 ? (tier === 2 ? [0, 12] : [0]) : []) {+ if (tier === 2) {+ for (const along of [-3 * U, 3 * U]) if (!(door && floor === 0)) d.window(side, a, along, floor + 5)+ } else if (!door) d.window(side, a, 0, 5)+ }+ }+ if (fit > 0)+ d.gable(+ a,+ H,+ (tier === 2 ? 10 : 8) * fit,+ variant.ridge,+ variant.roof.face,+ variant.roof.shade,+ fit > 0.8 && (variant.chimney || tier === 2)+ )+ return d.asset+}diff --git a/src/asset-lab/land.ts b/src/asset-lab/land.tsnew file mode 100644index 0000000..fff69c3--- /dev/null+++ b/src/asset-lab/land.ts@@ -0,0 +1,309 @@+import { Drawing, palette, square, type Vertex } from "./primitives.ts"+import { U } from "../iso.ts"++export const hash = (x: number, y: number) => {+ let h = (x * 374761393 + y * 668265263) >>> 0+ h = Math.imul(h ^ (h >>> 13), 1274126177) >>> 0+ return ((h ^ (h >>> 16)) >>> 0) / 4294967296+}+const leaves = [+ { light: 0xe4ecd6, shade: 0xc6d4b2 },+ { light: 0xdde8cf, shade: 0xbccfa8 },+ { light: 0xe8ecd2, shade: 0xccd5ae },+ { light: 0xdbe6d4, shade: 0xb8cbb2 },+ { light: 0xefe7c9, shade: 0xd7c99c }+]+export function makeTree(+ type: "fir" | "broadleaf" | "poplar",+ grown: number,+ id: string,+ options?: { x: number; y: number; segments?: number }+) {+ let x = 0,+ y = 0+ for (let i = 0; i < 1000; i++) {+ const h = hash(i * 3, i * 7),+ found = h < 0.45 ? "fir" : h > 0.88 ? "poplar" : "broadleaf"+ if (found === type && (type !== "broadleaf" || h > 0.6)) {+ x = i * 3+ y = i * 7+ break+ }+ }+ if (options) {+ x = options.x+ y = options.y+ }+ const h = hash(x, y),+ h2 = hash(y * 3 + 17, x * 5 + 7),+ h3 = hash(x * 11 + 101, y * 13 + 3)+ const s = (grown >= 1 ? 1 : grown >= 0.5 ? 0.75 : 0.5) * (0.85 + h2 * 0.3),+ ox = Math.round((h3 - 0.5) * 12),+ oy = Math.round((h2 - 0.5) * 5)+ const u = ox / 64 + oy / 32,+ v = -ox / 64 + oy / 32,+ trunk = Math.round(6 * s)+ const d = new Drawing(+ id,+ `${type === "broadleaf" ? "Broadleaf" : type === "poplar" ? "Poplar" : "Fir"} · ${grown >= 1 ? "grown" : grown >= 0.5 ? "young" : "sapling"}`,+ "Seeded tree shape, original leaf colours and growth stages, built as a complete volume."+ )+ d.asset.category = "land"+ d.asset.reference = { type: "tree", x, y, grown }+ d.asset.footprint = 1+ d.face(+ Array.from({ length: 32 }, (_, i): Vertex => {+ const t = (i / 32) * Math.PI * 2,+ sx = ox + 3 * s + 9 * s * Math.cos(t),+ sy = oy + 3.5 * s * Math.sin(t)+ return [sx / 64 + sy / 32, -sx / 64 + sy / 32, -0.02]+ }),+ 0xe3e6de,+ 0+ )+ if (type === "fir") {+ d.fir(u, v, 0, s, h2 < 0.5 ? 2 : 3)+ if (h3 >= 0.5) for (const face of d.asset.faces) {+ if (face.color === 0xd9e5d7) face.color = 0xd3e0d3+ else if (face.color === 0xb3c7b4) face.color = 0xa9bfab+ }+ return d.asset+ }+ d.line(+ [+ [u, v, 0],+ [u, v, trunk]+ ],+ 1.5,+ 0x6b5a45+ )+ const color = leaves[Math.floor(h2 * 97) % leaves.length]!+ const lobe = (sx: number, sy: number, rx: number, ry: number, forward = 0) => {+ const du = (sx - ox) / 64,+ dv = -(sx - ox) / 64,+ z = oy - sy+ d.ellipsoid(+ u + du + (forward * 0.6123724) / 45.2548,+ v + dv + (forward * 0.6123724) / 45.2548,+ z + forward * 0.5 * 0.8660254,+ rx / 45.2548,+ rx / 45.2548,+ Math.sqrt(Math.max(1, ry * ry - rx * rx * 0.25)),+ color.shade,+ 1.5,+ color.light,+ options?.segments ?? 48+ )+ }+ if (type === "poplar") lobe(ox, oy - trunk - 10 * s, 4.5 * s, 11 * s)+ else {+ const r = 7 * s,+ cy = oy - trunk - r+ if (s >= 0.75 && h > 0.6) {+ lobe(ox - r * 0.6, cy + r * 0.25, r * 0.7, r * 0.7)+ lobe(ox + r * 0.65, cy + r * 0.3, r * 0.65, r * 0.65)+ }+ const forward = s >= 0.75 && h > 0.6 ? r * 0.75 : 0+ lobe(ox, cy, r, r * 0.95, forward)+ // Lay the original twig stroke on the curved front surface, rather+ // than hiding it inside the canopy volume.+ const branch = Array.from({ length: 12 }, (_, i): Vertex => {+ const t = i / 11,+ sx = r * (-0.35 + 0.4 * t),+ sy = r * (0.15 - 0.45 * t),+ q = [sx / Math.SQRT2 + sy * 0.353553, -sy * 0.8660254, -sx / Math.SQRT2 + sy * 0.353553],+ direction = [0.6123724, 0.5, 0.6123724],+ radii = [r, r * 0.932738, r]+ let A = 0,+ B = 0,+ C = -1+ for (let j = 0; j < 3; j++) {+ A += (direction[j]! / radii[j]!) ** 2+ B += (2 * q[j]! * direction[j]!) / radii[j]! ** 2+ C += (q[j]! / radii[j]!) ** 2+ }+ const depth = (-B + Math.sqrt(B * B - 4 * A * C)) / (2 * A) + 0.15 + forward+ return [+ u + (q[0]! + depth * direction[0]!) / 45.2548,+ v + (q[2]! + depth * direction[2]!) / 45.2548,+ trunk + r + (q[1]! + depth * direction[1]!) * 0.8660254+ ]+ })+ d.line(branch, 1, palette.ink, 0.35)+ }+ return d.asset+}++export function makeRock(ore: boolean, full: boolean) {+ const x = ore ? 5 : 0,+ y = ore ? 3 : 0,+ h = hash(x, y),+ h2 = hash(x * 7 + 3, y * 5 + 11),+ h3 = hash(y * 17 + 5, x * 3 + 29)+ const colors = ore ? { top: 0xe8ebf0, left: 0xd5dae3, right: 0xbcc3d0 } : { top: 0xeeefe9, left: 0xdfe1da, right: 0xcbcfc7 }+ const d = new Drawing(+ `${ore ? "ore" : "stone"}-${full ? "full" : "quarried"}`,+ `${ore ? "Ore" : "Stone"} · ${full ? "full" : "quarried"}`,+ "Faceted boulders, pebbles and mineral flecks, in both resource states."+ )+ d.asset.category = "land"+ d.asset.reference = { type: "rock", x, y, ore, amount: full ? 40 : 10 }+ d.asset.footprint = 1+ const s = (full ? 5 : 4) * U * (0.85 + h2 * 0.3),+ tall = Math.round((full ? 10 : 7) * (0.8 + h3 * 0.4)),+ u = (h - 0.5) * 4 * U,+ v = (h3 - 0.5) * 3 * U+ const boulder = (u: number, v: number, s: number, H: number, k: number, j: number) => {+ const base = square(u, v, s),+ top: Array<Vertex> = [+ [u - s * j, v - s * j, H],+ [u + s * k, v - s * j, H],+ [u + s, v + s * k, H],+ [u - s * j, v + s * k, H]+ ]+ for (let i = 0; i < 4; i++) d.face([base[i]!, base[(i + 1) % 4]!, top[(i + 1) % 4]!, top[i]!], i === 1 ? colors.right : colors.left)+ d.face(top, colors.top)+ d.face([...base].reverse(), colors.left, 0)+ }+ if (h2 > 0.35) boulder(u - s * 0.9, v - s * 1.1, s * 0.55, Math.round(tall * 0.6), 0.3 + h * 0.3, 0.5)+ boulder(u, v, s, tall, 0.3 + h2 * 0.3, 0.5 + h3 * 0.2)+ if (full && h3 > 0.5) boulder(u + s * 0.9, v + s * 1.2, s * 0.4, Math.round(tall * 0.45), 0.4, 0.6)+ for (let i = 0; i < 3; i++)+ d.ellipsoid(u + (hash(x + i, y * 3) - 0.5) * 14 * U, v + s + (hash(y + i, x * 5) * 3 + 1) * U, 0.4, 0.02, 0.02, 0.4, 0xaab1a6, 0)+ if (ore) {+ for (const [du, dv, z] of [+ [-0.3, 1, 3],+ [0.2, 1, 6],+ [1, 0.1, 4],+ [1, -0.5, 7]+ ]) {+ const U0 = u + du! * s,+ V0 = v + dv! * s,+ H = z! * (tall / 10),+ w = 1 / 64+ d.face(+ [+ [U0 - w, V0 + 0.003, H - 1],+ [U0 + w, V0 + 0.003, H - 1],+ [U0 + w, V0 + 0.003, H + 1],+ [U0 - w, V0 + 0.003, H + 1]+ ],+ 0x4a5368,+ 0+ )+ }+ const base = square(u - s * 0.2, v + s * 0.1, 0.035, tall)+ for (let i = 0; i < 4; i++) d.face([base[i]!, base[(i + 1) % 4]!, [u - s * 0.2, v + s * 0.1, tall + 4]], 0x8fa3c8, 1)+ }+ return d.asset+}++export function makeField(stage: 0 | 1 | 2 | 3) {+ const d = new Drawing(+ `field-${stage}`,+ `Field · ${["sown", "sprouting", "growing", "ripe"][stage]}`,+ "The original soil, three furrows and four crop stages."+ )+ d.asset.category = "land"+ d.asset.reference = { type: "field", grown: stage / 3 }+ d.asset.footprint = 1+ const s = 7 * U+ d.face(square(0, 0, s, -0.1), 0xece8dc, 1)+ for (const v of [-4 * U, 0, 4 * U]) {+ d.line(+ [+ [-s + U, v, 0],+ [s - U, v, 0]+ ],+ 1,+ palette.ink,+ 0.35+ )+ if (stage)+ for (let u = -s + 2 * U; u <= s - 2 * U; u += 2 * U)+ d.line(+ [+ [u, v, 0],+ [u, v, stage + 1]+ ],+ 1,+ stage === 3 ? 0xcdb46a : palette.ink,+ stage === 3 ? 1 : 0.6+ )+ }+ return d.asset+}++export function makeRoadPatch() {+ const d = new Drawing("roads", "Road junction", "Twelve-unit paving, kerbs, worn stones and dashed markings, with clean junctions.")+ d.asset.category = "land"+ d.asset.reference = { type: "roads" }+ d.asset.footprint = 3+ for (const [x, y] of [+ [0, 0],+ [-1, 0],+ [1, 0],+ [0, -1],+ [0, 1]+ ]) {+ d.face(square(x!, y!, 0.375, -0.1), 0xe6e8e2, 0)+ for (const [dx, dy] of [+ [1, 0],+ [-1, 0],+ [0, 1],+ [0, -1]+ ]) {+ const q = (a: number, c: number): Vertex => [x! + dx! * a - dy! * c, y! + dy! * a + dx! * c, 0]+ if (x! + dx! === 0 || y! + dy! === 0) {+ if (Math.abs(x! + dx!) + Math.abs(y! + dy!) <= 1) {+ d.face([q(0.375, -0.375), q(0.5, -0.375), q(0.5, 0.375), q(0.375, 0.375)], 0xe6e8e2, 0)+ d.line([q(0.375, -0.375), q(0.5, -0.375)], 1.5)+ d.line([q(0.375, 0.375), q(0.5, 0.375)], 1.5)+ d.line([q(0.0625, 0), q(0.1875, 0)], 1, 0xb4b9b1)+ continue+ }+ }+ d.line([q(0.375, -0.375), q(0.375, 0.375)], 1.5)+ }+ }+ return d.asset+}+export function makeWater() {+ const d = new Drawing("water", "Water & shore", "Flat pale water, ink waves, shore edges and white glints.")+ d.asset.category = "land"+ d.asset.reference = { type: "water" }+ d.asset.footprint = 3+ d.face(square(0, 0, 1.5, -0.2), 0xdfe8e6, 1)+ for (const [u, v] of [+ [-0.8, -0.7],+ [0.6, -0.2],+ [-0.4, 0.9]+ ])+ d.line(+ [+ [u! - 0.15, v!, 0],+ [u! - 0.05, v! - 0.04, 0],+ [u! + 0.05, v!, 0],+ [u! + 0.15, v! - 0.04, 0]+ ],+ 1,+ 0x9fb3b0+ )+ d.line(+ [+ [0.72, 0.9, 0],+ [0.88, 0.9, 0]+ ],+ 1,+ 0xffffff+ )+ d.line(+ [+ [0.8, 0.82, 0],+ [0.8, 0.98, 0]+ ],+ 1,+ 0xffffff+ )+ return d.asset+}diff --git a/src/asset-lab/main.ts b/src/asset-lab/main.tsnew file mode 100644index 0000000..d7f920f--- /dev/null+++ b/src/asset-lab/main.ts@@ -0,0 +1,412 @@+import { Application, Graphics } from "pixi.js"+import * as THREE from "three"+import {+ drawBuilding,+ drawCrate,+ drawCargo,+ drawHouse,+ drawTree,+ drawRock,+ drawField,+ drawWalker,+ drawSite,+ drawRoads,+ drawWater,+ homeVariant,+ plate,+ plateHalf+} from "../art.ts"+import { kinds, goods } from "../content.ts"+import { key } from "../grid.ts"+import { drawPlot } from "../art.ts"+import { U, toScreen } from "../iso.ts"+import { inkAssets, assetCategoryTitles, type InkAsset } from "./assets.ts"+import { buildAsset, exportAsset, reloadExportedAsset } from "./renderer.ts"+import "./style.css"++const root = document.querySelector<HTMLDivElement>("#lab")!+root.innerHTML = `+ <header><a href="/">Inkline Town</a><span>COMPLETE ASSET STUDY</span></header>+ <div class="intro"><div><h1>The same ink.<br>A different angle.</h1><p>Original game drawings and complete 3D assets, side by side.</p></div><span class="tag">Procedural · Orthographic · Rotatable</span></div>+ <div class="filters"><label>Collection <select id="category"></select></label><label>Find <input id="search" type="search" placeholder="Name or material"></label><a href="/map-lab.html">See everything on the map ↗</a></div><nav class="assets" aria-label="Choose an asset"></nav>+ <section class="comparison" aria-label="Compare the original drawing with the 3D model">+ <div class="view"><div class="view-label"><span>01 / CURRENT GAME</span><span>Fixed isometric drawing</span></div><canvas id="reference" aria-label="Original 2D asset"></canvas><span class="view-foot">Original art.ts drawing</span></div>+ <div class="view"><div class="view-label"><span>02 / 3D STUDY</span><span id="angle-label">Original angle</span></div><div id="viewer" role="img" aria-label="Rotatable 3D asset. Drag horizontally to rotate."></div><span class="view-foot">Drag to rotate · wheel to zoom</span></div>+ </section>+ <section class="controls" aria-label="Camera controls"><button id="reset">Match original view</button><label>Rotation <input id="rotation" type="range" min="-180" max="180" value="0" step="1"><output id="rotation-value">0°</output></label><label>Elevation <input id="elevation" type="range" min="10" max="65" value="30" step="1"><output id="elevation-value">30°</output></label><button id="rear">See the back</button></section>+ <section class="caption"><div><h2 id="asset-title"></h2><p id="asset-note"></p></div><div class="downloads"><button id="download-glb">Download GLB</button><button id="download-source">Download geometry</button><button id="download-png">Save comparison</button></div></section>+ <footer><span>Same palette, dimensions and two ink weights. New faces complete the volume.</span><span>Three.js prototype · PixiJS 3D integration pending</span></footer>+`+const viewer = document.querySelector<HTMLDivElement>("#viewer")!+const reference = document.querySelector<HTMLCanvasElement>("#reference")!+const rotation = document.querySelector<HTMLInputElement>("#rotation")!+const elevation = document.querySelector<HTMLInputElement>("#elevation")!+const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true })+renderer.setPixelRatio(Math.min(devicePixelRatio, 2))+renderer.setClearColor(0xf0f2ec, 0)+renderer.outputColorSpace = THREE.SRGBColorSpace+renderer.toneMapping = THREE.NoToneMapping+viewer.append(renderer.domElement)+const scene = new THREE.Scene()+const camera = new THREE.OrthographicCamera(-100, 100, 100, -100, 0.1, 4000)+const pixi = new Application()+await pixi.init({ width: 32, height: 32, antialias: true, resolution: 3, backgroundAlpha: 0 })++function original(asset: InkAsset) {+ const g = new Graphics()+ const r = asset.reference+ if (r) {+ switch (r.type) {+ case "building":+ plate(g, plateHalf(kinds[r.kind].size))+ drawBuilding(g, kinds[r.kind], r.build ?? 1, 0, 1.2, { right: true, left: true })+ break+ case "house":+ plate(g, plateHalf(1))+ drawHouse(g, r.tier, r.build ?? 1, { right: true, left: false }, homeVariant(r.variant))+ break+ case "tree":+ drawTree(g, r.x, r.y, r.grown)+ break+ case "rock":+ drawRock(g, r.x, r.y, r.ore, r.amount)+ break+ case "field":+ drawField(g, r.grown)+ break+ case "walker":+ drawWalker(g, r.dress, r.load, r.cart, { x: 1, y: 0 }, r.phase)+ break+ case "crate":+ drawCrate(g, goods[r.good].color, 3 * U, 12)+ break+ case "cargo":+ drawCargo(g, 0, 0, { x: 1, y: 0 }, r.good, r.count, 0)+ break+ case "site":+ plate(g, plateHalf(2))+ drawSite(g, plateHalf(2), r.share)+ break+ case "plot":+ drawPlot(g, -1, -1, 2, r.look, 0)+ break+ case "roads": {+ const cells = new Set([key(8, 8), key(7, 8), key(9, 8), key(8, 7), key(8, 9)])+ const p = toScreen(8.5, 8.5)+ g.translateTransform(-p.x, -p.y)+ drawRoads(g, cells)+ g.resetTransform()+ break+ }+ case "water": {+ const cells = new Set<number>()+ for (let x = 7; x <= 9; x++) for (let y = 7; y <= 9; y++) cells.add(key(x, y))+ const p = toScreen(8.5, 8.5)+ g.translateTransform(-p.x, -p.y)+ drawWater(g, cells)+ g.resetTransform()+ break+ }+ case "none":+ if (asset.id === "problem-marker") {+ g.roundRect(-7.5, -15, 15, 15, 2).fill(0xf6f7f3).stroke({ color: 0xc4523f, width: 1 })+ g.rect(-1, -12, 2, 6).rect(-1, -5, 2, 2).fill(0xc4523f)+ } else+ for (const t of [0.1, 0.4, 0.7])+ g.circle(Math.sin(t * 5) * 1.5, -t * 34, 4 + t * 7).stroke({ color: 0x3d4943, width: 1, alpha: (1 - t) * 0.55 })+ break+ }+ } else if (asset.id === "cottage" || asset.id === "citizen") {+ const tier = asset.id === "cottage" ? 1 : 2+ plate(g, plateHalf(1))+ drawHouse(g, tier, 1, { right: true, left: false }, homeVariant(tier === 1 ? 0.03 : 0.28))+ } else if (asset.id === "fir") drawTree(g, 0, 0, 1)+ else if (asset.id === "goods") {+ plate(g, plateHalf(2))+ // Exact crate drawings from the game; planks/stone use their original projected faces.+ drawCrate(g, 0x2f8c87, 3 * U, 12, 0, 0.35, 0.3)+ drawCrate(g, 0x8a58a8, 3 * U, 12, 0, -0.15, 0.3)+ drawCrate(g, 0xd27a34, 3 * U, 12, 12, 0.1, 0.3)+ const box = (u: number, v: number, a: number, b: number, z: number, h: number, top: number, left: number, right: number) => {+ const poly = (ps: Array<[number, number, number]>, fill: number) =>+ g+ .poly(+ ps.flatMap(([u, v, z]) => {+ const p = toScreen(u, v, z)+ return [p.x, p.y]+ })+ )+ .fill(fill)+ .stroke({ color: 0x3d4943, width: 1, join: "round" })+ poly(+ [+ [u - a, v + b, z],+ [u + a, v + b, z],+ [u + a, v + b, z + h],+ [u - a, v + b, z + h]+ ],+ left+ )+ poly(+ [+ [u + a, v - b, z],+ [u + a, v + b, z],+ [u + a, v + b, z + h],+ [u + a, v - b, z + h]+ ],+ right+ )+ poly(+ [+ [u - a, v - b, z + h],+ [u + a, v - b, z + h],+ [u + a, v + b, z + h],+ [u - a, v + b, z + h]+ ],+ top+ )+ }+ for (let i = 0; i < 3; i++) box(0.3, -0.4, 1.1 * U, 3 * U, i * 2.5, 2.5, 0xf0c59a, 0xe2a873, 0xd2945c)+ box(-0.4, -0.35, 1.2 * U, 1.2 * U, 0, 5, 0xeeefea, 0xdcded7, 0xc9ccc4)+ } else {+ const kind = kinds[asset.id as "townhall" | "mill" | "market"]+ plate(g, plateHalf(kind.size))+ drawBuilding(g, kind, 1, 0, 1.2, { right: true, left: true })+ }+ return g+}++const references = new Map<string, { image: HTMLImageElement; x: number; y: number; width: number; height: number }>()+for (const asset of inkAssets) {+ const g = original(asset),+ b = g.getLocalBounds(),+ image = new Image()+ image.src = await pixi.renderer.extract.base64({ target: g, resolution: Math.max(b.width, b.height) < 60 ? 12 : 4 })+ await image.decode()+ references.set(asset.id, { image, x: b.minX, y: b.minY, width: b.width, height: b.height })+ g.destroy()+}+pixi.destroy(true)++const models = new Map<string, ReturnType<typeof buildAsset>>()+let selected = inkAssets[2]!,+ yaw = 0,+ pitch = 30,+ zoom = 1,+ drawCount = 0+const nav = root.querySelector<HTMLElement>("nav")!+const category = root.querySelector<HTMLSelectElement>("#category")!+const search = root.querySelector<HTMLInputElement>("#search")!+for (const [id, title] of Object.entries(assetCategoryTitles)) {+ const option = document.createElement("option")+ option.value = id+ option.textContent = `${title} (${inkAssets.filter((a) => a.category === id).length})`+ category.append(option)+}+const filter = () =>+ nav.querySelectorAll<HTMLButtonElement>("button").forEach((b) => {+ const a = inkAssets.find((a) => a.id === b.dataset.asset)!+ b.hidden = a.category !== category.value || !a.title.toLowerCase().includes(search.value.toLowerCase())+ })+category.onchange = filter+search.oninput = filter+for (const asset of inkAssets) {+ const button = document.createElement("button")+ button.dataset.asset = asset.id+ button.innerHTML = `<img alt="" src="${references.get(asset.id)!.image.src}"><span>${asset.title}</span>`+ button.onclick = () => select(asset.id)+ nav.append(button)+}++function render() {+ const width = viewer.clientWidth,+ height = viewer.clientHeight+ if (!width || !height) return+ const ref = references.get(selected.id)!+ const vertical = Math.max(40, ref.height * 1.45, ((ref.width * height) / width) * 1.3) / zoom+ renderer.setSize(width, height, false)+ camera.left = (-vertical * width) / height / 2+ camera.right = -camera.left+ camera.top = vertical / 2+ camera.bottom = -camera.top+ const heading = ((45 + yaw) * Math.PI) / 180,+ altitude = (pitch * Math.PI) / 180+ const target = new THREE.Vector3(0, -(ref.y + ref.height / 2) / Math.cos(Math.PI / 6), 0)+ camera.position+ .copy(target)+ .add(+ new THREE.Vector3(+ Math.sin(heading) * Math.cos(altitude) * 1000,+ Math.sin(altitude) * 1000,+ Math.cos(heading) * Math.cos(altitude) * 1000+ )+ )+ camera.lookAt(target)+ camera.updateProjectionMatrix()+ camera.updateMatrixWorld()+ const model = models.get(selected.id)!+ for (const { material, width: lineWidth } of model.lineMaterials) material.linewidth = lineWidth+ model.updateContours(camera)+ renderer.render(scene, camera)+ const dpr = Math.min(devicePixelRatio, 2),+ ctx = reference.getContext("2d")!+ reference.width = Math.round(width * dpr)+ reference.height = Math.round(height * dpr)+ ctx.scale(dpr, dpr)+ const scale = height / vertical+ ctx.drawImage(ref.image, (width - ref.width * scale) / 2, (height - ref.height * scale) / 2, ref.width * scale, ref.height * scale)+ rotation.value = String(yaw)+ elevation.value = String(pitch)+ root.querySelector("#rotation-value")!.textContent = `${Math.round(yaw)}°`+ root.querySelector("#elevation-value")!.textContent = `${Math.round(pitch)}°`+ root.querySelector("#angle-label")!.textContent =+ yaw === 0 && pitch === 30 ? "Original angle" : `${Math.round(yaw)}° rotation · ${Math.round(pitch)}° elevation`+ drawCount+++}+function select(id: string) {+ selected = inkAssets.find((asset) => asset.id === id) ?? inkAssets[2]!+ id = selected.id+ if (!models.has(id) && models.size >= 3) {+ const oldest = models.keys().next().value!+ models.get(oldest)!.dispose()+ models.delete(oldest)+ }+ if (!models.has(id)) models.set(id, buildAsset(selected, { batchFaces: true }))+ scene.clear()+ scene.add(models.get(id)!.group)+ category.value = selected.category ?? "buildings"+ search.value = ""+ filter()+ yaw = 0+ pitch = 30+ zoom = 1+ nav.querySelectorAll<HTMLButtonElement>("button").forEach((button) => {+ button.classList.toggle("active", button.dataset.asset === id)+ button.setAttribute("aria-pressed", String(button.dataset.asset === id))+ })+ root.querySelector("#asset-title")!.textContent = selected.title+ root.querySelector("#asset-note")!.textContent = selected.note+ render()+}+rotation.oninput = () => {+ yaw = Number(rotation.value)+ render()+}+elevation.oninput = () => {+ pitch = Number(elevation.value)+ render()+}+root.querySelector<HTMLButtonElement>("#reset")!.onclick = () => {+ yaw = 0+ pitch = 30+ zoom = 1+ render()+}+root.querySelector<HTMLButtonElement>("#rear")!.onclick = () => {+ yaw = 180+ render()+}+let drag: { x: number; yaw: number } | null = null+viewer.onpointerdown = (event) => {+ drag = { x: event.clientX, yaw }+ viewer.setPointerCapture(event.pointerId)+}+viewer.onpointermove = (event) => {+ if (drag) {+ yaw = ((drag.yaw + (event.clientX - drag.x) * 0.5 + 540) % 360) - 180+ render()+ }+}+viewer.onpointerup = viewer.onpointercancel = () => {+ drag = null+}+viewer.onwheel = (event) => {+ event.preventDefault()+ zoom = Math.max(0.65, Math.min(2, zoom * Math.exp(-event.deltaY * 0.001)))+ render()+}+const resize = new ResizeObserver(render)+resize.observe(viewer)++function download(data: Blob, name: string) {+ const url = URL.createObjectURL(data),+ a = document.createElement("a")+ a.href = url+ a.download = name+ a.click()+ setTimeout(() => URL.revokeObjectURL(url), 1000)+}+root.querySelector<HTMLButtonElement>("#download-glb")!.onclick = async () =>+ download(new Blob([await exportAsset(selected)], { type: "model/gltf-binary" }), `inkline-${selected.id}.glb`)+root.querySelector<HTMLButtonElement>("#download-source")!.onclick = () =>+ download(new Blob([JSON.stringify(selected, null, 2)], { type: "application/json" }), `inkline-${selected.id}.json`)+root.querySelector<HTMLButtonElement>("#download-png")!.onclick = () => {+ const canvas = document.createElement("canvas"),+ ctx = canvas.getContext("2d")!,+ w = reference.width,+ h = reference.height+ canvas.width = w * 2+ canvas.height = h + 80+ ctx.fillStyle = "#f0f2ec"+ ctx.fillRect(0, 0, canvas.width, canvas.height)+ ctx.drawImage(reference, 0, 60)+ ctx.drawImage(renderer.domElement, w, 60, w, h)+ ctx.fillStyle = "#3d4943"+ ctx.font = "24px monospace"+ ctx.fillText(`${selected.title} / original`, 24, 38)+ ctx.fillText(`3D / ${Math.round(yaw)}°`, w + 24, 38)+ canvas.toBlob((blob) => {+ if (blob) download(blob, `inkline-${selected.id}-comparison.png`)+ })+}++// A local inspection/export bridge for reproducible visual checks and GLB delivery.+const capture = (side: "reference" | "model", width = 480) => {+ const input = side === "reference" ? reference : renderer.domElement+ const output = document.createElement("canvas")+ output.width = width+ output.height = Math.round((width * input.height) / input.width)+ const crop = 0.8+ output+ .getContext("2d")!+ .drawImage(+ input,+ (input.width * (1 - crop)) / 2,+ (input.height * (1 - crop)) / 2,+ input.width * crop,+ input.height * crop,+ 0,+ 0,+ output.width,+ output.height+ )+ return output.toDataURL()+}+Object.assign(window, {+ inkLab: {+ assets: inkAssets,+ select,+ rotate: (angle: number, altitude = 30) => {+ yaw = angle+ pitch = altitude+ render()+ },+ exportAsset,+ showExported: async () => {+ const model = await reloadExportedAsset(selected)+ scene.clear()+ scene.add(model)+ render()+ return { meshes: model.children.length }+ },+ stats: () => ({ selected: selected.id, yaw, pitch, drawCount, triangles: renderer.info.render.triangles }),+ capture+ }+})+select(new URLSearchParams(location.search).get("asset") ?? selected.id)+if (import.meta.hot)+ import.meta.hot.dispose(() => {+ resize.disconnect()+ models.forEach((model) => model.dispose())+ renderer.dispose()+ })diff --git a/src/asset-lab/people.ts b/src/asset-lab/people.tsnew file mode 100644index 0000000..9f4369e--- /dev/null+++ b/src/asset-lab/people.ts@@ -0,0 +1,329 @@+import { carrierDress, cartLook, residentDress, serviceDress, homeVariant, type CartLook, type Load, type PersonDress } from "../art.ts"+import { goods, type GoodId } from "../content.ts"+import { Drawing, palette, type Vertex } from "./primitives.ts"+import { U } from "../iso.ts"++const R = 45.2548+export function drawPerson(d: Drawing, dress: PersonDress, load: Load, cart: CartLook | null, phase = 0) {+ const swing = phase === 0 ? 1 : -1+ // Complete rounded volumes preserve the simple original silhouette.+ d.line(+ [+ [-1 / 64, 1 / 64, 5],+ [swing * 0.03, 0, 0]+ ],+ 1+ )+ d.line(+ [+ [1 / 64, -1 / 64, 5],+ [-swing * 0.03, 0, 0]+ ],+ 1+ )+ if (dress.long) {+ const start = d.asset.faces.length,+ ring = (z: number, r: number) =>+ Array.from({ length: 24 }, (_, i): Vertex => [+ (Math.cos((i / 24) * Math.PI * 2) * r) / R,+ (Math.sin((i / 24) * Math.PI * 2) * r) / R,+ z+ ]),+ bottom = ring(3, 3.2),+ top = ring(10.5, 2.6)+ for (let i = 0; i < 24; i++) d.face([bottom[i]!, bottom[(i + 1) % 24]!, top[(i + 1) % 24]!, top[i]!], dress.coat, 0)+ d.face(top, dress.coat, 0)+ d.face([...bottom].reverse(), dress.coat, 0)+ d.volume(start, 1)+ } else d.ellipsoid(0, 0, 7.5, 2.5 / R, 2.5 / R, 3.27, dress.coat, 1)+ d.ellipsoid(0, 0, 13.5, 2.2 / R, 2.2 / R, 1.905, dress.skin, 1)+ if (cart) {+ for (const v of [-0.038, 0.038])+ d.line(+ [+ [0, v, 9.5],+ [0.11, v, 7]+ ],+ 1+ )+ } else {+ d.line(+ [+ [-0.028, 0.038, 9.5],+ [swing * 0.02 - 0.028, 0.06, 6]+ ],+ 1+ )+ d.line(+ [+ [0.028, -0.038, 9.5],+ [-swing * 0.02 + 0.028, -0.06, 6]+ ],+ 1+ )+ }+ const hat = dress.trim === 0xf7f8f4 ? dress.coat : dress.trim+ switch (dress.hat) {+ case "cap":+ d.ellipsoid(0, 0, 15.4, 2.4 / R, 2.4 / R, 1.65, hat, 0.75)+ d.face(+ [+ [0.015, -0.05, 15],+ [0.09, -0.05, 14.7],+ [0.09, 0.05, 14.7],+ [0.015, 0.05, 15]+ ],+ hat,+ 0.75+ )+ break+ case "brim":+ d.cylinder(0, 0, 3.6 / R, 14.9, 0.25, dress.trim, dress.trim, 0.75)+ d.cylinder(0, 0, 1.8 / R, 15.1, 3, dress.trim, dress.trim, 0.75)+ break+ case "top":+ d.cylinder(0, 0, 3 / R, 14.9, 0.25, palette.ink, palette.ink, 0.75)+ d.cylinder(0, 0, 1.7 / R, 15.1, 4.3, palette.ink, palette.ink, 0.75)+ d.cylinder(0, 0, 1.74 / R, 16, 0.8, dress.coat, dress.coat, 0)+ break+ case "bonnet":+ d.ellipsoid(-0.028, 0, 14.7, 2.7 / R, 2.8 / R, 2.4, dress.trim, 0.75)+ d.ellipsoid(0.035, 0, 13.7, 1.5 / R, 1.5 / R, 1.3, dress.skin, 0.6)+ break+ case "hood":+ d.ellipsoid(-0.028, 0, 14.2, 2.9 / R, 2.9 / R, 3.5, dress.coat, 0.75)+ d.ellipsoid(0.038, 0, 13.7, 1.5 / R, 1.5 / R, 1.3, dress.skin, 0.6)+ break+ }+ if (load.kind === "basket") {+ const u = -0.07,+ v = 0.07+ d.cylinder(u, v, 2.2 / R, 5, 3.5, 0xe3c592, 0xc9a46a, 1)+ const handle = Array.from({ length: 12 }, (_, i): Vertex => [+ u + (Math.cos((i / 11) * Math.PI) * 1.8) / 64,+ v - (Math.cos((i / 11) * Math.PI) * 1.8) / 64,+ 8.5 + Math.sin((i / 11) * Math.PI) * 2+ ])+ d.line(handle, 0.75)+ load.goods.slice(0, 3).forEach((good, i) => d.ellipsoid(u + (i - 1) * 0.02, v, 9, 0.02, 0.02, 0.65, goods[good].color, 0))+ } else if (load.kind === "bell") {+ const u = 0.075,+ v = -0.015+ d.line(+ [+ [0.04, -0.025, 9],+ [u, v, 7.5]+ ],+ 1+ )+ d.cylinder(u, v, 1.3 / R, 5, 0.25, 0xe3c25a, 0xe3c25a, 0.75)+ d.ellipsoid(u, v, 6, 1 / R, 1 / R, 1.2, 0xe3c25a, 0.75)+ d.line(+ [+ [u, v, 7],+ [u, v, 8]+ ],+ 0.75,+ 0x8a6a45+ )+ }+}++export function drawCargo(d: Drawing, good: GoodId, count: number, u: number, v: number, z: number) {+ const n = count >= 4 ? 3 : count >= 2 ? 2 : 1+ switch (good) {+ case "wood":+ for (const [level, row] of [[-0.9, 0, 0.9], [-0.45, 0.45], [0]].slice(0, n).entries())+ for (const c of row) d.log("u", v + c * U, u - 2.2 * U, u + 2.2 * U, z + level * 2, 1.15, 0xb08a5e, 0xe9d2a8)+ break+ case "wheat":+ case "cloth":+ case "wool": {+ const side = good === "wheat" ? 0xe9cf7c : good === "cloth" ? 0x8a58a8 : 0xf4f4ef,+ end = good === "wheat" ? 0xf3e3a8 : good === "cloth" ? 0xc7aed6 : 0xffffff+ for (const [level, row] of [[-0.75, 0.75], [0]].slice(0, Math.min(2, n)).entries())+ for (const c of row) d.log("u", v + c * U, u - 2 * U, u + 2 * U, z + level * 2.6, good === "wool" ? 1.9 : 1.5, side, end)+ if (n === 3 && good !== "wool") d.log("u", v, u - 1.4 * U, u + 1.4 * U, z + 5, 1.3, side, end)+ break+ }+ case "planks":+ for (let i = 0; i < n + 1; i++) d.box(u, v, 2.4 * U, 1.1 * U, z + i * 1.5, 1.5, 0xf0c59a, 0xe2a873, 0xd2945c, 1)+ break+ case "stone":+ case "ore": {+ const colors = good === "stone" ? [0xeeefe9, 0xdfe1da, 0xcbcfc7] : [0xe8ebf0, 0xd5dae3, 0xbcc3d0]+ for (const [a, c, dz] of [+ [-1, -0.5, 0],+ [1, 0.5, 0],+ [0, 0, 3]+ ].slice(0, n))+ d.box(u + a! * U, v + c! * U, 0.8 * U, 0.8 * U, z + dz!, 3, colors[0]!, colors[1]!, colors[2]!, 1)+ if (good === "ore") d.ellipsoid(u, v, z + (n === 3 ? 6 : 3), 0.022, 0.025, 0.8, 0x4a5368, 0)+ break+ }+ case "fish":+ case "bread":+ d.box(u, v, 1.6 * U, 1.1 * U, z, 3, 0xc9a46a, 0xe3c592, 0xd2b07a, 1)+ for (let i = 0; i < n + 1; i++) {+ const x = u + (i - n / 2) * 0.9 * U,+ y = v + (i % 2 === 0 ? -0.3 : 0.3) * U+ d.ellipsoid(x, y, z + 3.6, good === "fish" ? 0.049 : 0.04, 0.028, 0.75, good === "fish" ? 0x2f8c87 : 0xd98a6a, 0.75)+ if (good === "fish")+ d.face(+ [+ [x - 0.055, y - 0.03, z + 3.6],+ [x - 0.055, y + 0.03, z + 3.6],+ [x - 0.02, y, z + 3.6]+ ],+ 0x2f8c87,+ 0.75+ )+ }+ break+ case "flour":+ ;[-1, 1, 0].slice(0, n).forEach((a, i) => d.sack(u + a * U, v, z + (i === 2 ? 4 : 0)))+ break+ case "tools":+ d.crate(u, v, z, goods[good].color, 1.6 * U, 4)+ d.line(+ [+ [u, v, z + 4],+ [u + 0.04, v, z + 9]+ ],+ 1.5,+ 0x8a6a45+ )+ d.box(u + 0.03, v, 0.035, 0.018, z + 8, 1.6, 0x8f9891, 0x8f9891, 0x7c857d, 0.75)+ break+ }+}++export function drawCart(d: Drawing, look: CartLook, load: Load) {+ const u = 5.5 * U,+ v = 0,+ L = 2.4 * U,+ W = 1.6 * U,+ bed = 5,+ r = 2.6+ const wheel = (x: number, y: number) => {+ const n = 20,+ p = (angle: number, out = 0): Vertex => [x + ((Math.cos(angle) * r) / Math.sqrt(5)) * U, y + out, r + Math.sin(angle) * r]+ const ring = Array.from({ length: n }, (_, i) => p((i / n) * Math.PI * 2)),+ back = ring.map(([u, v, z]): Vertex => [u, v + 0.013, z])+ for (let i = 0; i < n; i++) d.face([ring[i]!, ring[(i + 1) % n]!, back[(i + 1) % n]!, back[i]!], palette.ink, 0)+ d.face(ring, look.spokes ? 0xf2efe6 : look.wood.right, 1)+ d.face(back, look.spokes ? 0xf2efe6 : look.wood.right, 1)+ if (look.spokes) for (const t of [0, Math.PI / 2]) d.line([p(t, -0.002), p(t + Math.PI, -0.002)], 0.75)+ d.ellipsoid(x, y - 0.006, r, 0.015, 0.015, 0.6, palette.ink, 0)+ }+ if (look.wheels === 2) {+ wheel(u, v - W - 0.4 * U)+ wheel(u, v + W + 0.4 * U)+ } else {+ wheel(u + L + 0.5 * U, v)+ for (const c of [-W * 0.6, W * 0.6])+ d.line(+ [+ [u - L + U, v + c, 0],+ [u - L + U, v + c, bed - 1]+ ],+ 1+ )+ }+ d.box(u, v, L, W, bed - 2, 2.5, look.wood.top, look.wood.left, look.wood.right, 1)+ for (const side of [-1, 1])+ d.line(+ [+ [0.06, side * 0.035, 7],+ [u - L, v + side * W * 0.7, 4]+ ],+ 1+ )+ if (load.kind === "cart" && load.count > 0) drawCargo(d, load.good, load.count, u, v, bed + 0.5)+}++export function makePerson(+ id: string,+ title: string,+ dress: PersonDress,+ load: Load = { kind: "none" },+ cart: CartLook | null = null,+ phase = 0+) {+ const d = new Drawing(id, title, "Full 3D figure with the original coat, skin, hat and accessories. No flat character sprites.")+ d.asset.category = cart ? "cargo" : "people"+ d.asset.reference = { type: "walker", dress, load, cart, phase }+ d.asset.footprint = 1+ drawPerson(d, dress, load, cart, phase)+ if (cart) drawCart(d, cart, load)+ return d.asset+}++export function personCatalogue() {+ const items = []+ for (const [i, hat] of ["cap", "brim", "none"].entries())+ items.push(makePerson(`worker-${hat}`, `Carrier · ${hat}`, { ...carrierDress(0.2 + i * 0.2), hat: hat as PersonDress["hat"] }))+ for (const [i, hat] of ["bonnet", "cap", "none"].entries())+ items.push(+ makePerson(`settler-${hat}`, `Settler · ${hat}`, {+ ...residentDress(homeVariant(i / 4 + 0.03).cloth, 1, 0.2 + i * 0.3),+ hat: hat as PersonDress["hat"]+ })+ )+ items.push(makePerson("settler-long", "Settler · long coat", residentDress(0xb5654a, 1, 0.95)))+ for (const [i, hat] of ["top", "brim"].entries())+ items.push(+ makePerson(`citizen-${hat}`, `Citizen · ${hat} hat`, {+ ...residentDress(homeVariant(i / 4 + 0.03).cloth, 2, 0.2 + i * 0.5),+ hat: hat as PersonDress["hat"]+ })+ )+ items.push(+ makePerson("market-walker", "Market walker", serviceDress(0x3d6db5, 0.3, false), { kind: "basket", goods: ["fish", "bread", "cloth"] })+ )+ items.push(makePerson("chapel-walker", "Chapel walker", serviceDress(0x3d6db5, 0.6, true), { kind: "bell" }))+ for (let i = 0; i < 16; i++) {+ const tier = i < 8 ? 1 : 2,+ n = (i * 0.37) % 1,+ roof = homeVariant((i % 8) / 8 + 0.03)+ items.push(+ makePerson(+ `resident-${tier}-${i % 8}`,+ `${tier === 1 ? "Settler" : "Citizen"} · household ${(i % 8) + 1}`,+ residentDress(roof.cloth, tier, n),+ { kind: "none" },+ null,+ i % 2+ )+ )+ }+ return items+}+export function makeCarrier(good: GoodId | null, barrow = false, count = 4) {+ const id = `${barrow ? "barrow" : "cart"}-${good ?? "empty"}${good ? `-${count}` : ""}`,+ look = cartLook(barrow ? 0.12 : 0.45)+ const load: Load = good ? { kind: "cart", good, count } : { kind: "none" }+ return makePerson(+ id,+ `${barrow ? "Barrow" : "Handcart"} · ${good ? `${goods[good].title}, ${count === 1 ? "small" : "full"} load` : "empty"}`,+ carrierDress(barrow ? 0.2 : 0.4),+ load,+ look+ )+}+export function makeGoods(good: GoodId) {+ const d = new Drawing(`goods-${good}`, goods[good].title, "Distinct cargo geometry, not a colour-swapped box.")+ d.asset.category = "cargo"+ d.asset.reference = { type: "cargo", good, count: 4 }+ d.asset.footprint = 1+ drawCargo(d, good, 4, 0, 0, 0)+ return d.asset+}+export function makeCrate(good: GoodId) {+ const d = new Drawing(`crate-${good}`, `${goods[good].title} crate`, "Cardboard crate with its original coloured label and strap.")+ d.asset.category = "cargo"+ d.asset.reference = { type: "crate", good }+ d.asset.footprint = 1+ d.crate(0, 0, 0, goods[good].color, 3 * U, 12)+ return d.asset+}diff --git a/src/asset-lab/primitives.ts b/src/asset-lab/primitives.tsnew file mode 100644index 0000000..f1a0964--- /dev/null+++ b/src/asset-lab/primitives.ts@@ -0,0 +1,362 @@+/** Portable geometry in grid cells and original pixel heights. */+import { U } from "../iso.ts"+import type { GoodId, KindId, Tier } from "../content.ts"+import type { CartLook, Load, PersonDress } from "../art.ts"++export type Vertex = readonly [u: number, v: number, height: number]+export interface Face {+ opacity?: number+ points: ReadonlyArray<Vertex>+ color: number+ contour?: number+ contourWidth?: number+}+export interface Stroke {+ points: ReadonlyArray<Vertex>+ width: number+ color: number+ opacity: number+}+export type AssetCategory = "buildings" | "homes" | "land" | "people" | "cargo" | "construction"+export type AssetReference =+ | { type: "building"; kind: KindId; build?: number }+ | { type: "house"; tier: Tier; variant: number; build?: number }+ | { type: "tree"; x: number; y: number; grown: number }+ | { type: "rock"; x: number; y: number; ore: boolean; amount: number }+ | { type: "field"; grown: number }+ | { type: "walker"; dress: PersonDress; load: Load; cart: CartLook | null; phase: number }+ | { type: "crate"; good: GoodId }+ | { type: "cargo"; good: GoodId; count: number }+ | { type: "site"; share: number }+ | { type: "plot"; look: "hover" | "picked" | "blocked" | "reach" }+ | { type: "roads" | "water" }+ | { type: "none" }+export interface InkAsset {+ category?: AssetCategory+ reference?: AssetReference+ footprint?: number+ id: string+ title: string+ note: string+ faces: Array<Face>+ strokes: Array<Stroke>+}++export const palette = { ink: 0x3d4943, plate: 0xf5f6f2, roof: 0xf7f8f4, left: 0xe9ebe5, right: 0xdde0d9, glass: 0xdbe6ea }+export const mix = (a: number, b: number, t: number) =>+ [16, 8, 0].reduce((out, s) => out | (Math.round(((a >> s) & 255) * (1 - t) + ((b >> s) & 255) * t) << s), 0)+export const pale = (c: number, t = 0.7) => mix(c, 0xffffff, t)+export const square = (u: number, v: number, a: number, z = 0): Array<Vertex> => [+ [u - a, v - a, z],+ [u + a, v - a, z],+ [u + a, v + a, z],+ [u - a, v + a, z]+]+export const sides = ["right", "left", "backRight", "backLeft"] as const+export type Side = (typeof sides)[number]++export class Drawing {+ readonly asset: InkAsset+ constructor(id: string, title: string, note: string) {+ this.asset = { id, title, note, faces: [], strokes: [] }+ }+ line(points: ReadonlyArray<Vertex>, width = 1, color = palette.ink, opacity = 1) {+ this.asset.strokes.push({ points, width, color, opacity })+ }+ face(points: ReadonlyArray<Vertex>, color: number, width = 1.5, edge = palette.ink, opacity = 1) {+ this.asset.faces.push({ points, color, opacity })+ if (width) this.line([...points, points[0]!], width, edge)+ }+ plate(size: number) {+ this.face(square(0, 0, (size * 8 - 1) * U, -0.15), palette.plate)+ }+ box(+ u: number,+ v: number,+ a: number,+ b: number,+ z: number,+ h: number,+ top = palette.roof,+ left = palette.left,+ right = palette.right,+ width = 1.5,+ edge = palette.ink+ ) {+ this.face(+ [+ [u - a, v + b, z],+ [u + a, v + b, z],+ [u + a, v + b, z + h],+ [u - a, v + b, z + h]+ ],+ left,+ width,+ edge+ )+ this.face(+ [+ [u + a, v - b, z],+ [u + a, v + b, z],+ [u + a, v + b, z + h],+ [u + a, v - b, z + h]+ ],+ right,+ width,+ edge+ )+ this.face(+ [+ [u - a, v - b, z],+ [u + a, v - b, z],+ [u + a, v - b, z + h],+ [u - a, v - b, z + h]+ ],+ right,+ width,+ edge+ )+ this.face(+ [+ [u - a, v - b, z],+ [u - a, v + b, z],+ [u - a, v + b, z + h],+ [u - a, v - b, z + h]+ ],+ left,+ width,+ edge+ )+ this.face(+ square(u, v, a, z + h).map(([x, y, H]) => [x, v + ((y - v) * b) / a, H]),+ top,+ width,+ edge+ )+ this.face(+ square(u, v, a, z).map(([x, y, H]) => [x, v + ((y - v) * b) / a, H]),+ left,+ 0+ )+ }+ wall(side: Side, a: number, along: number, z: number, out = 0.003): Vertex {+ switch (side) {+ case "right":+ return [a + out, along, z]+ case "left":+ return [along, a + out, z]+ case "backRight":+ return [-a - out, along, z]+ case "backLeft":+ return [along, -a - out, z]+ }+ }+ window(side: Side, a: number, along: number, z: number, height = 5, glass = palette.glass, sill = false) {+ const p = (s: number, h: number) => this.wall(side, a, s, h)+ this.face([p(along - U, z), p(along + U, z), p(along + U, z + height), p(along - U, z + height)], glass, 1)+ if (sill) this.line([p(along - 1.5 * U, z), p(along + 1.5 * U, z)])+ }+ door(side: Side, a: number, h: number, half: number, awning: number, depth: number, color: number, industrial = false, open = 0) {+ const p = (s: number, z: number, out = 0.004) => this.wall(side, a, s, z, out)+ this.face([p(-half, 0), p(half, 0), p(half, h), p(-half, h)], industrial ? 0xeef0ea : 0x8f9891, 1.5)+ const opening = Math.round(h * open * 0.75)+ if (industrial && opening > 0)+ this.face([p(-half, 0, 0.01), p(half, 0, 0.01), p(half, opening, 0.01), p(-half, opening, 0.01)], 0x68726c, 0)+ if (industrial) for (let z = h - 3; z > opening; z -= 3) this.line([p(-half, z, 0.008), p(half, z, 0.008)], 1, 0x9aa29b)+ this.face([p(-awning, h + 3), p(awning, h + 3), p(awning, h + 1, depth), p(-awning, h + 1, depth)], color)+ }+ gable(a: number, H: number, rise: number, ridge: "x" | "y", face: number, shade: number, chimney: boolean) {+ const t = ([u, v, z]: Vertex): Vertex => (ridge === "x" ? [u, v, z] : [v, u, z])+ const transform = (points: Array<Vertex>) => points.map(t)+ this.face(+ transform([+ [-a, -a, H],+ [a, -a, H],+ [a, 0, H + rise],+ [-a, 0, H + rise]+ ]),+ shade+ )+ this.face(+ transform([+ [-a, a, H],+ [a, a, H],+ [a, 0, H + rise],+ [-a, 0, H + rise]+ ]),+ face+ )+ for (const s of [-1, 1])+ this.face(+ transform([+ [s * a, -a, H],+ [s * a, a, H],+ [s * a, 0, H + rise]+ ]),+ ridge === "x" ? palette.right : palette.left+ )+ if (chimney) {+ const u = -a / 2,+ v = ridge === "x" ? -a / 2 : a / 2+ this.box(u, v, U, U, H + Math.round(rise / 2), rise - Math.round(rise / 2) + 4)+ }+ }+ pyramid(a: number, z: number, rise: number, face: number, shade: number) {+ const base = square(0, 0, a, z)+ for (let i = 0; i < 4; i++) this.face([base[i]!, base[(i + 1) % 4]!, [0, 0, z + rise]], i === 2 || i === 3 ? face : shade)+ }+ crate(u: number, v: number, z: number, label: number, s = 1.2 * U, h = 5) {+ this.box(u, v, s, s, z, h, 0xf4dcab, 0xe9c48a, 0xd5a86c, 1, 0x7d6140)+ this.face(+ [+ [u - s, v - 0.5 * U, z + h + 0.03],+ [u + s, v - 0.5 * U, z + h + 0.03],+ [u + s, v + 0.5 * U, z + h + 0.03],+ [u - s, v + 0.5 * U, z + h + 0.03]+ ],+ 0xc79a5b,+ 0+ )+ const lh = Math.max(2, Math.round(h * 0.4)),+ lz = z + Math.round((h - lh) / 2)+ for (const sign of [-1, 1])+ this.face(+ [+ [u - s + U, v + sign * (s + 0.003), lz],+ [u + s - U, v + sign * (s + 0.003), lz],+ [u + s - U, v + sign * (s + 0.003), lz + lh],+ [u - s + U, v + sign * (s + 0.003), lz + lh]+ ],+ label,+ 0+ )+ }+ circle(side: Side, a: number, z: number, r: number) {+ const ps = Array.from({ length: 32 }, (_, i) =>+ this.wall(side, a, ((Math.cos((i * Math.PI) / 16) * r) / Math.sqrt(5)) * U, z + Math.sin((i * Math.PI) / 16) * r, 0.006)+ )+ this.face(ps, 0xfaf8ee, 1)+ this.line([this.wall(side, a, 0, z, 0.012), this.wall(side, a, 0, z + 3.5, 0.012)])+ this.line([this.wall(side, a, 0, z, 0.012), this.wall(side, a, -2.5 / 32, z - 1.75, 0.012)])+ }+ volume(start: number, width = 1) {+ const id = Math.max(0, ...this.asset.faces.map((face) => face.contour ?? 0)) + 1+ for (const face of this.asset.faces.slice(start)) {+ face.contour = id+ face.contourWidth = width+ }+ }+ cylinder(u: number, v: number, r: number, z: number, h: number, side: number, top: number, width = 1, n = 20) {+ const start = this.asset.faces.length+ const ring = (height: number) =>+ Array.from({ length: n }, (_, i): Vertex => [+ u + Math.cos((i / n) * Math.PI * 2) * r,+ v + Math.sin((i / n) * Math.PI * 2) * r,+ height+ ])+ const bottom = ring(z),+ upper = ring(z + h)+ for (let i = 0; i < n; i++) this.face([bottom[i]!, bottom[(i + 1) % n]!, upper[(i + 1) % n]!, upper[i]!], side, 0)+ this.face(upper, top, 0)+ this.face([...bottom].reverse(), side, 0)+ this.volume(start, width)+ this.line([...upper, upper[0]!], width)+ if (h > 1) this.line([...bottom, bottom[0]!], width)+ }+ ellipsoid(u: number, v: number, z: number, ru: number, rv: number, rz: number, color: number, width = 1, light?: number, segments = 16) {+ const start = this.asset.faces.length,+ n = segments,+ lat = segments / 2+ const point = (j: number, i: number): Vertex => {+ const phi = -Math.PI / 2 + (j / lat) * Math.PI,+ theta = (i / n) * Math.PI * 2+ return [u + Math.cos(phi) * Math.cos(theta) * ru, v + Math.cos(phi) * Math.sin(theta) * rv, z + Math.sin(phi) * rz]+ }+ for (let j = 0; j < lat; j++)+ for (let i = 0; i < n; i++) {+ const points =+ j === 0+ ? [point(j, i), point(j + 1, i + 1), point(j + 1, i)]+ : j === lat - 1+ ? [point(j, i), point(j, i + 1), point(j + 1, i)]+ : [point(j, i), point(j, i + 1), point(j + 1, i + 1), point(j + 1, i)]+ let fill = color+ if (light !== undefined) {+ const center = points+ .reduce((sum, p) => [sum[0] + p[0], sum[1] + p[1], sum[2] + p[2]] as Vertex, [0, 0, 0] as Vertex)+ .map((n) => n / points.length) as unknown as Vertex+ const sx = (center[0] - u - center[1] + v) * 32,+ sy = (center[0] - u + center[1] - v) * 16 - (center[2] - z),+ rx = Math.hypot(ru, rv) * 32,+ ry = Math.hypot((ru + rv) * 8, rz)+ if (((sx + rx * 0.22) / (rx * 0.7)) ** 2 + ((sy + ry * 0.24) / (ry * 0.68)) ** 2 < 1) fill = light+ }+ this.face(points, fill, 0)+ }+ if (width) this.volume(start, width)+ }+ log(axis: "u" | "v", across: number, from: number, to: number, z: number, r: number, side: number, end: number) {+ const start = this.asset.faces.length,+ n = 16+ const ring = (along: number) =>+ Array.from({ length: n }, (_, i): Vertex => {+ const t = (i / n) * Math.PI * 2,+ s = ((Math.cos(t) * r) / Math.sqrt(5)) * U,+ h = z + r + Math.sin(t) * r+ return axis === "u" ? [along, across + s, h] : [across + s, along, h]+ })+ const a = ring(from),+ b = ring(to)+ for (let i = 0; i < n; i++) this.face([a[i]!, a[(i + 1) % n]!, b[(i + 1) % n]!, b[i]!], side, 0)+ this.face([...a].reverse(), end, 0)+ this.face(b, end, 0)+ this.volume(start, 1)+ this.line([...a, a[0]!])+ this.line([...b, b[0]!])+ const small = ring(to + 0.002).map(([u, v, h]): Vertex =>+ axis === "u"+ ? [u, across + (v - across) * 0.35, z + r + (h - z - r) * 0.35]+ : [across + (u - across) * 0.35, v, z + r + (h - z - r) * 0.35]+ )+ this.line([...small, small[0]!], 1, palette.ink, 0.45)+ }+ sack(u: number, v: number, z = 0, color = 0xf2ecdc) {+ this.ellipsoid(u, v, z + 3.5, 3 / 45.2548, 3 / 45.2548, 3.15, color, 1)+ this.line(+ [+ [u - 0.03, v + 0.055, z + 5.5],+ [u + 0.03, v + 0.055, z + 5.5]+ ],+ 1,+ palette.ink,+ 0.6+ )+ }+ fir(u: number, v: number, z = 0, size = 1, tiers = 2) {+ const step = (24 * size) / (tiers + 1)+ this.line(+ [+ [u, v, z],+ [u, v, z + 6 * size]+ ],+ 1.5,+ 0x6b5a45+ )+ for (let i = 0; i < tiers; i++) {+ const start = this.asset.faces.length,+ w = (8 * size * (1 - i * 0.22)) / 64,+ base = z + 4 * size + i * step,+ lift = w * 32 - 1.5 * size+ const ring: Array<Vertex> = [+ [u - w, v - w, base - lift],+ [u + w, v - w, base],+ [u + w, v + w, base + lift],+ [u - w, v + w, base]+ ]+ for (let j = 0; j < 4; j++) this.face([ring[j]!, ring[(j + 1) % 4]!, [u, v, base + step * 2]], j >= 2 ? 0xd9e5d7 : 0xb3c7b4, 0)+ this.face(ring, 0xb3c7b4, 0)+ this.volume(start, 1.5)+ this.line([...ring, ring[0]!], 1.5)+ }+ }+}diff --git a/src/asset-lab/renderer.ts b/src/asset-lab/renderer.tsnew file mode 100644index 0000000..beb01d6--- /dev/null+++ b/src/asset-lab/renderer.ts@@ -0,0 +1,367 @@+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"++/** 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()+ return new THREE.Mesh(geometry, fillMaterial(color, opacity))+}++export interface BuiltAsset {+ group: THREE.Group+ lineMaterials: Array<{ material: LineMaterial; width: number }>+ updateContours: (camera: THREE.Camera) => void+ dispose: () => void+}+export function buildAsset(asset: InkAsset, options: { batchFaces?: boolean; meshInk?: boolean; hullContours?: boolean; meshContours?: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())+ group.add(new THREE.Mesh(geometry, fillMaterial(color, opacity)))+ }+ } 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 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 dispose = () => {+ group.traverse((object) => {+ if (object instanceof THREE.Mesh) object.geometry.dispose()+ })+ for (const { material } of lineMaterials) material.dispose()+ curveMaterials.forEach((material) => material.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, 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+ 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+ 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/asset-lab/style.css b/src/asset-lab/style.cssnew file mode 100644index 0000000..efde7aa--- /dev/null+++ b/src/asset-lab/style.css@@ -0,0 +1,354 @@+@import url("https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=DM+Mono:wght@400;500&display=swap");+:root {+ font-family: "DM Sans", sans-serif;+ color: #3d4943;+ background: #f0f2ec;+ font-synthesis: none;+ font-smooth: always;+}+* {+ box-sizing: border-box;+}+body {+ margin: 0;+}+button,+input {+ font: inherit;+}+button {+ cursor: pointer;+ color: inherit;+}+#lab {+ max-width: 1320px;+ margin: auto;+ padding: 28px 48px;+}+header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding-bottom: 22px;+ border-bottom: 1px solid #cbd1c6;+}+header a {+ font-size: 18px;+ font-weight: 700;+ color: inherit;+ text-decoration: none;+}+header span,+.tag,+.view-label,+.view-foot,+footer {+ font-family: "DM Mono", monospace;+ font-size: 10px;+ color: #748073;+}+header span {+ letter-spacing: 0.13em;+}+.intro {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin: 28px 0 30px;+ gap: 20px;+}+h1 {+ font-weight: 500;+ font-size: 43px;+ line-height: 1.06;+ letter-spacing: -0.045em;+ margin: 0 0 13px;+}+.intro p {+ font-size: 14px;+ margin: 0;+ color: #748073;+}+.tag {+ border: 1px solid #cbd1c6;+ border-radius: 30px;+ padding: 10px 14px;+ white-space: nowrap;+}+.assets {+ display: flex;+ overflow-x: auto;+ gap: 8px;+ margin: 0 0 18px;+}+.assets button {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: flex-end;+ gap: 8px;+ min-width: 108px;+ min-height: 104px;+ border: 1px solid #d6dbd1;+ background: #f7f8f3;+ border-radius: 5px;+ padding: 12px 6px;+ font-family: "DM Mono", monospace;+ font-size: 10px;+}+.assets img {+ width: 74px;+ height: 56px;+ object-fit: contain;+}+.assets button[hidden] {+ display: none;+}+.filters {+ display: flex;+ gap: 20px;+ align-items: center;+ margin-bottom: 14px;+ flex-wrap: wrap;+ font-size: 12px;+}+.filters label {+ display: flex;+ align-items: center;+ gap: 8px;+}+.filters select,+.filters input {+ padding: 8px;+ border: 1px solid #cbd1c6;+ background: #f7f8f3;+ color: inherit;+ border-radius: 4px;+ max-width: 200px;+}+.filters a {+ color: #657360;+ margin-left: auto;+}+.assets button.active {+ border-color: #3d4943;+ background: #e3e8dd;+ box-shadow: inset 0 -2px #3d4943;+}+.assets button:hover {+ border-color: #98a18f;+}+.comparison {+ display: grid;+ grid-template-columns: 1fr 1fr;+ border: 1px solid #cbd1c6;+ border-radius: 6px;+ overflow: hidden;+ background: #f0f2ec;+}+.view {+ position: relative;+ height: 420px;+ min-width: 0;+}+.view:first-child {+ border-right: 1px solid #cbd1c6;+}+.view-label {+ position: absolute;+ top: 19px;+ left: 20px;+ right: 20px;+ display: flex;+ justify-content: space-between;+ gap: 10px;+ z-index: 1;+ pointer-events: none;+}+.view-label span:first-child {+ color: #3d4943;+}+.view-foot {+ position: absolute;+ bottom: 18px;+ left: 20px;+ pointer-events: none;+}+.view > canvas,+#viewer {+ width: 100%;+ height: 100%;+ display: block;+}+#viewer {+ touch-action: none;+ cursor: grab;+}+#viewer:active {+ cursor: grabbing;+}+#viewer canvas {+ display: block;+ width: 100%;+ height: 100%;+}+.controls {+ display: flex;+ gap: 22px;+ align-items: center;+ padding: 18px 0 22px;+ border-bottom: 1px solid #cbd1c6;+}+.controls button,+.downloads button {+ background: transparent;+ border: 1px solid #cbd1c6;+ border-radius: 4px;+ padding: 9px 12px;+ font-size: 11px;+ font-family: "DM Mono", monospace;+}+.controls button:hover,+.downloads button:hover {+ background: #e3e8dd;+ border-color: #748073;+}+.controls label {+ display: flex;+ align-items: center;+ gap: 10px;+ flex: 1;+ font-family: "DM Mono", monospace;+ font-size: 11px;+}+.controls input {+ width: 100%;+ min-width: 40px;+ accent-color: #5c7154;+}+.controls output {+ min-width: 31px;+ color: #748073;+}+.caption {+ display: flex;+ justify-content: space-between;+ gap: 28px;+ padding: 22px 0 30px;+}+.caption h2 {+ font-size: 19px;+ font-weight: 600;+ margin: 0 0 8px;+}+.caption p {+ font-size: 13px;+ line-height: 1.6;+ color: #748073;+ margin: 0;+ max-width: 600px;+}+.downloads {+ display: flex;+ gap: 8px;+ align-items: flex-start;+ white-space: nowrap;+}+footer {+ display: flex;+ justify-content: space-between;+ gap: 24px;+ line-height: 1.6;+ border-top: 1px solid #cbd1c6;+ padding-top: 18px;+}+@media (max-width: 850px) {+ #lab {+ padding: 22px;+ }+ .tag {+ display: none;+ }+ .assets {+ gap: 4px;+ }+ .assets button {+ font-size: 9px;+ }+ .assets img {+ width: 55px;+ }+ .controls {+ flex-wrap: wrap;+ gap: 12px;+ }+ .controls label {+ min-width: 180px;+ }+ .caption {+ flex-direction: column;+ gap: 16px;+ }+ footer {+ flex-direction: column;+ gap: 8px;+ }+ .view {+ height: 350px;+ }+ .view-label {+ flex-direction: column;+ gap: 5px;+ }+}+@media (max-width: 500px) {+ #lab {+ padding: 16px;+ }+ h1 {+ font-size: 36px;+ }+ .intro {+ margin: 24px 0;+ }+ .assets {+ display: flex;+ overflow-x: auto;+ padding-bottom: 5px;+ }+ .assets button {+ min-width: 87px;+ }+ .comparison {+ grid-template-columns: 1fr;+ }+ .view {+ height: 300px;+ }+ .view:first-child {+ border-right: 0;+ border-bottom: 1px solid #cbd1c6;+ }+ .view-label {+ flex-direction: row;+ left: 14px;+ right: 14px;+ font-size: 9px;+ }+ .view-foot {+ left: 14px;+ font-size: 9px;+ }+ .controls label {+ flex-basis: 100%;+ }+ .controls button {+ order: 2;+ }+ .downloads {+ flex-wrap: wrap;+ }+ header span {+ font-size: 9px;+ }+}diff --git a/src/factory.css b/src/factory.cssindex 95e1248..6ff70be 100644--- a/src/factory.css+++ b/src/factory.css@@ -2,6 +2,12 @@ html, body { margin: 0; height: 100%; overflow: hidden; background: #f0f2ec; toubody { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace; color: #3d4943; -webkit-user-select: none; user-select: none; }#app { position: fixed; inset: 0; }#app canvas { display: block; }+#app .world-canvas { width:100%; height:100%; touch-action:none; outline:none; }+.camera-controls { position:fixed;left:16px;bottom:calc(74px + env(safe-area-inset-bottom));display:flex;align-items:center;gap:3px;padding:5px;background:#f7f8f4;border:1px solid #c9cec4;border-radius:8px;box-shadow:0 2px 0 #dfe2db;z-index:2; }+.camera-controls button { font:inherit;font-size:12px;color:#3d4943;border:1px solid transparent;background:transparent;border-radius:5px;padding:6px 9px;cursor:pointer;min-height:32px; }+.camera-controls button:hover {background:#eceee8}+.camera-controls button[aria-pressed=true] {background:#3d4943;color:#f7f8f4}+.camera-controls output {font-size:11px;color:#77817a;min-width:33px;text-align:center}.icon { display: block; flex: none; }.glyph { display: inline-flex; align-items: center; justify-content: center; flex: none; }@@ -246,3 +252,19 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;background: #3d4943; color: #f7f8f4; border: 0; border-radius: 4px; cursor: pointer; box-shadow: 0 2px 0 #c9cec4;}.result.show { display: block; }++@media(max-width:760px){+ .hud.left {left:10px;right:10px;max-width:none}+ .hud.right,.panel-open .hud.right {top:64px;left:10px;right:10px;max-width:none;align-items:flex-start}+ .hud .card .cell {padding:7px 9px}+ .hud.left .stock {margin-top:48px;max-width:100%;overflow-x:auto;flex:none}+ .hud .stock .group {flex:none}+ .hud.right .card {max-width:100%;overflow-x:auto}+ .toolbar {left:10px;right:10px;bottom:calc(64px + env(safe-area-inset-bottom))}+ .toolbar .group,.toolbar .town-button {flex:none}+ .system,.panel-open .system {right:10px;bottom:calc(12px + env(safe-area-inset-bottom))}+ .camera-controls {left:10px;max-width:calc(100vw - 20px);bottom:calc(118px + env(safe-area-inset-bottom))}+ .camera-controls button {padding:6px 7px;min-height:34px}+ .panel {width:calc(100vw - 24px);max-width:360px}+ .toast {bottom:calc(165px + env(safe-area-inset-bottom));max-width:calc(100vw - 28px)}+}diff --git a/src/host.ts b/src/host.tsindex 99c55dc..f1a337f 100644--- a/src/host.ts+++ b/src/host.ts@@ -1,22 +1,45 @@/**- * The page around the town: the Pixi stage and its layers, the camera (drag- * to pan, wheel or pinch to zoom), the pointer turned into gestures, and the+ * The page around the town: the 3D scene, camera and pointer gestures, and the* top bar, toolbar, build menu, panel, tooltip, and toasts; the dialog a new* town is founded from, and the reckoning at the end of its term.*/-import { Application, Container, Graphics } from "pixi.js"+import { Application, Graphics } from "pixi.js"-import { drawBuilding, drawHouse, homeVariant, plate, plateHalf, seaFill, type Stage } from "./art.ts"+import { drawBuilding, drawHouse, homeVariant, plate, plateHalf } from "./art.ts"import {- categoryColor, categoryOrder, costText, defaultCharter, goodIds, goods, home, kindOrder, kinds, landIds, lands, mood as moodRules, needTitle,- RESERVES, ROAD_COST, sizeIds, sizes, TAX_STEPS, TERMS, type Category, type CharterValue, type GoodId, type Kind, type KindId+ categoryColor,+ categoryOrder,+ costText,+ defaultCharter,+ goodIds,+ goods,+ home,+ kindOrder,+ kinds,+ landIds,+ lands,+ mood as moodRules,+ needTitle,+ RESERVES,+ ROAD_COST,+ sizeIds,+ sizes,+ TAX_STEPS,+ TERMS,+ type Category,+ type CharterValue,+ type GoodId,+ type Kind,+ type KindId} from "./content.ts"-import { GRID, toScreen, type Point } from "./iso.ts"+import { GRID } from "./iso.ts"import { goodIcon, icon, iconEl, type IconName } from "./icons.ts"import { generate } from "./mapgen.ts"import { askOf, priceOf } from "./sim/index.ts"import type { Stats, Tool, TradeMode, UiValue } from "./ui.ts"import { emptyPreview } from "./ui.ts"+import { GameScene } from "./render3d/scene.ts"+import { MapInput } from "./render3d/input.ts"const el = <K extends keyof HTMLElementTagNameMap>(tag: K, className: string, text = "") => {const node = document.createElement(tag)@@ -37,58 +60,10 @@ export interface Persistence {export const createHost = async (mount: HTMLElement, persistence: () => Persistence) => {const app = new Application()- await app.init({- resizeTo: window,- antialias: true,- background: seaFill,- resolution: Math.min(window.devicePixelRatio || 1, 2),- autoDensity: true- })- mount.appendChild(app.canvas)-- // ── Layers ──- const world = new Container()- const floor = new Graphics()- const ground = new Graphics()- const plates = new Container()- const roads = new Graphics()- const preview = new Container()- const overlay = new Graphics()- preview.addChild(overlay)- const objects = new Container({ sortableChildren: true })- const ghost = new Graphics()- ghost.zIndex = 1e6- objects.addChild(ghost)- const labels = new Container()- world.addChild(floor, ground, plates, roads, preview, objects, labels)- app.stage.addChild(world)- const stage: Stage = { world, floor, ground, plates, roads, preview, objects, labels, overlay, ghost }-- // ── Camera ──- const centre = toScreen(GRID / 2, GRID / 2)- // Zoom steps at which a unit (2 × 1 px at 1×) is still a whole number of- // device pixels on a 2× screen, so the drawing stays on its lattice.- const zooms = [0.5, 1, 1.5, 2] as const- let zoom: number = window.innerWidth >= 1200 && window.innerHeight >= 800 ? 1 : 0.5- const look = { x: centre.x, y: centre.y }- const placeCamera = () => {- world.scale.set(zoom)- const dpr = app.renderer.resolution- world.position.set(- Math.round((app.screen.width / 2 - look.x * zoom) * dpr) / dpr,- Math.round((app.screen.height / 2 - look.y * zoom) * dpr) / dpr- )- }- placeCamera()- app.renderer.on("resize", placeCamera)- const toWorld = (sx: number, sy: number): Point => ({ x: (sx - world.position.x) / zoom, y: (sy - world.position.y) / zoom })- const zoomTo = (sx: number, sy: number, next: number) => {- const before = toWorld(sx, sy)- zoom = Math.min(2, Math.max(0.5, next))- look.x = before.x - (sx - app.screen.width / 2) / zoom- look.y = before.y - (sy - app.screen.height / 2) / zoom- placeCamera()- }+ // Pixi remains an offscreen thumbnail renderer for the unchanged menus.+ await app.init({ width: 64, height: 64, antialias: true, resolution: 2, autoStart: false, backgroundAlpha: 0 })+ app.stop()+ const stage = new GameScene(mount)// ── DOM ──// Top left: the term's clock and the treasury, the goods in stock below, then the crown's request and any alarm.@@ -99,7 +74,11 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst coins = el("div", "cell coins")bar.append(clock, coins)const stock = el("div", "card stock")- const groups: ReadonlyArray<ReadonlyArray<GoodId>> = [["wood", "planks", "stone", "tools"], ["fish", "bread"], ["wool", "cloth"]]+ const groups: ReadonlyArray<ReadonlyArray<GoodId>> = [+ ["wood", "planks", "stone", "tools"],+ ["fish", "bread"],+ ["wool", "cloth"]+ ]const goodCells = new Map<GoodId, HTMLElement>()for (const group of groups) {const cell = el("div", "group")@@ -174,8 +153,20 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste}}- const tools: ReadonlyArray<{ readonly tool: Tool | "build"; readonly label: string; readonly key: string; readonly icon: IconName; readonly tip: string }> = [- { tool: "select", label: "select", key: "S", icon: "select", tip: "Click a building or home to see what it does · drag to pan · wheel to zoom" },+ const tools: ReadonlyArray<{+ readonly tool: Tool | "build"+ readonly label: string+ readonly key: string+ readonly icon: IconName+ readonly tip: string+ }> = [+ {+ tool: "select",+ label: "select",+ key: "S",+ icon: "select",+ tip: "Click a building or home to see what it does · drag to pan · wheel to zoom"+ },{ tool: "road", label: "road", key: "R", icon: "road", tip: `Drag to lay a road · ${ROAD_COST} coins a cell` },{ tool: "home", label: "homes", key: "H", icon: "homes", tip: `Drag to lay a row of homes along a road · ${costText(home.cost)} each` },{ tool: "build", label: "build", key: "B", icon: "build", tip: "Choose a building, then click to place it · Esc to stop" },@@ -227,11 +218,19 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistebutton.onclick = runsystem.append(button)}- action("save", "save", "Save the town in this browser (it also autosaves every two minutes)", () => ui.toast(persistence().save() ?? "Saved"))+ action("save", "save", "Save the town in this browser (it also autosaves every two minutes)", () =>+ ui.toast(persistence().save() ?? "Saved")+ )action("load", "load", "Load the latest save: yours or the autosave, whichever is newer", () =>- confirmLeave("load the latest save?", "The town as it is now is replaced by the latest save (yours or the autosave).", "Load", () => ui.toast(persistence().load() ?? "Loaded")))+ confirmLeave("load the latest save?", "The town as it is now is replaced by the latest save (yours or the autosave).", "Load", () =>+ ui.toast(persistence().load() ?? "Loaded")+ )+ )action("newTown", "new town", "Found a new town on new land", () =>- confirmLeave("found a new town?", "This town is left behind for good unless it is saved first.", "Choose new land", () => openCharter(true)))+ confirmLeave("found a new town?", "This town is left behind for good unless it is saved first.", "Choose new land", () =>+ openCharter(true)+ )+ )/** Asks before something that replaces the town: save first, go ahead, or stay. */const confirmLeave = (title: string, text: string, go: string, run: () => void) => {@@ -294,6 +293,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistechoose("select")window.addEventListener("keydown", (event) => {+ if (event.target instanceof HTMLElement && event.target.closest("input,select,textarea,[contenteditable=true]")) return+ if (event.key === " " && event.target instanceof HTMLButtonElement) returnif (confirmBox.classList.contains("open") && event.key === "Escape") confirmBox.querySelector<HTMLButtonElement>(".primary")?.click()if (ui.founding || reckoning.classList.contains("open") || confirmBox.classList.contains("open")) returnif (event.key === " ") {@@ -343,7 +344,9 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst lo = Math.min(...values)const hi = Math.max(...values)const span = hi - lo || 1- const points = values.map((v, i) => `${((i / (values.length - 1)) * w).toFixed(1)},${(h - 2 - ((v - lo) / span) * (h - 4)).toFixed(1)}`).join(" ")+ const points = values+ .map((v, i) => `${((i / (values.length - 1)) * w).toFixed(1)},${(h - 2 - ((v - lo) / span) * (h - 4)).toFixed(1)}`)+ .join(" ")return `<svg viewBox="0 0 ${w} ${h}" preserveAspectRatio="none"><polyline points="${points}" fill="none" stroke="#3d4943" stroke-width="1.5" vector-effect="non-scaling-stroke"/></svg>`}@@ -447,7 +450,13 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistereturn { box, refresh }}- const categoryIcon: Readonly<Record<Category, IconName>> = { storage: "jobs", gathering: "wood", crafts: "tools", food: "bread", services: "faith" }+ const categoryIcon: Readonly<Record<Category, IconName>> = {+ storage: "jobs",+ gathering: "wood",+ crafts: "tools",+ food: "bread",+ services: "faith"+ }const buildMenu = () => {panel.append(header("build", iconEl("build", 30), el("p", "sub", "Pick one, then click the map · Esc to stop")))@@ -507,7 +516,11 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst goalNote = el("p", "empty")panel.append(goals)- const mood = section("approval", "approval", `Homes hold more residents when approval is high and fewer when it is low. At −50 for two minutes, the town turns the mayor out.`)+ const mood = section(+ "approval",+ "approval",+ `Homes hold more residents when approval is high and fewer when it is low. At −50 for two minutes, the town turns the mayor out.`+ )const moodLine = el("div", "row")const moodValue = el("span", "count total")moodLine.append(el("span", "label", "now → heading for"), moodValue)@@ -518,7 +531,11 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistemood.append(moodLine, moodTrack, moodParts)panel.append(mood)- const treasury = section("treasury", "treasury", "Coins a minute. Administration grows faster than the town. Three minutes in debt and the town is bankrupt.")+ const treasury = section(+ "treasury",+ "treasury",+ "Coins a minute. Administration grows faster than the town. Three minutes in debt and the town is bankrupt."+ )const taxes = row(treasury, "taxes", "taxes")const traded = row(treasury, "trade", "trade")const upkeep = row(treasury, "upkeep", "upkeep")@@ -529,7 +546,11 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistetreasury.append(coinLine)panel.append(treasury)- const levers = section("tax rates", "taxes", "Lower taxes raise approval, higher ones lower it, weighed by how many of each tier there are.")+ const levers = section(+ "tax rates",+ "taxes",+ "Lower taxes raise approval, higher ones lower it, weighed by how many of each tier there are."+ )for (const tier of ["settlers", "citizens"] as const) {const line = el("div", "row lever")const minus = el("button", "frame step", "−")@@ -570,8 +591,17 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistetown.append(peopleLine)panel.append(town)- const needs = section("homes supplied", "homes", "Settlers need food (fish or bread) from a market; citizens need bread, cloth, and faith.")- const needIcons: Readonly<Record<"food" | "bread" | "cloth" | "faith", IconName>> = { food: "fish", bread: "bread", cloth: "cloth", faith: "faith" }+ const needs = section(+ "homes supplied",+ "homes",+ "Settlers need food (fish or bread) from a market; citizens need bread, cloth, and faith."+ )+ const needIcons: Readonly<Record<"food" | "bread" | "cloth" | "faith", IconName>> = {+ food: "fish",+ bread: "bread",+ cloth: "cloth",+ faith: "faith"+ }const bars = (["food", "bread", "cloth", "faith"] as const).map((n) => {const line = el("div", "need")const label = el("span", "label")@@ -588,13 +618,21 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst larderLine = row(needs, "food in store", "flour")panel.append(needs)- const crown = section("the crown", "crown", `Sending what the crown asks for earns coins. A missed request is a fine, and the town remembers the snub for a while; too many missed in a row and the crown dismisses the mayor.`)+ const crown = section(+ "the crown",+ "crown",+ `Sending what the crown asks for earns coins. A missed request is a fine, and the town remembers the snub for a while; too many missed in a row and the crown dismisses the mayor.`+ )const crownLine = row(crown, "requests met · missed", "goal")const crownNext = el("p", "empty")crown.append(crownNext)panel.append(crown)- const store = section("goods and trade", "trade", "Traders buy what the town sells beyond what it keeps, and sell it what it buys up to that, at half again the price. Prices fall as the town sells and rise as it buys. Click sell / buy / — to change a good.")+ const store = section(+ "goods and trade",+ "trade",+ "Traders buy what the town sells beyond what it keeps, and sell it what it buys up to that, at half again the price. Prices fall as the town sells and rise as it buys. Click sell / buy / — to change a good."+ )const reserveLine = el("div", "row lever")const reserveControls = el("span", "controls")const fewer = el("button", "frame step", "−")@@ -667,8 +705,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => PersistegoalNote.textContent = s.fate.governing? "Complete: the mayor governs on to the end of the term.": s.fate.complete !== null- ? `All met: hold them ${clockText(s.fate.complete)} more.`- : ""+ ? `All met: hold them ${clockText(s.fate.complete)} more.`+ : ""goalNote.style.display = goalNote.textContent ? "" : "none"// Approval.moodValue.textContent = `${signed(s.mood.approval)} → ${signed(s.mood.target)}`@@ -676,7 +714,12 @@ export const createHost = async (mount: HTMLElement, persistence: () => PersistemoodFill.style.left = `${Math.min(50, 50 + s.mood.approval / 2)}%`moodFill.style.width = `${Math.abs(s.mood.approval) / 2}%`moodFill.classList.toggle("low", s.mood.approval < 0)- const parts = s.mood.parts.map((p) => `<div class="row"><span class="label">${p.label}</span><span class="count ${p.value > 0 ? "up" : p.value < 0 ? "down" : ""}">${signed(p.value)}</span></div>`).join("")+ const parts = s.mood.parts+ .map(+ (p) =>+ `<div class="row"><span class="label">${p.label}</span><span class="count ${p.value > 0 ? "up" : p.value < 0 ? "down" : ""}">${signed(p.value)}</span></div>`+ )+ .join("")if (moodParts.dataset.html !== parts) {moodParts.dataset.html = partsmoodParts.innerHTML = parts@@ -724,7 +767,11 @@ export const createHost = async (mount: HTMLElement, persistence: () => PersistepeopleLine.dataset.svg = peopleSvgpeopleLine.innerHTML = peopleSvg}- const recent = s.chronicle.slice(-10).reverse().map((l) => `<p><b>${clockText(Math.round(l.tick / 60))}</b> ${l.text}</p>`).join("")+ const recent = s.chronicle+ .slice(-10)+ .reverse()+ .map((l) => `<p><b>${clockText(Math.round(l.tick / 60))}</b> ${l.text}</p>`)+ .join("")if (lines.dataset.html !== recent) {lines.dataset.html = recentlines.innerHTML = recent@@ -757,7 +804,15 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst title = p.type === "building" ? kinds[p.kind].title.toLowerCase() : `${home.tiers[p.tier].title}' home`const status = el("span", "pill")- const about = el("p", "sub", p.type === "building" ? kinds[p.kind].blurb : p.tier === 1 ? "settlers: fish or bread from a market keeps them" : "citizens: they need bread, cloth, and faith")+ const about = el(+ "p",+ "sub",+ p.type === "building"+ ? kinds[p.kind].blurb+ : p.tier === 1+ ? "settlers: fish or bread from a market keeps them"+ : "citizens: they need bread, cloth, and faith"+ )const below = el("div", "")below.append(status, about)panel.append(header(title, picture(p.type === "building" ? p.kind : p.tier), below))@@ -815,7 +870,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste/** Rebuilds the panel when what it shows changes, and refreshes its numbers every frame. */const syncPanel = () => {const p = ui.panel- const next = p === null ? "" : p.type === "build" || p.type === "town" ? p.type : `${p.type}|${p.id}|${p.type === "house" ? p.tier : ""}`+ const next =+ p === null ? "" : p.type === "build" || p.type === "town" ? p.type : `${p.type}|${p.id}|${p.type === "house" ? p.tier : ""}`if (next !== shape) {shape = next// Keep the old contents while the closed panel slides away.@@ -844,7 +900,15 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistefor (let x = 0; x < GRID; x++) {const k = y * GRID + xif (land.mask[k] !== "1") continue- g.fillStyle = water.has(k) ? "#b9cfcb" : trees.has(k) ? "#9bb08a" : rocks.has(k) ? (rocks.get(k) ? "#5a6479" : "#8f9891") : "#f7f8f4"+ g.fillStyle = water.has(k)+ ? "#b9cfcb"+ : trees.has(k)+ ? "#9bb08a"+ : rocks.has(k)+ ? rocks.get(k)+ ? "#5a6479"+ : "#8f9891"+ : "#f7f8f4"g.fillRect(x * scale, y * scale, scale, scale)}}@@ -854,7 +918,14 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteui.founding = truedialog.replaceChildren()const card = el("div", "sheet")- card.append(el("h2", "", "found a town"), el("p", "sub", "Choose the land and how long the term runs. Grow the town until it is complete, or keep it from bankruptcy, revolt, and ruin until the term is out."))+ card.append(+ el("h2", "", "found a town"),+ el(+ "p",+ "sub",+ "Choose the land and how long the term runs. Grow the town until it is complete, or keep it from bankruptcy, revolt, and ruin until the term is out."+ )+ )const body = el("div", "charter")const options = el("div", "")const preview = el("div", "preview")@@ -862,7 +933,14 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst facts = el("p", "sub")preview.append(map, facts)body.append(options, preview)- const group = <T extends string | number>(title: string, values: ReadonlyArray<T>, label: (v: T) => string, blurb: (v: T) => string, get: () => T, set: (v: T) => void) => {+ const group = <T extends string | number>(+ title: string,+ values: ReadonlyArray<T>,+ label: (v: T) => string,+ blurb: (v: T) => string,+ get: () => T,+ set: (v: T) => void+ ) => {const box = section(title)const row = el("div", "choices")const note = el("p", "empty")@@ -883,9 +961,30 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste}}const refreshers = [- group("land", sizeIds, (v) => sizes[v].title, (v) => `${sizes[v].goal.residents} residents and ${sizes[v].goal.coins} coins to complete it`, () => choice.size, (v) => (choice.size = v)),- group("term", TERMS, (v) => `${v} min`, (v) => `${v} minutes of the town at 1×: six years, a winter at the end of each after the first`, () => choice.term, (v) => (choice.term = v)),- group("richness", landIds, (v) => lands[v].title, (v) => lands[v].blurb, () => choice.land, (v) => (choice.land = v))+ group(+ "land",+ sizeIds,+ (v) => sizes[v].title,+ (v) => `${sizes[v].goal.residents} residents and ${sizes[v].goal.coins} coins to complete it`,+ () => choice.size,+ (v) => (choice.size = v)+ ),+ group(+ "term",+ TERMS,+ (v) => `${v} min`,+ (v) => `${v} minutes of the town at 1×: six years, a winter at the end of each after the first`,+ () => choice.term,+ (v) => (choice.term = v)+ ),+ group(+ "richness",+ landIds,+ (v) => lands[v].title,+ (v) => lands[v].blurb,+ () => choice.land,+ (v) => (choice.land = v)+ )]const seedLine = el("div", "row")const seedText = el("span", "")@@ -940,7 +1039,9 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst line = (values: ReadonlyArray<number>, lo: number, hi: number, color: string, dash = "") => {if (values.length < 2) return ""const span = hi - lo || 1- const points = s.history.map((p, i) => `${((p.tick / end) * w).toFixed(1)},${(h - 4 - ((values[i]! - lo) / span) * (h - 8)).toFixed(1)}`).join(" ")+ const points = s.history+ .map((p, i) => `${((p.tick / end) * w).toFixed(1)},${(h - 4 - ((values[i]! - lo) / span) * (h - 8)).toFixed(1)}`)+ .join(" ")return `<polyline points="${points}" fill="none" stroke="${color}" stroke-width="1.5" stroke-dasharray="${dash}" vector-effect="non-scaling-stroke"/>`}const residents = s.history.map((p) => p.residents)@@ -951,7 +1052,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst winters = Array.from({ length: 5 }, (_, i) => {const y = i + 1const from = ((y + 0.7) / 6) * w- return `<rect x="${from.toFixed(1)}" y="0" width="${(w * 0.3 / 6).toFixed(1)}" height="${h}" fill="#3d6db5" opacity="0.06"/>`+ return `<rect x="${from.toFixed(1)}" y="0" width="${((w * 0.3) / 6).toFixed(1)}" height="${h}" fill="#3d6db5" opacity="0.06"/>`}).join("")return `<svg viewBox="0 0 ${w} ${h}" preserveAspectRatio="none">${winters}<line x1="0" x2="${w}" y1="${goal}" y2="${goal}" stroke="#77817a" stroke-dasharray="3 3" vector-effect="non-scaling-stroke"/>${line(coinsLine, Math.min(0, ...coinsLine), Math.max(1, ...coinsLine), "#d6ae2e")}${line(approvalLine, -100, 100, "#3d6db5", "4 3")}${line(residents, 0, top, "#3d4943")}</svg>`}@@ -979,10 +1080,20 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistereturn}const id = `${s.charter.seed}|${s.fate.state}|${s.fate.at}`- result.textContent = s.fate.state === "won" ? "the town is complete · see how" : s.fate.state === "lost" ? "the term is lost · see how" : "the term is over · see how"+ result.textContent =+ s.fate.state === "won"+ ? "the town is complete · see how"+ : s.fate.state === "lost"+ ? "the term is lost · see how"+ : "the term is over · see how"if (id === reckoned) returnreckoned = id- const title = s.fate.state === "won" ? "the town is complete" : s.fate.state === "lost" ? s.fate.reason.split(":")[0]!.toLowerCase() : `the term is over: ${verdictOf(s)}`+ const title =+ s.fate.state === "won"+ ? "the town is complete"+ : s.fate.state === "lost"+ ? s.fate.reason.split(":")[0]!.toLowerCase()+ : `the term is over: ${verdictOf(s)}`reckoning.replaceChildren()const card = el("div", "sheet wide")card.append(el("h2", "", title), el("p", "sub", s.fate.reason))@@ -1029,94 +1140,13 @@ export const createHost = async (mount: HTMLElement, persistence: () => PersisteshowReckoning(true)}- // ── Pointer ──- const canvas = app.canvas- const pointers = new Map<number, Point>()- let press: { id: number; start: Point; last: Point; pan: boolean; panned: boolean } | null = null- let pinch: { distance: number } | null = null- let screenPointer: Point | null = null- let wheel = 0-- const spread = () => {- const [a, b] = [...pointers.values()]- return a && b ? { distance: Math.hypot(a.x - b.x, a.y - b.y), mid: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 } } : null- }-- canvas.addEventListener("pointerdown", (event) => {- canvas.setPointerCapture(event.pointerId)- const at = { x: event.clientX, y: event.clientY }- pointers.set(event.pointerId, at)- screenPointer = at- ui.pointer = toWorld(at.x, at.y)- if (pointers.size === 2) {- pinch = { distance: spread()!.distance }- press = null- ui.dragFrom = null- return- }- // Roads and homes are laid by dragging; with any other tool a drag pans.- const pan = event.button !== 0 || (ui.tool !== "road" && ui.tool !== "home")- press = { id: event.pointerId, start: at, last: at, pan, panned: false }- if (event.button === 0) ui.gestures.push({ type: "press", at: toWorld(at.x, at.y) })- })-- canvas.addEventListener("pointermove", (event) => {- const at = { x: event.clientX, y: event.clientY }- if (pointers.has(event.pointerId)) pointers.set(event.pointerId, at)- if (pinch && pointers.size === 2) {- const now = spread()!- zoomTo(now.mid.x, now.mid.y, zoom * (now.distance / pinch.distance))- pinch.distance = now.distance- return- }- screenPointer = at- ui.pointer = toWorld(at.x, at.y)- if (press && press.id === event.pointerId && press.pan) {- if (!press.panned && Math.hypot(at.x - press.start.x, at.y - press.start.y) > 6) press.panned = true- if (press.panned) {- look.x -= (at.x - press.last.x) / zoom- look.y -= (at.y - press.last.y) / zoom- placeCamera()- }- }- if (press) press.last = at- })-- const release = (event: PointerEvent, cancelled: boolean) => {- pointers.delete(event.pointerId)- if (pinch && pointers.size < 2) {- pinch = null- const nearest = zooms.reduce((best, z) => (Math.abs(z - zoom) < Math.abs(best - zoom) ? z : best), zooms[0])- zoomTo(event.clientX, event.clientY, nearest)- }- if (press && press.id === event.pointerId) {- const at = toWorld(event.clientX, event.clientY)- ui.gestures.push({ type: "release", at, panned: press.panned || cancelled || event.button !== 0 })- press = null- }- if (event.pointerType !== "mouse") {- ui.pointer = null- screenPointer = null- }+ const input = new MapInput(stage, ui)+ const resetPage = () => {+ choose("select")+ ui.menu = null+ ui.selected = null+ input.reset()}- canvas.addEventListener("pointerup", (event) => release(event, false))- canvas.addEventListener("pointercancel", (event) => release(event, true))- canvas.addEventListener("pointerleave", (event) => {- if (event.pointerType === "mouse" && !press) {- ui.pointer = null- screenPointer = null- }- })- canvas.addEventListener("contextmenu", (event) => event.preventDefault())- canvas.addEventListener("wheel", (event) => {- event.preventDefault()- wheel += event.deltaY- if (Math.abs(wheel) < 40) return- const index = zooms.findIndex((z) => z >= zoom - 1e-6)- const next = zooms[Math.min(zooms.length - 1, Math.max(0, index + (wheel > 0 ? -1 : 1)))]!- wheel = 0- zoomTo(event.clientX, event.clientY, next)- }, { passive: false })/** Copies the town's numbers and preview into the page, once a frame. */const syncPage = () => {@@ -1128,7 +1158,9 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistecoins.classList.toggle("debt", s.coins < 0)const left = Math.max(0, s.charter.term * 60 - Math.floor(s.minute * 60))clock.innerHTML = `${icon(s.season.winter ? "winter" : "clock", 20)}<span class="stack"><b>${clockText(left)}</b><small class="${s.season.winter ? "winter" : ""}">year ${s.season.year} · ${s.season.winter ? `spring in ${clockText(s.season.left)}` : `winter in ${clockText(s.season.left)}`}</small></span>`- clock.title = s.season.winter ? "Winter: fields lie still, fishing is slow, and homes eat faster" : `Time left in the term · winter comes in ${clockText(s.season.left)}`+ clock.title = s.season.winter+ ? "Winter: fields lie still, fishing is slow, and homes eat faster"+ : `Time left in the term · winter comes in ${clockText(s.season.left)}`const trend = s.mood.target > s.mood.approval ? "↑" : s.mood.target < s.mood.approval ? "↓" : ""approval.innerHTML = `${icon("approval", 18)}<span class="stack"><b class="${s.mood.approval < 0 ? "down" : ""}">${signed(s.mood.approval)} <span class="${s.mood.target >= s.mood.approval ? "up" : "down"}">${trend}</span></b><small>approval</small></span>`settlerCell.innerHTML = `${icon("settlers", 18)}<span class="stack"><b>${s.settlers}</b><small>settlers</small></span>`@@ -1148,7 +1180,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste// What threatens the term, or is about to complete it.const warnings: Array<string> = []if (s.fate.state === "playing") {- if (s.fate.bankrupt !== null) warnings.push(`<b>In debt:</b> bankrupt in ${clockText(s.fate.bankrupt)} unless the treasury recovers`)+ if (s.fate.bankrupt !== null)+ warnings.push(`<b>In debt:</b> bankrupt in ${clockText(s.fate.bankrupt)} unless the treasury recovers`)else if (s.coins < 0) warnings.push("<b>In debt:</b> wages are going unpaid")if (s.fate.revolt !== null) warnings.push(`<b>Uproar:</b> the town turns the mayor out in ${clockText(s.fate.revolt)}`)else if (s.mood.approval < -30) warnings.push("<b>Restless:</b> approval is falling towards revolt")@@ -1158,7 +1191,9 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste}if (s.fate.complete !== null) warnings.push(`<b>Every goal met:</b> the town is complete in ${clockText(s.fate.complete)}`)}- const html = warnings.map((w) => `<div class="cell">${icon(w.startsWith("<b>Every goal") ? "goal" : "warning", 16)}<span>${w}</span></div>`).join("")+ const html = warnings+ .map((w) => `<div class="cell">${icon(w.startsWith("<b>Every goal") ? "goal" : "warning", 16)}<span>${w}</span></div>`)+ .join("")if (alarm.dataset.html !== html) {alarm.dataset.html = htmlalarm.innerHTML = html@@ -1167,6 +1202,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistealarm.classList.toggle("good", warnings.length === 1 && s.fate.complete !== null)syncReckoning(s)}+ input.sync()+ const screenPointer = input.pointerconst text = ui.preview.tooltipif (text && screenPointer) {tooltip.textContent = text@@ -1174,8 +1211,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistetooltip.style.left = `${Math.min(screenPointer.x, window.innerWidth - tooltip.offsetWidth - 20)}px`tooltip.style.top = `${screenPointer.y}px`} else tooltip.style.display = "none"- canvas.style.cursor = press?.panned ? "grabbing" : ui.preview.hover !== null || ui.tool !== "select" ? "pointer" : "default"}- return { app, stage, ui, syncPage }+ return { app, stage, ui, syncPage, resetPage, input }}diff --git a/src/main.ts b/src/main.tsindex 0564ccd..0c9b39e 100644--- a/src/main.ts+++ b/src/main.ts@@ -1,14 +1,13 @@/*** A town simulation of line-drawn buildings, homes, roads, and land, on the- * bevy-ts ECS with Pixi drawing it. The simulation runs on a fixed step;+ * bevy-ts ECS with a 3D view. The simulation runs on a fixed step;* the views follow once a frame.*/import { Result } from "@typeonce/bevy-ts"import { Effect } from "effect"import { FixedLoop } from "@typeonce/bevy-ts-browser"-import { PixiNodeRegistry } from "@typeonce/bevy-ts-pixi"-import type { BuildingView, FieldView, HouseView, RockView, TreeView, WalkerView } from "./art.ts"+import type { BuildingView, FieldView, HouseView, RockView, TreeView, WalkerView } from "./render3d/views.ts"import { lands, sizes, STEP_SECONDS } from "./content.ts"import { createHost, type Persistence } from "./host.ts"import { present } from "./present.ts"@@ -22,20 +21,31 @@ const AUTOSAVE_MINUTES = 2const start = async () => {const mount = document.getElementById("app")!let persistence: Persistence = { save: () => "Not ready", load: () => "Not ready" }- const { app, stage, ui, syncPage } = await createHost(mount, () => persistence)+ const { stage, ui, syncPage, resetPage } = await createHost(mount, () => persistence)const clock = { deltaSeconds: STEP_SECONDS, elapsed: 0 }+ const buildingNodes = stage.registry<BuildingView>(),+ houseNodes = stage.registry<HouseView>(),+ walkerNodes = stage.registry<WalkerView>(),+ treeNodes = stage.registry<TreeView>(),+ rockNodes = stage.registry<RockView>(),+ fieldNodes = stage.registry<FieldView>()+ const resetPresentation = () => {+ for (const registry of [buildingNodes, houseNodes, walkerNodes, treeNodes, rockNodes, fieldNodes]) registry.clear()+ stage.resetPresentation()+ resetPage()+ }const made = Game.Runtime.make({services: Game.Runtime.services(Game.Runtime.service(Ui, ui),Game.Runtime.service(Clock, clock),Game.Runtime.service(StageService, stage),- Game.Runtime.service(BuildingNodes, PixiNodeRegistry.make<BuildingView>(stage.objects)),- Game.Runtime.service(HouseNodes, PixiNodeRegistry.make<HouseView>(stage.objects)),- Game.Runtime.service(WalkerNodes, PixiNodeRegistry.make<WalkerView>(stage.objects)),- Game.Runtime.service(TreeNodes, PixiNodeRegistry.make<TreeView>(stage.objects)),- Game.Runtime.service(RockNodes, PixiNodeRegistry.make<RockView>(stage.objects)),- Game.Runtime.service(FieldNodes, PixiNodeRegistry.make<FieldView>(stage.plates))+ Game.Runtime.service(BuildingNodes, buildingNodes),+ Game.Runtime.service(HouseNodes, houseNodes),+ Game.Runtime.service(WalkerNodes, walkerNodes),+ Game.Runtime.service(TreeNodes, treeNodes),+ Game.Runtime.service(RockNodes, rockNodes),+ Game.Runtime.service(FieldNodes, fieldNodes)),resources: blankResources()})@@ -50,7 +60,7 @@ const start = async () => {const advance = (seconds: number) => {for (let i = 0; i < Math.round(seconds / STEP_SECONDS); i++) runtime.tick(simulate)}- Object.assign(window, { town: { ui, runtime, advance } })+ Object.assign(window, { town: { ui, runtime, advance, view: stage } })}// Saves are Effect programs over the browser's storage and this town (see `save.ts`);@@ -59,15 +69,20 @@ const start = async () => {snapshot: () => runtime.snapshot(),restore: (data) => {const restored = runtime.restore(data as never)+ if (restored.ok) resetPresentation()return restored.ok ? null : restored.error._tag},title: () => {const s = ui.stats- return s ? `${sizes[s.charter.size].title}, ${lands[s.charter.land].title} land · year ${s.season.year} · ${Math.floor(s.minute)} min in` : "a town"+ return s+ ? `${sizes[s.charter.size].title}, ${lands[s.charter.land].title} land · year ${s.season.year} · ${Math.floor(s.minute)} min in`+ : "a town"}}const run = <A, E>(program: Effect.Effect<A, E, Storage | World>) =>- Effect.runSync(Effect.result(program.pipe(Effect.provideService(Storage, browserStorage(localStorage)), Effect.provideService(World, world))))+ Effect.runSync(+ Effect.result(program.pipe(Effect.provideService(Storage, browserStorage(localStorage)), Effect.provideService(World, world)))+ )persistence = {save: () => {const saved = run(save("manual"))@@ -92,11 +107,7 @@ const start = async () => {}const loop = FixedLoop.start({- source: FixedLoop.source((onTick) => {- const tick = (ticker: { readonly deltaMS: number }) => onTick(ticker)- app.ticker.add(tick)- return { stop: () => app.ticker.remove(tick) }- }),+ source: FixedLoop.source((onTick) => stage.subscribe(onTick)),stepSeconds: STEP_SECONDS,maxFrameSeconds: 0.25,maxStepsPerFrame: 4,@@ -104,6 +115,10 @@ const start = async () => {// new-town dialog is open, and once the term has ended (an edit, such as// founding a new town, still gets its step).update: () => {+ if (ui.edits.some((edit) => edit.type === "newTown")) {+ resetPresentation()+ stage.resetCamera()+ }const waiting = ui.speed === 0 || ui.founding || (ui.stats !== null && ui.stats.fate.state !== "playing")const steps = waiting ? (ui.edits.length > 0 ? 1 : 0) : ui.speedfor (let i = 0; i < steps; i++) {@@ -115,15 +130,19 @@ const start = async () => {render: ({ elapsedSeconds }) => {clock.deltaSeconds = elapsedSecondsclock.elapsed += elapsedSeconds- runtime.tick(present)+ const shown = runtime.tick(present)+ if (!shown.ok) throw new Error(`The town view stopped: ${JSON.stringify(shown.error)}`)syncPage()autosave()},onFailure: (failure) => {- mount.textContent = failure.kind === "InvalidTickDelta" ? `Invalid frame delta: ${failure.deltaMS}` : "The town stopped after a system failure."+ mount.textContent =+ failure.kind === "InvalidTickDelta" ? `Invalid frame delta: ${failure.deltaMS}` : "The town stopped after a system failure."}})if (!loop.ok) mount.textContent = `Invalid fixed-loop option: ${loop.error.field}`}void start()++if (import.meta.hot) import.meta.hot.accept(() => location.reload())diff --git a/src/map-lab/main.ts b/src/map-lab/main.tsnew file mode 100644index 0000000..609d4c5--- /dev/null+++ b/src/map-lab/main.ts@@ -0,0 +1,326 @@+import * as THREE from "three"+import { OrbitControls } from "three/addons/controls/OrbitControls.js"+import { buildAsset, floorScale } from "../asset-lab/renderer.ts"+import { inkAssets } from "../asset-lab/assets.ts"+import { makePerson } from "../asset-lab/people.ts"+import { testMap, districts } from "./map.ts"+import "./style.css"++const root = document.querySelector<HTMLElement>("#map-lab")!+root.innerHTML = `+ <div id="viewport"></div>+ <header class="card"><div><h1>Inkline harbour</h1><p>${inkAssets.length} models · complete world asset study</p></div><a href="/asset-lab.html">Asset study ↗</a></header>+ <section class="review card"><label>Explore <select id="district"></select></label><label>Inspect <select id="inspect"><option value="">Choose an asset…</option></select></label><div><button id="motion" aria-pressed="true">People moving</button><a id="asset-link" href="/asset-lab.html">Compare with original ↗</a></div></section>+ <aside class="compass card" aria-label="Camera orientation"><span id="north" aria-hidden="true">↑</span><span id="heading">0°</span></aside>+ <div class="hint card"><span class="desktop-hint">Drag to pan · right-drag to rotate · scroll to zoom</span><span class="touch-hint">Drag to pan · pinch to zoom · switch to Rotate to turn</span><span>WASD / arrows pan · Q / E turn · double-click to focus</span></div>+ <nav class="card controls" aria-label="Map camera controls">+ <div class="group"><button id="pan" aria-pressed="true" title="Left-drag or one finger pans the map">Pan</button><button id="rotate" aria-pressed="false" title="Left-drag or one finger rotates the map">Rotate</button></div>+ <div class="group"><button id="zoom-out" aria-label="Zoom out">−</button><output id="zoom">1.0×</output><button id="zoom-in" aria-label="Zoom in">+</button></div>+ <div class="group"><button id="turn-left" aria-label="Rotate left 45 degrees">↶</button><button id="turn-right" aria-label="Rotate right 45 degrees">↷</button></div>+ <label class="tilt">Tilt <input id="tilt" type="range" min="15" max="65" step="1" value="30" aria-label="Camera elevation"><output id="tilt-value">30°</output></label>+ <button id="reset" title="Restore the original view (Home)">Reset view</button>+ </nav>+ <span class="scene-note">Every model on the island · Original scale</span>+`+const viewport = root.querySelector<HTMLDivElement>("#viewport")!+const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false, preserveDrawingBuffer: true })+renderer.setPixelRatio(Math.min(devicePixelRatio, 2))+renderer.setClearColor(0xe2e9e6)+renderer.outputColorSpace = THREE.SRGBColorSpace+renderer.toneMapping = THREE.NoToneMapping+renderer.domElement.tabIndex = 0+renderer.domElement.setAttribute("aria-label", "3D island map. Drag to pan, right-drag to rotate, scroll to zoom.")+viewport.append(renderer.domElement)+const scene = new THREE.Scene()+const map = buildAsset(testMap.asset, { batchFaces: true })+scene.add(map.group)+const effects = testMap.effects.map((p) => {+ const model = buildAsset(+ inkAssets.find((a) => a.id === p.asset)!,+ { batchFaces: true }+ )+ model.group.position.set(p.x * floorScale, p.height / Math.cos(Math.PI / 6), p.y * floorScale)+ scene.add(model.group)+ return model+})+const camera = new THREE.OrthographicCamera(-600, 600, 450, -450, 0.1, 6000)+const controls = new OrbitControls(camera, renderer.domElement)+controls.screenSpacePanning = false+controls.zoomToCursor = true+controls.minZoom = 0.65+controls.maxZoom = 28+controls.minPolarAngle = THREE.MathUtils.degToRad(25)+controls.maxPolarAngle = THREE.MathUtils.degToRad(75)+controls.panSpeed = 0.85+controls.rotateSpeed = 0.65+controls.zoomSpeed = 0.85+controls.mouseButtons = { LEFT: THREE.MOUSE.PAN, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.ROTATE }+controls.touches = { ONE: THREE.TOUCH.PAN, TWO: THREE.TOUCH.DOLLY_PAN }+controls.listenToKeyEvents(renderer.domElement)+const tilt = root.querySelector<HTMLInputElement>("#tilt")!+const district = root.querySelector<HTMLSelectElement>("#district")!+const inspect = root.querySelector<HTMLSelectElement>("#inspect")!+for (const [id, d] of Object.entries(districts)) {+ const option = document.createElement("option")+ option.value = id+ option.textContent = d.title+ district.append(option)+}+for (const a of [...inkAssets].sort((a, b) => a.title.localeCompare(b.title))) {+ const option = document.createElement("option")+ option.value = a.id+ option.textContent = a.title+ inspect.append(option)+}+let moving = true+const actors = inkAssets+ .filter((a) => a.category === "people")+ .slice(0, 8)+ .map((a, i) => {+ const r = a.reference!+ if (r.type !== "walker") throw new Error("Actor requires walker reference")+ const frames = [0, 1].map((phase) => buildAsset(makePerson(a.id, a.title, r.dress, r.load, r.cart, phase), { batchFaces: true }))+ frames.forEach((f) => scene.add(f.group))+ return { frames, offset: i / 8 }+ })+let draws = 0+let mode: "pan" | "rotate" = "pan"++function render() {+ for (const effect of effects) effect.group.rotation.y = controls.getAzimuthalAngle() - Math.PI / 4+ map.updateContours(camera)+ for (const actor of actors) for (const frame of actor.frames) frame.updateContours(camera)+ renderer.render(scene, camera)+ draws+++ const degrees = THREE.MathUtils.radToDeg(controls.getAzimuthalAngle()) - 45+ const heading = ((degrees + 540) % 360) - 180+ const elevation = 90 - THREE.MathUtils.radToDeg(controls.getPolarAngle())+ root.querySelector("#zoom")!.textContent = `${camera.zoom.toFixed(1)}×`+ root.querySelector("#heading")!.textContent = `${Math.round(heading)}°`+ root.querySelector<HTMLElement>("#north")!.style.transform = `rotate(${-heading}deg)`+ tilt.value = String(Math.round(elevation))+ root.querySelector("#tilt-value")!.textContent = `${Math.round(elevation)}°`+}+controls.addEventListener("change", render)++function reset() {+ district.value = "all"+ inspect.value = ""+ controls.target.set(0, 0, 0)+ camera.position.set(1600, Math.sqrt(2) * 1600 * Math.tan(Math.PI / 6), 1600)+ camera.zoom = 1+ camera.updateProjectionMatrix()+ controls.update()+ render()+}+function resize() {+ const width = viewport.clientWidth,+ height = viewport.clientHeight+ renderer.setSize(width, height, false)+ const viewHeight = Math.max(1350, (2150 * height) / width)+ camera.top = viewHeight / 2+ camera.bottom = -viewHeight / 2+ camera.right = (viewHeight * width) / height / 2+ camera.left = -camera.right+ camera.updateProjectionMatrix()+ render()+}+function focus(x: number, y: number, zoom: number) {+ const next = new THREE.Vector3(x * floorScale, 0, y * floorScale)+ const delta = next.clone().sub(controls.target)+ controls.target.copy(next)+ camera.position.add(delta)+ camera.zoom = zoom+ camera.updateProjectionMatrix()+ controls.update()+ render()+}+function focusDistrict(id: keyof typeof districts) {+ const d = districts[id]+ focus(d.x, d.y, d.zoom)+ district.value = id+ inspect.value = ""+}+district.onchange = () => focusDistrict(district.value as keyof typeof districts)+inspect.onchange = () => {+ const p = testMap.buildings.find((p) => p.asset === inspect.value)+ if (!p) return+ const a = inkAssets.find((a) => a.id === p.asset)!+ focus(p.x, p.y, a.category === "people" ? 24 : a.category === "cargo" ? 18 : 6)+ district.value = ""+ root.querySelector<HTMLAnchorElement>("#asset-link")!.href = `/asset-lab.html?asset=${p.asset}`+}+root.querySelector<HTMLButtonElement>("#motion")!.onclick = () => {+ moving = !moving+ root.querySelector("#motion")!.textContent = moving ? "People moving" : "People paused"+ root.querySelector("#motion")!.setAttribute("aria-pressed", String(moving))+}+function zoomBy(amount: number) {+ camera.zoom = THREE.MathUtils.clamp(camera.zoom * amount, controls.minZoom, controls.maxZoom)+ camera.updateProjectionMatrix()+ controls.update()+ render()+}+function rotateBy(angle: number) {+ const offset = camera.position.clone().sub(controls.target)+ offset.applyAxisAngle(new THREE.Vector3(0, 1, 0), THREE.MathUtils.degToRad(angle))+ camera.position.copy(controls.target).add(offset)+ controls.update()+}+function setTilt(angle: number) {+ const spherical = new THREE.Spherical().setFromVector3(camera.position.clone().sub(controls.target))+ spherical.phi = THREE.MathUtils.degToRad(90 - angle)+ camera.position.copy(controls.target).add(new THREE.Vector3().setFromSpherical(spherical))+ controls.update()+}+function setMode(next: "pan" | "rotate") {+ mode = next+ controls.mouseButtons.LEFT = mode === "pan" ? THREE.MOUSE.PAN : THREE.MOUSE.ROTATE+ controls.touches.ONE = mode === "pan" ? THREE.TOUCH.PAN : THREE.TOUCH.ROTATE+ controls.touches.TWO = mode === "pan" ? THREE.TOUCH.DOLLY_PAN : THREE.TOUCH.DOLLY_ROTATE+ root.querySelector("#pan")!.setAttribute("aria-pressed", String(mode === "pan"))+ root.querySelector("#rotate")!.setAttribute("aria-pressed", String(mode === "rotate"))+ renderer.domElement.style.cursor = mode === "pan" ? "grab" : "ew-resize"+}+function panBy(right: number, forward: number) {+ const direction = camera.getWorldDirection(new THREE.Vector3())+ direction.y = 0+ direction.normalize()+ const side = new THREE.Vector3().crossVectors(direction, camera.up).normalize()+ const delta = side.multiplyScalar(right).add(direction.multiplyScalar(forward))+ controls.target.add(delta)+ camera.position.add(delta)+ controls.update()+}+root.querySelector<HTMLButtonElement>("#pan")!.onclick = () => setMode("pan")+root.querySelector<HTMLButtonElement>("#rotate")!.onclick = () => setMode("rotate")+root.querySelector<HTMLButtonElement>("#reset")!.onclick = reset+root.querySelector<HTMLButtonElement>("#zoom-in")!.onclick = () => zoomBy(1.25)+root.querySelector<HTMLButtonElement>("#zoom-out")!.onclick = () => zoomBy(0.8)+root.querySelector<HTMLButtonElement>("#turn-left")!.onclick = () => rotateBy(-45)+root.querySelector<HTMLButtonElement>("#turn-right")!.onclick = () => rotateBy(45)+tilt.oninput = () => setTilt(Number(tilt.value))+renderer.domElement.addEventListener("pointerdown", () => renderer.domElement.focus({ preventScroll: true }))+const onKeyDown = (event: KeyboardEvent) => {+ if (event.target instanceof HTMLElement && event.target.closest("input,select,button,a")) return+ const amount = 45 / camera.zoom+ switch (event.key.toLowerCase()) {+ case "a":+ panBy(-amount, 0)+ break+ case "d":+ panBy(amount, 0)+ break+ case "w":+ panBy(0, amount)+ break+ case "s":+ panBy(0, -amount)+ break+ case "q":+ rotateBy(-15)+ break+ case "e":+ rotateBy(15)+ break+ case "+":+ case "=":+ zoomBy(1.2)+ break+ case "-":+ zoomBy(1 / 1.2)+ break+ case "home":+ reset()+ break+ default:+ return+ }+ event.preventDefault()+}+window.addEventListener("keydown", onKeyDown)+const raycaster = new THREE.Raycaster()+const ground = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0)+renderer.domElement.addEventListener("dblclick", (event) => {+ const rect = renderer.domElement.getBoundingClientRect()+ raycaster.setFromCamera(+ new THREE.Vector2(((event.clientX - rect.left) / rect.width) * 2 - 1, (-(event.clientY - rect.top) / rect.height) * 2 + 1),+ camera+ )+ const point = raycaster.ray.intersectPlane(ground, new THREE.Vector3())+ if (point) {+ const delta = point.clone().sub(controls.target)+ controls.target.copy(point)+ camera.position.add(delta)+ controls.update()+ }+})+let previous = 0,+ elapsed = 0+renderer.setAnimationLoop((now) => {+ if (!previous) previous = now+ if (moving) elapsed += Math.min(0.05, (now - previous) / 1000)+ previous = now+ if (!moving && draws > 0) return+ for (const actor of actors) {+ const t = (elapsed * 0.035 + actor.offset) % 1,+ forward = t < 0.5+ const x = -8 + 16 * (forward ? t * 2 : (1 - t) * 2),+ phase = Math.floor(elapsed * 5) % 2+ actor.frames.forEach((f, i) => {+ f.group.visible = i === phase+ f.group.position.set(x * floorScale, 0, 4 * floorScale)+ f.group.rotation.y = forward ? 0 : Math.PI+ f.updateContours(camera)+ })+ }+ renderer.render(scene, camera)+})+const resizeObserver = new ResizeObserver(resize)+resizeObserver.observe(viewport)+reset()+resize()++// Reproducible camera/scene checks, without adding diagnostics to the map UI.+Object.assign(window, {+ mapLab: {+ reset,+ focusDistrict,+ focus,+ capture: () => renderer.domElement.toDataURL("image/webp", 0.95),+ rotateBy,+ zoomBy,+ setTilt,+ panBy,+ setMode,+ stats: () => ({+ buildings: inkAssets.filter((a) => a.category === "buildings").length,+ assets: inkAssets.length,+ represented: testMap.coverage,+ people: inkAssets.filter((a) => a.category === "people").length,+ actors: actors.length,+ trees: testMap.trees,+ roadCells: testMap.roads,+ zoom: camera.zoom,+ heading: THREE.MathUtils.radToDeg(controls.getAzimuthalAngle()),+ elevation: 90 - THREE.MathUtils.radToDeg(controls.getPolarAngle()),+ target: controls.target.toArray().map((value) => value / floorScale),+ draws,+ drawCalls: renderer.info.render.calls,+ triangles: renderer.info.render.triangles,+ mode+ })+ }+})++if (import.meta.hot)+ import.meta.hot.dispose(() => {+ renderer.setAnimationLoop(null)+ controls.dispose()+ resizeObserver.disconnect()+ window.removeEventListener("keydown", onKeyDown)+ map.dispose()+ effects.forEach((model) => model.dispose())+ actors.forEach((actor) => actor.frames.forEach((frame) => frame.dispose()))+ renderer.dispose()+ })diff --git a/src/map-lab/map.ts b/src/map-lab/map.tsnew file mode 100644index 0000000..9298f2b--- /dev/null+++ b/src/map-lab/map.ts@@ -0,0 +1,208 @@+import { inkAssets, palette, type InkAsset, type Vertex } from "../asset-lab/assets.ts"++export interface MapBuilding {+ id: number+ asset: string+ title: string+ x: number+ y: number+ size: number+}+const town: InkAsset = { id: "map", title: "Inkline harbour", note: "", faces: [], strokes: [] }+const buildings: Array<MapBuilding> = []+const effects: Array<{ asset: string; x: number; y: number; height: number }> = []+let contour = 1+const edge = (points: ReadonlyArray<Vertex>, width = 1, color = palette.ink, opacity = 1) =>+ town.strokes.push({ points, width, color, opacity })+const face = (points: ReadonlyArray<Vertex>, color: number, outline = false) => {+ town.faces.push({ points, color })+ if (outline) edge([...points, points[0]!], 1.5)+}+const square = (x: number, y: number, half: number, z: number): Array<Vertex> => [+ [x - half, y - half, z],+ [x + half, y - half, z],+ [x + half, y + half, z],+ [x - half, y + half, z]+]++// A slightly irregular coast, with all coordinates in the game's cell units.+const coast: Array<Vertex> = [+ [-19, -10, -0.5],+ [-17, -14, -0.5],+ [-10, -16, -0.5],+ [-2, -16.5, -0.5],+ [8, -15, -0.5],+ [16, -12, -0.5],+ [19, -6, -0.5],+ [19.5, 2, -0.5],+ [17, 10, -0.5],+ [13, 14, -0.5],+ [5, 16, -0.5],+ [-5, 16, -0.5],+ [-14, 13, -0.5],+ [-18, 7, -0.5],+ [-20, 0, -0.5]+]+face(coast, 0xf0f2ec, true)+// Pale foreshore and a second restrained shoreline outside the land.+edge([...coast.map(([x, y, z]): Vertex => [x * 1.016, y * 1.016, z - 0.1]), [-19 * 1.016, -10 * 1.016, -0.6]], 1, 0x9fb3b0, 0.45)++const roads = new Set<string>()+for (let x = -15; x <= 15; x++) for (const y of [-8, -2, 4, 10]) roads.add(`${x},${y}`)+for (let y = -12; y <= 13; y++) for (const x of [-10, 0, 10]) roads.add(`${x},${y}`)+for (const cell of roads) {+ const [x, y] = cell.split(",").map(Number) as [number, number]+ const half = 0.375,+ z = -0.28+ const variant = ((x * 37 + y * 19 + 131) >>> 0) % 10+ const color = variant < 3 ? 0xe2e4dd : variant > 8 ? 0xe9eae4 : 0xe6e8e2+ face(square(x, y, half, z), color)+ for (const [dx, dy] of [+ [1, 0],+ [-1, 0],+ [0, 1],+ [0, -1]+ ] as const) {+ const q = (along: number, across: number, height = z): Vertex => [x + dx * along - dy * across, y + dy * along + dx * across, height]+ if (roads.has(`${x + dx},${y + dy}`)) {+ face([q(half, -half), q(0.5, -half), q(0.5, half), q(half, half)], color)+ edge([q(half, -half, z + 0.02), q(0.5, -half, z + 0.02)], 1.5)+ edge([q(half, half, z + 0.02), q(0.5, half, z + 0.02)], 1.5)+ edge([q(1 / 16, 0, z + 0.03), q(3 / 16, 0, z + 0.03)], 1, 0xb4b9b1)+ edge([q(5 / 16, 0, z + 0.03), q(7 / 16, 0, z + 0.03)], 1, 0xb4b9b1)+ } else edge([q(half, -half, z + 0.02), q(half, half, z + 0.02)], 1.5)+ }+}++function place(id: string, x: number, y: number, scale = 1, record = true, height = 0) {+ const asset = inkAssets.find((asset) => asset.id === id)!+ const transform = ([u, v, z]: Vertex): Vertex => [x + u * scale, y + v * scale, z * scale + height]+ const groups = new Map<number, number>()+ const effect = id === "smoke" || id === "problem-marker"+ if (effect) effects.push({ asset: id, x, y, height })+ for (const polygon of asset.faces) {+ if (effect) continue+ const result = { ...polygon, points: polygon.points.map(transform) }+ if (polygon.contour) {+ if (!groups.has(polygon.contour)) groups.set(polygon.contour, contour++)+ result.contour = groups.get(polygon.contour)!+ }+ town.faces.push(result)+ }+ if (!effect) for (const stroke of asset.strokes) town.strokes.push({ ...stroke, points: stroke.points.map(transform) })+ if (record)+ buildings.push({+ id: buildings.length,+ asset: id,+ title: asset.title,+ x,+ y,+ size: asset.footprint ?? 1+ })+}++// The main streets contain every building type; each workshop keeps its yard.+const layout: Array<[string, number, number]> = [+ ["townhall", -3, -5],+ ["market", 2.5, -5],+ ["chapel", 6.5, -5],+ ["warehouse", 13, -5],+ ["lumberjack", -13, -5],+ ["forester", -13, -11],+ ["farm", -6, -11],+ ["mill", -2, -11],+ ["sheep", 4, -11],+ ["quarry", -13, 1],+ ["mine", -13, 7],+ ["sawmill", -6, 1],+ ["smithy", -2, 1],+ ["bakery", 3, 1],+ ["weaver", 7, 1],+ ["fishery", 13, 1]+]+for (const [id, x, y] of layout) place(id, x, y)+const homes = inkAssets.filter((a) => a.category === "homes")+homes.forEach((a, i) => place(a.id, -7 + (i % 4) * 1.8, 6 + Math.floor(i / 4) * 2))+const trees = inkAssets.filter((a) => a.reference?.type === "tree")+trees.forEach((a, i) => place(a.id, -17 + (i % 3) * 1.3, -11 + Math.floor(i / 3) * 1.4))+for (let i = 0; i < 18; i++) place(trees[i % trees.length]!.id, -8 + (i % 9) * 2.4, -14 + Math.floor(i / 9) * 1.2, 1, false)+inkAssets.filter((a) => a.reference?.type === "rock").forEach((a, i) => place(a.id, -16 + (i % 2) * 1.5, 4 + Math.floor(i / 2) * 1.5))+inkAssets.filter((a) => a.reference?.type === "field").forEach((a, i) => place(a.id, -8 + (i % 2) * 1.2, -10 + Math.floor(i / 2) * 1.2))+place("roads", 15, 8)+place("water", 7, 14)++// A cargo yard at the quay. Every product has a handcart and a barrow,+// with both one-item and full loads. People stay at their original scale.+const carts = inkAssets.filter((a) => a.reference?.type === "walker" && a.reference.cart)+carts.forEach((a, i) => place(a.id, 2 + (i % 8) * 1.5, 5 + Math.floor(i / 8) * 1.05))+const cargo = inkAssets.filter((a) => a.reference?.type === "cargo" || a.reference?.type === "crate")+cargo.forEach((a, i) => place(a.id, -8 + (i % 11) * 0.8, 12 + Math.floor(i / 11) * 1.1))+place("goods", -5, 14)+const people = inkAssets.filter((a) => a.category === "people")+people.forEach((a, i) => place(a.id, i < 11 ? -8 + i * 1.4 : -8 + (i - 11), i < 11 ? -2 : 4))+inkAssets+ .filter((a) => a.category === "construction" && a.reference?.type !== "plot" && a.id !== "smoke" && a.id !== "problem-marker")+ .forEach((a, i) => place(a.id, 12 + (i % 2) * 3, -11 + Math.floor(i / 2) * 2.1))+place("smoke", -2.5, 0.5, 1, true, 56)+place("problem-marker", 12, -8.9, 1, true, 35)+inkAssets.filter((a) => a.reference?.type === "plot").forEach((a, i) => place(a.id, -12 + (i % 2) * 3, 9.5 + Math.floor(i / 2) * 2.6))++// A timber jetty and drawn sea ripples use the same restrained palette.+for (let i = 0; i < 16; i++) {+ const y = 15 + i * 0.2+ face(+ [+ [-1, y, 0],+ [1, y, 0],+ [1, y + 0.2, 0],+ [-1, y + 0.2, 0]+ ],+ 0xe9d2a8+ )+ edge(+ [+ [-1, y, 0.04],+ [1, y, 0.04]+ ],+ 0.8,+ 0x8a6a45+ )+}+edge(+ [+ [-1, 15, 0],+ [-1, 18.2, 0],+ [1, 18.2, 0],+ [1, 15, 0]+ ],+ 1.5+)+for (let i = 0; i < 120; i++) {+ const x = ((i * 17) % 51) - 25,+ y = ((i * 11) % 45) - 22+ if ((x * x) / 420 + (y * y) / 300 < 1.14) continue+ edge(+ [+ [x - 0.14, y, -0.8],+ [x, y - 0.08, -0.8],+ [x + 0.14, y, -0.8],+ [x + 0.28, y - 0.08, -0.8]+ ],+ 0.8,+ 0x9fb3b0,+ 0.7+ )+}+const represented = new Set(buildings.map((p) => p.asset))+const missing = inkAssets.filter((a) => !represented.has(a.id)).map((a) => a.id)+if (missing.length) throw new Error(`Review map is missing: ${missing.join(", ")}`)+export const districts = {+ all: { title: "Whole island", x: 0, y: 0, zoom: 1 },+ town: { title: "Town centre", x: 2, y: -5, zoom: 2.8 },+ industry: { title: "Workshops", x: -7, y: 1, zoom: 3.2 },+ homes: { title: "Homes", x: -4, y: 7, zoom: 5 },+ people: { title: "People", x: 0, y: -2, zoom: 7 },+ cargo: { title: "Cargo yard", x: 7, y: 7, zoom: 4 },+ forest: { title: "Forest & farms", x: -10, y: -11, zoom: 3.2 }+} as const+export const testMap = { asset: town, buildings, effects, trees: trees.length + 18, roads: roads.size, coverage: represented.size }diff --git a/src/map-lab/style.css b/src/map-lab/style.cssnew file mode 100644index 0000000..dbbadcb--- /dev/null+++ b/src/map-lab/style.css@@ -0,0 +1,302 @@+@import url("https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=DM+Mono:wght@400;500&display=swap");+:root {+ font-family: "DM Sans", sans-serif;+ color: #3d4943;+ background: #e2e9e6;+ font-synthesis: none;+}+* {+ box-sizing: border-box;+}+body {+ margin: 0;+ overflow: hidden;+}+#map-lab,+#viewport {+ position: fixed;+ inset: 0;+}+canvas {+ display: block;+ width: 100%;+ height: 100%;+ touch-action: none;+ outline: none;+}+button,+input {+ font: inherit;+}+button {+ color: inherit;+ cursor: pointer;+}+.card {+ position: absolute;+ background: #f5f6f0ed;+ border: 1px solid #c2cbc1;+ border-radius: 6px;+ box-shadow: 0 3px 12px #3d49430a;+ backdrop-filter: blur(6px);+}+header {+ top: 22px;+ left: 24px;+ display: flex;+ align-items: center;+ gap: 34px;+ padding: 16px 20px;+}+h1 {+ font-size: 21px;+ font-weight: 600;+ letter-spacing: -0.03em;+ margin: 0 0 4px;+}+header p {+ font-family: "DM Mono", monospace;+ font-size: 10px;+ color: #778277;+ margin: 0;+}+header a {+ color: #657360;+ text-decoration: none;+ font-size: 11px;+ border-left: 1px solid #cbd1c6;+ padding-left: 20px;+}+.compass {+ right: 24px;+ top: 22px;+ min-width: 64px;+ display: flex;+ flex-direction: column;+ align-items: center;+ padding: 11px;+ gap: 4px;+ font-family: "DM Mono", monospace;+ font-size: 10px;+}+.review {+ top: 110px;+ left: 24px;+ padding: 12px 14px;+ display: flex;+ flex-direction: column;+ gap: 10px;+ max-width: 280px;+}+.review label {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ font-size: 11px;+}+.review select {+ max-width: 185px;+ color: inherit;+ background: #f7f8f3;+ border: 1px solid #cbd1c6;+ border-radius: 4px;+ padding: 6px;+ font: inherit;+}+.review a {+ color: #657360;+ text-decoration: none;+ font-size: 10px;+}+.review button {+ font-size: 10px;+ padding: 5px;+ min-height: 28px;+ margin-right: 6px;+}+#north {+ display: block;+ font-size: 28px;+ line-height: 30px;+}+.hint {+ left: 24px;+ bottom: 90px;+ padding: 11px 14px;+ display: flex;+ flex-direction: column;+ gap: 4px;+ font-family: "DM Mono", monospace;+ font-size: 10px;+ line-height: 1.4;+ color: #748073;+}+.hint span:first-child {+ color: #3d4943;+}+.touch-hint {+ display: none;+}+.controls {+ bottom: 22px;+ left: 50%;+ transform: translateX(-50%);+ display: flex;+ align-items: center;+ padding: 7px 9px;+ gap: 12px;+ white-space: nowrap;+}+.group {+ display: flex;+ align-items: center;+ gap: 3px;+}+.group + .group {+ border-left: 1px solid #cbd1c6;+ padding-left: 12px;+}+.tilt {+ display: flex;+ align-items: center;+ gap: 8px;+ font-family: "DM Mono", monospace;+ font-size: 10px;+ border-left: 1px solid #cbd1c6;+ padding-left: 12px;+}+.tilt input {+ width: 85px;+ accent-color: #5c7154;+}+button {+ border: 1px solid transparent;+ border-radius: 4px;+ background: transparent;+ padding: 10px 12px;+ font-family: "DM Mono", monospace;+ font-size: 11px;+ min-height: 38px;+}+button:hover {+ background: #e3e8dd;+}+button[aria-pressed="true"] {+ background: #e3e8dd;+ border-color: #b9c4b2;+}+.group button[aria-label] {+ font-size: 19px;+ padding: 5px 12px;+}+output {+ font-family: "DM Mono", monospace;+ font-size: 10px;+ min-width: 39px;+ text-align: center;+}+.scene-note {+ position: absolute;+ right: 24px;+ bottom: 94px;+ font-family: "DM Mono", monospace;+ font-size: 10px;+ color: #7a8980;+ pointer-events: none;+}+@media (pointer: coarse) {+ .desktop-hint {+ display: none;+ }+ .touch-hint {+ display: block;+ }+ .hint span:last-child {+ display: none;+ }+}+@media (max-width: 760px) {+ .review {+ top: 91px;+ left: 14px;+ max-width: calc(100% - 28px);+ padding: 8px 10px;+ gap: 6px;+ }+ .review label {+ font-size: 10px;+ }+ .review select {+ padding: 4px;+ }+ header {+ left: 14px;+ top: 14px;+ padding: 12px 15px;+ gap: 16px;+ }+ header a {+ padding-left: 14px;+ }+ .compass {+ right: 14px;+ top: 14px;+ min-width: 51px;+ padding: 8px;+ }+ h1 {+ font-size: 18px;+ }+ .controls {+ gap: 6px;+ flex-wrap: wrap;+ justify-content: center;+ max-width: calc(100% - 28px);+ width: fit-content;+ bottom: 14px;+ }+ .group + .group {+ padding-left: 6px;+ }+ .tilt {+ display: none;+ }+ .hint {+ left: 14px;+ bottom: 85px;+ font-size: 9px;+ padding: 9px 11px;+ max-width: calc(100% - 28px);+ }+ .scene-note {+ display: none;+ }+ button {+ padding: 8px 10px;+ }+ .group button[aria-label] {+ padding: 4px 10px;+ }+ .controls #reset {+ padding: 8px;+ }+}+@media (max-width: 420px) {+ header a {+ display: none;+ }+ .controls {+ width: calc(100% - 28px);+ }+ .hint {+ bottom: 125px;+ }+ .controls #reset {+ width: 100%;+ border-top: 1px solid #cbd1c6;+ border-radius: 0;+ padding: 5px;+ min-height: 30px;+ }+}diff --git a/src/present.ts b/src/present.tsindex 9aec9fe..d8dac57 100644--- a/src/present.ts+++ b/src/present.ts@@ -5,56 +5,95 @@*/import { RenderSync } from "@typeonce/bevy-ts-render"-import {- BuildingView, drawFloor, drawGhost, drawPlot, drawRoads, drawWater, FieldView, homeHeight, HouseView, RockView, topOf, TreeView, WalkerView, type Load,- type Doors, type Emphasis-} from "./art.ts"+import { homeHeight, topOf, type Load, type Emphasis } from "./art.ts"+import { BuildingView, HouseView, WalkerView, TreeView, RockView, FieldView } from "./render3d/views.ts"+import type { DoorSet } from "./render3d/models.ts"import { BUILD_TICKS, crown as crownRules, fate, goodIds, goods, home, kinds, needTitle, total, type Kind } from "./content.ts"import { around, canPlace, entrances, isRoad, key, lPath, useAt, type TileLike } from "./grid.ts"-import { inside, TILE_H, TILE_W, toGrid, toScreen, U, type Point } from "./iso.ts"+import { inside, U, type Point } from "./iso.ts"import {- Building, BuildingNodes, Census, Charter, Chronicle, Clock, Crown, Errand, Fate, Field, FieldNodes, Figure, Game, Grid, History, House,- HouseNodes, Inventory, Land, Ledger, Market, Mood, Paused, Policy, Recipe, Rising, Road, Roam, Rock, RockNodes, Route, Service, Site,- Staff, StageService, Status, Stock, Tile, Time, TownHall, Treasury, Tree, TreeNodes, Ui, WalkerNodes, WalkerOf, Water, maybe,- type GridValue, type Status as StatusValue+ Building,+ BuildingNodes,+ Census,+ Charter,+ Chronicle,+ Clock,+ Crown,+ Errand,+ Fate,+ Field,+ FieldNodes,+ Figure,+ Game,+ Grid,+ History,+ House,+ HouseNodes,+ Inventory,+ Land,+ Ledger,+ Market,+ Mood,+ Paused,+ Policy,+ Recipe,+ Rising,+ Road,+ Roam,+ Rock,+ RockNodes,+ Route,+ Service,+ Site,+ Staff,+ StageService,+ Status,+ Stock,+ Tile,+ Time,+ TownHall,+ Treasury,+ Tree,+ TreeNodes,+ Ui,+ WalkerNodes,+ WalkerOf,+ Water,+ maybe,+ type GridValue,+ type Status as StatusValue} from "./schema.ts"import { capacity, CELL_STEPS, elapsed, goalsOf, larder, met, seasonAt, SITE_SHARE, taxOf, termTicks } from "./sim/index.ts"import { Townsfolk } from "./townsfolk.ts"import { emptyPreview, type HitBox } from "./ui.ts"const cellAt = (at: Point): Point => {- const g = toGrid(at.x, at.y)- return { x: Math.floor(g.x), y: Math.floor(g.y) }+ return { x: Math.floor(at.x), y: Math.floor(at.y) }}/** The footprint `size` cells a side centred on a point, by its top cell. */const footprintAt = (at: Point, size: number): Point => {- const g = toGrid(at.x, at.y)- return { x: Math.floor(g.x - (size - 1) / 2), y: Math.floor(g.y - (size - 1) / 2) }+ return { x: Math.floor(at.x - (size - 1) / 2), y: Math.floor(at.y - (size - 1) / 2) }}/** A thing's hit area: its footprint on the floor, or its body as drawn. */-const hitBox = (id: number, tile: TileLike, half: number, height: number): HitBox => {- const centre = toScreen(tile.x + tile.size / 2, tile.y + tile.size / 2)- const a = half * U- const top = centre.y - a * TILE_H - height- return {- id,- depth: tile.x + tile.y + tile.size,- contains: (at) => {- const g = toGrid(at.x, at.y)- if (g.x >= tile.x && g.x <= tile.x + tile.size && g.y >= tile.y && g.y <= tile.y + tile.size) return true- return Math.abs(at.x - centre.x) <= a * TILE_W && at.y >= top && at.y <= centre.y- }- }-}--const hitAt = (hits: ReadonlyArray<HitBox>, at: Point): number | null => hits.find((h) => h.contains(at))?.id ?? null+const hitBox = (id: number, tile: TileLike, _half: number, _height: number): HitBox => ({+ id,+ depth: tile.x + tile.y + tile.size,+ contains: (at) => at.x >= tile.x && at.x <= tile.x + tile.size && at.y >= tile.y && at.y <= tile.y + tile.size+})+const hitAt = (hits: ReadonlyArray<HitBox>, at: Point, entity?: number | null) =>+ entity === undefined ? (hits.find((h) => h.contains(at))?.id ?? null) : entity-/** The walls facing the viewer a road meets: the +x side's entrances and the +y side's. */-const doorsOf = (grid: GridValue, tile: TileLike): Doors => {+/** Doors follow road entrances on all four sides as the camera turns. */+const doorsOf = (grid: GridValue, tile: TileLike): DoorSet => {const open = entrances(tile).filter((c) => isRoad(grid, c.x, c.y))- return { right: open.some((c) => c.side === 0), left: open.some((c) => c.side === 1) }+ return {+ right: open.some((c) => c.side === 0),+ left: open.some((c) => c.side === 1),+ backRight: open.some((c) => c.side === 2),+ backLeft: open.some((c) => c.side === 3)+ }}/** How far a kind's work reaches, if it works the land around it. */@@ -75,7 +114,8 @@ const problemOf = (kind: Kind, status: StatusValue, growing = false): string | nreturn "paused: no workers, a quarter of its upkeep"case "starved":if (kind.gathers && growing) return `the ${kind.gathers.source === "tree" ? "trees" : "fields"} in reach are still growing`- if (kind.gathers) return `no ${sourceTitle[kind.gathers.source]} within ${kind.gathers.radius} cells${kind.gathers.source === "tree" ? ": a forester nearby replants" : ""}`+ if (kind.gathers)+ return `no ${sourceTitle[kind.gathers.source]} within ${kind.gathers.radius} cells${kind.gathers.source === "tree" ? ": a forester nearby replants" : ""}`if (kind.recipe?.input) return `waiting for ${kind.recipe.input}`if (kind.service?.service === "goods") return "nothing to hand out: no fish, bread, or cloth here"return "waiting"@@ -108,19 +148,28 @@ const BuildingRead = Game.Query({}})const HouseRead = Game.Query({- selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House), site: Game.Query.optional(Site), rising: Game.Query.optional(Rising) }+ selection: {+ tile: Game.Query.read(Tile),+ house: Game.Query.read(House),+ site: Game.Query.optional(Site),+ rising: Game.Query.optional(Rising)+ }})/** How far up a building or home is: a site rises to its frame as materials come in, then the rest of the way. */-const buildOf = (site: { readonly owed: Parameters<typeof total>[0]; readonly total: number } | undefined, rising: { readonly ticks: number } | undefined) =>- site ? PLATE_SHARE + (SITE_SHARE - PLATE_SHARE) * delivered(site) : rising ? rising.ticks / BUILD_TICKS : 1+const buildOf = (+ site: { readonly owed: Parameters<typeof total>[0]; readonly total: number } | undefined,+ rising: { readonly ticks: number } | undefined+) => (site ? PLATE_SHARE + (SITE_SHARE - PLATE_SHARE) * delivered(site) : rising ? rising.ticks / BUILD_TICKS : 1)-const siteShare = (site: { readonly owed: Parameters<typeof total>[0]; readonly total: number } | undefined) => (site ? delivered(site) : null)+const siteShare = (site: { readonly owed: Parameters<typeof total>[0]; readonly total: number } | undefined) =>+ site ? delivered(site) : null/** A site's plate is marked out the moment it is placed. */const PLATE_SHARE = 0.12/** The share of a site's materials that has arrived. */-const delivered = (site: { readonly owed: Parameters<typeof total>[0]; readonly total: number }) => 1 - total(site.owed) / Math.max(1, site.total)+const delivered = (site: { readonly owed: Parameters<typeof total>[0]; readonly total: number }) =>+ 1 - total(site.owed) / Math.max(1, site.total)export const Interact = Game.System("Town/Interact",@@ -186,13 +235,13 @@ export const Interact = Game.System(}case "bulldoze": {if (gesture.panned) break- const hit = hitAt(hits, gesture.at)+ const hit = hitAt(hits, gesture.at, gesture.hit)ui.edits.push({ type: "remove", cell: (hit !== null ? tileOf(hit) : undefined) ?? cell })break}case "select": {if (gesture.panned) break- ui.selected = hitAt(hits, gesture.at)+ ui.selected = hitAt(hits, gesture.at, gesture.hit)if (ui.selected !== null) ui.menu = nullbreak}@@ -204,7 +253,7 @@ export const Interact = Game.System(const preview = emptyPreview()const pointer = ui.pointerconst cell = pointer ? cellAt(pointer) : null- preview.hover = pointer && (ui.tool === "select" || ui.tool === "bulldoze") ? hitAt(hits, pointer) : null+ preview.hover = pointer && (ui.tool === "select" || ui.tool === "bulldoze") ? hitAt(hits, pointer, ui.pointerHit) : nullconst showReach = (tile: TileLike, kind: Kind) => {const r = reachOf(kind)if (r !== null) preview.plots.push({ x: tile.x - r, y: tile.y - r, size: tile.size + 2 * r, look: "reach" })@@ -230,7 +279,8 @@ export const Interact = Game.System(else preview.plots.push({ ...tile, look: "blocked" })} else if (ui.tool === "bulldoze") {preview.danger = true- if (preview.hover === null && cell && ["road", "tree", "field"].includes(useAt(grid, cell.x, cell.y))) preview.plots.push({ ...cell, size: 1, look: "blocked" })+ if (preview.hover === null && cell && ["road", "tree", "field"].includes(useAt(grid, cell.x, cell.y)))+ preview.plots.push({ ...cell, size: 1, look: "blocked" })}if (ui.selected !== null) {const row = buildings.find((b) => b.entity.id === ui.selected)@@ -246,7 +296,9 @@ export const Interact = Game.System(const site = maybe(row.data.site)const lines: Array<string> = []if (site) {- const owed = Object.entries(site.owed).filter(([, n]) => n > 0).map(([g, n]) => `${n} ${g}`)+ const owed = Object.entries(site.owed)+ .filter(([, n]) => n > 0)+ .map(([g, n]) => `${n} ${g}`)lines.push(owed.length > 0 ? `waiting for ${owed.join(", ")}` : "going up")return { kind, status, problem: null, lines }}@@ -254,7 +306,10 @@ export const Interact = Game.System(if (staff.needed > 0) lines.push(`workers ${staff.assigned} of ${staff.needed}`)const recipe = maybe(row.data.recipe)const inventory = maybe(row.data.inventory)- if (recipe) lines.push(`${recipe.input ? `${recipe.inputs} ${recipe.input} → ` : ""}${recipe.batch} ${goods[recipe.output].title} · ${recipe.made} made`)+ if (recipe)+ lines.push(+ `${recipe.input ? `${recipe.inputs} ${recipe.input} → ` : ""}${recipe.batch} ${goods[recipe.output].title} · ${recipe.made} made`+ )if (inventory && !maybe(row.data.hall)) {const held = inventory.accepts.filter((g) => inventory.stock[g] > 0).map((g) => `${inventory.stock[g]} ${g}`)lines.push(held.length > 0 ? `holds ${held.join(", ")}` : "holds nothing yet")@@ -304,8 +359,15 @@ export const Interact = Game.System(const { kind, status, problem, lines } = describeBuilding(pickedBuilding)const pausable = kind.id !== "townhall" && !pickedBuilding.data.site.present && !pickedBuilding.data.rising.presentui.panel = {- type: "building", id: pickedBuilding.entity.id, cell: pickedBuilding.data.tile.get(), kind: kind.id, status, problem, lines,- pausable, paused: pickedBuilding.data.paused.present+ type: "building",+ id: pickedBuilding.entity.id,+ cell: pickedBuilding.data.tile.get(),+ kind: kind.id,+ status,+ problem,+ lines,+ pausable,+ paused: pickedBuilding.data.paused.present}} else if (pickedHouse) {const { h, lines } = describeHouse(pickedHouse)@@ -315,7 +377,7 @@ export const Interact = Game.System(const centres = new Map<number, Point>()for (const { entity, data } of [...buildings, ...houses]) {const t = data.tile.get()- centres.set(entity.id, toScreen(t.x + t.size / 2, t.y + t.size / 2))+ centres.set(entity.id, { x: t.x + t.size / 2, y: t.y + t.size / 2 })}ui.centres = centres@@ -364,8 +426,16 @@ export const Interact = Game.System(].filter((p) => p.value !== 0)},crown: {- open: crown.open, good: crown.good, amount: crown.amount, left: seconds(crown.due - t), reward: crown.reward, met: crown.met,- missed: crown.missed, streak: crown.streak, patience: crownRules.patience, next: seconds(crown.next - t)+ open: crown.open,+ good: crown.good,+ amount: crown.amount,+ left: seconds(crown.due - t),+ reward: crown.reward,+ met: crown.met,+ missed: crown.missed,+ streak: crown.streak,+ patience: crownRules.patience,+ next: seconds(crown.next - t)},fate: {state: f.state,@@ -394,7 +464,7 @@ export const RenderBuildings = RenderSync.system(Game, {transform: Tile,registry: BuildingNodes,services: { stage: StageService },- create: ({ renderable, services }) => new BuildingView(renderable.kind, services.stage),+ create: ({ renderable, services, entity }) => new BuildingView(renderable.kind, services.stage, entity),apply: (node, { transform }) => node.place(transform.x, transform.y)})@@ -404,7 +474,7 @@ export const RenderHouses = RenderSync.system(Game, {transform: Tile,registry: HouseNodes,services: { stage: StageService },- create: ({ services }) => new HouseView(services.stage),+ create: ({ services, entity }) => new HouseView(services.stage, entity),apply: (node, { transform }) => node.place(transform.x, transform.y)})@@ -412,7 +482,8 @@ export const RenderWalkers = RenderSync.system(Game, {name: "Town/RenderWalkers",renderable: Figure,registry: WalkerNodes,- create: ({ renderable }) => WalkerView.forFigure(renderable.role, renderable.color),+ services: { stage: StageService },+ create: ({ renderable, services, entity }) => WalkerView.forFigure(renderable.role, renderable.color, services.stage, entity),apply: () => {}})@@ -421,7 +492,8 @@ export const RenderTrees = RenderSync.system(Game, {renderable: Tree,transform: Tile,registry: TreeNodes,- create: () => new TreeView(),+ services: { stage: StageService },+ create: ({ services, entity }) => new TreeView(services.stage, entity),apply: (node, { transform }) => node.place(transform.x, transform.y)})@@ -430,7 +502,8 @@ export const RenderRocks = RenderSync.system(Game, {renderable: Rock,transform: Tile,registry: RockNodes,- create: () => new RockView(),+ services: { stage: StageService },+ create: ({ services, entity }) => new RockView(services.stage, entity),apply: (node, { transform }) => node.place(transform.x, transform.y)})@@ -439,21 +512,18 @@ export const RenderFields = RenderSync.system(Game, {renderable: Field,transform: Tile,registry: FieldNodes,- create: () => new FieldView(),+ services: { stage: StageService },+ create: ({ services, entity }) => new FieldView(services.stage, entity),apply: (node, { transform }) => node.place(transform.x, transform.y)})/** The land, redrawn when a new town is founded (or one loaded). */-let floorFor = ""export const DrawLand = Game.System("Town/DrawLand",{ resources: { land: Game.System.readResource(Land) }, services: { stage: Game.System.service(StageService) } },({ resources, services }) => {const mask = resources.land.get().mask- if (mask === floorFor) return- floorFor = mask- services.stage.floor.clear()- drawFloor(services.stage.floor, mask)+ services.stage.setLand(mask)})@@ -470,13 +540,10 @@ export const DrawGround = Game.System(services: { stage: Game.System.service(StageService) }},({ queries, despawned, services }) => {- if (queries.laid.each().length === 0 && despawned.entities.all().length === 0) return+ if (!services.stage.groundDirty && queries.laid.each().length === 0 && despawned.entities.all().length === 0) returnconst cellsOf = (rows: ReadonlyArray<{ readonly data: { readonly tile: { get(): TileLike } } }>) =>new Set(rows.map(({ data }) => key(data.tile.get().x, data.tile.get().y)))- services.stage.roads.clear()- drawRoads(services.stage.roads, cellsOf(queries.roads.each()))- services.stage.ground.clear()- drawWater(services.stage.ground, cellsOf(queries.water.each()))+ services.stage.setGround(cellsOf(queries.roads.each()), cellsOf(queries.water.each()))})@@ -506,7 +573,9 @@ export const Animate = Game.System(queries: {buildings: BuildingRead,houses: HouseRead,- walkers: Game.Query({ selection: { route: Game.Query.read(Route), errand: Game.Query.optional(Errand), roam: Game.Query.optional(Roam) } }),+ walkers: Game.Query({+ selection: { route: Game.Query.read(Route), errand: Game.Query.optional(Errand), roam: Game.Query.optional(Roam) }+ }),trees: Game.Query({ selection: { tree: Game.Query.read(Tree) } }),rocks: Game.Query({ selection: { rock: Game.Query.read(Rock) } }),fields: Game.Query({ selection: { field: Game.Query.read(Field) } })@@ -548,10 +617,17 @@ export const Animate = Game.System()}for (const { entity, data } of queries.houses.each()) {- services.houseNodes.get(entity.id)?.update(- { tier: data.house.get().tier, build: buildOf(maybe(data.site), maybe(data.rising)), doors: doorsOf(grid, data.tile.get()), site: siteShare(maybe(data.site)) },- emphasis(entity.id)- )+ services.houseNodes+ .get(entity.id)+ ?.update(+ {+ tier: data.house.get().tier,+ build: buildOf(maybe(data.site), maybe(data.rising)),+ doors: doorsOf(grid, data.tile.get()),+ site: siteShare(maybe(data.site))+ },+ emphasis(entity.id)+ )}for (const { entity, data } of queries.walkers.each()) {const p = walkerAt(data.route.get())@@ -560,13 +636,14 @@ export const Animate = Game.System(const load: Load = errand? { kind: "cart", good: errand.good, count: !errand.back || errand.count > 0 ? errand.count : 0 }: roam?.service === "faith"- ? { kind: "bell" }- : roam && total(roam.basket) > 0- ? { kind: "basket", goods: goodIds.filter((g) => roam.basket[g] > 0) }- : { kind: "none" }+ ? { kind: "bell" }+ : roam && total(roam.basket) > 0+ ? { kind: "basket", goods: goodIds.filter((g) => roam.basket[g] > 0) }+ : { kind: "none" }services.walkerNodes.get(entity.id)?.update(p.x, p.y, p.dir, p.phase, load)}- for (const { entity, data } of queries.trees.each()) services.treeNodes.get(entity.id)?.update(data.tree.get().growth, emphasis(entity.id))+ for (const { entity, data } of queries.trees.each())+ services.treeNodes.get(entity.id)?.update(data.tree.get().growth, emphasis(entity.id))for (const { entity, data } of queries.rocks.each()) {const r = data.rock.get()services.rockNodes.get(entity.id)?.update(r.ore, r.amount)@@ -580,19 +657,12 @@ export const DrawPreview = Game.System("Town/DrawPreview",{ services: { ui: Game.System.service(Ui), stage: Game.System.service(StageService), clock: Game.System.service(Clock) } },({ services }) => {- const { plots, ghosts, roads } = services.ui.preview- const { overlay, ghost } = services.stage- overlay.clear()- ghost.clear()- for (const plot of plots) drawPlot(overlay, plot.x, plot.y, plot.size, plot.look, services.clock.elapsed)- if (roads.length > 0) drawRoads(overlay, new Set(roads.map((c) => key(c.x, c.y))), 0.6, 0x8f9891)- for (const g of ghosts) drawGhost(ghost, g.what, g.cell.x, g.cell.y)- ghost.alpha = 0.5+ services.stage.setPreview(services.ui.preview, services.clock.elapsed)})/** Residents out walking (see `townsfolk.ts`), on the town's time: still while it waits. */-let townsfolk: { readonly folk: Townsfolk; land: string } | null = null+let townsfolk: { readonly folk: Townsfolk; land: string; generation: number; stage: unknown } | null = nullexport const Stroll = Game.System("Town/Stroll",{@@ -602,14 +672,19 @@ export const Stroll = Game.System(},({ queries, resources, services }) => {const ui = services.ui- townsfolk ??= { folk: new Townsfolk(services.stage.objects), land: "" }+ if (townsfolk?.stage !== services.stage) {+ townsfolk?.folk.clear()+ townsfolk = { folk: new Townsfolk(services.stage), land: "", generation: -1, stage: services.stage }+ }const mask = resources.land.get().mask- if (mask !== townsfolk.land) {+ if (mask !== townsfolk.land || townsfolk.generation !== services.stage.generation) {+ townsfolk.generation = services.stage.generationtownsfolk.land = masktownsfolk.folk.clear()}const waiting = ui.founding || (ui.stats !== null && ui.stats.fate.state !== "playing")- const homes = queries.houses.each()+ const homes = queries.houses+ .each().filter(({ data }) => !maybe(data.site) && !maybe(data.rising)).map(({ data }) => ({ ...data.tile.get(), tier: data.house.get().tier, residents: data.house.get().residents }))townsfolk.folk.step(waiting ? 0 : services.clock.deltaSeconds * ui.speed, homes, resources.grid.get())diff --git a/src/render3d/input.ts b/src/render3d/input.tsnew file mode 100644index 0000000..cdc70d1--- /dev/null+++ b/src/render3d/input.ts@@ -0,0 +1,225 @@+import type { Point } from "../iso.ts"+import type { UiValue } from "../ui.ts"+import type { GameScene } from "./scene.ts"++/** Camera gestures and game gestures share the canvas, but a pan, orbit or+ * pinch never commits a build stroke or a selection. Game coordinates come+ * from the ground ray; object IDs come from the rendered instances. */+export class MapInput {+ private scene: GameScene+ private ui: UiValue+ private pointers = new Map<number, Point>()+ private press: { id: number; start: Point; last: Point; mode: "edit" | "pan" | "rotate"; moved: boolean } | null = null+ private pinch: { distance: number; angle: number; mid: Point } | null = null+ private screen: Point | null = null+ private mode: "pan" | "rotate" = "pan"+ readonly controls: HTMLElement+ private abort = new AbortController()+ constructor(scene: GameScene, ui: UiValue) {+ this.scene = scene+ this.ui = ui+ const canvas = scene.canvas,+ signal = this.abort.signal+ canvas.style.touchAction = "none"+ const at = (e: PointerEvent) => ({ x: e.clientX, y: e.clientY })+ canvas.addEventListener(+ "pointerdown",+ (e) => {+ canvas.focus({ preventScroll: true })+ canvas.setPointerCapture(e.pointerId)+ const p = at(e)+ this.pointers.set(e.pointerId, p)+ this.screen = p+ this.updatePointer()+ if (this.pointers.size === 2) {+ this.pinch = this.spread()+ this.press = null+ ui.dragFrom = null+ ui.gestures.length = 0+ return+ }+ if (this.pointers.size > 2) return+ const mode =+ e.button === 2 || e.altKey+ ? "rotate"+ : e.button === 1+ ? "pan"+ : this.mode === "rotate"+ ? "rotate"+ : ui.tool === "road" || ui.tool === "home"+ ? "edit"+ : "pan"+ this.press = { id: e.pointerId, start: p, last: p, mode, moved: false }+ if (e.button === 0 && this.mode !== "rotate") ui.gestures.push({ type: "press", at: scene.groundAt(p.x, p.y) })+ },+ { signal }+ )+ canvas.addEventListener(+ "pointermove",+ (e) => {+ const p = at(e)+ if (this.pointers.has(e.pointerId)) this.pointers.set(e.pointerId, p)+ if (this.pinch && this.pointers.size === 2) {+ const next = this.spread()+ if (next) {+ scene.zoomAt(next.mid.x, next.mid.y, next.distance / Math.max(1, this.pinch.distance))+ scene.rotate(next.angle - this.pinch.angle)+ scene.pan(next.mid.x - this.pinch.mid.x, next.mid.y - this.pinch.mid.y)+ this.pinch = next+ }+ this.screen = p+ this.updatePointer()+ return+ }+ const press = this.press+ if (press?.id === e.pointerId) {+ if (Math.hypot(p.x - press.start.x, p.y - press.start.y) > 6) press.moved = true+ if (press.mode === "rotate" && press.moved) scene.rotate((p.x - press.last.x) * 0.006, (p.y - press.last.y) * 0.004)+ if (press.mode === "pan" && press.moved) scene.pan(p.x - press.last.x, p.y - press.last.y)+ press.last = p+ }+ this.screen = p+ this.updatePointer()+ },+ { signal }+ )+ const release = (e: PointerEvent, cancelled: boolean) => {+ const p = at(e)+ this.pointers.delete(e.pointerId)+ if (this.pinch) {+ if (this.pointers.size < 2) this.pinch = null+ this.press = null+ ui.dragFrom = null+ }+ const press = this.press+ if (press?.id === e.pointerId) {+ const input = scene.inputAt(p.x, p.y, ui.tool)+ const panned = cancelled || press.mode === "rotate" || e.button !== 0 || (press.mode === "pan" && press.moved)+ ui.gestures.push({ type: "release", at: press.mode === "edit" ? scene.groundAt(p.x, p.y) : input.at, hit: input.hit, panned })+ if (panned) ui.dragFrom = null+ this.press = null+ }+ if (e.pointerType !== "mouse") {+ this.screen = null+ ui.pointer = null+ ui.pointerHit = null+ }+ }+ canvas.addEventListener("pointerup", (e) => release(e, false), { signal })+ canvas.addEventListener("pointercancel", (e) => release(e, true), { signal })+ canvas.addEventListener(+ "pointerleave",+ (e) => {+ if (!this.press && e.pointerType === "mouse") {+ this.screen = null+ ui.pointer = null+ ui.pointerHit = null+ }+ },+ { signal }+ )+ canvas.addEventListener("contextmenu", (e) => e.preventDefault(), { signal })+ canvas.addEventListener(+ "wheel",+ (e) => {+ e.preventDefault()+ scene.zoomAt(e.clientX, e.clientY, Math.exp(-e.deltaY * 0.0015))+ this.updatePointer()+ },+ { signal, passive: false }+ )+ this.controls = document.createElement("nav")+ this.controls.className = "camera-controls"+ this.controls.setAttribute("aria-label", "Map camera")+ this.controls.innerHTML = `<button data-mode="pan" aria-pressed="true" title="Drag to pan; road and home tools drag to build">Pan</button><button data-mode="rotate" aria-pressed="false" title="Drag to rotate instead of placing. Right-drag also rotates.">Rotate</button><button data-action="left" aria-label="Rotate map left" title="Rotate left (Q)">↶</button><button data-action="right" aria-label="Rotate map right" title="Rotate right (E)">↷</button><button data-action="out" aria-label="Zoom out">−</button><output aria-label="Camera zoom"></output><button data-action="in" aria-label="Zoom in">+</button><button data-action="reset" aria-label="Reset camera" title="Original angle and centre (Home)">⌂</button>`+ this.controls.querySelectorAll<HTMLButtonElement>("button").forEach(+ (button) =>+ (button.onclick = () => {+ if (button.dataset.mode) {+ this.mode = button.dataset.mode as "pan" | "rotate"+ ui.dragFrom = null+ this.press = null+ }+ if (button.dataset.action === "left") scene.rotate(-Math.PI / 4)+ if (button.dataset.action === "right") scene.rotate(Math.PI / 4)+ if (button.dataset.action === "out") scene.zoomBy(0.8)+ if (button.dataset.action === "in") scene.zoomBy(1.25)+ if (button.dataset.action === "reset") scene.resetCamera()+ this.updatePointer()+ this.sync()+ })+ )+ document.body.append(this.controls)+ window.addEventListener(+ "keydown",+ (e) => {+ if (ui.founding || document.querySelector(".dialog.open")) return+ if (e.target instanceof HTMLElement && e.target.closest("input,select,textarea,button,a,[contenteditable=true]")) return+ const moves: Record<string, [number, number]> = { arrowleft: [40, 0], arrowright: [-40, 0], arrowup: [0, 40], arrowdown: [0, -40] }+ const key = e.key.toLowerCase()+ if (moves[key]) scene.pan(...moves[key]!)+ else if (key === "q") scene.rotate(-Math.PI / 4)+ else if (key === "e") scene.rotate(Math.PI / 4)+ else if (key === "home") scene.resetCamera()+ else if (key === "+" || key === "=") scene.zoomBy(1.25)+ else if (key === "-") scene.zoomBy(0.8)+ else return+ e.preventDefault()+ this.updatePointer()+ this.sync()+ },+ { signal }+ )+ this.sync()+ }+ private spread() {+ const [a, b] = [...this.pointers.values()]+ return a && b+ ? {+ distance: Math.hypot(a.x - b.x, a.y - b.y),+ angle: Math.atan2(b.y - a.y, b.x - a.x),+ mid: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }+ }+ : null+ }+ private updatePointer() {+ if (this.screen) {+ const input = this.scene.inputAt(this.screen.x, this.screen.y, this.ui.tool)+ this.ui.pointer = input.at+ this.ui.pointerHit = input.hit+ }+ }+ get pointer() {+ return this.screen+ }+ sync() {+ this.updatePointer()+ this.controls.querySelector("output")!.textContent = this.scene.camera.zoom.toFixed(1) + "×"+ this.controls+ .querySelectorAll("[data-mode]")+ .forEach((b) => b.setAttribute("aria-pressed", String((b as HTMLElement).dataset.mode === this.mode)))+ this.scene.canvas.style.cursor = this.press?.moved+ ? this.press.mode === "rotate"+ ? "ew-resize"+ : "grabbing"+ : this.mode === "rotate"+ ? "ew-resize"+ : this.ui.preview.hover !== null || this.ui.tool !== "select"+ ? "pointer"+ : "grab"+ }+ reset() {+ this.mode = "pan"+ this.press = null+ this.pinch = null+ this.pointers.clear()+ this.ui.dragFrom = null+ this.ui.gestures.length = 0+ this.ui.pointerHit = null+ this.sync()+ }+ dispose() {+ this.abort.abort()+ this.controls.remove()+ }+}diff --git a/src/render3d/models.ts b/src/render3d/models.tsnew file mode 100644index 0000000..5a828ca--- /dev/null+++ b/src/render3d/models.ts@@ -0,0 +1,308 @@+import { buildStages, homeVariant } from "../art.ts"+import { makeBuilding, type BuildingOptions } from "../asset-lab/buildings.ts"+import { house } from "../asset-lab/homes.ts"+import { Drawing, palette, square, type InkAsset, type Vertex, type Side } from "../asset-lab/primitives.ts"+import { hash } from "../asset-lab/land.ts"+import { kinds, home, type KindId, type Tier } from "../content.ts"+import { GRID, U, type Point } from "../iso.ts"+import { key, cellOf, DIRS } from "../grid.ts"+import type { Preview } from "../ui.ts"++export type DoorSet = Record<Side, boolean>+export const noDoors: DoorSet = { right: false, left: false, backRight: false, backLeft: false }+export const doorKey = (doors: DoorSet) => Object.values(doors).map(Boolean).map(Number).join("")++export function plateAsset(size: number, build = 1) {+ const d = new Drawing("plate", "Plate", ""),+ stage = buildStages(build),+ a = (size * 8 - 1) * U+ if (stage.walls > 0) d.face(square(0, 0, a, -0.15), palette.plate, 0)+ d.line([...square(0, 0, a, -0.13), [-a, -a, -0.13]], 1.5, palette.ink, stage.plate)+ return d.asset+}+export function constructionAsset(size: number, half: number, height: number, build: number, share: number | null) {+ const d = new Drawing("construction", "Construction", ""),+ stage = buildStages(build),+ a = half * U+ if (share !== null) {+ const s = (size * 8 - 2) * U+ for (const [u, v] of square(0, 0, s))+ d.line(+ [+ [u, v, 0],+ [u, v, 7]+ ],+ 1.5+ )+ d.line([...square(0, 0, s, 6), [-s, -s, 6]], 1, palette.ink, 0.45)+ const spots = [+ [s - 3 * U, s - 3 * U, 0],+ [s - 3 * U, s - 8 * U, 0],+ [s - 3 * U, s - 5.5 * U, 5]+ ]+ for (let i = 0; i < Math.ceil(share * 3); i++) {+ const [u, v, z] = spots[i]!+ d.crate(u!, v!, z!, 0x8f9891, 2 * U, 5)+ }+ }+ if (stage.frame > 0 && stage.walls < 1) {+ const top = Math.round(height * stage.frame)+ d.line([...square(0, 0, a, top), [-a, -a, top]], 1)+ for (const [u, v] of square(0, 0, a))+ d.line(+ [+ [u, v, 0],+ [u, v, top]+ ],+ 1+ )+ }+ if (stage.walls > 0) d.box(0, 0, a, a, 0, Math.max(2, Math.round(height * stage.walls)))+ return d.asset+}+export function buildingAsset(id: KindId, build: number, share: number | null, doors: DoorSet, open: number) {+ const kind = kinds[id],+ stage = buildStages(build)+ if (build < 0.78) return constructionAsset(kind.size, kind.half, kind.roof === "gable" ? 20 : kind.stories * 32, build, share)+ return makeBuilding(id, { doors, open, fit: stage.fit, plate: false, motion: false } satisfies BuildingOptions)+}+export function homeAsset(tier: Tier, n: number, build: number, share: number | null, doors: DoorSet) {+ if (build < 0.78) return constructionAsset(1, home.half + (tier === 2 ? 1 : 0), home.tiers[tier].height, build, share)+ return house(tier, n, "home", { doors, fit: buildStages(build).fit, plate: false })+}+export function homeKey(n: number) {+ return JSON.stringify(homeVariant(n))+}++/** A finite set of seeded tree variants retains palette, shape and size+ * variation while letting a forest share geometry and GPU instances. */+const treeSeeds = new Map<string, Point>()+export function treeVariant(x: number, y: number) {+ const h = hash(x, y),+ h2 = hash(y * 3 + 17, x * 5 + 7),+ type: "fir" | "poplar" | "broadleaf" = h < 0.45 ? "fir" : h > 0.88 ? "poplar" : "broadleaf",+ lobes = h > 0.6,+ paletteIndex = type === "fir" ? Number(hash(x * 11 + 101, y * 13 + 3) >= 0.5) : Math.floor(h2 * 97) % 5,+ size = Math.floor(h2 * 2)+ const id = `${type}/${type === "broadleaf" ? Number(lobes) : 0}/${paletteIndex}/${size}`+ let seed = treeSeeds.get(id)+ if (!seed) {+ for (let i = 0; i < 20000; i++) {+ const sx = i * 3,+ sy = i * 7,+ sh = hash(sx, sy),+ sh2 = hash(sy * 3 + 17, sx * 5 + 7),+ st = sh < 0.45 ? "fir" : sh > 0.88 ? "poplar" : "broadleaf"+ if (+ st === type &&+ (type !== "broadleaf" || sh > 0.6 === lobes) &&+ (type === "fir" ? Number(hash(sx * 11 + 101, sy * 13 + 3) >= 0.5) : Math.floor(sh2 * 97) % 5) === paletteIndex &&+ Math.floor(sh2 * 2) === size+ ) {+ seed = { x: sx, y: sy }+ break+ }+ }+ seed ??= { x, y }+ treeSeeds.set(id, seed)+ }+ const sh2 = hash(seed.y * 3 + 17, seed.x * 5 + 7),+ sh3 = hash(seed.x * 11 + 101, seed.y * 13 + 3),+ scale = (0.85 + h2 * 0.3) / (0.85 + sh2 * 0.3),+ dx = Math.round((hash(x * 11 + 101, y * 13 + 3) - 0.5) * 12) - Math.round((sh3 - 0.5) * 12) * scale,+ dy = Math.round((h2 - 0.5) * 5) - Math.round((sh2 - 0.5) * 5) * scale+ return { id, type, seed, scale, offset: [dx / 64 + dy / 32, -dx / 64 + dy / 32, 0] as Vertex }+}++export function landAsset(mask: string) {+ const d = new Drawing("land", "Land", ""),+ land = (x: number, y: number) => x >= 0 && y >= 0 && x < GRID && y < GRID && mask[key(x, y)] === "1"+ for (let y = 0; y < GRID; y++)+ for (let x = 0; x < GRID; x++) {+ if (!land(x, y)) continue+ d.face(+ [+ [x, y, -0.3],+ [x + 1, y, -0.3],+ [x + 1, y + 1, -0.3],+ [x, y + 1, -0.3]+ ],+ 0xf0f2ec,+ 0+ )+ if (land(x + 1, y))+ d.line(+ [+ [x + 1, y, -0.27],+ [x + 1, y + 1, -0.27]+ ],+ 1,+ 0xe0e3db+ )+ if (land(x, y + 1))+ d.line(+ [+ [x, y + 1, -0.27],+ [x + 1, y + 1, -0.27]+ ],+ 1,+ 0xe0e3db+ )+ for (const [dx, dy] of [+ [1, 0],+ [0, 1],+ [-1, 0],+ [0, -1]+ ]) {+ if (land(x + dx!, y + dy!)) continue+ const edge: Vertex[] =+ dx === 1+ ? [+ [x + 1, y, -0.25],+ [x + 1, y + 1, -0.25]+ ]+ : dx === -1+ ? [+ [x, y, -0.25],+ [x, y + 1, -0.25]+ ]+ : dy === 1+ ? [+ [x, y + 1, -0.25],+ [x + 1, y + 1, -0.25]+ ]+ : [+ [x, y, -0.25],+ [x + 1, y, -0.25]+ ]+ d.line(edge, 1.5, palette.ink, 0.75)+ }+ }+ return d.asset+}+export function groundAsset(roads: ReadonlySet<number>, water: ReadonlySet<number>, preview = false) {+ const d = new Drawing("ground", "Ground", ""),+ z = preview ? 0.16 : -0.14+ for (const k of roads) {+ const cell = cellOf(k),+ x = cell.x + 0.5,+ y = cell.y + 0.5,+ half = 0.375,+ color = hash(cell.x, cell.y) < 0.25 ? 0xe2e4dd : 0xe6e8e2+ d.face(square(x, y, half, z), color, 0)+ for (const { x: dx, y: dy } of DIRS) {+ const q = (along: number, across: number, height = z + 0.02): Vertex => [+ x + dx * along - dy * across,+ y + dy * along + dx * across,+ height+ ]+ if (roads.has(key(cell.x + dx, cell.y + dy))) {+ d.face([q(half, -half, z), q(0.5, -half, z), q(0.5, half, z), q(half, half, z)], color, 0)+ d.line([q(half, -half), q(0.5, -half)], 1.5)+ d.line([q(half, half), q(0.5, half)], 1.5)+ d.line([q(0.0625, 0), q(0.1875, 0)], 1, 0xb4b9b1)+ d.line([q(0.3125, 0), q(0.4375, 0)], 1, 0xb4b9b1)+ } else d.line([q(half, -half), q(half, half)], 1.5)+ }+ }+ for (const k of water) {+ const { x, y } = cellOf(k),+ near = DIRS.every((v) => water.has(key(x + v.x, y + v.y)))+ d.face(+ [+ [x, y, -0.22],+ [x + 1, y, -0.22],+ [x + 1, y + 1, -0.22],+ [x, y + 1, -0.22]+ ],+ near ? 0xdee8e5 : 0xe2ebe8,+ 0+ )+ for (const { x: dx, y: dy } of DIRS) {+ if (water.has(key(x + dx, y + dy))) continue+ const edge: Vertex[] =+ dx === 1+ ? [+ [x + 1, y, -0.18],+ [x + 1, y + 1, -0.18]+ ]+ : dx === -1+ ? [+ [x, y, -0.18],+ [x, y + 1, -0.18]+ ]+ : dy === 1+ ? [+ [x, y + 1, -0.18],+ [x + 1, y + 1, -0.18]+ ]+ : [+ [x, y, -0.18],+ [x + 1, y, -0.18]+ ]+ d.line(edge, 1.5, 0x9fb3b0, 0.7)+ }+ if (hash(x, y) < 0.34) {+ const u = x + 0.3 + hash(x + 7, y * 3) * 0.4,+ v = y + 0.3 + hash(y + 5, x * 7) * 0.4+ d.line(+ [+ [-6, 0],+ [-3, -2],+ [0, 0],+ [3, -2],+ [6, 0]+ ].map(([sx, sy]): Vertex => [u + sx! / 64 + sy! / 32, v - sx! / 64 + sy! / 32, -0.16]),+ 1,+ 0x9fb3b0+ )+ }+ if (hash(y * 13 + 1, x * 31 + 7) < 0.08) {+ const u = x + 0.5,+ v = y + 0.5+ d.line(+ [+ [u - 0.04, v + 0.04, -0.16],+ [u + 0.04, v - 0.04, -0.16]+ ],+ 1,+ 0xffffff,+ 0.9+ )+ }+ }+ return d.asset+}+export function previewAsset(preview: Preview, time: number) {+ const d = new Drawing("preview", "Preview", "")+ for (const { x, y, size, look } of preview.plots) {+ const color = look === "blocked" ? 0xc4523f : look === "picked" ? 0x3d6db5 : palette.ink,+ half = size / 2,+ u = x + half,+ v = y + half,+ ring = square(u, v, half, 0.13)+ const bold = look === "picked" || look === "blocked"+ d.face(ring, color, 0, palette.ink, bold ? 0.07 : look === "hover" ? 0.04 : 0.03)+ d.line([...ring, ring[0]!], bold ? 1.5 : 1, color, bold ? 0.85 : look === "hover" ? 0.35 : 0.45)+ if (bold) {+ const reach = (4 + Math.sin(time * 4)) * U+ for (const [a, b] of ring) {+ const dx = Math.sign(a - u),+ dy = Math.sign(b - v)+ d.line(+ [+ [a - dx * reach, b, 0.15],+ [a + dx * U, b, 0.15],+ [a, b + dy * U, 0.15],+ [a, b - dy * reach, 0.15]+ ],+ 1.5,+ color,+ 0.9+ )+ }+ }+ }+ return d.asset+}+export const quantizeBuild = (build: number) => Math.min(1, Math.round(build * 32) / 32)diff --git a/src/render3d/pool.ts b/src/render3d/pool.tsnew file mode 100644index 0000000..48c8cd2--- /dev/null+++ b/src/render3d/pool.ts@@ -0,0 +1,200 @@+import * as THREE from "three"+import { buildAsset, type BuiltAsset } from "../asset-lab/renderer.ts"+import type { InkAsset } from "../asset-lab/primitives.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+ 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+ 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()+ acquire(key: string, create: () => InkAsset): Template {+ let entry = this.templates.get(key)+ if (!entry) {+ const model = buildAsset(create(), { batchFaces: true, meshInk: true, meshContours: true })+ 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"+ parts.push({ source, material, mesh: null, color })+ }+ entry = {+ key,+ model,+ parts,+ group: new THREE.Group(),+ handles: new Set(),+ capacity: 0,+ alpha: 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)+ 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.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))+ 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+ 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/render3d/scene.ts b/src/render3d/scene.tsnew file mode 100644index 0000000..c24c038--- /dev/null+++ b/src/render3d/scene.ts@@ -0,0 +1,280 @@+import * as THREE from "three"+import { NodeRegistry } from "@typeonce/bevy-ts-render"+import { buildAsset, floorScale, vertex3, type BuiltAsset } from "../asset-lab/renderer.ts"+import { house } from "../asset-lab/homes.ts"+import { makeBuilding } from "../asset-lab/buildings.ts"+import type { InkAsset } from "../asset-lab/primitives.ts"+import { GRID, type Point } from "../iso.ts"+import { key } from "../grid.ts"+import { kinds } from "../content.ts"+import type { Preview, UiValue } from "../ui.ts"+import { ModelHandle, ModelPool } from "./pool.ts"+import { groundAsset, landAsset, previewAsset } from "./models.ts"++export interface SceneNode {+ readonly group: THREE.Group+ orient(): void+ destroy(): void+}++/** 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 pool = new ModelPool()+ readonly camera = new THREE.OrthographicCamera(-500, 500, 400, -400, 0.1, 14000)+ readonly renderer: THREE.WebGLRenderer+ readonly nodes = new Set<SceneNode>()+ readonly target = new THREE.Vector3((GRID / 2) * floorScale, 0, (GRID / 2) * floorScale)+ heading = Math.PI / 4+ elevation = Math.PI / 6+ generation = 0+ groundDirty = true+ private landKey: string | null = null+ private groundKey = ""+ private previewKey = ""+ private land: BuiltAsset | null = null+ private ground: BuiltAsset | null = null+ private overlays: BuiltAsset | null = null+ private roadPreview: BuiltAsset | null = null+ private ghostHandles: Array<ModelHandle> = []+ private raycaster = new THREE.Raycaster()+ private plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0)+ private width = 1+ private height = 1+ private observer: ResizeObserver+ private mount: HTMLElement+ private previous = 0+ private frames = 0+ private frameMS = 16.67+ constructor(mount: HTMLElement) {+ 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.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+ }+ 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()+ }+ 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.lookAt(this.target)+ this.camera.updateMatrixWorld(true)+ }+ groundAt(sx: number, sy: number): Point {+ 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: point.x / floorScale, y: point.z / floorScale }+ }+ inputAt(sx: number, sy: number, tool: UiValue["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+ }+ 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 }+ }+ 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)+ this.target.x += (a.x - b.x) * floorScale+ this.target.z += (a.y - b.y) * floorScale+ this.placeCamera()+ }+ panGrid(dx: number, dy: number) {+ this.target.x += dx * floorScale+ this.target.z += dy * floorScale+ this.placeCamera()+ }+ rotate(dx: number, dy = 0) {+ this.heading += dx+ this.elevation = THREE.MathUtils.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()+ 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)+ }+ 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) {+ this.target.set(x * floorScale, 0, y * floorScale)+ this.placeCamera()+ }+ registry<T extends SceneNode>(): NodeRegistry.NodeRegistry<T> {+ return NodeRegistry.make<T>({+ attach: (node) => {+ this.nodes.add(node)+ this.objects.add(node.group)+ },+ detach: (node) => {+ this.nodes.delete(node)+ node.destroy()+ }+ })+ }+ add(node: SceneNode) {+ this.nodes.add(node)+ this.objects.add(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()+ }+ if (!asset.faces.length && !asset.strokes.length) return null+ const model = buildAsset(asset, { batchFaces: true })+ this.scene.add(model.group)+ return model+ }+ setLand(mask: string) {+ if (mask === this.landKey) return+ this.landKey = mask+ this.land = this.replace(this.land, landAsset(mask))+ }+ setGround(roads: ReadonlySet<number>, water: ReadonlySet<number>) {+ const id = [...roads].join(",") + "|" + [...water].join(",")+ if (!this.groundDirty && id === this.groundKey) return+ this.groundDirty = false+ this.groundKey = id+ this.ground = this.replace(this.ground, groundAsset(roads, water))+ }+ setPreview(preview: Preview, time: number) {+ const beat = preview.plots.some((p) => p.look === "picked" || p.look === "blocked") ? Math.floor(time * 8) : 0+ const id = JSON.stringify([preview.plots, preview.ghosts, preview.roads, beat])+ if (id === this.previewKey) return+ this.previewKey = id+ this.overlays = this.replace(this.overlays, previewAsset(preview, time))+ this.roadPreview = this.replace(this.roadPreview, groundAsset(new Set(preview.roads.map((p) => key(p.x, p.y))), new Set(), true))+ for (const handle of this.ghostHandles) handle.dispose()+ this.ghostHandles = []+ for (const ghost of preview.ghosts) {+ const handle = new ModelHandle(this.pool),+ 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)+ this.ghostHandles.push(handle)+ }+ }+ resetPresentation() {+ this.generation+++ this.landKey = null+ this.groundDirty = true+ this.previewKey = ""+ for (const node of [...this.nodes]) node.destroy()+ 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: [] })+ this.roadPreview = this.replace(this.roadPreview, { id: "empty", title: "", note: "", faces: [], strokes: [] })+ }+ subscribe(onTick: (tick: { deltaMS: number }) => void) {+ this.previous = 0+ this.renderer.setAnimationLoop((now) => {+ 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.flush()+ this.renderer.render(this.scene, this.camera)+ this.frames+++ })+ return { stop: () => this.renderer.setAnimationLoop(null) }+ }+ stats() {+ return {+ renderer: "three",+ frames: this.frames,+ frameMS: this.frameMS,+ drawCalls: this.renderer.info.render.calls,+ triangles: this.renderer.info.render.triangles,+ nodes: this.nodes.size,+ ...this.pool.stats(),+ zoom: this.camera.zoom,+ heading: THREE.MathUtils.radToDeg(this.heading),+ elevation: THREE.MathUtils.radToDeg(this.elevation),+ target: [this.target.x / floorScale, this.target.z / floorScale],+ generation: this.generation+ }+ }+ capture() {+ return this.canvas.toDataURL("image/webp", 0.94)+ }+ dispose() {+ this.renderer.setAnimationLoop(null)+ this.observer.disconnect()+ this.resetPresentation()+ for (const model of [this.land, this.ground]) model?.dispose()+ this.pool.dispose()+ this.renderer.dispose()+ }+}diff --git a/src/render3d/views.ts b/src/render3d/views.tsnew file mode 100644index 0000000..539628c--- /dev/null+++ b/src/render3d/views.ts@@ -0,0 +1,313 @@+import * as THREE from "three"+import {+ carrierDress,+ cartLook,+ serviceDress,+ type BuildingLook,+ type HouseLook,+ type PersonDress,+ type CartLook,+ type Load,+ type Emphasis+} from "../art.ts"+import { kinds, GROWN, ROCK_AMOUNT, type KindId } from "../content.ts"+import { U, type Point } from "../iso.ts"+import { vertex3 } from "../asset-lab/renderer.ts"+import { Drawing, type Vertex } from "../asset-lab/primitives.ts"+import { makeSails, makeFlag } from "../asset-lab/buildings.ts"+import { makeMarker } from "../asset-lab/construction.ts"+import { makePerson } from "../asset-lab/people.ts"+import { makeTree, makeRock, makeField, hash } from "../asset-lab/land.ts"+import { ModelHandle } from "./pool.ts"+import { buildingAsset, homeAsset, homeKey, doorKey, noDoors, quantizeBuild, plateAsset, treeVariant } from "./models.ts"+import type { GameScene, SceneNode } from "./scene.ts"++export class WorldView implements SceneNode {+ readonly group = new THREE.Group()+ readonly anchor = { x: 0, y: 0 }+ readonly stage: GameScene+ readonly entity: number+ protected models: Array<ModelHandle> = []+ private disposed = false+ private opacity = 1+ constructor(stage: GameScene, entity: number) {+ this.stage = stage+ this.entity = entity+ }+ 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)+ return model+ }+ get alpha() {+ return this.opacity+ }+ set alpha(value: number) {+ this.opacity = value+ for (const m of this.models) m.alpha = value+ }+ orient() {}+ protected emphasis(emphasis: Emphasis) {+ for (const m of this.models) m.tint.setHex(emphasis === "danger" ? 0xf3b5aa : 0xffffff)+ }+ destroy() {+ if (this.disposed) return+ this.disposed = true+ for (const m of this.models) m.dispose()+ this.group.removeFromParent()+ this.stage.remove(this)+ }+}++export class BuildingView extends WorldView {+ private kindId: KindId+ private body: ModelHandle+ private plate: ModelHandle+ private marker: ModelHandle+ private motion: ModelHandle+ private smokes: Array<ModelHandle>+ private rings: Array<number> = []+ private puff = 0+ private wave = 0+ private opening = 0+ private beat = -1+ private pulse = 0+ constructor(kindId: KindId, stage: GameScene, entity: number) {+ super(stage, entity)+ this.kindId = kindId+ this.body = this.model()+ this.plate = this.model()+ this.marker = this.model()+ this.motion = this.model()+ this.marker.use("problem-marker", makeMarker)+ this.marker.root.visible = false+ this.body.root.add(this.motion.root)+ this.smokes = [this.model(false), this.model(false), this.model(false)]+ for (const s of this.smokes) s.root.visible = false+ }+ 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]))+ }+ update(look: BuildingLook, dt: number, emphasis: Emphasis) {+ const kind = kinds[this.kindId],+ build = quantizeBuild(look.build),+ doors = { ...noDoors, ...look.doors },+ share = look.site === null ? null : Math.round(look.site * 3) / 3+ if (this.beat >= 0 && look.beat > this.beat) this.pulse = 1+ this.beat = look.beat+ this.pulse = Math.max(0, this.pulse - dt * 3)+ this.opening += (Number(look.working || this.pulse > 0.2) - this.opening) * Math.min(1, dt * 6)+ const open = Math.round(this.opening * 4) / 4+ this.body.use(`building/${this.kindId}/${build}/${share}/${doorKey(doors)}/${open}`, () =>+ buildingAsset(this.kindId, build, share, doors, open)+ )+ this.plate.use(`plate/${kind.size}/${build}`, () => plateAsset(kind.size, build))+ this.body.root.scale.set(1 + this.pulse * 0.04, 1 - this.pulse * 0.06, 1 + this.pulse * 0.04)+ const H = kind.roof === "gable" ? 20 : kind.stories * 32+ this.marker.root.position.set(+ 0,+ (H ++ (kind.topper === "chimney" ? 24 : kind.topper === "cupola" ? 25 : kind.topper === "flag" ? 24 : kind.topper === "sails" ? 16 : 0) ++ 8) /+ Math.cos(Math.PI / 6),+ 0+ )+ this.marker.root.visible = look.problem && look.build >= 1+ this.motion.root.visible = look.build >= 1 && (kind.topper === "flag" || kind.topper === "sails")+ if (kind.topper === "flag") {+ this.wave += dt * (look.working ? 6 : 3)+ this.motion.use("flag/" + this.kindId, () => makeFlag(this.kindId))+ const a = kind.half * U,+ 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.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.rotation.x = this.wave+ }+ this.puff -= dt+ if (look.working && kind.topper === "chimney" && look.build >= 1 && this.puff <= 0) {+ this.rings.push(0)+ if (this.rings.length > 3) this.rings.shift()+ this.puff = 0.7+ }+ this.rings = this.rings.map((age) => age + dt / 1.8).filter((age) => age < 1)+ const a = kind.half * U,+ pitch = (2 * a) / kind.bays,+ u = -a + pitch * 0.5,+ v = -a + pitch * 0.5+ this.smokes.forEach((smoke, i) => {+ const t = this.rings[i]+ smoke.root.visible = t !== undefined+ if (t === undefined) return+ const r = Math.round(4 + t * 7)+ smoke.use("smoke-ring/" + r, () => {+ const d = new Drawing("smoke-ring", "Smoke", "")+ d.line(+ Array.from({ length: 25 }, (_, j): Vertex => [+ (Math.cos((j / 24) * Math.PI * 2) * r) / 64,+ (-Math.cos((j / 24) * Math.PI * 2) * r) / 64,+ Math.sin((j / 24) * Math.PI * 2) * r+ ]),+ 1,+ 0x3d4943,+ 0.55+ )+ return d.asset+ })+ smoke.alpha = 1 - t+ smoke.root.position.copy(vertex3([u + (Math.sin(t * 5) * 1.5) / 64, v - (Math.sin(t * 5) * 1.5) / 64, H + 24 + t * 34]))+ })+ this.emphasis(emphasis)+ }+ override orient() {+ this.marker.root.rotation.y = this.stage.heading - Math.PI / 4+ for (const smoke of this.smokes) smoke.root.rotation.y = this.stage.heading - Math.PI / 4+ }+}++export class HouseView extends WorldView {+ private body: ModelHandle+ private plate: ModelHandle+ private n = 0.03+ constructor(stage: GameScene, entity: number) {+ super(stage, entity)+ this.body = this.model()+ this.plate = this.model()+ }+ place(x: number, y: number) {+ 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]))+ }+ update(look: HouseLook, emphasis: Emphasis) {+ const build = quantizeBuild(look.build),+ share = look.site === null ? null : Math.round(look.site * 3) / 3,+ doors = { ...noDoors, ...look.doors }+ this.body.use(`home/${look.tier}/${homeKey(this.n)}/${build}/${share}/${doorKey(doors)}`, () =>+ homeAsset(look.tier, this.n, build, share, doors)+ )+ this.plate.use(`plate/1/${build}`, () => plateAsset(1, build))+ this.emphasis(emphasis)+ }+}++export class TreeView extends WorldView {+ private body: ModelHandle+ private variant = treeVariant(0, 0)+ constructor(stage: GameScene, entity: number) {+ super(stage, entity)+ this.body = this.model()+ }+ 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.anchor.x = x + 0.5+ this.anchor.y = y + 0.5+ this.group.position.copy(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,+ v = this.variant+ this.body.use(`tree/${v.id}/${stage}`, () => makeTree(v.type, stage, "tree", { ...v.seed, segments: 32 }))+ this.emphasis(emphasis)+ }+}+export class RockView extends WorldView {+ private body: ModelHandle+ constructor(stage: GameScene, entity: number) {+ super(stage, entity)+ this.body = this.model()+ }+ 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]))+ }+ update(ore: boolean, amount: number) {+ const full = amount > ROCK_AMOUNT / 2+ this.body.use(`rock/${ore}/${full}`, () => makeRock(ore, full))+ }+}+export class FieldView extends WorldView {+ private body: ModelHandle+ constructor(stage: GameScene, entity: number) {+ super(stage, entity)+ this.body = this.model()+ }+ 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]))+ }+ update(growth: number) {+ const stage = Math.min(3, Math.floor((growth / GROWN.field) * 3)) as 0 | 1 | 2 | 3+ this.body.use("field/" + stage, () => makeField(stage))+ }+}++export class WalkerView extends WorldView {+ private body: ModelHandle+ private dress: PersonDress+ private cart: CartLook | null+ private faithDress: PersonDress | null = null+ private currentDress: PersonDress | null = null+ constructor(stage: GameScene, entity: number, dress: PersonDress, cart: CartLook | null) {+ super(stage, entity)+ this.dress = dress+ this.cart = cart+ this.body = this.model(false)+ }+ static forFigure(role: "carrier" | "walker", color: number, stage: GameScene, entity: number) {+ const n = hash(entity, 7)+ const view = new WalkerView(+ stage,+ entity,+ role === "carrier" ? carrierDress(n) : serviceDress(color, n, false),+ role === "carrier" ? cartLook(hash(entity, 31)) : null+ )+ if (role === "walker") view.faithDress = serviceDress(color, n, true)+ return view+ }+ update(x: number, y: number, dir: Point, phase: number, load: Load) {+ const dress = load.kind === "bell" && this.faithDress ? this.faithDress : this.dress+ // Costume colours vary per person without duplicating the same geometry.+ const canonicalDress = { ...dress, coat: 0xff0001, skin: 0xff0003, trim: dress.trim === 0xf7f8f4 ? dress.trim : 0xff0002 },+ canonicalCart = this.cart ? { ...this.cart, wood: { top: 0xff0004, left: 0xff0005, right: 0xff0006 } } : null+ if (this.currentDress !== dress) {+ this.currentDress = dress+ this.body.colors = new Map([[0xff0001, dress.coat], [0xff0002, dress.trim], [0xff0003, dress.skin],+ [0xff0004, this.cart?.wood.top ?? 0], [0xff0005, this.cart?.wood.left ?? 0], [0xff0006, this.cart?.wood.right ?? 0]])+ }+ const visualLoad = load.kind === "cart" ? { ...load, count: load.count >= 4 ? 4 : load.count >= 2 ? 2 : load.count > 0 ? 1 : 0 } : load+ const key = JSON.stringify([canonicalDress, canonicalCart, phase, visualLoad])+ this.body.use("walker/" + key, () => {+ const asset = makePerson("walker", "Walker", canonicalDress, visualLoad, canonicalCart, phase)+ const shadow = new Drawing("shadow", "Shadow", "")+ shadow.face(+ Array.from({ length: 24 }, (_, i): Vertex => {+ const t = (i / 24) * Math.PI * 2,+ sx = Math.cos(t) * 2.8,+ sy = Math.sin(t)+ return [sx / 64 + sy / 32, -sx / 64 + sy / 32, -0.02]+ }),+ 0xe3e6de,+ 0+ )+ asset.faces.push(...shadow.asset.faces)+ return asset+ })+ this.group.position.copy(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/schema.ts b/src/schema.tsindex 620749a..b944bc7 100644--- a/src/schema.ts+++ b/src/schema.ts@@ -15,7 +15,8 @@ import { Decode, Descriptor, Schema } from "@typeonce/bevy-ts"import type { OptionalReadCell } from "@typeonce/bevy-ts/Query"import type { NodeRegistry } from "@typeonce/bevy-ts-render"-import type { BuildingView, FieldView, HouseView, RockView, Stage, TreeView, WalkerView } from "./art.ts"+import type { BuildingView, FieldView, HouseView, RockView, TreeView, WalkerView } from "./render3d/views.ts"+import type { GameScene } from "./render3d/scene.ts"import { goodIds, kindIds, landIds, sizeIds, type Amounts } from "./content.ts"import type { UiValue } from "./ui.ts"@@ -273,7 +274,7 @@ export const Stock = Descriptor.TransientResource<Amounts>()("Town/Stock")export const Ui = Descriptor.Service<UiValue>()("Town/Ui")/** The frame's length, for animation only: the simulation runs on `Time`. */export const Clock = Descriptor.Service<{ deltaSeconds: number; elapsed: number }>()("Town/Clock")-export const StageService = Descriptor.Service<Stage>()("Town/Stage")+export const StageService = Descriptor.Service<GameScene>()("Town/Stage")export const BuildingNodes = Descriptor.Service<NodeRegistry.NodeRegistry<BuildingView>>()("Town/BuildingNodes")export const HouseNodes = Descriptor.Service<NodeRegistry.NodeRegistry<HouseView>>()("Town/HouseNodes")export const WalkerNodes = Descriptor.Service<NodeRegistry.NodeRegistry<WalkerView>>()("Town/WalkerNodes")diff --git a/src/townsfolk.ts b/src/townsfolk.tsindex 0c02279..c1e6f21 100644--- a/src/townsfolk.ts+++ b/src/townsfolk.ts@@ -4,9 +4,9 @@* `residentDress`). They are only for looking at: not part of the* simulation, not saved, and they do nothing to the town.*/-import type { Container } from "pixi.js"--import { homeAt, residentDress, WalkerView } from "./art.ts"+import { homeAt, residentDress } from "./art.ts"+import { WalkerView } from "./render3d/views.ts"+import type { GameScene } from "./render3d/scene.ts"import type { Tier } from "./content.ts"import { DIRS, doors, isRoad } from "./grid.ts"import { U, type Point } from "./iso.ts"@@ -43,11 +43,11 @@ const MOST = 40const PACE = 0.7export class Townsfolk {- private readonly layer: Container+ private readonly layer: GameSceneprivate folk: Array<Stroller> = []private wait = 0- constructor(layer: Container) {+ constructor(layer: GameScene) {this.layer = layer}@@ -98,13 +98,20 @@ export class Townsfolk {if (out.length === 0) returnconst start = out[Math.floor(Math.random() * out.length)]!const n = Math.random()- const view = new WalkerView(residentDress(homeAt(h.x, h.y).cloth, h.tier, n), null)+ const view = new WalkerView(this.layer, 0, residentDress(homeAt(h.x, h.y).cloth, h.tier, n), null)view.alpha = 0- this.layer.addChild(view)+ this.layer.add(view)const cell = { x: start.x, y: start.y }this.folk.push({- view, cell, prev: null, next: this.onward(cell, null, grid), t: 0, left: 6 + Math.floor(Math.random() * 14),- pace: PACE * (h.tier === 2 ? 0.85 : 1) * (0.85 + n * 0.3), side: (4 + Math.round(n)) * U, fade: 0+ view,+ cell,+ prev: null,+ next: this.onward(cell, null, grid),+ t: 0,+ left: 6 + Math.floor(Math.random() * 14),+ pace: PACE * (h.tier === 2 ? 0.85 : 1) * (0.85 + n * 0.3),+ side: (4 + Math.round(n)) * U,+ fade: 0})}diff --git a/src/ui.ts b/src/ui.tsindex fc88439..b8464c6 100644--- a/src/ui.ts+++ b/src/ui.ts@@ -35,10 +35,10 @@ export type Edit =export type TradeMode = "sell" | "buy" | "none"-/** What the pointer did, in world pixels. */+/** What the pointer did, in grid coordinates. */export type Gesture =| { readonly type: "press"; readonly at: Point }- | { readonly type: "release"; readonly at: Point; readonly panned: boolean }+ | { readonly type: "release"; readonly at: Point; readonly panned: boolean; readonly hit?: number | null }export type Look = "hover" | "picked" | "blocked" | "reach"@@ -64,25 +64,25 @@ export type Panel =| { readonly type: "build" }| { readonly type: "town" }| {- readonly type: "building"- readonly id: number- readonly cell: Point- readonly kind: KindId- readonly status: Status- /** Why it is not working, when it is not. */- readonly problem: string | null- /** Whether it can be paused (not the town hall, not a site), and whether it is. */- readonly pausable: boolean- readonly paused: boolean- readonly lines: ReadonlyArray<string>- }+ readonly type: "building"+ readonly id: number+ readonly cell: Point+ readonly kind: KindId+ readonly status: Status+ /** Why it is not working, when it is not. */+ readonly problem: string | null+ /** Whether it can be paused (not the town hall, not a site), and whether it is. */+ readonly pausable: boolean+ readonly paused: boolean+ readonly lines: ReadonlyArray<string>+ }| {- readonly type: "house"- readonly id: number- readonly cell: Point- readonly tier: Tier- readonly lines: ReadonlyArray<string>- }+ readonly type: "house"+ readonly id: number+ readonly cell: Point+ readonly tier: Tier+ readonly lines: ReadonlyArray<string>+ }/** A thing's hit area for the pointer, nearest first. */export interface HitBox {@@ -157,7 +157,14 @@ export interface Stats {}readonly goals: ReadonlyArray<{ readonly text: string; readonly value: string; readonly met: boolean }>readonly larder: number- readonly history: ReadonlyArray<{ readonly tick: number; readonly coins: number; readonly residents: number; readonly citizens: number; readonly approval: number; readonly net: number }>+ readonly history: ReadonlyArray<{+ readonly tick: number+ readonly coins: number+ readonly residents: number+ readonly citizens: number+ readonly approval: number+ readonly net: number+ }>readonly chronicle: ReadonlyArray<{ readonly tick: number; readonly text: string }>}@@ -167,8 +174,10 @@ export interface UiValue {placing: KindId | null/** Which side panel the toolbar opened, when nothing is selected. */menu: "build" | "town" | null- /** The pointer in world pixels, or `null` off the canvas. */+ /** The pointer on the grid, or `null` off the canvas. */pointer: Point | null+ /** Camera-ray entity hit. Undefined allows grid-only headless interaction. */+ pointerHit?: number | null/** Where a road or a row of homes being dragged started. */dragFrom: Point | nullselected: number | null@@ -177,7 +186,7 @@ export interface UiValue {preview: Previewhits: ReadonlyArray<HitBox>panel: Panel | null- /** Where each building and home stands (world pixels), for the camera to look at. */+ /** Where each building and home stands on the grid, for the camera to look at. */centres: ReadonlyMap<number, Point>stats: Stats | null/** Steps of the simulation a fixed step: 0 (paused), 1, 2, or 4. */diff --git a/test/ink-assets.test.ts b/test/ink-assets.test.tsnew file mode 100644index 0000000..e63e85c--- /dev/null+++ b/test/ink-assets.test.ts@@ -0,0 +1,51 @@+import assert from "node:assert/strict"+import { test } from "node:test"+import { inkAssets, assetById } from "../src/asset-lab/assets.ts"+import { kindIds, goodIds, kinds } from "../src/content.ts"+import { testMap } from "../src/map-lab/map.ts"++test("the portable catalogue covers all world object families", () => {+ assert.equal(assetById.size, inkAssets.length, "Asset IDs must be unique")+ for (const id of kindIds) {+ const a = assetById.get(id)!+ assert.equal(a.reference?.type, "building", id)+ assert.equal(a.footprint, kinds[id].size, id)+ }+ for (const good of goodIds) {+ assert.ok(assetById.has(`goods-${good}`))+ assert.ok(assetById.has(`crate-${good}`))+ for (const vehicle of ["cart", "barrow"]) for (const count of [1, 4]) assert.ok(assetById.has(`${vehicle}-${good}-${count}`))+ }+ const hats = new Set(inkAssets.flatMap((a) => (a.reference?.type === "walker" ? [a.reference.dress.hat] : [])))+ assert.deepEqual([...hats].sort(), ["bonnet", "brim", "cap", "hood", "none", "top"])+ for (const tier of [1, 2]) assert.equal(inkAssets.filter((a) => a.reference?.type === "house" && a.reference.tier === tier).length, 4)+ assert.equal(inkAssets.filter((a) => a.reference?.type === "tree").length, 9)+ assert.equal(inkAssets.filter((a) => a.reference?.type === "rock").length, 4)+ assert.equal(inkAssets.filter((a) => a.reference?.type === "field").length, 4)+})++test("all geometry is finite, nondegenerate and uses valid ink weights", () => {+ for (const a of inkAssets) {+ assert.ok(a.faces.length + a.strokes.length > 0, a.id)+ for (const face of a.faces) {+ assert.ok(face.points.length >= 3, a.id)+ for (const p of face.points) assert.ok(p.every(Number.isFinite), a.id)+ const [a0, b, c] = face.points as [readonly number[], readonly number[], readonly number[], ...unknown[]]+ const ab = b.map((n, i) => n - a0[i]!),+ ac = c.map((n, i) => n - a0[i]!)+ const cross = [ab[1]! * ac[2]! - ab[2]! * ac[1]!, ab[2]! * ac[0]! - ab[0]! * ac[2]!, ab[0]! * ac[1]! - ab[1]! * ac[0]!]+ assert.ok(Math.hypot(...cross) > 1e-10, `${a.id}: zero-area face`)+ }+ for (const stroke of a.strokes) {+ assert.ok(stroke.width >= 0 && Number.isFinite(stroke.width), a.id)+ assert.ok(stroke.opacity >= 0 && stroke.opacity <= 1, a.id)+ for (const p of stroke.points) assert.ok(p.every(Number.isFinite), a.id)+ }+ }+})++test("the review map includes every catalogue model at least once", () => {+ const represented = new Set(testMap.buildings.map((p) => p.asset))+ assert.deepEqual([...represented].sort(), inkAssets.map((a) => a.id).sort())+ assert.equal(testMap.coverage, inkAssets.length)+})diff --git a/test/render3d.test.ts b/test/render3d.test.tsnew file mode 100644index 0000000..c74a14d--- /dev/null+++ b/test/render3d.test.ts@@ -0,0 +1,84 @@+import assert from "node:assert/strict"+import { test } from "node:test"+import * as THREE from "three"+import { kindIds } from "../src/content.ts"+import { Drawing, type InkAsset } from "../src/asset-lab/primitives.ts"+import { buildingAsset, homeAsset, noDoors, treeVariant } from "../src/render3d/models.ts"+import { ModelHandle, ModelPool } from "../src/render3d/pool.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`)+ }+ for (const stroke of asset.strokes) assert.ok(stroke.points.every(p => p.every(Number.isFinite)), asset.id)+}++test("live construction and fitting are valid for every building and both home tiers", () => {+ for (const build of [0, 0.125, 0.3, 0.55, 0.77, 0.78, 0.8, 0.9, 1]) {+ for (const kind of kindIds) for (const side of Object.keys(noDoors)) {+ valid(buildingAsset(kind, build, 0.5, { ...noDoors, [side]: true }, 0.5))+ }+ for (const tier of [1, 2] as const) valid(homeAsset(tier, 0.62, build, 1, { ...noDoors, backLeft: true }))+ }+})++test("shared geometry retains independent colours, transforms and entity picking", () => {+ const pool = new ModelPool(), root = new THREE.Group()+ let built = 0+ const create = () => {+ built+++ const d = new Drawing("box", "Box", "")+ d.box(0, 0, 0.1, 0.1, 0, 5, 0xff0001, 0xff0001, 0xff0001)+ return d.asset+ }+ const a = new ModelHandle(pool, 17), b = new ModelHandle(pool, 29)+ root.add(a.root, b.root)+ b.root.position.x = 30+ a.colors = new Map([[0xff0001, 0x89aabb]])+ b.colors = new Map([[0xff0001, 0x663311]])+ a.use("box", create)+ b.use("box", create)+ 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)+ assert.ok(hit)+ assert.equal(hit.object.userData.handles[hit.instanceId!].entity, 29)+ b.dispose()+ pool.flush()+ assert.equal(fill.count, 1)+ a.dispose()+ for (let i = 0; i < 100; i++) {+ a.use(`state/${i}`, create)+ pool.flush()+ }+ assert.ok(pool.stats().templates <= 65, "Idle animation/construction states must not accumulate")+ pool.dispose()+})++test("a seeded forest uses a bounded set of variants and preserves cell offsets", () => {+ const variants = new Set<string>()+ for (let y = 0; y < 64; y++) for (let x = 0; x < 64; x++) {+ const v = treeVariant(x, y)+ variants.add(v.id)+ assert.ok(v.scale > 0.8 && v.scale < 1.25)+ assert.ok(v.offset.every(Number.isFinite))+ }+ assert.ok(variants.size <= 34)+})