medieval-kit/my-registry/models/core/kit.ts
CRT 5db9a1bb19 Add the oak
The first thing in this kit that grew rather than got made, and the first one
built entirely against reference photographs from the start rather than after
three rounds of guessing.

Two references, generated with the same Codex tool the rest of the kit now
uses: one oak in full leaf and the same tree bare. Both of them contradicted
what I was about to build, and the default lowpoly tree -- a tall pole with a
ball on it -- turns out to be 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.
  widest at                     24% of the height. Not halfway up: a quarter,
                                just above the ground, because the lowest limbs
                                are the longest and leave almost horizontally.
  bole runs to                  72% of the height as one continuous stem. It
                                does not fork low into equal leaders, which is
                                what the leafy photograph alone suggested and
                                the winter one disproved.
  bole width / height           0.130 at 2% of the height, 0.073 at 10%. It
                                nearly halves in the bottom tenth and then
                                barely tapers at all for a quarter of the tree.

The taper table in the model is those rows, read off the photograph one at a
time. The limbs SWEEP -- out at a shallow angle, turning up at the end -- which
comes free from bending each limb along its own axis before rotating it into
place, and which cost a correction I had not expected: bending a limb swings
its whole chord up by half the arc, so every limb was arriving 0.21 rad high
and the crown's widest point had climbed to 38%. Aiming low by exactly what the
bend will lift is the fix, and it is a constant.

Measuring is the whole story of this one. `scripts/probe-tree.ts` prints the
four reference numbers off the built geometry the same way they came off the
photographs, plus one a photograph cannot give: how many separate pieces the
crown is in. A crown is one piece. This one was four, then one, then two, then
one again, and the flood fill was right every time my eye was vague.

Four things it caught that looking would not have:

  - Forks throwing DOWNWARD. The rise of a fork is sin(splay) * sin(spin), so
    the sign of the PRODUCT decides it. I constrained the spin and alternated
    the splay, which left every second fork pointing at the floor. The
    measurement said so plainly while the reasoning said the opposite.
  - The crown torn in two, and not where I kept looking. Locating the loose
    piece -- height 10-64%, bearing 228-313, reaching 5.7 m where the main mass
    stopped at 4.5 -- ended four rounds of widening clumps and evening out
    bearings, none of which were the gap. The gap was the MIDDLE: pushing the
    leaves outboard to open the space under the crown had taken the inside out
    with it, and nine lobes hung off a bare hub. The reference's crown is full
    from the bole outward; the clear space is underneath.
  - Occlusion, exonerated. Turning it off entirely changed the clipping by
    nothing at all, which took two minutes and saved a redesign.
  - My own metric, wrong twice. It counted every dark pixel in the crown's box
    and 87% of what it found was the cast shadow, so it read 10.8% clipping on
    a crown that was barely clipping. And it measured the reference by row
    width but our own geometry by twice its radius, which is a different
    quantity on anything that is not symmetric.

Colour is measured too, and the measurement contradicted me again: I was about
to bake a top-to-bottom gradient into the crown, and sampled in three bands the
reference reads 0.362, 0.336, 0.324 -- no gradient at all. What is there is
local, a spread of 0.45 in lightness within one band. Foliage varies leaf to
leaf, not top to bottom. Chasing that 0.45 with tint, mottle and occlusion all
at once put 2.2% of the crown through the floor into pure black against the
reference's 0.19%, which is the straw trap for the third time: a statistic taken
off fine detail cannot be added on top of the machinery that already
reproduces it.

The bark is measured off the WINTER photograph after the summer one gave a
colour 28 degrees too green -- a trunk under a full crown is lit through the
leaves. Low saturation made it worse than the hue did: a nearly neutral colour
takes its hue from its light, and this renderer's blue-grey sky dragged the
rendered bole to hue 119 on a tree whose bark is brown.

Finished: hue 79.6 against 77.9, saturation 0.386 against 0.381, lightness
0.386 against 0.373, 0.00% clipped. Crown 1.325 wide for its height, in one
piece, hanging from 8% where the reference hangs from 11%.

