A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Simplify park statue and animate fountain water
SandroMaglione2002e6179771
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.mdindex fc56fad..f0e5fe4 100644--- a/DEVELOPMENT.md+++ b/DEVELOPMENT.md@@ -68,24 +68,24 @@ and elevation controls also work with a keyboard. The original view uses a| Collection | Entries | Coverage || --- | ---: | --- |-| Buildings | 42 | Every building kind, plus winter and worn material presets of the seven town services and stores |+| Buildings | 37 | Every building kind, plus winter and worn material presets of the seven town services and stores || Homes | 21 | Four settler and citizen roof palettes, townhouse, and fine/poor/worn/winter material presets of every tier |-| Land | 20 | Trees, rocks, crops, roads, water and raised stone paving |+| Land | 24 | Trees, rocks, crops, roads, water, raised stone paving, three retained park furnishings and the park layout || People | 32 | Carriers, residents, market and chapel walkers, and five equipped service workers || Cargo and vehicles | 75 | Twelve distinct goods and labelled crates; empty handcart/barrow and small/full loads of each good; the approved mixed goods plate || Construction and effects | 14 | Sites, frame/walls, problem sign, smoke, placement outlines and three kinds of ruin |-The 204 entries cover object families and representative seeded variants.+The 203 entries cover object families and representative seeded variants.Continuous growth, construction progress, walk poses and colours can begenerated; this is not a list of every possible random seed. Page iconsremain the game's original 2D UI art.-`pnpm assets:build` exports 204 GLBs and editable geometry descriptions,-a manifest, and four standalone viewers to `output/inkline-3d/`:+`pnpm assets:build` exports 203 GLBs and editable geometry descriptions,+a manifest, and five standalone viewers to `output/inkline-3d/`:`inkline-3d-study.html`, `inkline-3d-map.html`, and-`inkline-town-model-review.html`, and `inkline-house-effects.html`. It reimports every GLB and+`inkline-town-model-review.html`, `inkline-house-effects.html`, and `inkline-park.html`. It reimports every GLB andchecks geometry and unlit materials. The viewers work without a dev server;their optional web fonts use the network. The game build remains separate.Material effects render in the viewers and live game. Ordinary GLB viewers@@ -117,7 +117,7 @@ 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 204 entries and links to its original+forest. Inspect selects any of the 203 entries and links to its originaldrawing comparison. Eight additional people walk along the street using twoprocedural poses; pause them for review. Smoke and the problem sign facethe camera so they stay readable when the map turns.@@ -197,6 +197,15 @@ same instanced renderer and effect code.The original 2D menu drawings remain in `art.ts` for comparison. The live3D town uses the new geometry, including equipped service workers and curedfish cargo. The game has no audio, so winter music is outside this model work.++Open `/park-lab.html` for a park assembled from 25 cells using the current+park layout system, with two street entrances. The three retained furnishings+are lamps, fountains and statues. The statue is a simple bust and pedestal;+`render3d/fountain-effects.ts` supplies moving droplets and impact ripples in+the actual basin. Park rendering in the game, catalogue, map and preview shares+the same emitter metadata and water renderer. `pnpm check:park` verifies the+rendered animation, pause, camera controls and phone layout, and captures stills+and a five-second MP4 in `output/inkline-3d/park-review/`.- `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/package.json b/package.jsonindex f627426..ac1076c 100644--- a/package.json+++ b/package.json@@ -14,6 +14,7 @@"check:models": "node scripts/check-town-models.ts","check:effects": "node scripts/check-house-effects.ts","check:revisions": "node scripts/check-model-revisions.ts",+ "check:park": "node scripts/check-park.ts","test": "node --test \"test/*.test.ts\"","release": "pnpm --dir deploy release"},diff --git a/park-lab.html b/park-lab.htmlnew file mode 100644index 0000000..38e7d5b--- /dev/null+++ b/park-lab.html@@ -0,0 +1 @@+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="/favicon.svg"><title>Inkline Town · Park review</title></head><body><main id="park-lab"></main><script type="module" src="/src/park-lab/main.ts"></script></body></html>diff --git a/scripts/check-model-revisions.ts b/scripts/check-model-revisions.tsindex c5f7b29..61e11d9 100644--- a/scripts/check-model-revisions.ts+++ b/scripts/check-model-revisions.ts@@ -2,6 +2,7 @@ import assert from "node:assert/strict"import { existsSync } from "node:fs"import { mkdir, writeFile } from "node:fs/promises"import { chromium } from "playwright"+import { inkAssets } from "../src/asset-lab/assets.ts"const executablePath=process.env.BROWSER_EXECUTABLE_PATH??["/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"].find(existsSync)const browser=await chromium.launch({headless:true,...(executablePath?{executablePath}:{})})@@ -31,7 +32,7 @@ try{assert.notEqual(first,next,"Smoke must animate in the actual GPU rendering")await writeFile(`${output}/smoke.png`,Buffer.from(next.split(",")[1],"base64"))const count=await page.evaluate(()=>{const lab=(window as any).inkLab;for(const a of lab.assets){lab.select(a.id);assertGeometry(lab.stats().triangles,a.id)}function assertGeometry(n:number,id:string){if(n<=0)throw new Error(`${id}: empty render`)}return lab.assets.length})- assert.equal(count,204)+ assert.equal(count,inkAssets.length)assert.deepEqual(errors,[])console.log(JSON.stringify({catalogueModels:count,markerViews:[0,180],animatedSmoke:true,browserErrors:errors}))}finally{await browser.close()}diff --git a/scripts/check-park.ts b/scripts/check-park.tsnew file mode 100644index 0000000..eb83798--- /dev/null+++ b/scripts/check-park.ts@@ -0,0 +1,44 @@+import assert from "node:assert/strict"+import { existsSync } from "node:fs"+import { mkdir,writeFile } from "node:fs/promises"+import { execFileSync } from "node:child_process"+import { chromium } from "playwright"++declare global {interface Window {parkLab:{capture:(time?:number,width?:number,height?:number)=>string;pause:()=>void;stats:()=>{view:string;yaw:number;pitch:number;time:number;frames:number;fountains:number;parkCells:number;entrances:number;triangles:number}}}}+const executablePath=process.env.BROWSER_EXECUTABLE_PATH??["/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"].find(existsSync)+const browser=await chromium.launch({headless:true,...(executablePath?{executablePath}:{})}),page=await browser.newPage({viewport:{width:1440,height:1100},deviceScaleFactor:2})+const output="output/inkline-3d/park-review",errors:string[]=[]+page.on("pageerror",e=>errors.push(e.message));page.on("console",m=>{if(m.type()==="error")errors.push(m.text())});page.on("response",r=>{if(r.status()>=400)errors.push(`${r.status()} ${r.url()}`)})+await mkdir(`${output}/frames`,{recursive:true})+const save=async(name:string,time=2)=>{const data=await page.evaluate(t=>window.parkLab.capture(t),time);await writeFile(`${output}/${name}.png`,Buffer.from(data.split(",")[1]!,"base64"));return data}+try{+ await page.goto(`${process.env.GAME_BASE_URL??"http://127.0.0.1:5232"}/park-lab.html`)+ await page.waitForFunction(()=>window.parkLab?.stats().frames>2)+ await page.evaluate(()=>window.parkLab.pause())+ const stats=await page.evaluate(()=>window.parkLab.stats())+ assert.equal(stats.parkCells,25);assert.equal(stats.entrances,2);assert.equal(stats.fountains,1);assert.ok(stats.triangles>0)+ assert.equal(await page.locator(".stage canvas").evaluate(c=>Math.round(c.getBoundingClientRect().width)),await page.locator(".stage").evaluate(c=>c.clientWidth),"Canvas CSS size must fit at high DPI")+ const front=await save("park")+ await page.getByRole("button",{name:"See the back",exact:true}).click();assert.notEqual(await save("park-rear"),front)+ await page.getByRole("button",{name:"Reset view",exact:true}).click()+ await page.getByLabel("Park elevation").selectOption("55");await save("park-above")+ await page.getByRole("button",{name:"Reset view",exact:true}).click()+ await page.getByRole("button",{name:"Statue close-up",exact:true}).click();await save("statue")+ await page.getByRole("button",{name:"See the back",exact:true}).click();await save("statue-rear")+ await page.getByRole("button",{name:"Reset view",exact:true}).click()+ await page.getByRole("button",{name:"Fountain close-up",exact:true}).click()+ const a=await save("fountain",0),b=await save("fountain",1)+ assert.notEqual(a,b,"Actual rendered fountain pixels must animate")+ const now=await page.evaluate(()=>window.parkLab.stats())+ await page.waitForFunction(f=>window.parkLab.stats().frames>f+4,now.frames)+ assert.equal(await page.evaluate(()=>window.parkLab.stats().time),now.time,"Pausing must freeze the water")+ for(let i=0;i<150;i++){+ const image=await page.evaluate(t=>window.parkLab.capture(t,800,650),i/30)+ await writeFile(`${output}/frames/${String(i).padStart(4,"0")}.png`,Buffer.from(image.split(",")[1]!,"base64"))+ }+ execFileSync("ffmpeg",["-y","-loglevel","error","-framerate","30","-i",`${output}/frames/%04d.png`,"-c:v","libx264","-crf","19","-pix_fmt","yuv420p","-movflags","+faststart",`${output}/fountain.mp4`])+ await page.getByRole("button",{name:"Built park",exact:true}).click();await page.screenshot({path:`${output}/page.png`})+ await page.setViewportSize({width:390,height:844});assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));await page.screenshot({path:`${output}/phone.png`})+ assert.deepEqual(errors,[])+ console.log(JSON.stringify({parkCells:stats.parkCells,entrances:stats.entrances,fountains:stats.fountains,videoFrames:150,phoneLayout:true,browserErrors:errors}))+}finally{await browser.close()}diff --git a/scripts/ink-assets.ts b/scripts/ink-assets.tsindex e279843..7d2ef21 100644--- a/scripts/ink-assets.ts+++ b/scripts/ink-assets.ts@@ -31,6 +31,7 @@ for (const asset of inkAssets) {const imported = await loader.parseAsync(glb, "")if(asset.effects&&!imported.scene.getObjectByName(asset.id)?.userData.inklineSurfaceEffects)throw new Error(`${asset.id}: surface state metadata lost on export`)if(asset.smokeEffect&&!imported.scene.getObjectByName(asset.id)?.userData.inklineSmokeEffect)throw new Error(`${asset.id}: smoke emitter metadata lost on export`)+ if(asset.fountains?.length&&!imported.scene.getObjectByName(asset.id)?.userData.inklineFountains)throw new Error(`${asset.id}: fountain metadata lost on export`)let meshes = 0,vertices = 0imported.scene.traverse((object) => {@@ -54,6 +55,7 @@ for (const asset of inkAssets) {category: asset.category,effects: asset.effects,smokeEffect: asset.smokeEffect,+ fountains: asset.fountains,glb: `models/${asset.id}.glb`,geometry: `models/${asset.id}.json`,bytes: glb.byteLength,@@ -68,7 +70,8 @@ for (const [input, directory, filename] of [["asset-lab.html", "viewer", "inkline-3d-study.html"],["map-lab.html", "map-viewer", "inkline-3d-map.html"],["model-review.html", "town-viewer", "inkline-town-model-review.html"],- ["effects-lab.html", "effects-viewer", "inkline-house-effects.html"]+ ["effects-lab.html", "effects-viewer", "inkline-house-effects.html"],+ ["park-lab.html", "park-viewer", "inkline-park.html"]]) {await build({configFile: false,diff --git a/src/asset-lab/main.ts b/src/asset-lab/main.tsindex 5db5f0f..ee4be30 100644--- a/src/asset-lab/main.ts+++ b/src/asset-lab/main.ts@@ -12,12 +12,15 @@ import {drawSite,drawRoads,drawWater,+ drawParkPiece,homeVariant,plate,plateHalf} from "../art.ts"import { kinds, goods } from "../content.ts"import { key } from "../grid.ts"+import { samplePark } from "./town-props.ts"+import type { PropId } from "../content.ts"import { drawPlot } from "../art.ts"import { U, toScreen } from "../iso.ts"import { inkAssets, assetCategoryTitles, type InkAsset } from "./assets.ts"@@ -54,6 +57,12 @@ await pixi.init({ width: 32, height: 32, antialias: true, resolution: 3, backgrofunction original(asset: InkAsset) {const g = new Graphics()+ if(asset.id.startsWith("park-")){+ if(asset.id==="park-sample")for(const c of samplePark){+ const p=toScreen(c.x-2,c.y-2);g.translateTransform(p.x,p.y);drawParkPiece(g,c.prop==="none"?c.ground:c.prop);g.resetTransform()+ }else drawParkPiece(g,asset.id.slice(5) as PropId)+ return g+ }const r = asset.referenceif (r) {switch (r.type) {@@ -225,7 +234,7 @@ function render() {if (!width || !height) returnconst ref = references.get(selected.id)!const model = models.get(selected.id)!- const effectBounds=selected.smokeEffect?new THREE.Box3().setFromObject(model.group):null+ const effectBounds=selected.smokeEffect||selected.fountains?.length?new THREE.Box3().setFromObject(model.group):nullconst vertical = Math.max(40, ref.height * 1.45, ((ref.width * height) / width) * 1.3, effectBounds?effectBounds.getSize(new THREE.Vector3()).y*1.45:0) / zoomrenderer.setSize(width, height, false)camera.left = (-vertical * width) / height / 2@@ -409,7 +418,7 @@ Object.assign(window, {})select(new URLSearchParams(location.search).get("asset") ?? selected.id)let effectFrame=0-const animateEffect=()=>{if(selected.smokeEffect)render();effectFrame=requestAnimationFrame(animateEffect)}+const animateEffect=()=>{if(selected.smokeEffect||selected.fountains?.length)render();effectFrame=requestAnimationFrame(animateEffect)}effectFrame=requestAnimationFrame(animateEffect)if (import.meta.hot)import.meta.hot.dispose(() => {diff --git a/src/asset-lab/primitives.ts b/src/asset-lab/primitives.tsindex f29b9b7..1bd7e10 100644--- a/src/asset-lab/primitives.ts+++ b/src/asset-lab/primitives.ts@@ -33,6 +33,7 @@ export type AssetReference =| { type: "roads" | "water" }| { type: "none" }export interface InkAsset {+ fountains?: Array<{ origin: Vertex; radius: number; level: number; nozzle: number }>smokeEffect?: { origin: Vertex }effects?: { half: number; height: number; state: SurfaceState }appearance?: "fine" | "poor" | "worn" | "winter"diff --git a/src/asset-lab/renderer.ts b/src/asset-lab/renderer.tsindex 8b7c247..04a2850 100644--- a/src/asset-lab/renderer.ts+++ b/src/asset-lab/renderer.ts@@ -8,6 +8,7 @@ import { mergeGeometries, mergeVertices } from "three/addons/utils/BufferGeometrimport { palette, type Face, type InkAsset, type Vertex } from "./primitives.ts"import { installSurfaceShader } from "../render3d/surface-shader.ts"import { SmokePlume } from "../render3d/smoke-effects.ts"+import { FountainWater } from "../render3d/fountain-effects.ts"/** A 30° elevation and 45° heading reproduce the game's 64×32 projection.* The vertical conversion preserves pixel-authored building heights exactly. */@@ -302,8 +303,11 @@ export function buildAsset(asset: InkAsset, options: { batchFaces?: boolean; mes}const plume=asset.smokeEffect&&options.surfaceEffects!==false?new SmokePlume():nullif(plume){plume.group.position.copy(vertex3(asset.smokeEffect!.origin));group.add(plume.group);plume.update(0)}+ const fountains=options.surfaceEffects!==false?(asset.fountains??[]).map(f=>new FountainWater(f)):[]+ for(const fountain of fountains)group.add(fountain.group)const dispose = () => {plume?.dispose()+ fountains.forEach(f=>f.dispose())group.traverse((object) => {if (object instanceof THREE.Mesh) object.geometry.dispose()})@@ -313,7 +317,7 @@ export function buildAsset(asset: InkAsset, options: { batchFaces?: boolean; mesif (hull) (hull.material as THREE.Material).dispose()for (const object of group.children) if (object instanceof LineSegments2) object.geometry.dispose()}- return { group, lineMaterials, updateContours, updateEffects: time => { effectTime.value = time;plume?.update(time) }, dispose }+ return { group, lineMaterials, updateContours, updateEffects: time => { effectTime.value = time;plume?.update(time);fountains.forEach(f=>f.update(time)) }, dispose }}/** GLB uses ordinary meshes for ink strokes so the outlines survive import.@@ -323,6 +327,7 @@ export async function exportAsset(asset: InkAsset) {group.name = asset.idif(asset.effects)group.userData.inklineSurfaceEffects=asset.effectsif(asset.smokeEffect)group.userData.inklineSmokeEffect=asset.smokeEffect+ if(asset.fountains?.length)group.userData.inklineFountains=asset.fountainsfor (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) : nulldiff --git a/src/asset-lab/town-props.ts b/src/asset-lab/town-props.tsindex 0ad95a0..84675fa 100644--- a/src/asset-lab/town-props.ts+++ b/src/asset-lab/town-props.ts@@ -44,32 +44,35 @@ export function setts(d: Drawing, x: number, y: number, half: number, z: number)}}-const figure = (d: Drawing, u: number, v: number, z: number) => {- d.box(u, v, 3.3 * U, 3.3 * U, z - 6, 2)- d.box(u, v, 2.5 * U, 2.5 * U, z - 4, 7, stone, 0xd5d9d0, 0xbec5bb)- d.face([[u + 2.51 * U, v - U, z - 2], [u + 2.51 * U, v + U, z - 2], [u + 2.51 * U, v + U, z + 1], [u + 2.51 * U, v - U, z + 1]], 0xc1af81, 0.75)- for (const x of [-0.7, 0.7]) d.cylinder(u + x * U, v, 0.55 * U, z + 3, 5, 0xaebbb0, 0xc9d2c7, 0.75, 8)- d.ellipsoid(u, v, z + 11, 1.7 * U, 1.3 * U, 4, 0xaebbb0, 1, 0xc9d2c7, 12)- d.ellipsoid(u, v, z + 16.3, 1.1 * U, 1.1 * U, 1.8, 0xc9d2c7, 1, undefined, 12)- d.cylinder(u, v, 1.7 * U, z + 17.2, 0.5, 0xaebbb0, 0xc9d2c7, 0.75, 12)- d.line([[u - 1.2 * U, v, z + 13], [u - 2.4 * U, v, z + 10], [u - 2.4 * U, v, z + 7]], 2, 0xaebbb0)- d.box(u - 2.4 * U, v, U, 0.5 * U, z + 6, 3, 0xc9d2c7, 0xaebbb0, 0x9daa9f, 1)- d.line([[u + 1.2 * U, v, z + 13], [u + 2.8 * U, v, z + 14], [u + 2.8 * U, v, z + 20]], 2, 0xaebbb0)- d.face([[u + 2.8 * U, v, z + 19], [u + 5 * U, v, z + 17], [u + 2.8 * U, v, z + 16]], 0xc9d2c7, 1)+const figure = (d: Drawing, u: number, v: number) => {+ d.box(u, v, 2.4 * U, 2.4 * U, 1.5, 6.5, stone, 0xd5d9d0, 0xbec5bb, 1)+ const ring=(width:number,depth:number,z:number):Vertex[]=>[[u-width,v-depth,z],[u+width,v-depth,z],[u+width,v+depth,z],[u-width,v+depth,z]]+ const bottom=ring(1.4*U,U,8), shoulders=ring(2.1*U,1.1*U,12.5)+ for(let i=0;i<4;i++)d.face([bottom[i]!,bottom[(i+1)%4]!,shoulders[(i+1)%4]!,shoulders[i]!],i<2?0xc9d2c7:0xe2e6dc,1)+ d.face(shoulders,0xe2e6dc,1)+ d.cylinder(u,v,0.45*U,12.5,1.3,0xc9d2c7,0xc9d2c7,0,8)+ d.ellipsoid(u,v,16.5,U,0.9*U,3,0xc9d2c7,0.8,0xe2e6dc,8)}-/** A fountain's basin, column, and jets, centred on (u, v). */+/** A simple stone basin. Running water is supplied by the shared effects renderer. */function fountain(d: Drawing, u: number, v: number) {- d.cylinder(u, v, 5.5 * U, 0, 4, 0xdfe3dc, water, 1, 16)- d.cylinder(u, v, 1.2 * U, 4, 7, 0xdfe3dc, stone, 1, 10)- d.cylinder(u, v, 2.5 * U, 11, 2, 0xdfe3dc, water, 1, 12)- d.cylinder(u, v, 4.6 * U, 4.03, 0.2, water, 0xd8e8ee, 0.75, 24)- d.ellipsoid(u, v, 15, U, U, 1.8, stone, 1, undefined, 12)- for (let i = 0; i < 4; i++) {- const a = i * Math.PI / 2- d.line(Array.from({ length: 9 }, (_, j): Vertex => { const t = j / 8; return [u + Math.cos(a) * (1 + 3 * t) * U, v + Math.sin(a) * (1 + 3 * t) * U, 13 + 2 * Math.sin(t * Math.PI) - 8 * t] }), 1, 0x8faebd)+ const n=16, outer=5.5*U, inner=4.5*U+ const ring=(r:number,z:number)=>Array.from({length:n},(_,i):Vertex=>[u+Math.cos(i*Math.PI*2/n)*r,v+Math.sin(i*Math.PI*2/n)*r,z])+ d.cylinder(u,v,5.8*U,0,1,0xd5d9d0,stone,1,n)+ const low=ring(outer,1),rim=ring(outer,4),inside=ring(inner,4),bed=ring(inner,1)+ for(let i=0;i<n;i++){+ const j=(i+1)%n+ d.face([low[i]!,low[j]!,rim[j]!,rim[i]!],0xd5d9d0,0)+ d.face([rim[i]!,rim[j]!,inside[j]!,inside[i]!],stone,0)+ d.face([inside[i]!,inside[j]!,bed[j]!,bed[i]!],0xbec5bb,0)}- for (const r of [2.5, 3.5]) d.line(Array.from({ length: 25 }, (_, i): Vertex => [u + Math.cos(i * Math.PI / 12) * r * U, v + Math.sin(i * Math.PI / 12) * r * U, 4.3]), 0.75, 0xa9c5d0)+ // Only the basin rims carry ink; water has no drawn guide curves.+ d.line([...rim,rim[0]!],1)+ d.line([...inside,inside[0]!],0.75)+ d.cylinder(u,v,4.4*U,2.6,0.15,water,0xd8e8ee,0,n)+ d.cylinder(u,v,U,2.75,7.5,0xd5d9d0,stone,1,8)+ d.cylinder(u,v,1.5*U,10.25,0.75,0xd5d9d0,stone,0.75,8)+ ;(d.asset.fountains??=[]).push({origin:[u,v,0],radius:4.4*U,level:2.75,nozzle:11})}/** An iron lamp post with a lantern. */@@ -85,8 +88,8 @@ function lamp(d: Drawing, u: number, v: number) {export function parkProp(d: Drawing, prop: PropId, u: number, v: number) {if (prop === "lamp") lamp(d, u + 4 * U, v - 4 * U)else if (prop === "statue") {- d.box(u, v, 4.5 * U, 4.5 * U, 0, 2, 0xe9ebe5, 0xd5d9d0, 0xbec5bb, 1)- figure(d, u, v, 8)+ d.box(u, v, 3.8 * U, 3.8 * U, 0, 1.5, 0xe9ebe5, 0xd5d9d0, 0xbec5bb, 1)+ figure(d, u, v)} else fountain(d, u, v)}@@ -147,6 +150,7 @@ export function parkAsset(cells: ReadonlyMap<number, ParkCell>, roads: ReadonlyS// A low stone kerb where the park ends.for (const { x: dx, y: dy } of DIRS) {if (isPark(x + dx, y + dy)) continue+ if ((c.ground==="path"||c.ground==="square")&&roads.has(key(x+dx,y+dy))) continueconst q = (along: number, across: number): Vertex => [u + dx * along - dy * across, v + dy * along + dx * across, z]const centre = q(0.47, 0)d.box(centre[0], centre[1], dx ? 0.03 : 0.5, dy ? 0.03 : 0.5, z, 1.2, 0xeceee8, 0xd7dbd2, 0xc9cec4, 0.75)@@ -163,9 +167,10 @@ export function makeParkProp(prop: PropId) {const shift = ([u, v, z]: Vertex): Vertex => [u - 0.5, v - 0.5, z]asset.faces.forEach((f) => { f.points = f.points.map(shift) })asset.strokes.forEach((s) => { s.points = s.points.map(shift) })+ asset.fountains?.forEach(f=>{f.origin=shift(f.origin)})asset.id = `park-${prop}`asset.title = `Park · ${props[prop].title.toLowerCase()}`- asset.note = props[prop].blurb+ asset.note = prop==="statue"?"A simple stone bust on a plain pedestal, readable at the town's scale.":prop==="fountain"?"A stone basin with running water and soft surface ripples.":props[prop].blurbasset.category = "land"asset.reference = { type: "none" }asset.footprint = 1@@ -195,6 +200,7 @@ export function makeSamplePark() {const shift = ([u, v, z]: Vertex): Vertex => [u - 2.5, v - 2.5, z]asset.faces.forEach((f) => { f.points = f.points.map(shift) })asset.strokes.forEach((s) => { s.points = s.points.map(shift) })+ asset.fountains?.forEach(f=>{f.origin=shift(f.origin)})asset.id = "park-sample"asset.title = "Park · laid out"asset.note = "A five-by-five park built piece by piece: lawn, a cross of walks, flower beds in the corners, lamps, a fountain, and a statue on paved squares."diff --git a/src/map-lab/main.ts b/src/map-lab/main.tsindex 609d4c5..0fd2f6e 100644--- a/src/map-lab/main.ts+++ b/src/map-lab/main.ts@@ -274,6 +274,8 @@ renderer.setAnimationLoop((now) => {f.updateContours(camera)})}+ map.updateEffects(elapsed)+ effects.forEach(e=>e.updateEffects(elapsed))renderer.render(scene, camera)})const resizeObserver = new ResizeObserver(resize)diff --git a/src/map-lab/map.ts b/src/map-lab/map.tsindex 2111334..30917b6 100644--- a/src/map-lab/map.ts+++ b/src/map-lab/map.ts@@ -78,6 +78,7 @@ function place(id: string, x: number, y: number, scale = 1, record = true, heighconst 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>()+ for(const fountain of asset.fountains??[])(town.fountains??=[]).push({...fountain,origin:transform(fountain.origin),radius:fountain.radius*scale,level:fountain.level*scale,nozzle:fountain.nozzle*scale})const effect = id === "smoke" || id === "problem-marker"if (effect) effects.push({ asset: id, x, y, height })for (const polygon of asset.faces) {diff --git a/src/model-review/main.ts b/src/model-review/main.tsindex 62b14a7..21b8232 100644--- a/src/model-review/main.ts+++ b/src/model-review/main.ts@@ -18,7 +18,7 @@ const root = document.querySelector<HTMLElement>("#review")!root.innerHTML = `<header><a href="/">Inkline Town</a><span>PR 03 / MODEL REVIEW</span><a href="/map-lab.html">Town map ↗</a></header><section class="intro"><div><p class="eyebrow">A town with a little more life</p><h1>New places.<br>The same ink.</h1><p>Inspect the models together, turn them around, then open any one for a closer look.</p></div><aside>7 buildings<br>3 park furnishings<br>3 home tiers<br><span>Plus people, hazards, paving,<br>snow and signs of wear.</span></aside></section><nav aria-label="Model collections"></nav><section class="camera"><label>Turn the models <input aria-label="Model rotation" type="range" min="-180" max="180" value="0"><output>0°</output></label><button id="rear">See the back</button><button id="reset">Reset view</button><button id="sheet">Save model sheet</button><a id="sheet-link" hidden download>Download sheet ↗</a><label>View <select aria-label="View elevation"><option value="30">Street angle</option><option value="50">From above</option><option value="15">Near the ground</option></select></label></section>- <section class="grid" aria-label="3D models"></section><footer><a href="/effects-lab.html">Animated house effects ↗</a> · Drag a model to turn the collection · <a href="/asset-lab.html">Full asset catalogue ↗</a> · <a href="/">Play this town ↗</a></footer>`+ <section class="grid" aria-label="3D models"></section><footer><a href="/park-lab.html">Built park & running water ↗</a> · <a href="/effects-lab.html">Animated house effects ↗</a> · Drag a model to turn the collection · <a href="/asset-lab.html">Full asset catalogue ↗</a> · <a href="/">Play this town ↗</a></footer>`const nav = root.querySelector("nav")!, grid = root.querySelector<HTMLElement>(".grid")!, rotation = root.querySelector<HTMLInputElement>("input")!, elevation = root.querySelector<HTMLSelectElement>("select")!const renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true, preserveDrawingBuffer: true })renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); renderer.outputColorSpace = THREE.SRGBColorSpace@@ -115,7 +115,7 @@ addEventListener("scroll", schedule, {passive: true}); addEventListener("resize"const query = new URLSearchParams(location.search).get("collection")select(query && query in families ? query as Family : "buildings")let effectFrame=0-const animateEffects=()=>{if(families[family].ids.some(id=>assetById.get(id)?.smokeEffect))render();effectFrame=requestAnimationFrame(animateEffects)}+const animateEffects=()=>{if(families[family].ids.some(id=>assetById.get(id)?.smokeEffect||assetById.get(id)?.fountains?.length))render();effectFrame=requestAnimationFrame(animateEffects)}effectFrame=requestAnimationFrame(animateEffects)Object.assign(window, { townModelReview: { stats: () => ({ family, models: models.length, renders, yaw, pitch }) } })if (import.meta.hot) import.meta.hot.dispose(() => { cancelAnimationFrame(effectFrame);models.forEach(m => m.built.dispose()); renderer.dispose(); renderer.domElement.remove(); removeEventListener("scroll", schedule); removeEventListener("resize", schedule) })diff --git a/src/park-lab/main.ts b/src/park-lab/main.tsnew file mode 100644index 0000000..5f570b4--- /dev/null+++ b/src/park-lab/main.ts@@ -0,0 +1,53 @@+import * as THREE from "three"+import { assetById } from "../asset-lab/assets.ts"+import { buildAsset, type BuiltAsset } from "../asset-lab/renderer.ts"+import { builtPark, parkCells, parkSummary } from "./park.ts"+import "./style.css"++const assets={park:builtPark(),fountain:assetById.get("park-fountain")!,statue:assetById.get("park-statue")!}+type View=keyof typeof assets+const root=document.querySelector<HTMLElement>("#park-lab")!+root.innerHTML=`<header><a href="/model-review.html?collection=ornaments">Inkline Town · Parks</a><a href="/asset-lab.html?asset=park-sample">Full catalogue ↗</a></header><section class="intro"><h1>A park, piece by piece.</h1><p>Lawn, flower beds and walks connect two street entrances. A quiet fountain and a simple stone bust give the park its centre.</p></section><nav aria-label="Park review views"><button data-view="park" aria-pressed="true">Built park</button><button data-view="fountain" aria-pressed="false">Fountain close-up</button><button data-view="statue" aria-pressed="false">Statue close-up</button></nav><section class="controls"><label>Turn <input aria-label="Park rotation" type="range" min="-180" max="180" value="0"><output>0°</output></label><label>View <select aria-label="Park elevation"><option value="30">Street angle</option><option value="55">From above</option><option value="15">Near the ground</option></select></label><button id="rear">See the back</button><button id="pause">Pause water</button><button id="reset">Reset view</button></section><section class="stage" aria-label="Rendered park"></section><footer><div><h2 id="title"></h2><p id="note"></p></div><span id="summary">25 park cells · 2 entrances · 3 lamps</span></footer>`+const stage=root.querySelector<HTMLElement>(".stage")!,renderer=new THREE.WebGLRenderer({alpha:true,antialias:true,preserveDrawingBuffer:true}),scene=new THREE.Scene(),camera=new THREE.OrthographicCamera(-100,100,100,-100,0.1,4000)+renderer.setPixelRatio(Math.min(devicePixelRatio,2));renderer.setClearColor(0xf0f2ec,0);renderer.outputColorSpace=THREE.SRGBColorSpace;stage.append(renderer.domElement)+let view:View="park",yaw=0,pitch=30,time=0,paused=false,last=0,frames=0,built:BuiltAsset|null=null,bounds=new THREE.Box3()+function aim(width:number,height:number){+ const target=bounds.getCenter(new THREE.Vector3()),heading=(45+yaw)*Math.PI/180,altitude=pitch*Math.PI/180+ camera.position.copy(target).add(new THREE.Vector3(Math.sin(heading)*Math.cos(altitude),Math.sin(altitude),Math.cos(heading)*Math.cos(altitude)).multiplyScalar(1000));camera.lookAt(target);camera.updateMatrixWorld(true)+ let x=1,y=1+ for(const u of [bounds.min.x,bounds.max.x])for(const v of [bounds.min.y,bounds.max.y])for(const z of [bounds.min.z,bounds.max.z]){+ const p=new THREE.Vector3(u,v,z).applyMatrix4(camera.matrixWorldInverse);x=Math.max(x,Math.abs(p.x));y=Math.max(y,Math.abs(p.y))+ }+ const half=Math.max(y,x*height/width)*1.12+ camera.top=half;camera.bottom=-half;camera.left=-half*width/height;camera.right=-camera.left;camera.updateProjectionMatrix()+ built!.updateContours(camera)+}+function draw(width=stage.clientWidth,height=stage.clientHeight){+ renderer.setSize(width,height,false);aim(width,height);built!.updateEffects(time);renderer.render(scene,camera);frames+++}+function select(next:View){+ built?.group.removeFromParent();built?.dispose();view=next;built=buildAsset(assets[view],{batchFaces:true});scene.add(built.group);bounds=new THREE.Box3().setFromObject(built.group)+ root.querySelectorAll<HTMLButtonElement>("nav button").forEach(b=>b.setAttribute("aria-pressed",String(b.dataset.view===view)))+ root.querySelector("#title")!.textContent=view==="park"?"Twenty-five cells, one park":view==="fountain"?"Running water":"A founder in stone"+ root.querySelector("#note")!.textContent=view==="park"?assets.park.note:view==="fountain"?"Water rises from the column, falls into the basin and makes soft ripples.":"A head, shoulders and pedestal. The silhouette stays clear at the game's scale."+ root.querySelector<HTMLElement>("#summary")!.hidden=view!=="park";draw()+ history.replaceState(null,"",`?view=${view}`)+}+function capture(t=time,width=960,height=700){+ time=t;renderer.setPixelRatio(1);renderer.setClearAlpha(1);draw(width,height);const image=renderer.domElement.toDataURL();renderer.setClearAlpha(0);renderer.setPixelRatio(Math.min(devicePixelRatio,2));draw();return image+}+root.querySelectorAll<HTMLButtonElement>("nav button").forEach(b=>b.onclick=()=>select(b.dataset.view as View))+root.querySelector<HTMLInputElement>("input")!.oninput=e=>{yaw=Number((e.target as HTMLInputElement).value);root.querySelector("output")!.textContent=`${yaw}°`;draw()}+root.querySelector<HTMLSelectElement>("select")!.onchange=e=>{pitch=Number((e.target as HTMLSelectElement).value);draw()}+root.querySelector<HTMLButtonElement>("#rear")!.onclick=()=>{yaw=yaw===180?0:180;root.querySelector<HTMLInputElement>("input")!.value=String(yaw);root.querySelector("output")!.textContent=`${yaw}°`;draw()}+root.querySelector<HTMLButtonElement>("#reset")!.onclick=()=>{yaw=0;pitch=30;root.querySelector<HTMLInputElement>("input")!.value="0";root.querySelector<HTMLSelectElement>("select")!.value="30";root.querySelector("output")!.textContent="0°";draw()}+root.querySelector<HTMLButtonElement>("#pause")!.onclick=e=>{paused=!paused;(e.target as HTMLButtonElement).textContent=paused?"Resume water":"Pause water"}+let drag:{x:number;yaw:number}|null=null+stage.onpointerdown=e=>{drag={x:e.clientX,yaw};stage.setPointerCapture(e.pointerId)}+stage.onpointermove=e=>{if(drag){yaw=((drag.yaw+(e.clientX-drag.x)*0.4+540)%360)-180;root.querySelector<HTMLInputElement>("input")!.value=String(yaw);root.querySelector("output")!.textContent=`${Math.round(yaw)}°`;draw()}}+stage.onpointerup=stage.onpointercancel=()=>{drag=null}+const initial=new URLSearchParams(location.search).get("view")+select(initial&&Object.hasOwn(assets,initial)?initial as View:"park")+renderer.setAnimationLoop(now=>{if(!paused&&last)time+=Math.min((now-last)/1000,0.1);last=now;draw()})+Object.assign(window,{parkLab:{capture,pause:()=>{paused=true},stats:()=>({view,yaw,pitch,time,frames,fountains:assets[view].fountains?.length??0,parkCells:parkCells.length,entrances:parkSummary.entrances,triangles:renderer.info.render.triangles})}})+if(import.meta.hot)import.meta.hot.dispose(()=>{renderer.setAnimationLoop(null);built?.dispose();renderer.dispose()})diff --git a/src/park-lab/park.ts b/src/park-lab/park.tsnew file mode 100644index 0000000..61ffa0f--- /dev/null+++ b/src/park-lab/park.ts@@ -0,0 +1,23 @@+import { samplePark, parkAsset } from "../asset-lab/town-props.ts"+import { groundAsset } from "../render3d/models.ts"+import { parksOf } from "../appeal.ts"+import { key } from "../grid.ts"+import type { InkAsset, Vertex } from "../asset-lab/primitives.ts"++// Place actual park cells beside two road entrances, inside the game's grid.+export const parkCells=samplePark.map(c=>({...c,x:c.x+28,y:c.y+28}))+export const parkRoads=new Set([key(30,27),...Array.from({length:7},(_,i)=>key(27+i,33))])+export const parkSummary=parksOf(parkCells,(x,y)=>parkRoads.has(key(x,y)))[0]!++export function builtPark(): InkAsset {+ const park=parkAsset(new Map(parkCells.map(c=>[key(c.x,c.y),c])),parkRoads)+ const roads=groundAsset(parkRoads,new Set())+ const shift=([u,v,z]:Vertex):Vertex=>[u-30.5,v-30.5,z]+ return {+ id:"park-built",title:"A park built cell by cell",category:"land",footprint:7,+ note:"Twenty-five cells of lawn, flower beds, gravel walks and paved squares, with two street entrances, three lamps, a fountain and a stone bust.",+ faces:[...park.faces,...roads.faces].map(f=>({...f,points:f.points.map(shift)})),+ strokes:[...park.strokes,...roads.strokes].map(s=>({...s,points:s.points.map(shift)})),+ fountains:(park.fountains??[]).map(f=>({...f,origin:shift(f.origin)}))+ }+}diff --git a/src/park-lab/style.css b/src/park-lab/style.cssnew file mode 100644index 0000000..0010ae6--- /dev/null+++ b/src/park-lab/style.css@@ -0,0 +1 @@+:root{font-family:system-ui,sans-serif;color:#3d4943;background:#f0f2ec;font-synthesis:none}*{box-sizing:border-box}body{margin:0}main{max-width:1320px;padding:28px 44px;margin:auto}header{display:flex;justify-content:space-between;gap:20px;font-size:13px;border-bottom:1px solid #cbd1c5;padding-bottom:22px}a{color:inherit;text-decoration:none}a:hover{text-decoration:underline}h1,h2{font-family:Georgia,serif;font-weight:500}h1{font-size:clamp(34px,4vw,54px);margin:24px 0 12px}.intro p{max-width:720px;font-size:16px;line-height:1.6;margin:0 0 24px}nav,.controls{display:flex;flex-wrap:wrap;align-items:center;gap:10px;padding:14px 0;border-top:1px solid #cbd1c5}button,select{font:inherit;font-size:13px;color:inherit;border:1px solid #b8c3b2;border-radius:4px;padding:9px 12px;background:#f5f6f2;cursor:pointer}button[aria-pressed=true]{color:#f5f6f2;background:#3d4943;border-color:#3d4943}button:hover{border-color:#3d4943}.controls{font-size:13px}.controls label{display:flex;gap:10px;align-items:center}.controls input{width:180px;accent-color:#65775d}output{min-width:38px}.stage{height:540px;background:#e9eee2;border:1px solid #cbd1c5;border-radius:6px;touch-action:none;cursor:grab;overflow:hidden}.stage:active{cursor:grabbing}.stage canvas{display:block;width:100%;height:100%}footer{display:flex;justify-content:space-between;gap:20px;margin-top:18px}footer h2{margin:0 0 7px;font-size:24px}footer p{max-width:780px;font-size:13px;line-height:1.6;margin:0}#summary{white-space:nowrap;font:12px ui-monospace,monospace;color:#68765f;padding-top:8px}@media(max-width:700px){main{padding:20px 16px}.stage{height:390px}footer{flex-direction:column;gap:10px}.controls input{width:110px}.controls button{padding:8px}header{font-size:12px}}diff --git a/src/render3d/fountain-effects.ts b/src/render3d/fountain-effects.tsnew file mode 100644index 0000000..566b7ef--- /dev/null+++ b/src/render3d/fountain-effects.ts@@ -0,0 +1,78 @@+import * as THREE from "three"+import type { InkAsset } from "../asset-lab/primitives.ts"++type Fountain = NonNullable<InkAsset["fountains"]>[number]+const floorScale=32*Math.SQRT2, heightScale=1/Math.cos(Math.PI/6)++const dropsVertex=`+attribute float waterPhase;+attribute float jetAngle;+uniform float time;+uniform float radius;+uniform float level;+uniform float nozzle;+varying float age;+varying float phase;+void main(){+ age=fract(time*0.85+waterPhase);phase=waterPhase;+ float distance=radius*0.84*age;+ float h=mix(nozzle,level,age)+4.0*age*(1.0-age)*6.9282;+ vec3 center=vec3(cos(jetAngle)*distance,h,sin(jetAngle)*distance);+ vec3 drop=position*vec3(0.8,1.7,0.8)+center;+ gl_Position=projectionMatrix*modelViewMatrix*vec4(drop,1.0);+}`+const dropsFragment=`+varying float age;+varying float phase;+void main(){+ float alpha=smoothstep(0.0,0.07,age)*(1.0-smoothstep(0.94,1.0,age))*0.68;+ vec3 color=mix(vec3(0.65,0.78,0.82),vec3(0.96,0.99,0.96),fract(phase*13.0));+ gl_FragColor=vec4(pow(color,vec3(2.2)),alpha);+ #include <colorspace_fragment>+}`+const poolVertex=`+uniform float radius;+varying vec2 poolPoint;+void main(){poolPoint=position.xz/radius;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);}+`+const poolFragment=`+uniform float time;+varying vec2 poolPoint;+void main(){+ float waves=0.0;+ for(int i=0;i<4;i++){+ float a=float(i)*1.5707963+0.7853982;+ float d=length(poolPoint-vec2(cos(a),sin(a))*0.84);+ waves+=pow(max(0.0,sin(d*28.0-time*6.0)),14.0)*exp(-d*7.0);+ }+ float edge=1.0-smoothstep(0.96,1.0,length(poolPoint));+ float shimmer=sin(poolPoint.x*17.0+time)*sin(poolPoint.y*13.0-time*0.7)*0.015;+ gl_FragColor=vec4(pow(vec3(0.94,0.98,0.97),vec3(2.2)),edge*(0.025+waves*0.28+shimmer));+ #include <colorspace_fragment>+}`++/** Flowing droplets and impact ripples, constrained to the actual stone basin. */+export class FountainWater {+ readonly group=new THREE.Group()+ private time={value:0}+ private drops: THREE.InstancedMesh<THREE.SphereGeometry,THREE.ShaderMaterial>+ private pool: THREE.Mesh<THREE.CircleGeometry,THREE.ShaderMaterial>+ constructor(fountain: Fountain) {+ const r=fountain.radius*floorScale, level=fountain.level*heightScale, nozzle=fountain.nozzle*heightScale+ this.group.position.set(fountain.origin[0]*floorScale,fountain.origin[2]*heightScale,fountain.origin[1]*floorScale)+ const count=64,geometry=new THREE.SphereGeometry(0.34,6,4)+ geometry.setAttribute("waterPhase",new THREE.InstancedBufferAttribute(Float32Array.from({length:count},(_,i)=>Math.floor(i/4)/16),1))+ geometry.setAttribute("jetAngle",new THREE.InstancedBufferAttribute(Float32Array.from({length:count},(_,i)=>i%4*Math.PI/2+Math.PI/4),1))+ geometry.boundingBox=new THREE.Box3(new THREE.Vector3(-r,level-1,-r),new THREE.Vector3(r,nozzle+7,r))+ geometry.boundingSphere=new THREE.Sphere(new THREE.Vector3(0,(level+nozzle)/2,0),r+nozzle+7)+ const material=new THREE.ShaderMaterial({vertexShader:dropsVertex,fragmentShader:dropsFragment,uniforms:{time:this.time,radius:{value:r},level:{value:level},nozzle:{value:nozzle}},transparent:true,depthWrite:false,depthTest:true})+ this.drops=new THREE.InstancedMesh(geometry,material,count)+ for(let i=0;i<count;i++)this.drops.setMatrixAt(i,new THREE.Matrix4())+ this.drops.frustumCulled=false;this.drops.renderOrder=3;this.group.add(this.drops)+ const poolGeometry=new THREE.CircleGeometry(r,32);poolGeometry.rotateX(-Math.PI/2)+ const poolMaterial=new THREE.ShaderMaterial({vertexShader:poolVertex,fragmentShader:poolFragment,uniforms:{time:this.time,radius:{value:r}},transparent:true,depthWrite:false,depthTest:true,side:THREE.DoubleSide})+ this.pool=new THREE.Mesh(poolGeometry,poolMaterial);this.pool.position.y=level+0.07;this.pool.renderOrder=2;this.group.add(this.pool)+ }+ update(time: number){this.time.value=time}+ dispose(){this.group.removeFromParent();this.drops.geometry.dispose();this.drops.material.dispose();this.drops.dispose();this.pool.geometry.dispose();this.pool.material.dispose()}+}diff --git a/src/render3d/scene.ts b/src/render3d/scene.tsindex 846cae9..0938c77 100644--- a/src/render3d/scene.ts+++ b/src/render3d/scene.ts@@ -275,6 +275,8 @@ export class GameScene {for (const node of this.nodes) node.orient()this.camera.getWorldDirection(this.pool.viewDirection).negate()this.pool.time.value = now / 1000+ this.parks?.updateEffects(now/1000)+ this.parkPreview?.updateEffects(now/1000)this.pool.flush()this.renderer.render(this.scene, this.camera)this.frames++diff --git a/vite.config.ts b/vite.config.tsindex ca7ec93..581efd7 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -9,7 +9,8 @@ export default defineConfig({assets: "asset-lab.html",map: "map-lab.html",models: "model-review.html",- effects: "effects-lab.html"+ effects: "effects-lab.html",+ parks: "park-lab.html"}}}