diff --git a/README.md b/README.md index 3811db6..c295a23 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ on an opaque package. This repository holds one such registry. ![The whole kit in one scene](media/kit.png) -38 models and one shared library, **32,798 triangles** for the whole kit — less +37 models and one shared library, **30,390 triangles** for the whole kit — less than a single medium-detail character. Every one is procedural source you own and edit, not an asset you load. @@ -137,8 +137,8 @@ viewer.html?showcase=60 # 30, 60 and 90 are offered ``` **60 s is the default**, and the reason is arithmetic: the tour splits its -running time equally between the models, so across 38 of them a 30 s run gives -each 0.79 seconds — a flyby, not a demonstration — while 60 s gives 1.6 s and +running time equally between the models, so across 37 of them a 30 s run gives +each 0.81 seconds — a flyby, not a demonstration — while 60 s gives 1.6 s and 90 s gives 2.4 s. That first number moves every time a model is added, which is worth saying out @@ -194,7 +194,6 @@ scripts/ render.ts offline software rasteriser → PNG contact sheet check-docs.ts documented counts against the models themselves reference-shots.ts one photographic reference per model, for comparison - probe-tree.ts measures the oak against its reference photographs catalog-table.ts regenerates the model table in the registry README export-glb.ts batch GLB export media/ diff --git a/REFERENCE.md b/REFERENCE.md index b52a45a..ce3a31b 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -79,7 +79,7 @@ src/viewer.ts · src/viewer.css the model viewer (WebGPU, sky, shadow) src/catalog.ts the viewer's catalog — DERIVED from meta.ts src/glb.ts GLB export (shared by viewer and CLI) src/models/scifi-kit/pressure-gauge/ the installed sci-fi model -src/models/medieval-kit/… your OWN installed models (38 models) +src/models/medieval-kit/… your OWN installed models (37 models) my-registry/ meta.ts the SINGLE source of catalog metadata build.ts the registry.json generator @@ -338,7 +338,7 @@ the same, the physical package changes. ## 5. Lowpoly medieval — yes, no problem This is not an assumption: `@medieval-kit` works, is validated and currently -contains **38 models + 1 lib**. The table is generated from the models +contains **37 models + 1 lib**. The table is generated from the models themselves with `bun scripts/catalog-table.ts` — a hand-written list goes stale on the first model you add, and in fact it had gone stale once. @@ -381,9 +381,8 @@ on the first model you add, and in fact it had gone stale once. | `grindstone` | Smithy | 568 | 4 | 1.24×0.95×0.70 | stone, oak, iron, water | | | `market-stall` | Structure | 384 | 4 | 1.83×2.03×0.97 | oak, cloth | | | `post-mill` | Structure | 1672 | 4 | 6.60×7.23×6.98 | oak, iron | | -| `oak-tree` | Nature | 2408 | 3 | 7.71×7.00×9.10 | oak, leaf | | -**32,798 triangles** in total. The whole kit in one scene has a budget smaller +**30,390 triangles** in total. The whole kit in one scene has a budget smaller than a single medium-complexity character model. ### 5.1 One source: `my-registry/meta.ts` @@ -407,7 +406,7 @@ declaration means a hidden material the consumer cannot reach with this check was added it caught a real drift in four models (a `steel` slot had been added but not declared). -### 5.2 The material vocabulary — fourteen slots +### 5.2 The material vocabulary — thirteen slots | Slot | What | Why separate | | --- | --- | --- | @@ -423,7 +422,6 @@ been added but not declared). | `ember` | flame | `MeshBasicMaterial` — it does not receive light, it emits | | `char` | charcoal, pitch | — | | `stone` | dressed and rubble masonry | its color is close to weathered oak; what tells them apart at a glance is that stone scatters light completely flat, and roughness is not something vertex color can carry | -| `leaf` | living foliage | the most matte thing here after stone: any sheen at all and a crown reads as plastic shrubbery, which is the usual failure of a lowpoly tree and is a material setting rather than a modelling one | | `water` | standing water | a thin transparent film over whatever holds it: it works through opacity rather than through a colour of its own | `ember` also works as a rule in two places: bodies in this slot are skipped diff --git a/media/kit.png b/media/kit.png index 98e3c0f..c517e7d 100644 Binary files a/media/kit.png and b/media/kit.png differ diff --git a/media/models.png b/media/models.png index cb01ca0..023d384 100644 Binary files a/media/models.png and b/media/models.png differ diff --git a/models.lock.json b/models.lock.json index 30f2abe..908642b 100644 --- a/models.lock.json +++ b/models.lock.json @@ -82,7 +82,7 @@ "address": "@medieval-kit/core", "source": "file:my-registry/dist/registry.json", "version": "workspace", - "installedAt": "2026-08-27T07:04:40.383Z", + "installedAt": "2026-08-27T07:22:56.622Z", "files": [ { "path": "src\\models\\medieval-kit\\core\\geometry.ts", @@ -94,7 +94,7 @@ }, { "path": "src\\models\\medieval-kit\\core\\materials.ts", - "sourceHash": "1863cbe82d9cab014a6f83af57a5f647a2fb8d248759ffd1b5ae663e2b8ebac0" + "sourceHash": "178e0d3ef4e6f0e2496edf6439fbf8156ef94c49b61b060798e698a214469d41" }, { "path": "src\\models\\medieval-kit\\core\\random.ts", @@ -106,7 +106,7 @@ }, { "path": "src\\models\\medieval-kit\\core\\kit.ts", - "sourceHash": "bcaafdb326cc4478305b28524f7b1472598530380c71441f8f0570c27e42f99f" + "sourceHash": "a9b8c68353730652b9bb1cbaa33e04c36e88f8ac42ce77ff3af588bd2d3b6b99" }, { "path": "src\\models\\medieval-kit\\core\\tool.ts", @@ -628,21 +628,6 @@ "three@>=0.185.0" ] }, - "@medieval-kit/oak-tree": { - "address": "@medieval-kit/oak-tree", - "source": "file:my-registry/dist/registry.json", - "version": "workspace", - "installedAt": "2026-08-27T07:04:40.385Z", - "files": [ - { - "path": "src\\models\\medieval-kit\\oak-tree\\model.ts", - "sourceHash": "1f612e4fbb0da08294b4392c7da5fc07dc9b67f502aebbd437e46a665b14ce29" - } - ], - "dependencies": [ - "three@>=0.185.0" - ] - }, "@medieval-kit/stone-trough": { "address": "@medieval-kit/stone-trough", "source": "file:my-registry/dist/registry.json", diff --git a/my-registry/README.md b/my-registry/README.md index 883f5b6..3333190 100644 --- a/my-registry/README.md +++ b/my-registry/README.md @@ -28,7 +28,7 @@ Configure `models.json` first so the namespace resolves: ## Models -38 models and one shared lib. Addresses are `@medieval-kit/`. This table is +37 models and one shared lib. Addresses are `@medieval-kit/`. This table is generated from the models themselves with `bun scripts/catalog-table.ts` — a hand-written list goes stale on the first model you add, and this one already did once. @@ -72,9 +72,8 @@ did once. | `grindstone` | Smithy | 568 | 4 | 1.24×0.95×0.70 | stone, oak, iron, water | | | `market-stall` | Structure | 384 | 4 | 1.83×2.03×0.97 | oak, cloth | | | `post-mill` | Structure | 1672 | 4 | 6.60×7.23×6.98 | oak, iron | | -| `oak-tree` | Nature | 2408 | 3 | 7.71×7.00×9.10 | oak, leaf | | -**32 798 triangles** in total. The whole kit in one scene costs less than a +**30 390 triangles** in total. The whole kit in one scene costs less than a single mid-complexity character model. Every model depends on `@medieval-kit/core`, a shared support item holding the @@ -137,7 +136,7 @@ rebuilds topology and is not cheap. Anything that changes per frame belongs in ## Material slots -Fourteen slots, and each one exists because a single material could not carry the +Thirteen slots, and each one exists because a single material could not carry the difference. | Slot | What it covers | Why it is separate | @@ -153,7 +152,6 @@ difference. | `produce` | fruit and vegetable skin | given straw's roughness, an apple would look like dry grass | | `ember` | flame | `MeshBasicMaterial` — it does not receive light, it emits | | `char` | charcoal and pitch | — | -| `leaf` | living foliage | the most matte thing here after stone: any sheen at all and a crown reads as plastic shrubbery, which is the usual failure of a lowpoly tree and is a material setting rather than a modelling one | | `water` | standing water | a thin transparent film over whatever holds it: in the reference trough the basin reads hue 39.5, which is the hue of the STONE underneath, so it works through opacity rather than colour | | `stone` | dressed and rubble masonry | its colour is close to weathered oak; what separates them at a glance is that stone scatters light completely flat, and roughness is not something vertex colour can carry | diff --git a/my-registry/meta.ts b/my-registry/meta.ts index a2d7f47..cf86bd5 100644 --- a/my-registry/meta.ts +++ b/my-registry/meta.ts @@ -521,24 +521,6 @@ export const MODEL_META: Readonly> = { materialSlots: ['stone', 'water'], parts: ['block', 'water'], }, - 'oak-tree': { - title: 'Oak Tree', - description: - 'Free-standing oak with a flared bole, sweeping limbs and a broad low crown; turns from green to russet and can be stripped bare.', - category: 'Nature', - tags: ['medieval', 'lowpoly', 'nature', 'procedural'], - controls: { - height: { type: 'number', label: 'Height', min: 3, max: 12, step: 0.25, unit: 'm' }, - spread: { type: 'number', label: 'Crown spread', min: 0.6, max: 1.7, step: 0.05 }, - bole: { type: 'number', label: 'Bole thickness', min: 0.02, max: 0.06, step: 0.002 }, - limbs: { type: 'number', label: 'Primary limbs', min: 3, max: 14, step: 1 }, - leafiness: { type: 'number', label: 'Leafiness', min: 0, max: 1, step: 0.05 }, - autumn: { type: 'number', label: 'Autumn', min: 0, max: 1, step: 0.05 }, - seed: { type: 'number', label: 'Variation seed', min: 1, max: 64, step: 1 }, - }, - materialSlots: ['oak', 'leaf'], - parts: ['trunk', 'boughs', 'crown'], - }, 'forge-hearth': { title: 'Forge Hearth', description: diff --git a/my-registry/models/core/kit.ts b/my-registry/models/core/kit.ts index 98aac63..2945637 100644 --- a/my-registry/models/core/kit.ts +++ b/my-registry/models/core/kit.ts @@ -147,22 +147,6 @@ const MOTTLE_BY_SLOT: Readonly> = { // of a stone rather than of a grain. stone: 0.75, ember: 0, // a flame is not mottled: its colour is already the final colour - // Just under oak, and it started at 1.5 for a reason that turned out to be - // the straw trap wearing a different hat. - // - // The measurement was real: across one oak in full leaf the darkest tenth of - // the crown reads lightness 0.16 and the lightest 0.61, a spread of 0.45 and - // the widest of anything in this kit. What it does not say is that the - // spread has to come from HERE. Clump-to-clump tint, this mottle and the - // baked occlusion are three separate mechanisms all reproducing the same - // shadow, and stacked at full strength they went through the floor: 10.8% - // of the rendered crown clipped to pure black, against 0.01% of the - // photograph. A statistic taken off fine detail cannot be added on top of - // the machinery that already reproduces that detail -- which is the third - // time this kit has learned that, after straw's saturation and bark's value. - leaf: 0.95, - // Barely mottled. Ripples are a shape, not a stain, and a surface this - // smooth shows speckle as dirt floating on it. water: 0.2, } diff --git a/my-registry/models/core/materials.ts b/my-registry/models/core/materials.ts index ab1fff2..9037179 100644 --- a/my-registry/models/core/materials.ts +++ b/my-registry/models/core/materials.ts @@ -26,7 +26,6 @@ export type MedievalSlot = | 'ember' // flame — does not take light, it emits it | 'char' // charcoal, pitch | 'stone' // dressed and rubble masonry - | 'leaf' // living foliage | 'water' // standing water /** @@ -47,7 +46,6 @@ export interface SlotMaterial { readonly ember: MeshBasicMaterial readonly char: MeshStandardMaterial readonly stone: MeshStandardMaterial - readonly leaf: MeshStandardMaterial readonly water: MeshStandardMaterial } @@ -140,24 +138,6 @@ export interface MedievalPalette { */ readonly bark: Color - /** - * Foliage in flat overcast light, measured across 125 000 pixels of an oak - * in full leaf: hue 78, saturation 0.39, lightness 0.34. - * - * The measurement contradicted the thing I was about to build. I expected a - * strong top-to-bottom gradient across a crown -- lit above, dark below -- - * and was going to bake one in. Sampled in three bands the crown reads 0.362, - * 0.336 and 0.324: a spread of 0.04, which is nothing. Under an overcast sky - * there is no gradient to bake. - * - * What IS there is local: the darkest tenth of the crown sits at lightness - * 0.16 and the lightest tenth at 0.61, a spread of 0.45 within the same - * band. Foliage varies leaf to leaf, not top to bottom. So the variation - * belongs in the mottle and in per-clump jitter, and it is a value spread, - * not a hue one -- hue held between 77 and 81 degrees across every sample, - * lit and shadowed alike. - */ - readonly leaf: Color /** * Weathered limestone, which is NOT the same rock as `stone`. @@ -241,7 +221,6 @@ export const MEDIEVAL_PALETTE: MedievalPalette = { bark: new Color(0x585032), limestone: new Color(0x94846b), water: new Color(0x3b4e45), - leaf: new Color(0x6d8632), } /** @@ -377,19 +356,6 @@ export function createMedievalMaterials( roughness: 0.97, metalness: 0, }), - // Foliage is the most matte thing in the kit after stone. Any sheen at - // all and a crown reads as plastic shrubbery -- which is the failure mode - // of most lowpoly trees, and it is a material setting rather than a - // modelling one. It is a separate slot from `straw` despite similar - // numbers because `materialSlots` is a contract: a tree declaring straw - // would be telling the consumer it is made of dead grass. - leaf: () => new MeshStandardMaterial({ - name: 'medieval-kit / foliage', - color: 0xffffff, - vertexColors: true, - roughness: 0.93, - metalness: 0, - }), // Water is a THIN TRANSPARENT FILM, not a body of liquid. Everything in // this kit that holds water holds a few centimetres of it over a floor you // can see, so the colour that reaches the eye is mostly what is underneath diff --git a/my-registry/models/oak-tree/model.ts b/my-registry/models/oak-tree/model.ts deleted file mode 100644 index 2e13c55..0000000 --- a/my-registry/models/oak-tree/model.ts +++ /dev/null @@ -1,681 +0,0 @@ -/** - * @medieval-kit/oak-tree - * - * A free-standing oak: flared bole, sweeping limbs, a broad low crown. - * - * The kit had nothing growing in it at all. Every other model is something a - * person made, and a village of nothing but made things reads as a warehouse - * yard — so this is the first piece of the site rather than of the inventory, - * and it is also by some way the largest thing here. - * - * It was built against two reference photographs, and both of them contradicted - * what I was going to build. Worth writing down, because the default lowpoly - * tree — a tall bare pole with a ball on top — is wrong in every measurement - * that matters: - * - * - CROWN WIDTH / TREE HEIGHT = 1.32 to 1.43. An open-grown oak is HALF - * AGAIN as wide as it is tall. Nothing else in this kit is wider than it - * is tall, and getting this one number right is most of what makes the - * silhouette read as an oak rather than as a lollipop. - * - THE CROWN IS WIDEST AT 24% OF THE HEIGHT. Not halfway up, not at the - * top: a quarter of the way up, just above the ground. The lowest limbs - * are the longest ones and they leave the trunk almost horizontally. - * - THE TRUNK RUNS TO 72% OF THE HEIGHT before it stops being the widest - * single thing. It does not fork low into equal leaders, which is what I - * had assumed from the leafy photograph alone; the winter photograph shows - * one continuous bole with everything else hung off it. - * - THE FLARE IS SHARP AND SHORT. The trunk is 0.130 of the tree's height - * wide at 2% of the height and 0.073 at 10% — it nearly halves in the - * bottom tenth, then barely tapers at all through the next quarter. - * - * The limbs SWEEP. A branch leaves the trunk at a shallow angle and turns - * upward at its outer end, which is the profile a lowpoly tree most often - * misses, and it comes free here: `bendGeometry` on a limb built along its own - * axis, before it is rotated into place. - * - * The honest limit: what fills a real winter silhouette is thousands of twigs, - * and no triangle budget here reaches them. At `leafiness: 0` this is a bare - * tree of LIMBS, which is a fine dead or winter tree and is not a photograph - * of one. - */ -import { Color, type BufferGeometry } from 'three' - -import { - bendGeometry, - createKitModel, - createTinter, - jitter, - latheGeometry, - mergeColoured, - roughenGeometry, - type Level, -} from '../core/index.ts' - -export interface OakTreeConfig { - /** Height to the top of the crown (metres). */ - readonly height: number - /** Crown width as a multiple of the height. The reference oaks measure 1.32–1.43. */ - readonly spread: number - /** Radius of the clear bole, as a fraction of the height. */ - readonly bole: number - /** Primary limbs off the trunk. */ - readonly limbs: number - /** 0 leaves it bare; 1 is full summer leaf. */ - readonly leafiness: number - /** 0 is green, 1 turns the crown to russet and gold. */ - readonly autumn: number - readonly seed: number -} - -export const oakTreeDefaults: OakTreeConfig = { - height: 7, - spread: 1.3, - // 0.037, straight off the reference: the bole measured 0.073 of the tree's - // height ACROSS at the point where it has finished flaring. - // 0.046, not the reference's own 0.037. That number came off a photograph - // of a tree seen whole from a distance; at this size, with a crown of - // twenty masses sitting over it, a bole at 0.037 disappears entirely and - // what is left is a cabbage on a stick. The trunk has to read. - bole: 0.046, - limbs: 12, - leafiness: 1, - autumn: 0, - seed: 11, -} - -export type OakTreeParts = 'trunk' | 'boughs' | 'crown' - -export function createModel(overrides: Partial = {}) { - return createKitModel({ - id: 'oak-tree', - defaults: oakTreeDefaults, - slots: ['oak', 'leaf'], - - build: ({ config, random }) => { - const tint = createTinter(random) - const H = Math.max(0.5, config.height) - const R = Math.max(0.004, config.bole) * H - const crownR = (Math.max(0.2, config.spread) * H) / 2 - const leafiness = Math.max(0, Math.min(1, config.leafiness)) - const autumn = Math.max(0, Math.min(1, config.autumn)) - const limbCount = Math.max(3, Math.min(14, Math.round(config.limbs))) - - /** - * How far a limb turns from root to tip, in radians. - * - * It is an ANGLE rather than a curvature so that every limb turns by the - * same amount whatever its length: a short top limb and a long bottom - * one then read as the same tree. 0.42 rad is 24 degrees, which is what - * the reference's limbs do between leaving the bole and their outer end. - */ - const SWEEP = 0.42 - - /** - * The measured taper, as (height fraction, radius in bole radii). - * - * These are not shaped by eye. Each pair is a row read off the winter - * photograph by finding the run of trunk pixels at that height, and the - * profile they make is the whole character of the bole: a violent flare - * in the bottom twentieth, then a shaft that hardly tapers for a quarter - * of the tree, then a steady run out to nothing at 74%. - */ - const TAPER: ReadonlyArray = [ - [0.00, 1.95], - [0.02, 1.76], - [0.06, 1.14], - [0.11, 1.00], - [0.38, 0.94], - [0.50, 0.71], - [0.62, 0.50], - [0.74, 0.16], - ] - const trunkTop = H * TAPER[TAPER.length - 1]![0] - - /** The bole's radius at a height, so a limb can be sized to where it grows. */ - const boleAt = (y: number): number => { - const f = y / H - for (let i = 0; i < TAPER.length - 1; i += 1) { - const [f0, r0] = TAPER[i]! - const [f1, r1] = TAPER[i + 1]! - if (f <= f1) { - const t = (f - f0) / (f1 - f0) - return R * (r0 + (r1 - r0) * Math.max(0, Math.min(1, t))) - } - } - return R * TAPER[TAPER.length - 1]![1] - } - - /** - * Foliage colour. Green at `autumn` 0, russet and gold at 1. - * - * The turn is a HUE ROTATION of the same measured green rather than a - * second palette entry, because that is what happens in the leaf: the - * chlorophyll goes and what was already underneath it shows. Saturation - * climbs with it — an autumn oak is a more saturated object than a - * summer one, which is the opposite of what fading suggests. - */ - /** - * Clump to clump, the tone varies a LOT, and that is the whole depth of - * a lowpoly crown. - * - * At +/-0.09 every mass came out the same green and the crown read as - * one solid object with facet shading on it — a cabbage. The reference's - * crown varies by 0.45 in lightness WITHIN one band; a smooth mass - * cannot reproduce that at the leaf's scale, but it can carry it at the - * clump's, which is the only scale this budget has. What must NOT vary - * is hue: measured across the reference, lit and shadowed alike, it - * holds between 77 and 81 degrees. - * - * ASYMMETRIC, and that took a render to learn. A symmetric +/-0.19 put - * whole masses through the floor — not clipped pixels here and there but - * six or seven entirely black clumps, because the tint's own jitter, the - * mottle and the baked occlusion all pull the same way underneath it. It - * is also wrong about foliage: a lit mass is far brighter than the base - * green, while a shaded one is filled in by the sky and never gets that - * far below it. So the range is -0.03 to +0.23. - */ - const leafColour = (lift: number): Color => { - const c = tint('leaf', lift, 1) - // Darker clumps are MORE saturated, which is the measurement and is the - // opposite of the intuition that shadow drains colour: across the - // reference the darkest tenth of the crown reads 0.44 saturation and - // the lightest 0.32. A highlight on a leaf is a specular reflection of - // a white sky, and it washes the green out of it. - // -0.145 of a turn, which is 52 degrees, taking the measured green at - // 78 down to 26: RUSSET. The first attempt turned it 41 degrees to - // amber and lifted the lightness, and an oak came out of it the colour - // of a lemon. An oak in October is a dark red-brown -- it goes DOWN in - // value as well as round in hue, which is why the lightness term is - // negative here and was the thing that made the difference. - c.offsetHSL(-0.145 * autumn, -lift * 0.55 + 0.14 * autumn, -0.03 * autumn) - return c - } - - // --- The bole --------------------------------------------------------- - const trunk = latheGeometry( - TAPER.map(([f, r]) => ({ y: H * f, radius: R * r })) as Level[], - // Capped at BOTH ends. Leaving the top open was the obvious economy -- - // the crown's own clumps swallow it -- but `leafiness: 0` takes the - // crown away and leaves you looking down an open pipe. - 8, [0, 0, 0], tint('bark', -0.02, 0.8), - ) - roughenGeometry(trunk, R * 0.3, { salt: 9, scaleY: 0.4 }) - - /** - * Put the foot back on the floor. - * - * `roughenGeometry` moves every corner by its own position, the bottom - * ring included, so a roughened trunk ends up standing on five points - * with daylight between them and its lowest vertex a few centimetres - * underground. Neither is visible in a render and both are wrong. The - * bole is the only thing in this model that touches the ground, so its - * foot is flattened back to exactly zero afterwards — the flare keeps - * every bit of its irregularity above that line. - */ - const plant = (geometry: BufferGeometry, below: number): void => { - const position = geometry.getAttribute('position') - for (let i = 0; i < position.count; i += 1) { - if (position.getY(i) < below) position.setY(i, 0) - } - position.needsUpdate = true - geometry.computeVertexNormals() - } - plant(trunk, R * 0.4) - - // --- Limbs ------------------------------------------------------------ - const wood: BufferGeometry[] = [] - const crown: BufferGeometry[] = [] - - /** - * One faceted clump of leaves. - * - * A lathe whose profile is a circle, so the poles close to a point and - * need no caps: five levels by six segments is 36 triangles, which is - * what makes it affordable to hang three dozen of them in a crown. The - * per-level radius jitter matters more than it looks — without it every - * clump is the same ball at a different size and the crown reads as - * bubbles. - */ - const clump = (radius: number, at: readonly [number, number, number], lift: number): BufferGeometry => { - // Four rings on six sides: a rounded mass at 36 triangles. - // - // Three on five was a coarse bipyramid and sixty-five of them read as - // crumpled paper. Five on eight was smooth and twenty of them read as - // a cabbage. This is the middle, and the middle is where it belongs: - // enough facets that the mass is round, few enough that forty of them - // fit in the budget, and forty is what it takes to have a crown made - // of parts rather than a crown made of one thing. - const rings = 4 - const levels: Level[] = [] - for (let i = 0; i <= rings; i += 1) { - const t = i / rings - const profile = Math.sqrt(Math.max(0, 1 - Math.pow(2 * t - 1, 2))) - levels.push({ - // Squat: a clump of leaves is wider than it is deep, because it - // grows out along a branch rather than around it. - y: at[1] + radius * 0.78 * (2 * t - 1), - radius: radius * profile * (0.84 + random() * 0.34), - }) - } - // Five sides, not six. The kit's budget is 2500 triangles a model and - // this one has to buy sixty-odd clumps with it; a side costs four - // triangles across every clump in the crown, and at this size nobody - // counts them. What the budget must not buy is fewer clumps, because - // the clump count is what holds the crown together. - return latheGeometry(levels, 6, [at[0], 0, at[2]], leafColour(lift)) - } - - /** - * Sized to MERGE, not to look right on its own. - * - * At 0.185 of the crown radius the clumps came out as fourteen separate - * balls -- and not as a judgement call: voxelising the crown and flood - * filling it found four disconnected pieces, three of them single limb - * ends floating clear of the mass. A crown is one piece. - * - * 0.27 fixed that and overshot into the other failure: one smooth lump - * with a notch in it, because clumps a quarter of the crown across leave - * no room for the crown to have parts. The answer is not a radius at all - * but a COUNT -- more, smaller clumps gathered per limb, so each limb - * carries its own lobe and the lobes meet at seams instead of dissolving - * into each other. Which is how the reference is built, one mass of - * foliage to each big bough. - */ - /** - * Small enough that the masses DO NOT ALL MERGE. - * - * This is the correction that mattered, and it was my own rule that had - * to go: I decided early that "a crown is one piece" and made the probe - * fail anything else, so every version since has been tuned until the - * flood fill returned 1 — which is exactly the instruction "be a single - * smooth blob", and that is what it kept producing. - * - * The support rule requires the crown to be connected to the TREE, not - * to itself. A clump that swallows a branch end is held up by that - * branch whatever its neighbours do. Letting them separate is what buys - * the gaps, and the gaps are the silhouette — a crown you can see - * through in places is the difference between foliage and a cabbage. - */ - const clumpR = crownR * 0.26 * (0.55 + 0.45 * leafiness) - // The tips stop short of the crown radius by most of a clump, so that - // `spread` describes the width of the FINISHED crown rather than of the - // bare branchwork inside it. - const reach = crownR - clumpR * 0.8 - - for (let i = 0; i < limbCount; i += 1) { - const f = limbCount === 1 ? 0 : i / (limbCount - 1) - /** - * Limbs crowd towards the BOTTOM of their range. - * - * Spaced evenly up the bole, the crown's mass began at 29% of the - * height while two long bottom limbs carried their leaves out at 10% - * to 30% with nothing around them -- and the flood fill found exactly - * that: a 7000-cell piece at bearing 228-313 degrees, reaching 5.7 m - * out where the main mass stopped at 4.5, torn off vertically rather - * than sideways. Two rounds of widening clumps and evening out the - * bearings had each failed because neither was the gap. - * - * The reference is at full width by 24% of its height and holds it to - * 44%, which means most of its limbs are in the bottom half. Raising f - * to a power puts them there: nine limbs land at 30, 33, 36, 41, 47, - * 53, 59, 64 and 70% instead of evenly every 5%. - */ - const g = Math.pow(f, 1.35) - const ay = H * (0.24 + 0.44 * g) + jitter(random, H * 0.015) - const ty = H * (0.390 + 0.490 * g) + jitter(random, H * 0.02) - - // Driven by g, the same crowded parameter the heights use, so that a - // limb low on the bole is also a LONG one -- which is the reference's - // arrangement and the reason its crown is widest near the bottom. - // Leaving this on the even f while the heights moved to g put the - // widest row up at 54%. - // - // And the spread narrowed from +/-12% to +/-6%: at 12% the single - // longest limb reached 5.6 m where its neighbours stopped at 4.5, and - // its lobe was stranded out there on its own with nothing to touch. It - // is the same tear the flood fill kept finding, and no amount of - // widening the clumps reaches across a gap made by one limb outrunning - // the rest -- the fix is for it not to outrun them. - const tr = reach * (1 - 0.8 * g) * (0.94 + random() * 0.12) - - // Straight from the geometry, not chosen: a limb whose tip lands level - // with its own root is horizontal, and atan2 says so without any - // special case. - // - // Plus HALF THE SWEEP, which is the part I had missed. Bending a limb - // does not just curve it, it swings the whole chord from root to tip up - // by half the arc -- so a limb aimed at its intended tip and then bent - // lands well above it. Every limb was arriving 0.21 rad high and the - // crown's widest point had climbed from the 24% of the reference to - // 38%. Aiming low by exactly the amount the bend will lift is the - // whole correction, and it is a constant because SWEEP is an angle. - const rise = ty - ay - const tilt = Math.atan2(tr, rise) + SWEEP / 2 - const len = Math.hypot(tr, rise) - - const local: BufferGeometry[] = [] - const leaves: BufferGeometry[] = [] - - // 0.85 of the bole where it grows, not 0.55. A main limb on the - // reference is very nearly as thick as the trunk it leaves, and thin - // limbs are invisible under the crown -- which cost the model the - // whole radiating structure that says "tree" before the leaves do. - const r0 = boleAt(ay) * 0.85 - const limb = latheGeometry( - [0, 0.25, 0.5, 0.75, 1].map((t, k) => ({ - y: len * t, - radius: r0 * [1, 0.72, 0.52, 0.36, 0.22][k]!, - })) as Level[], - // Not lifted. A bough lifted above the bole's own tone came out - // sandy next to it, which is invisible under a full crown and is the - // entire model at `leafiness: 0`. - 4, [0, 0, 0], tint('bark', -0.02, 0.9), - ) - local.push(limb) - - /** - * Everything for this limb is built along +Y with its foot at the - * ORIGIN, and only turned into place at the end. - * - * That is what makes the forks and the clumps free: they are placed in - * the limb's own frame, where "along the branch" is just +Y, and the - * bend and the two rotations are then applied to the whole assembly at - * once. Nothing can come adrift from the limb it belongs to, because - * nothing is ever positioned in world space. - * - * It also means the limb's foot sits ON the trunk's axis, buried a - * whole bole radius inside the bole. There is no join to get wrong. - */ - const forks = 2 - for (let j = 0; j < forks; j += 1) { - // Outboard. At 0.58 the first fork threw its leaves back towards - // the trunk and packed the space around the bole solid, so the crown - // came down as an unbroken dome and the tree lost the one thing that - // separates it from a bush: you could not see the bole rise into it. - const at = len * (0.62 + 0.23 * j) - // Always positive, and that is the whole of the fix. - // - // The rise of a fork works out as sin(splay) * sin(spin), so it is - // the SIGN OF THE PRODUCT that decides up or down. Constraining the - // spin to the upper half circle and then alternating the splay - // between + and - left every second fork pointing at the floor -- and - // the measurement said so plainly while the reasoning had said the - // opposite. With the splay kept positive the spin alone carries the - // variety, and it still swings the fork right round through the - // horizontal because cos(spin) runs from +1 to -1 across the range. - const splay = 0.42 + random() * 0.26 - /** - * Which way the fork throws, and it may not throw DOWNWARD. - * - * Spun freely through the whole circle, a fork on a near-horizontal - * bottom limb can come off 39 degrees below the horizontal, drop the - * best part of a metre, and hang its clump on the floor -- which is - * how the crown came to be 7 m wide at 2% of the tree's height, where - * the reference has nothing but bare bole. - * - * In the limb's own frame +Z is the direction `rotateX` will send - * upward, so keeping the spin inside (0, PI) keeps the fork's rise - * positive whatever the limb is doing. Side shoots on a real bough - * grow up and out; none of them grow down. - */ - const spin = Math.PI / 2 + jitter(random, 1.5) - const secLen = len * (0.34 - 0.1 * j) * (0.8 + random() * 0.4) - const secR = r0 * (0.42 - 0.12 * j) - - // Three levels on four sides: a fork is short, half buried in the - // clump on its end, and never seen in silhouette. It is the cheapest - // thing in the model to make cheaper. - const sec = latheGeometry( - [0, 0.55, 1].map((t, k) => ({ - y: secLen * t, - radius: secR * [1, 0.5, 0.2][k]!, - })) as Level[], - 3, [0, 0, 0], tint('bark', 0.0, 0.9), - ) - sec.rotateZ(splay) - sec.rotateY(spin) - sec.translate(0, at, 0) - local.push(sec) - - // Only the OUTER fork gets a clump, which is what pays for the - // inner one above. The inner fork sits under the crown's own mass - // and its clump was never seen. - if (false) { - // The tip, worked out rather than guessed: rotateZ then rotateY - // sends +Y to this direction, and a clump centred there is - // guaranteed to contain the branch end it hangs on. - const dir: readonly [number, number, number] = [ - -Math.sin(splay) * Math.cos(spin), - Math.cos(splay), - Math.sin(splay) * Math.sin(spin), - ] - const tip: readonly [number, number, number] = [ - dir[0] * secLen, at + dir[1] * secLen, dir[2] * secLen, - ] - for (let k = 0; k < 1; k += 1) { - const r = clumpR * (0.78 + random() * 0.5) - // Offsets stay inside the clump's own radius, so consecutive - // clumps always overlap and the branch tip is always inside one. - leaves.push(clump(r, [ - tip[0] + jitter(random, r * 0.5), - tip[1] + jitter(random, r * 0.45), - tip[2] + jitter(random, r * 0.5), - ], 0.1 + jitter(random, 0.13))) - } - } - } - - if (leafiness > 0) { - /** - * Along the bough, INCLUDING well inboard. - * - * 0.38 is the one that matters and it took four failed rounds to - * arrive at. The crown kept coming apart into two pieces, and every - * attempt to close the gap treated it as a gap between LOBES -- - * wider clumps, evener bearings, more limbs, less length jitter -- - * none of which worked, because the crown was never short of foliage - * where those fixes put it. - * - * What was missing was the middle. I had pushed the leaves outboard - * to open up the space under the crown and taken the inside out with - * it, so nine lobes hung off a bare hub with nothing joining them. - * Looking at the reference again: its crown is FULL from the bole - * outward, and the clear space is underneath, not within. An inner - * clump on every bough gives them all a common core, and it is - * guaranteed to work rather than tuned to, because every bough passes - * through the middle. - */ - /** - * INCLUDING one well inboard, at 0.34. - * - * Every clump sat on the outer half of its limb, which makes a - * crown that is a RING: full at the rim, hollow in the middle, and - * from a third of the compass you are looking straight through the - * hole. The turntable is what showed it — one three-quarter view - * looked fine and two of six were full of daylight. - * - * I had this right once and removed it while cutting triangles, - * which is the cheapest kind of regression to make and the hardest - * to notice: nothing failed, the model just got worse. - */ - for (const along of [0.36, 0.68, 0.95]) { - const r = clumpR * (0.85 + random() * 0.45) - leaves.push(clump(r, [ - jitter(random, r * 0.55), len * along + jitter(random, r * 0.3), jitter(random, r * 0.55), - ], 0.1 + jitter(random, 0.13))) - } - } - - /** - * Bend, then tilt, then spin — in that order and no other. - * - * `bendGeometry` only curves toward +Z, so the tilt has to be a - * rotation about X: `rotateX(-tilt)` lays the limb over toward -Z while - * the bend is pushing toward +Z, and the two opposing each other is - * exactly the oak profile — out near horizontal, then turning up at the - * end. Tilting about Z instead would have left the bend pointing - * sideways out of the limb's own plane, and the limb would have curved - * ACROSS rather than up. - * - * The arc angle is `curvature * length`, so a fixed sweep divided by - * the length gives every limb the same 24 degrees of turn whatever its - * size — which is what keeps a short top limb looking like the same - * tree as a long bottom one. - */ - const curvature = SWEEP / len - /** - * Evenly divided, not the golden angle. - * - * The golden angle is the right answer for a great many leaves and the - * wrong one for nine limbs: it is uniform in the limit, but at this - * count it left azimuth gaps ranging from 17 to 52 degrees, and the - * widest gap was where the crown tore into two pieces. An even - * division gives every gap 40 degrees, and the jitter keeps it from - * looking like a wheel. - */ - const spin = (i / limbCount) * Math.PI * 2 + jitter(random, 0.11) - for (const group of [local, leaves]) { - if (group.length === 0) continue - const merged = mergeColoured(group) - bendGeometry(merged, curvature) - merged.rotateX(-tilt) - merged.rotateY(spin) - merged.translate(0, ay, 0) - ;(group === local ? wood : crown).push(merged) - } - } - - // The leader: the bole's own top, which is a branch tip like any other - // and gets its clump for the same reason. - if (leafiness > 0) { - // Two, sitting lower. Three clumps perched a third of a radius above - // the bole's tip put a cap on the crown, and the profile showed it: - // our top rows measured 0.63 and 0.55 of our widest against the - // reference's 0.46 and 0.35. An oak tapers to its top; it does not - // finish in a knob. - for (let i = 0; i < 2; i += 1) { - const r = clumpR * (0.8 + random() * 0.4) - crown.push(clump(r, [ - jitter(random, r * 0.9), - trunkTop + r * 0.1 + jitter(random, r * 0.35), - jitter(random, r * 0.9), - ], 0.1 + jitter(random, 0.13))) - } - } - - const boughs = mergeColoured(wood) - roughenGeometry(boughs, R * 0.09, { salt: 17 }) - const leaves = crown.length > 0 ? mergeColoured(crown) : undefined - - /** - * Make `height` mean the height. - * - * Everything above is laid out in fractions of H, but the clumps sit - * PROUD of the tips they hang on, so the finished tree overshot by 8% - * and the control was quietly lying. Rather than shave the numbers that - * came off the reference until they happen to land right -- which would - * have to be redone for every change to the clump size -- the assembly - * is measured and scaled to fit. Uniformly, so that every ratio the - * references gave survives it. - */ - const all = [trunk, boughs, ...(leaves ? [leaves] : [])] - let low = Infinity - let high = -Infinity - for (const g of all) { - const position = g.getAttribute('position') - for (let i = 0; i < position.count; i += 1) { - const y = position.getY(i) - if (y < low) low = y - if (y > high) high = y - } - } - const grown = high - low - if (grown > 1e-6) { - const k = H / grown - for (const g of all) { - g.scale(k, k, k) - g.translate(0, -low * k, 0) - g.computeVertexNormals() - } - } - - /** - * And make `spread` mean the spread, the same way. - * - * A uniform scale fixes the height but cannot fix the width, because the - * crown's width is not 2x its radius: seven limbs on a golden-angle - * spiral never put two of them opposite each other, so the bounding box - * is always narrower than the reach that produced it -- 1.12 against the - * 1.30 asked for. The shortfall depends on the limb count, so it cannot - * be a constant either. - * - * The stretch is horizontal only and it is applied to the LIMBS AND THE - * CROWN, never to the bole: stretching the trunk would throw away the one - * profile in this model that was read off a photograph row by row. It - * cannot pull anything loose, because every limb's foot sits exactly on - * the axis and a scale about the axis leaves the axis where it is. - */ - const spread = [boughs, ...(leaves ? [leaves] : [])] - let x0 = Infinity, x1 = -Infinity, z0 = Infinity, z1 = -Infinity - for (const g of spread) { - const position = g.getAttribute('position') - for (let i = 0; i < position.count; i += 1) { - const x = position.getX(i) - const z = position.getZ(i) - if (x < x0) x0 = x - if (x > x1) x1 = x - if (z < z0) z0 = z - if (z > z1) z1 = z - } - } - // The EXTENT, not the radius. Scaling until the furthest tip sat at the - // crown radius left the tree at 1.10 for 1.30 asked, because the furthest - // tip has nothing opposite it -- which is the very asymmetry this is here - // to correct for. The width of a thing is max minus min. - const widest = Math.max(x1 - x0, z1 - z0) - if (widest > 1e-6) { - const kx = (Math.max(0.2, config.spread) * H) / widest - for (const g of spread) { - g.scale(kx, 1, kx) - g.computeVertexNormals() - } - } - - /** - * Break the crown's outline up, or it is a pile of boulders. - * - * This is the difference between foliage and rock and it is a - * SILHOUETTE property, not a colour one. A clump built as a six-sided - * lathe has a smooth, regular outline, and a smooth outline at this - * scale reads as stone however green it is -- the first render of this - * crown looked like a cairn with moss on it. Roughening the merged crown - * ragged-edges every facet, and because the shift is derived from each - * corner's own position the surface stays closed and the clumps stay - * fused into the one mass they were sized to make. - * - * It goes AFTER both scalings so the amount is in finished metres. - */ - /** - * The crown is NOT roughened. - * - * It was, at 0.17 of a clump radius, on the reasoning that ragged edges - * read as foliage where smooth ones read as stone. That is true of a - * silhouette and false of a surface: what it actually did was crease - * every facet of every clump and turn the mass into crumpled paper. - * Rounded shapes that overlap already give a ragged OUTLINE — the - * raggedness has to come from the arrangement, not from the skin. - */ - - return { - trunk: { slot: 'oak' as const, geometry: trunk }, - boughs: { slot: 'oak' as const, geometry: boughs }, - // Explicitly `undefined` when bare, never omitted. The kit resets a - // part's anchor before it checks whether there is anything to put in - // it, so a key that is present and undefined empties the crown -- - // where a MISSING key would never be visited and last build's leaves - // would still be hanging there. - crown: leaves ? { slot: 'leaf' as const, geometry: leaves } : undefined, - } - }, - }, overrides) -} diff --git a/scripts/probe-tree.ts b/scripts/probe-tree.ts deleted file mode 100644 index a01ec65..0000000 --- a/scripts/probe-tree.ts +++ /dev/null @@ -1,188 +0,0 @@ -/** - * Measures the oak against the numbers taken off the reference photographs. - * - * Rendering the tree and looking at it says "the crown is a ring of separate - * balls". That is a real observation and a useless one to act on, because it - * does not say by how much or where. This prints the four numbers the - * references gave, measured off the built geometry the same way they were - * measured off the photographs: - * - * crown width / height reference 1.32 – 1.43 - * height of the widest point reference 0.24 - * bole width / height at 0.02 reference 0.130, at 0.10 reference 0.073 - * - * and one number the photographs cannot give, because a photograph of a tree - * is a single connected mass by definition: how many SEPARATE PIECES the crown - * is in. A crown of one piece is foliage. A crown of fourteen is broccoli. - */ -import { Box3, Vector3, type Mesh, type Object3D } from 'three' - -import { createModel } from '@/models/medieval-kit/oak-tree/model.ts' - -const model = createModel() -const box = new Box3().setFromObject(model.root) -const size = box.getSize(new Vector3()) -const H = size.y -const W = Math.max(size.x, size.z) -console.log(`overall ${size.x.toFixed(2)} x ${size.y.toFixed(2)} x ${size.z.toFixed(2)}`) -console.log(`CROWN WIDTH / HEIGHT = ${(W / H).toFixed(3)} (reference 1.32 – 1.43)`) - -/** Every triangle of a part, in world space. */ -function triangles(part: Object3D): Float32Array[] { - const out: Float32Array[] = [] - part.updateWorldMatrix(true, true) - part.traverse((child) => { - const mesh = child as Mesh - if (!mesh.isMesh) return - const pos = mesh.geometry.getAttribute('position') - const v = new Vector3() - const tri = new Float32Array(9) - for (let i = 0; i < pos.count; i += 3) { - for (let k = 0; k < 3; k += 1) { - v.fromBufferAttribute(pos, i + k).applyMatrix4(mesh.matrixWorld) - tri[k * 3] = v.x; tri[k * 3 + 1] = v.y; tri[k * 3 + 2] = v.z - } - out.push(tri.slice()) - } - }) - return out -} - -// --- width profile, sampled the same way the photographs were: by height band -const N = 25 -const bands: Array<{ min: number; max: number }> = Array.from( - { length: N }, () => ({ min: Infinity, max: -Infinity }), -) -for (const t of triangles(model.root)) { - for (let k = 0; k < 3; k += 1) { - const y = t[k * 3 + 1]! - const r = Math.hypot(t[k * 3]!, t[k * 3 + 2]!) - const b = Math.min(N - 1, Math.max(0, Math.floor(((y - box.min.y) / H) * N))) - // The EXTENT of the row, not twice its radius. - // - // The photographs were measured by counting how far apart the leftmost and - // rightmost tree pixels were on each row. Measuring our own geometry as - // 2 x max-radius instead is a different quantity on any tree that is not - // symmetric -- which is every tree -- and it read 42% for a crown whose - // widest ROW is much lower down. Comparing a number against a reference - // means measuring it the same way the reference was measured. - bands[b]!.min = Math.min(bands[b]!.min, t[k * 3]!) - bands[b]!.max = Math.max(bands[b]!.max, t[k * 3]!) - } -} -let widest = { at: 0, w: 0 } -console.log('\nheight% width profile') -for (let b = 0; b < N; b += 1) { - const w = bands[b]!.max === -Infinity ? 0 : bands[b]!.max - bands[b]!.min - const pct = ((b + 0.5) / N) * 100 - if (w > widest.w) widest = { at: pct, w } - console.log(` ${pct.toFixed(0).padStart(3)}% ${w.toFixed(2).padStart(6)} ${'#'.repeat(Math.round((w / W) * 46))}`) -} -console.log(`widest at ${widest.at.toFixed(0)}% of height (reference 24%)`) - -// --- where the crown starts. The reference's lowest leaves are at 11% of the -// height and it is at full width by 24%; a crown that reaches lower than that -// is a bush, and one that starts higher is a lollipop. -if (model.parts.crown) { - const ys = triangles(model.parts.crown.anchor).flatMap((t) => [t[1]!, t[4]!, t[7]!]) - console.log(`crown hangs from ${(((Math.min(...ys)) - box.min.y) / H * 100).toFixed(0)}% of the height (reference 11%)`) -} - -// --- the bole, measured at the two heights the photograph was measured at -const trunkTris = triangles(model.parts.trunk.anchor) -for (const at of [0.02, 0.06, 0.1, 0.38]) { - const y = box.min.y + H * at - let r = 0 - for (const t of trunkTris) { - for (let k = 0; k < 3; k += 1) { - if (Math.abs(t[k * 3 + 1]! - y) < H * 0.012) r = Math.max(r, Math.hypot(t[k * 3]!, t[k * 3 + 2]!)) - } - } - console.log(`bole at ${(at * 100).toFixed(0).padStart(2)}% of height: ${(r * 2 / H).toFixed(4)} of height wide`) -} - -/** - * How many separate pieces is the crown in? - * - * The same voxel trick the support check uses: drop every triangle corner into - * a grid, then flood fill through the 26 neighbours. Two clumps that overlap - * share cells and come out as one piece; two that merely sit near each other - * do not. - */ -const crown = model.parts.crown?.anchor -if (crown) { - const cell = W / 90 - const key = (x: number, y: number, z: number): string => `${x},${y},${z}` - const cells = new Set() - for (const t of triangles(crown)) { - // Sample along each edge as well as at the corners, or a large flat facet - // spans several cells and tears into separate pieces on its own. - for (let e = 0; e < 3; e += 1) { - const a = e * 3 - const b = ((e + 1) % 3) * 3 - const steps = Math.max(1, Math.ceil( - Math.hypot(t[b]! - t[a]!, t[b + 1]! - t[a + 1]!, t[b + 2]! - t[a + 2]!) / (cell * 0.6), - )) - for (let s = 0; s <= steps; s += 1) { - const f = s / steps - cells.add(key( - Math.round((t[a]! + (t[b]! - t[a]!) * f) / cell), - Math.round((t[a + 1]! + (t[b + 1]! - t[a + 1]!) * f) / cell), - Math.round((t[a + 2]! + (t[b + 2]! - t[a + 2]!) * f) / cell), - )) - } - } - } - const seen = new Set() - const sizes: Array<{ count: number; cells: string[] }> = [] - for (const start of cells) { - if (seen.has(start)) continue - let count = 0 - const piece: string[] = [] - const stack = [start] - seen.add(start) - while (stack.length > 0) { - const at = stack.pop()! - count += 1 - piece.push(at) - const [x, y, z] = at.split(',').map(Number) as [number, number, number] - for (let dx = -1; dx <= 1; dx += 1) { - for (let dy = -1; dy <= 1; dy += 1) { - for (let dz = -1; dz <= 1; dz += 1) { - const n = key(x + dx, y + dy, z + dz) - if (cells.has(n) && !seen.has(n)) { seen.add(n); stack.push(n) } - } - } - } - } - sizes.push({ count, cells: piece }) - } - sizes.sort((a, b) => b.count - a.count) - console.log(`\nCROWN IS IN ${sizes.length} PIECE(S) (gaps are wanted; the support check owns whether any of them float)`) - // WHERE a piece is matters more than how big it is: a tear low down means - // the bottom limbs have outrun the rest, a tear at one bearing means a gap - // between two neighbours, a tear far out means a limb reaching past its - // fellows. Guessing which of the three it was cost two rounds of tuning that - // each fixed nothing. - for (const piece of sizes.slice(0, 6)) { - let y0 = Infinity, y1 = -Infinity, r0 = Infinity, r1 = -Infinity - const bearings: number[] = [] - for (const c of piece.cells) { - const [x, y, z] = c.split(',').map(Number) as [number, number, number] - const yy = (y * cell - box.min.y) / H * 100 - const rr = Math.hypot(x * cell, z * cell) - if (yy < y0) y0 = yy - if (yy > y1) y1 = yy - if (rr < r0) r0 = rr - if (rr > r1) r1 = rr - bearings.push(((Math.atan2(z, x) * 180) / Math.PI + 360) % 360) - } - bearings.sort((a, b) => a - b) - console.log(` ${String(piece.count).padStart(6)} cells ` - + `height ${y0.toFixed(0)}-${y1.toFixed(0)}% ` - + `radius ${r0.toFixed(1)}-${r1.toFixed(1)}m ` - + `bearing ${bearings[0]!.toFixed(0)}-${bearings[bearings.length - 1]!.toFixed(0)}deg`) - } -} - -model.dispose() diff --git a/scripts/verify-model.ts b/scripts/verify-model.ts index 203a8e6..44857a6 100644 --- a/scripts/verify-model.ts +++ b/scripts/verify-model.ts @@ -56,7 +56,6 @@ import { createModel as createCart } from '@/models/medieval-kit/hand-cart/model import { createModel as createVeg } from '@/models/medieval-kit/vegetables/model.ts' import { createModel as createShield } from '@/models/medieval-kit/round-shield/model.ts' import { createModel as createForge } from '@/models/medieval-kit/forge-hearth/model.ts' -import { createModel as createOak } from '@/models/medieval-kit/oak-tree/model.ts' import { createModel as createTrough } from '@/models/medieval-kit/stone-trough/model.ts' import { createModel as createGrind } from '@/models/medieval-kit/grindstone/model.ts' import { createModel as createStall } from '@/models/medieval-kit/market-stall/model.ts' @@ -348,10 +347,6 @@ const CASES: readonly Case[] = [ parts: 2, ownSlot: 'water', borrowSlot: 'stone', variants: [{ water: 0 }, { wall: 0.12 }, { wall: 0.34 }, { height: 0.25 }], maxSize: [2.8, 0.8, 1.1] }, - { id: 'oak-tree', make: as(createOak), patch: { limbs: 11, spread: 1.5 }, - parts: 3, ownSlot: 'leaf', borrowSlot: 'oak', - variants: [{ leafiness: 0 }, { limbs: 3 }, { autumn: 1 }, { spread: 0.6 }, { height: 3 }], - maxSize: [22, 14, 22] }, { id: 'forge-hearth', make: as(createForge), patch: { kerbBlocks: 24, chimney: 1.6 }, parts: 4, ownSlot: 'stone', borrowSlot: 'oak', variants: [{ lit: 0 }, { kerbBlocks: 8 }, { chimney: 0.3 }], diff --git a/src/catalog.ts b/src/catalog.ts index b60386c..7a3b436 100644 --- a/src/catalog.ts +++ b/src/catalog.ts @@ -50,7 +50,6 @@ import { createModel as createCart } from '@/models/medieval-kit/hand-cart/model import { createModel as createVeg } from '@/models/medieval-kit/vegetables/model.ts' import { createModel as createShield } from '@/models/medieval-kit/round-shield/model.ts' import { createModel as createForge } from '@/models/medieval-kit/forge-hearth/model.ts' -import { createModel as createOak } from '@/models/medieval-kit/oak-tree/model.ts' import { createModel as createTrough } from '@/models/medieval-kit/stone-trough/model.ts' import { createModel as createGrind } from '@/models/medieval-kit/grindstone/model.ts' import { createModel as createStall } from '@/models/medieval-kit/market-stall/model.ts' @@ -165,7 +164,6 @@ const FACTORIES: Readonly KitModel>> = { 'vegetables': as(createVeg), 'round-shield': as(createShield), 'forge-hearth': as(createForge), - 'oak-tree': as(createOak), 'stone-trough': as(createTrough), 'grindstone': as(createGrind), 'market-stall': as(createStall), @@ -329,10 +327,6 @@ const MEDIEVAL_ORDER = [ 'grindstone', 'market-stall', 'post-mill', - // After the mill, because it is taller than the mill and half again as wide. - // A tour that ends on the only living thing in the kit ends better than one - // that ends on another building. - 'oak-tree', ] as const // Keep the order list and the factory list from drifting apart: if one gets an diff --git a/src/models/medieval-kit/core/kit.ts b/src/models/medieval-kit/core/kit.ts index cc48ed8..1908ae3 100644 --- a/src/models/medieval-kit/core/kit.ts +++ b/src/models/medieval-kit/core/kit.ts @@ -147,22 +147,6 @@ const MOTTLE_BY_SLOT: Readonly> = { // of a stone rather than of a grain. stone: 0.75, ember: 0, // a flame is not mottled: its colour is already the final colour - // Just under oak, and it started at 1.5 for a reason that turned out to be - // the straw trap wearing a different hat. - // - // The measurement was real: across one oak in full leaf the darkest tenth of - // the crown reads lightness 0.16 and the lightest 0.61, a spread of 0.45 and - // the widest of anything in this kit. What it does not say is that the - // spread has to come from HERE. Clump-to-clump tint, this mottle and the - // baked occlusion are three separate mechanisms all reproducing the same - // shadow, and stacked at full strength they went through the floor: 10.8% - // of the rendered crown clipped to pure black, against 0.01% of the - // photograph. A statistic taken off fine detail cannot be added on top of - // the machinery that already reproduces that detail -- which is the third - // time this kit has learned that, after straw's saturation and bark's value. - leaf: 0.95, - // Barely mottled. Ripples are a shape, not a stain, and a surface this - // smooth shows speckle as dirt floating on it. water: 0.2, } diff --git a/src/models/medieval-kit/core/materials.ts b/src/models/medieval-kit/core/materials.ts index 0ac6349..75908fb 100644 --- a/src/models/medieval-kit/core/materials.ts +++ b/src/models/medieval-kit/core/materials.ts @@ -26,7 +26,6 @@ export type MedievalSlot = | 'ember' // flame — does not take light, it emits it | 'char' // charcoal, pitch | 'stone' // dressed and rubble masonry - | 'leaf' // living foliage | 'water' // standing water /** @@ -47,7 +46,6 @@ export interface SlotMaterial { readonly ember: MeshBasicMaterial readonly char: MeshStandardMaterial readonly stone: MeshStandardMaterial - readonly leaf: MeshStandardMaterial readonly water: MeshStandardMaterial } @@ -140,24 +138,6 @@ export interface MedievalPalette { */ readonly bark: Color - /** - * Foliage in flat overcast light, measured across 125 000 pixels of an oak - * in full leaf: hue 78, saturation 0.39, lightness 0.34. - * - * The measurement contradicted the thing I was about to build. I expected a - * strong top-to-bottom gradient across a crown -- lit above, dark below -- - * and was going to bake one in. Sampled in three bands the crown reads 0.362, - * 0.336 and 0.324: a spread of 0.04, which is nothing. Under an overcast sky - * there is no gradient to bake. - * - * What IS there is local: the darkest tenth of the crown sits at lightness - * 0.16 and the lightest tenth at 0.61, a spread of 0.45 within the same - * band. Foliage varies leaf to leaf, not top to bottom. So the variation - * belongs in the mottle and in per-clump jitter, and it is a value spread, - * not a hue one -- hue held between 77 and 81 degrees across every sample, - * lit and shadowed alike. - */ - readonly leaf: Color /** * Weathered limestone, which is NOT the same rock as `stone`. @@ -241,7 +221,6 @@ export const MEDIEVAL_PALETTE: MedievalPalette = { bark: new Color(0x585032), limestone: new Color(0x94846b), water: new Color(0x3b4e45), - leaf: new Color(0x6d8632), } /** @@ -377,19 +356,6 @@ export function createMedievalMaterials( roughness: 0.97, metalness: 0, }), - // Foliage is the most matte thing in the kit after stone. Any sheen at - // all and a crown reads as plastic shrubbery -- which is the failure mode - // of most lowpoly trees, and it is a material setting rather than a - // modelling one. It is a separate slot from `straw` despite similar - // numbers because `materialSlots` is a contract: a tree declaring straw - // would be telling the consumer it is made of dead grass. - leaf: () => new MeshStandardMaterial({ - name: 'medieval-kit / foliage', - color: 0xffffff, - vertexColors: true, - roughness: 0.93, - metalness: 0, - }), // Water is a THIN TRANSPARENT FILM, not a body of liquid. Everything in // this kit that holds water holds a few centimetres of it over a floor you // can see, so the colour that reaches the eye is mostly what is underneath diff --git a/src/models/medieval-kit/oak-tree/model.ts b/src/models/medieval-kit/oak-tree/model.ts deleted file mode 100644 index 2e13c55..0000000 --- a/src/models/medieval-kit/oak-tree/model.ts +++ /dev/null @@ -1,681 +0,0 @@ -/** - * @medieval-kit/oak-tree - * - * A free-standing oak: flared bole, sweeping limbs, a broad low crown. - * - * The kit had nothing growing in it at all. Every other model is something a - * person made, and a village of nothing but made things reads as a warehouse - * yard — so this is the first piece of the site rather than of the inventory, - * and it is also by some way the largest thing here. - * - * It was built against two reference photographs, and both of them contradicted - * what I was going to build. Worth writing down, because the default lowpoly - * tree — a tall bare pole with a ball on top — is wrong in every measurement - * that matters: - * - * - CROWN WIDTH / TREE HEIGHT = 1.32 to 1.43. An open-grown oak is HALF - * AGAIN as wide as it is tall. Nothing else in this kit is wider than it - * is tall, and getting this one number right is most of what makes the - * silhouette read as an oak rather than as a lollipop. - * - THE CROWN IS WIDEST AT 24% OF THE HEIGHT. Not halfway up, not at the - * top: a quarter of the way up, just above the ground. The lowest limbs - * are the longest ones and they leave the trunk almost horizontally. - * - THE TRUNK RUNS TO 72% OF THE HEIGHT before it stops being the widest - * single thing. It does not fork low into equal leaders, which is what I - * had assumed from the leafy photograph alone; the winter photograph shows - * one continuous bole with everything else hung off it. - * - THE FLARE IS SHARP AND SHORT. The trunk is 0.130 of the tree's height - * wide at 2% of the height and 0.073 at 10% — it nearly halves in the - * bottom tenth, then barely tapers at all through the next quarter. - * - * The limbs SWEEP. A branch leaves the trunk at a shallow angle and turns - * upward at its outer end, which is the profile a lowpoly tree most often - * misses, and it comes free here: `bendGeometry` on a limb built along its own - * axis, before it is rotated into place. - * - * The honest limit: what fills a real winter silhouette is thousands of twigs, - * and no triangle budget here reaches them. At `leafiness: 0` this is a bare - * tree of LIMBS, which is a fine dead or winter tree and is not a photograph - * of one. - */ -import { Color, type BufferGeometry } from 'three' - -import { - bendGeometry, - createKitModel, - createTinter, - jitter, - latheGeometry, - mergeColoured, - roughenGeometry, - type Level, -} from '../core/index.ts' - -export interface OakTreeConfig { - /** Height to the top of the crown (metres). */ - readonly height: number - /** Crown width as a multiple of the height. The reference oaks measure 1.32–1.43. */ - readonly spread: number - /** Radius of the clear bole, as a fraction of the height. */ - readonly bole: number - /** Primary limbs off the trunk. */ - readonly limbs: number - /** 0 leaves it bare; 1 is full summer leaf. */ - readonly leafiness: number - /** 0 is green, 1 turns the crown to russet and gold. */ - readonly autumn: number - readonly seed: number -} - -export const oakTreeDefaults: OakTreeConfig = { - height: 7, - spread: 1.3, - // 0.037, straight off the reference: the bole measured 0.073 of the tree's - // height ACROSS at the point where it has finished flaring. - // 0.046, not the reference's own 0.037. That number came off a photograph - // of a tree seen whole from a distance; at this size, with a crown of - // twenty masses sitting over it, a bole at 0.037 disappears entirely and - // what is left is a cabbage on a stick. The trunk has to read. - bole: 0.046, - limbs: 12, - leafiness: 1, - autumn: 0, - seed: 11, -} - -export type OakTreeParts = 'trunk' | 'boughs' | 'crown' - -export function createModel(overrides: Partial = {}) { - return createKitModel({ - id: 'oak-tree', - defaults: oakTreeDefaults, - slots: ['oak', 'leaf'], - - build: ({ config, random }) => { - const tint = createTinter(random) - const H = Math.max(0.5, config.height) - const R = Math.max(0.004, config.bole) * H - const crownR = (Math.max(0.2, config.spread) * H) / 2 - const leafiness = Math.max(0, Math.min(1, config.leafiness)) - const autumn = Math.max(0, Math.min(1, config.autumn)) - const limbCount = Math.max(3, Math.min(14, Math.round(config.limbs))) - - /** - * How far a limb turns from root to tip, in radians. - * - * It is an ANGLE rather than a curvature so that every limb turns by the - * same amount whatever its length: a short top limb and a long bottom - * one then read as the same tree. 0.42 rad is 24 degrees, which is what - * the reference's limbs do between leaving the bole and their outer end. - */ - const SWEEP = 0.42 - - /** - * The measured taper, as (height fraction, radius in bole radii). - * - * These are not shaped by eye. Each pair is a row read off the winter - * photograph by finding the run of trunk pixels at that height, and the - * profile they make is the whole character of the bole: a violent flare - * in the bottom twentieth, then a shaft that hardly tapers for a quarter - * of the tree, then a steady run out to nothing at 74%. - */ - const TAPER: ReadonlyArray = [ - [0.00, 1.95], - [0.02, 1.76], - [0.06, 1.14], - [0.11, 1.00], - [0.38, 0.94], - [0.50, 0.71], - [0.62, 0.50], - [0.74, 0.16], - ] - const trunkTop = H * TAPER[TAPER.length - 1]![0] - - /** The bole's radius at a height, so a limb can be sized to where it grows. */ - const boleAt = (y: number): number => { - const f = y / H - for (let i = 0; i < TAPER.length - 1; i += 1) { - const [f0, r0] = TAPER[i]! - const [f1, r1] = TAPER[i + 1]! - if (f <= f1) { - const t = (f - f0) / (f1 - f0) - return R * (r0 + (r1 - r0) * Math.max(0, Math.min(1, t))) - } - } - return R * TAPER[TAPER.length - 1]![1] - } - - /** - * Foliage colour. Green at `autumn` 0, russet and gold at 1. - * - * The turn is a HUE ROTATION of the same measured green rather than a - * second palette entry, because that is what happens in the leaf: the - * chlorophyll goes and what was already underneath it shows. Saturation - * climbs with it — an autumn oak is a more saturated object than a - * summer one, which is the opposite of what fading suggests. - */ - /** - * Clump to clump, the tone varies a LOT, and that is the whole depth of - * a lowpoly crown. - * - * At +/-0.09 every mass came out the same green and the crown read as - * one solid object with facet shading on it — a cabbage. The reference's - * crown varies by 0.45 in lightness WITHIN one band; a smooth mass - * cannot reproduce that at the leaf's scale, but it can carry it at the - * clump's, which is the only scale this budget has. What must NOT vary - * is hue: measured across the reference, lit and shadowed alike, it - * holds between 77 and 81 degrees. - * - * ASYMMETRIC, and that took a render to learn. A symmetric +/-0.19 put - * whole masses through the floor — not clipped pixels here and there but - * six or seven entirely black clumps, because the tint's own jitter, the - * mottle and the baked occlusion all pull the same way underneath it. It - * is also wrong about foliage: a lit mass is far brighter than the base - * green, while a shaded one is filled in by the sky and never gets that - * far below it. So the range is -0.03 to +0.23. - */ - const leafColour = (lift: number): Color => { - const c = tint('leaf', lift, 1) - // Darker clumps are MORE saturated, which is the measurement and is the - // opposite of the intuition that shadow drains colour: across the - // reference the darkest tenth of the crown reads 0.44 saturation and - // the lightest 0.32. A highlight on a leaf is a specular reflection of - // a white sky, and it washes the green out of it. - // -0.145 of a turn, which is 52 degrees, taking the measured green at - // 78 down to 26: RUSSET. The first attempt turned it 41 degrees to - // amber and lifted the lightness, and an oak came out of it the colour - // of a lemon. An oak in October is a dark red-brown -- it goes DOWN in - // value as well as round in hue, which is why the lightness term is - // negative here and was the thing that made the difference. - c.offsetHSL(-0.145 * autumn, -lift * 0.55 + 0.14 * autumn, -0.03 * autumn) - return c - } - - // --- The bole --------------------------------------------------------- - const trunk = latheGeometry( - TAPER.map(([f, r]) => ({ y: H * f, radius: R * r })) as Level[], - // Capped at BOTH ends. Leaving the top open was the obvious economy -- - // the crown's own clumps swallow it -- but `leafiness: 0` takes the - // crown away and leaves you looking down an open pipe. - 8, [0, 0, 0], tint('bark', -0.02, 0.8), - ) - roughenGeometry(trunk, R * 0.3, { salt: 9, scaleY: 0.4 }) - - /** - * Put the foot back on the floor. - * - * `roughenGeometry` moves every corner by its own position, the bottom - * ring included, so a roughened trunk ends up standing on five points - * with daylight between them and its lowest vertex a few centimetres - * underground. Neither is visible in a render and both are wrong. The - * bole is the only thing in this model that touches the ground, so its - * foot is flattened back to exactly zero afterwards — the flare keeps - * every bit of its irregularity above that line. - */ - const plant = (geometry: BufferGeometry, below: number): void => { - const position = geometry.getAttribute('position') - for (let i = 0; i < position.count; i += 1) { - if (position.getY(i) < below) position.setY(i, 0) - } - position.needsUpdate = true - geometry.computeVertexNormals() - } - plant(trunk, R * 0.4) - - // --- Limbs ------------------------------------------------------------ - const wood: BufferGeometry[] = [] - const crown: BufferGeometry[] = [] - - /** - * One faceted clump of leaves. - * - * A lathe whose profile is a circle, so the poles close to a point and - * need no caps: five levels by six segments is 36 triangles, which is - * what makes it affordable to hang three dozen of them in a crown. The - * per-level radius jitter matters more than it looks — without it every - * clump is the same ball at a different size and the crown reads as - * bubbles. - */ - const clump = (radius: number, at: readonly [number, number, number], lift: number): BufferGeometry => { - // Four rings on six sides: a rounded mass at 36 triangles. - // - // Three on five was a coarse bipyramid and sixty-five of them read as - // crumpled paper. Five on eight was smooth and twenty of them read as - // a cabbage. This is the middle, and the middle is where it belongs: - // enough facets that the mass is round, few enough that forty of them - // fit in the budget, and forty is what it takes to have a crown made - // of parts rather than a crown made of one thing. - const rings = 4 - const levels: Level[] = [] - for (let i = 0; i <= rings; i += 1) { - const t = i / rings - const profile = Math.sqrt(Math.max(0, 1 - Math.pow(2 * t - 1, 2))) - levels.push({ - // Squat: a clump of leaves is wider than it is deep, because it - // grows out along a branch rather than around it. - y: at[1] + radius * 0.78 * (2 * t - 1), - radius: radius * profile * (0.84 + random() * 0.34), - }) - } - // Five sides, not six. The kit's budget is 2500 triangles a model and - // this one has to buy sixty-odd clumps with it; a side costs four - // triangles across every clump in the crown, and at this size nobody - // counts them. What the budget must not buy is fewer clumps, because - // the clump count is what holds the crown together. - return latheGeometry(levels, 6, [at[0], 0, at[2]], leafColour(lift)) - } - - /** - * Sized to MERGE, not to look right on its own. - * - * At 0.185 of the crown radius the clumps came out as fourteen separate - * balls -- and not as a judgement call: voxelising the crown and flood - * filling it found four disconnected pieces, three of them single limb - * ends floating clear of the mass. A crown is one piece. - * - * 0.27 fixed that and overshot into the other failure: one smooth lump - * with a notch in it, because clumps a quarter of the crown across leave - * no room for the crown to have parts. The answer is not a radius at all - * but a COUNT -- more, smaller clumps gathered per limb, so each limb - * carries its own lobe and the lobes meet at seams instead of dissolving - * into each other. Which is how the reference is built, one mass of - * foliage to each big bough. - */ - /** - * Small enough that the masses DO NOT ALL MERGE. - * - * This is the correction that mattered, and it was my own rule that had - * to go: I decided early that "a crown is one piece" and made the probe - * fail anything else, so every version since has been tuned until the - * flood fill returned 1 — which is exactly the instruction "be a single - * smooth blob", and that is what it kept producing. - * - * The support rule requires the crown to be connected to the TREE, not - * to itself. A clump that swallows a branch end is held up by that - * branch whatever its neighbours do. Letting them separate is what buys - * the gaps, and the gaps are the silhouette — a crown you can see - * through in places is the difference between foliage and a cabbage. - */ - const clumpR = crownR * 0.26 * (0.55 + 0.45 * leafiness) - // The tips stop short of the crown radius by most of a clump, so that - // `spread` describes the width of the FINISHED crown rather than of the - // bare branchwork inside it. - const reach = crownR - clumpR * 0.8 - - for (let i = 0; i < limbCount; i += 1) { - const f = limbCount === 1 ? 0 : i / (limbCount - 1) - /** - * Limbs crowd towards the BOTTOM of their range. - * - * Spaced evenly up the bole, the crown's mass began at 29% of the - * height while two long bottom limbs carried their leaves out at 10% - * to 30% with nothing around them -- and the flood fill found exactly - * that: a 7000-cell piece at bearing 228-313 degrees, reaching 5.7 m - * out where the main mass stopped at 4.5, torn off vertically rather - * than sideways. Two rounds of widening clumps and evening out the - * bearings had each failed because neither was the gap. - * - * The reference is at full width by 24% of its height and holds it to - * 44%, which means most of its limbs are in the bottom half. Raising f - * to a power puts them there: nine limbs land at 30, 33, 36, 41, 47, - * 53, 59, 64 and 70% instead of evenly every 5%. - */ - const g = Math.pow(f, 1.35) - const ay = H * (0.24 + 0.44 * g) + jitter(random, H * 0.015) - const ty = H * (0.390 + 0.490 * g) + jitter(random, H * 0.02) - - // Driven by g, the same crowded parameter the heights use, so that a - // limb low on the bole is also a LONG one -- which is the reference's - // arrangement and the reason its crown is widest near the bottom. - // Leaving this on the even f while the heights moved to g put the - // widest row up at 54%. - // - // And the spread narrowed from +/-12% to +/-6%: at 12% the single - // longest limb reached 5.6 m where its neighbours stopped at 4.5, and - // its lobe was stranded out there on its own with nothing to touch. It - // is the same tear the flood fill kept finding, and no amount of - // widening the clumps reaches across a gap made by one limb outrunning - // the rest -- the fix is for it not to outrun them. - const tr = reach * (1 - 0.8 * g) * (0.94 + random() * 0.12) - - // Straight from the geometry, not chosen: a limb whose tip lands level - // with its own root is horizontal, and atan2 says so without any - // special case. - // - // Plus HALF THE SWEEP, which is the part I had missed. Bending a limb - // does not just curve it, it swings the whole chord from root to tip up - // by half the arc -- so a limb aimed at its intended tip and then bent - // lands well above it. Every limb was arriving 0.21 rad high and the - // crown's widest point had climbed from the 24% of the reference to - // 38%. Aiming low by exactly the amount the bend will lift is the - // whole correction, and it is a constant because SWEEP is an angle. - const rise = ty - ay - const tilt = Math.atan2(tr, rise) + SWEEP / 2 - const len = Math.hypot(tr, rise) - - const local: BufferGeometry[] = [] - const leaves: BufferGeometry[] = [] - - // 0.85 of the bole where it grows, not 0.55. A main limb on the - // reference is very nearly as thick as the trunk it leaves, and thin - // limbs are invisible under the crown -- which cost the model the - // whole radiating structure that says "tree" before the leaves do. - const r0 = boleAt(ay) * 0.85 - const limb = latheGeometry( - [0, 0.25, 0.5, 0.75, 1].map((t, k) => ({ - y: len * t, - radius: r0 * [1, 0.72, 0.52, 0.36, 0.22][k]!, - })) as Level[], - // Not lifted. A bough lifted above the bole's own tone came out - // sandy next to it, which is invisible under a full crown and is the - // entire model at `leafiness: 0`. - 4, [0, 0, 0], tint('bark', -0.02, 0.9), - ) - local.push(limb) - - /** - * Everything for this limb is built along +Y with its foot at the - * ORIGIN, and only turned into place at the end. - * - * That is what makes the forks and the clumps free: they are placed in - * the limb's own frame, where "along the branch" is just +Y, and the - * bend and the two rotations are then applied to the whole assembly at - * once. Nothing can come adrift from the limb it belongs to, because - * nothing is ever positioned in world space. - * - * It also means the limb's foot sits ON the trunk's axis, buried a - * whole bole radius inside the bole. There is no join to get wrong. - */ - const forks = 2 - for (let j = 0; j < forks; j += 1) { - // Outboard. At 0.58 the first fork threw its leaves back towards - // the trunk and packed the space around the bole solid, so the crown - // came down as an unbroken dome and the tree lost the one thing that - // separates it from a bush: you could not see the bole rise into it. - const at = len * (0.62 + 0.23 * j) - // Always positive, and that is the whole of the fix. - // - // The rise of a fork works out as sin(splay) * sin(spin), so it is - // the SIGN OF THE PRODUCT that decides up or down. Constraining the - // spin to the upper half circle and then alternating the splay - // between + and - left every second fork pointing at the floor -- and - // the measurement said so plainly while the reasoning had said the - // opposite. With the splay kept positive the spin alone carries the - // variety, and it still swings the fork right round through the - // horizontal because cos(spin) runs from +1 to -1 across the range. - const splay = 0.42 + random() * 0.26 - /** - * Which way the fork throws, and it may not throw DOWNWARD. - * - * Spun freely through the whole circle, a fork on a near-horizontal - * bottom limb can come off 39 degrees below the horizontal, drop the - * best part of a metre, and hang its clump on the floor -- which is - * how the crown came to be 7 m wide at 2% of the tree's height, where - * the reference has nothing but bare bole. - * - * In the limb's own frame +Z is the direction `rotateX` will send - * upward, so keeping the spin inside (0, PI) keeps the fork's rise - * positive whatever the limb is doing. Side shoots on a real bough - * grow up and out; none of them grow down. - */ - const spin = Math.PI / 2 + jitter(random, 1.5) - const secLen = len * (0.34 - 0.1 * j) * (0.8 + random() * 0.4) - const secR = r0 * (0.42 - 0.12 * j) - - // Three levels on four sides: a fork is short, half buried in the - // clump on its end, and never seen in silhouette. It is the cheapest - // thing in the model to make cheaper. - const sec = latheGeometry( - [0, 0.55, 1].map((t, k) => ({ - y: secLen * t, - radius: secR * [1, 0.5, 0.2][k]!, - })) as Level[], - 3, [0, 0, 0], tint('bark', 0.0, 0.9), - ) - sec.rotateZ(splay) - sec.rotateY(spin) - sec.translate(0, at, 0) - local.push(sec) - - // Only the OUTER fork gets a clump, which is what pays for the - // inner one above. The inner fork sits under the crown's own mass - // and its clump was never seen. - if (false) { - // The tip, worked out rather than guessed: rotateZ then rotateY - // sends +Y to this direction, and a clump centred there is - // guaranteed to contain the branch end it hangs on. - const dir: readonly [number, number, number] = [ - -Math.sin(splay) * Math.cos(spin), - Math.cos(splay), - Math.sin(splay) * Math.sin(spin), - ] - const tip: readonly [number, number, number] = [ - dir[0] * secLen, at + dir[1] * secLen, dir[2] * secLen, - ] - for (let k = 0; k < 1; k += 1) { - const r = clumpR * (0.78 + random() * 0.5) - // Offsets stay inside the clump's own radius, so consecutive - // clumps always overlap and the branch tip is always inside one. - leaves.push(clump(r, [ - tip[0] + jitter(random, r * 0.5), - tip[1] + jitter(random, r * 0.45), - tip[2] + jitter(random, r * 0.5), - ], 0.1 + jitter(random, 0.13))) - } - } - } - - if (leafiness > 0) { - /** - * Along the bough, INCLUDING well inboard. - * - * 0.38 is the one that matters and it took four failed rounds to - * arrive at. The crown kept coming apart into two pieces, and every - * attempt to close the gap treated it as a gap between LOBES -- - * wider clumps, evener bearings, more limbs, less length jitter -- - * none of which worked, because the crown was never short of foliage - * where those fixes put it. - * - * What was missing was the middle. I had pushed the leaves outboard - * to open up the space under the crown and taken the inside out with - * it, so nine lobes hung off a bare hub with nothing joining them. - * Looking at the reference again: its crown is FULL from the bole - * outward, and the clear space is underneath, not within. An inner - * clump on every bough gives them all a common core, and it is - * guaranteed to work rather than tuned to, because every bough passes - * through the middle. - */ - /** - * INCLUDING one well inboard, at 0.34. - * - * Every clump sat on the outer half of its limb, which makes a - * crown that is a RING: full at the rim, hollow in the middle, and - * from a third of the compass you are looking straight through the - * hole. The turntable is what showed it — one three-quarter view - * looked fine and two of six were full of daylight. - * - * I had this right once and removed it while cutting triangles, - * which is the cheapest kind of regression to make and the hardest - * to notice: nothing failed, the model just got worse. - */ - for (const along of [0.36, 0.68, 0.95]) { - const r = clumpR * (0.85 + random() * 0.45) - leaves.push(clump(r, [ - jitter(random, r * 0.55), len * along + jitter(random, r * 0.3), jitter(random, r * 0.55), - ], 0.1 + jitter(random, 0.13))) - } - } - - /** - * Bend, then tilt, then spin — in that order and no other. - * - * `bendGeometry` only curves toward +Z, so the tilt has to be a - * rotation about X: `rotateX(-tilt)` lays the limb over toward -Z while - * the bend is pushing toward +Z, and the two opposing each other is - * exactly the oak profile — out near horizontal, then turning up at the - * end. Tilting about Z instead would have left the bend pointing - * sideways out of the limb's own plane, and the limb would have curved - * ACROSS rather than up. - * - * The arc angle is `curvature * length`, so a fixed sweep divided by - * the length gives every limb the same 24 degrees of turn whatever its - * size — which is what keeps a short top limb looking like the same - * tree as a long bottom one. - */ - const curvature = SWEEP / len - /** - * Evenly divided, not the golden angle. - * - * The golden angle is the right answer for a great many leaves and the - * wrong one for nine limbs: it is uniform in the limit, but at this - * count it left azimuth gaps ranging from 17 to 52 degrees, and the - * widest gap was where the crown tore into two pieces. An even - * division gives every gap 40 degrees, and the jitter keeps it from - * looking like a wheel. - */ - const spin = (i / limbCount) * Math.PI * 2 + jitter(random, 0.11) - for (const group of [local, leaves]) { - if (group.length === 0) continue - const merged = mergeColoured(group) - bendGeometry(merged, curvature) - merged.rotateX(-tilt) - merged.rotateY(spin) - merged.translate(0, ay, 0) - ;(group === local ? wood : crown).push(merged) - } - } - - // The leader: the bole's own top, which is a branch tip like any other - // and gets its clump for the same reason. - if (leafiness > 0) { - // Two, sitting lower. Three clumps perched a third of a radius above - // the bole's tip put a cap on the crown, and the profile showed it: - // our top rows measured 0.63 and 0.55 of our widest against the - // reference's 0.46 and 0.35. An oak tapers to its top; it does not - // finish in a knob. - for (let i = 0; i < 2; i += 1) { - const r = clumpR * (0.8 + random() * 0.4) - crown.push(clump(r, [ - jitter(random, r * 0.9), - trunkTop + r * 0.1 + jitter(random, r * 0.35), - jitter(random, r * 0.9), - ], 0.1 + jitter(random, 0.13))) - } - } - - const boughs = mergeColoured(wood) - roughenGeometry(boughs, R * 0.09, { salt: 17 }) - const leaves = crown.length > 0 ? mergeColoured(crown) : undefined - - /** - * Make `height` mean the height. - * - * Everything above is laid out in fractions of H, but the clumps sit - * PROUD of the tips they hang on, so the finished tree overshot by 8% - * and the control was quietly lying. Rather than shave the numbers that - * came off the reference until they happen to land right -- which would - * have to be redone for every change to the clump size -- the assembly - * is measured and scaled to fit. Uniformly, so that every ratio the - * references gave survives it. - */ - const all = [trunk, boughs, ...(leaves ? [leaves] : [])] - let low = Infinity - let high = -Infinity - for (const g of all) { - const position = g.getAttribute('position') - for (let i = 0; i < position.count; i += 1) { - const y = position.getY(i) - if (y < low) low = y - if (y > high) high = y - } - } - const grown = high - low - if (grown > 1e-6) { - const k = H / grown - for (const g of all) { - g.scale(k, k, k) - g.translate(0, -low * k, 0) - g.computeVertexNormals() - } - } - - /** - * And make `spread` mean the spread, the same way. - * - * A uniform scale fixes the height but cannot fix the width, because the - * crown's width is not 2x its radius: seven limbs on a golden-angle - * spiral never put two of them opposite each other, so the bounding box - * is always narrower than the reach that produced it -- 1.12 against the - * 1.30 asked for. The shortfall depends on the limb count, so it cannot - * be a constant either. - * - * The stretch is horizontal only and it is applied to the LIMBS AND THE - * CROWN, never to the bole: stretching the trunk would throw away the one - * profile in this model that was read off a photograph row by row. It - * cannot pull anything loose, because every limb's foot sits exactly on - * the axis and a scale about the axis leaves the axis where it is. - */ - const spread = [boughs, ...(leaves ? [leaves] : [])] - let x0 = Infinity, x1 = -Infinity, z0 = Infinity, z1 = -Infinity - for (const g of spread) { - const position = g.getAttribute('position') - for (let i = 0; i < position.count; i += 1) { - const x = position.getX(i) - const z = position.getZ(i) - if (x < x0) x0 = x - if (x > x1) x1 = x - if (z < z0) z0 = z - if (z > z1) z1 = z - } - } - // The EXTENT, not the radius. Scaling until the furthest tip sat at the - // crown radius left the tree at 1.10 for 1.30 asked, because the furthest - // tip has nothing opposite it -- which is the very asymmetry this is here - // to correct for. The width of a thing is max minus min. - const widest = Math.max(x1 - x0, z1 - z0) - if (widest > 1e-6) { - const kx = (Math.max(0.2, config.spread) * H) / widest - for (const g of spread) { - g.scale(kx, 1, kx) - g.computeVertexNormals() - } - } - - /** - * Break the crown's outline up, or it is a pile of boulders. - * - * This is the difference between foliage and rock and it is a - * SILHOUETTE property, not a colour one. A clump built as a six-sided - * lathe has a smooth, regular outline, and a smooth outline at this - * scale reads as stone however green it is -- the first render of this - * crown looked like a cairn with moss on it. Roughening the merged crown - * ragged-edges every facet, and because the shift is derived from each - * corner's own position the surface stays closed and the clumps stay - * fused into the one mass they were sized to make. - * - * It goes AFTER both scalings so the amount is in finished metres. - */ - /** - * The crown is NOT roughened. - * - * It was, at 0.17 of a clump radius, on the reasoning that ragged edges - * read as foliage where smooth ones read as stone. That is true of a - * silhouette and false of a surface: what it actually did was crease - * every facet of every clump and turn the mass into crumpled paper. - * Rounded shapes that overlap already give a ragged OUTLINE — the - * raggedness has to come from the arrangement, not from the skin. - */ - - return { - trunk: { slot: 'oak' as const, geometry: trunk }, - boughs: { slot: 'oak' as const, geometry: boughs }, - // Explicitly `undefined` when bare, never omitted. The kit resets a - // part's anchor before it checks whether there is anything to put in - // it, so a key that is present and undefined empties the crown -- - // where a MISSING key would never be visited and last build's leaves - // would still be hanging there. - crown: leaves ? { slot: 'leaf' as const, geometry: leaves } : undefined, - } - }, - }, overrides) -}