The honest limits. What fills a real winter silhouette is thousands of twigs
and no budget here reaches them, so `leafiness: 0` is a bare tree of LIMBS --
a good dead or winter tree, not a photograph of one. And the crown still
carries more of its width high than the reference does: widest at 50% against
24%, on a reference profile that is nearly flat from 24 to 44 so the peak is
softer than the number sounds.

2310 triangles, inside the kit's 2500 budget, which cost a side off every clump
and a level off every fork -- but not one clump, because the count is what
holds the crown together. 35 models, 31 404 triangles, thirteen material slots,
all checks pass, 0 floating cases, GLB round-trip clean, Conformant.
2026-08-23 12:47:21 +00:00

333 lines
13 KiB
TypeScript

import { Group, Mesh, type BufferGeometry, type Material } from 'three'
import type { ConfigureResult, MaterialBindings, ModelInstance, PartHandle } from '@vibe3d/model.ts'
import { ResourceScope } from '@vibe3d/ownership.ts'
import type { Vec3 } from './geometry.ts'
import { mottleGeometry } from './geometry.ts'
import { bakeOcclusion, type OcclusionOptions } from './occlusion.ts'
import { createPart, type PartSlot } from './parts.ts'
import { createRandom } from './random.ts'
import { createMedievalMaterials, type MedievalSlot, type SlotMaterial } from './materials.ts'
/**
* Kit model scaffold.
*
* Every model has to set up the same contract: resource ownership, material
* resolution and overrides, fixed anchor + replaceable content, a configure()
* that does not break identity, an idempotent dispose(). Writing that by hand
* in every model means ~80 lines of repetition plus a chance to get it wrong
* on each repetition — and indeed I got the anchor/content split wrong in the
* first three models at once.
*
* From here on, writing a model is just producing geometry: `build` returns a
* part name → geometry mapping, this function handles the rest.
*/
/** The body of a part that uses a single material slot. */
export interface PartBody<S extends string> {
readonly slot: S
readonly geometry: BufferGeometry
}
export interface BuiltPart<S extends string> extends PartBody<S> {
/**
* Extra bodies belonging to the same part that use a DIFFERENT slot.
*
* Parts are sibling children of the root, so when one moves the others
* cannot follow it. A chest's lid is oak boards and iron bands and the
* lock's hasp all at once, and the three MUST rotate together — if they were
* separate parts, the bands would hang in mid-air as the lid opened.
*
* So this field does not preserve the assumption "one part = one mesh", it
* preserves the principle "one part = one meaning". The meaning is not
* split, only the material is.
*/
readonly extras?: readonly PartBody<S>[]
/**
* The part's own centre of rotation (in model space).
*
* When given, the anchor is positioned here and the geometry is assumed to
* have been written RELATIVE TO THIS POINT. This is the only thing needed
* for a chest lid to rotate around its hinge: the lid geometry is produced
* at the hinge origin, the anchor is moved to the hinge, and
* `anchor.rotation.x` now opens the lid.
*
* Objects the consumer attached to the anchor join this rotation too — a
* candle placed on top of the lid rises with the lid. That is the correct
* behaviour.
*/
readonly origin?: Vec3
}
export interface BuildContext<C, S extends MedievalSlot> {
readonly config: Readonly<C>
/** Seed-bound deterministic randomness. Starts over on every rebuild. */
readonly random: () => number
/** The slot's current material (the override, if there is one). */
resolve(slot: S): Material
/** The slot's default material — even if it has been overridden. */
readonly defaults: Pick<SlotMaterial, S>
}
/**
* The runtime context handed to actions and to `update`.
*
* It gives access to the PARTS, not to the geometry: an action must not
* trigger a rebuild, it should only move something in the scene graph. Opening
* the lid does not change the model's identity, so it is not `configure()`'s
* job.
*/
export interface RuntimeContext<C, P extends string> {
readonly parts: Record<P, PartHandle<Group>>
getConfig(): Readonly<C>
}
export interface KitModelOptions<
C extends { seed: number },
S extends MedievalSlot,
P extends string,
A extends object = Record<string, never>,
> {
/** Registry item name; used in mesh names and in userData. */
readonly id: string
readonly defaults: C
readonly slots: readonly S[]
/** Part name → geometry. `undefined` means absent in that configuration. */
build(context: BuildContext<C, S>): Record<P, BuiltPart<S> | undefined>
/**
* Ambient occlusion to bake into the vertex colours. `false` turns it off.
*
* All parts are evaluated TOGETHER: the place where a board darkens is the
* surface of the neighbouring post, not its own surface.
*/
readonly occlusion?: OcclusionOptions | false
/**
* Surface mottle written into the vertex colours. `false` turns it off.
*
* The amount is scaled BY SLOT (see the table below): burnished steel is not
* mottled, straw is mottled badly. The model does not have to do anything
* else.
*/
readonly mottle?: { readonly amount?: number; readonly cell?: number } | false
/**
* The model's typed actions. Set up once, after the first build — so state
* held in the closure (is the lid open, which flame phase) survives a
* rebuild.
*/
actions?(context: RuntimeContext<C, P>): A
/** Called each frame. If the consumer never calls it, the model stays fully static. */
update?(deltaSeconds: number, context: RuntimeContext<C, P>): void
}
/**
* Mottle multiplier per slot.
*
* The rule comes from the physics of the material: the more polished a surface
* is, the more it becomes a SINGLE COLOUR, because the light reaching the eye
* comes from the reflection rather than from the surface's own pigment. For
* straw and cloth the exact opposite holds.
*
* Tying this to the slot is better than tuning it separately in every model:
* within the kit the same material looks the same everywhere.
*/
const MOTTLE_BY_SLOT: Readonly<Record<MedievalSlot, number>> = {
straw: 1.35,
cloth: 1.15,
oak: 1,
char: 0.85,
leather: 0.7,
produce: 0.6,
iron: 0.5,
brass: 0.35,
steel: 0.22,
glass: 0.15,
// Between timber and iron. Rubble masonry varies block to block, but each
// block is fairly even in itself, so the mottle wants to read at the scale
// 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,
}
export function createKitModel<
C extends { seed: number },
S extends MedievalSlot,
P extends string,
A extends object = Record<string, never>,
>(
options: KitModelOptions<C, S, P, A>,
overrides: Partial<C> = {},
): ModelInstance<C, Record<P, PartHandle<Group>>, A> {
let config: C = { ...options.defaults, ...overrides }
// The resources the model owns. Materials handed in by the consumer never
// enter here, so dispose() does not touch them.
const scope = new ResourceScope()
const defaults = createMedievalMaterials(scope, options.slots)
const overridesBySlot = new Map<S, Material>()
const resolve = (slot: S): Material => overridesBySlot.get(slot) ?? defaults[slot]
const root = new Group()
root.name = options.id
const parts = {} as Record<P, PartSlot>
let owned: BufferGeometry[] = []
function build(): void {
for (const geometry of owned) geometry.dispose()
owned = []
const produced = options.build({
config,
random: createRandom(config.seed),
resolve,
defaults,
})
const built = Object.values(produced)
.filter((part): part is BuiltPart<S> => part !== undefined)
const geometriesOf = (part: BuiltPart<S>): BufferGeometry[] =>
[part, ...(part.extras ?? [])]
// A flame neither TAKES shadow nor CASTS one. `ember` is an unlit
// material, so its vertex colour is the final colour going straight to
// the screen — if occlusion darkened it, the flame would go out. The
// rule is tied to the slot itself, not to a per-model flag: it must
// not be possible to forget it.
.filter((body) => body.slot !== 'ember')
.map((body) => body.geometry)
if (options.occlusion !== false) {
// Occlusion has to be computed in ASSEMBLY space: a lid written at its
// own origin looks as though it sits inside the body rather than beside
// it, and darkens the wrong places. So everything is first moved into
// place, baked, then moved back — the resulting geometries stay
// hinge-local.
const moved = built.filter((part) => part.origin !== undefined)
for (const part of moved) {
const [x, y, z] = part.origin!
for (const geometry of geometriesOf(part)) geometry.translate(x, y, z)
}
bakeOcclusion(built.flatMap(geometriesOf), options.occlusion ?? {})
for (const part of moved) {
const [x, y, z] = part.origin!
for (const geometry of geometriesOf(part)) geometry.translate(-x, -y, -z)
}
}
if (options.mottle !== false) {
const amount = options.mottle?.amount ?? 0.125
// The mottle size is derived from the model's scale, but WITH ABSOLUTE
// BOUNDS.
//
// The bounds were added later and closed a real bug: with scale used on
// its own, a 4.89 m fence got a 0.27 m cell. The fence's post is 0.09 m
// — so the entire post fell into ONE cell and came out completely flat.
// The model paid the cost of the texture system and got nothing back.
//
// The truth is this: wood grain mottle is 2–8 cm and has nothing to do
// with the size of the object. A fence post and a tankard stave come out
// of the same tree.
const extent = built.reduce((largest, part) => {
part.geometry.computeBoundingBox()
const box = part.geometry.boundingBox
if (!box) return largest
return Math.max(largest, box.max.x - box.min.x, box.max.y - box.min.y, box.max.z - box.min.z)
}, 0)
const cell = options.mottle?.cell ?? Math.min(0.08, Math.max(0.015, extent * 0.055))
for (const part of built) {
for (const body of [part, ...(part.extras ?? [])]) {
mottleGeometry(body.geometry, amount * MOTTLE_BY_SLOT[body.slot], { cell, salt: 3 })
}
}
}
for (const [name, part] of Object.entries(produced) as Array<[P, BuiltPart<S> | undefined]>) {
// The anchor is created on first setup and NEVER changes again; only its
// content is renewed. That is why objects the consumer attached to the
// anchor survive a rebuild.
let slot = parts[name]
if (!slot) {
slot = createPart(`${options.id}/${name}`)
parts[name] = slot
root.add(slot.anchor)
}
const target = slot.reset()
if (!part) continue
// The position is updated but the ROTATION is not: the angle an action
// moved has to survive a rebuild, otherwise the chest's lid slams shut
// every time `configure()` is called.
if (part.origin) slot.anchor.position.set(...part.origin)
for (const body of [part, ...(part.extras ?? [])]) {
owned.push(body.geometry)
const mesh = new Mesh(body.geometry, resolve(body.slot))
mesh.name = `${options.id}/${name}`
mesh.userData.vibe3d = {
model: `@medieval-kit/${options.id}`,
part: name,
materialSlot: body.slot,
}
target.add(mesh)
}
}
}
build()
const runtime: RuntimeContext<C, P> = {
parts: parts as unknown as Record<P, PartHandle<Group>>,
getConfig: () => config,
}
const actions = (options.actions?.(runtime) ?? {}) as A
const materials: MaterialBindings = {
get: (slot) => (options.slots.includes(slot as S) ? resolve(slot as S) : undefined),
override: (slot, material) => {
if (!options.slots.includes(slot as S)) return
overridesBySlot.set(slot as S, material)
build()
},
reset: (slot) => {
if (!overridesBySlot.delete(slot as S)) return
build()
},
}
return {
root,
parts: parts as unknown as Record<P, PartHandle<Group>>,
actions,
materials,
getConfig: () => config,
configure: (patch): ConfigureResult => {
const next = { ...config, ...patch }
const changed = (Object.keys(next) as Array<keyof C>).some((key) => next[key] !== config[key])
if (!changed) return { rebuilt: false }
config = next
build()
return { rebuilt: true }
},
update: (deltaSeconds) => options.update?.(deltaSeconds, runtime),
dispose: () => {
for (const geometry of owned) geometry.dispose()
owned = []
for (const part of Object.values(parts) as PartSlot[]) part.reset()
scope.dispose()
},
}
}