Draw the card with a command instead of a browser

The card a shared link unfurls to was a picture of the models with no title on
it, and the models on it were too small to tell apart. Both are fixed, but the
part worth writing down is how.

The first attempt was an HTML page composed in the site's own fonts and
screenshotted. It looked right and it was wrong: the model count on it becomes
a picture of a number the moment the shutter closes, and `check-docs.ts`
cannot read a picture. That is the exact failure that check exists for — the
READMEs claimed 27 models when there were 37 — and a card is the worse place
to have it, because nobody reading one can see the kit to know it is stale.

So `bun run cover:build` counts the catalogue and draws the numbers it counted.
`site:build` runs it, which means the published card cannot be older than the
models it shows, and the day a model is added the card says 38 without anyone
remembering to make it.

Drawing type needed type. `scripts/text.ts` reads the outlines out of a `.ttf`
and fills them with a scanline pass — four sub-scanlines a row with exact
horizontal coverage, which is more code than sampling a 4x4 grid and visibly
better at the 16px the two mono lines are set in. It is deliberately partial:
format 4 cmap, simple and composite outlines, advances, no kerning or shaping.
What it cannot draw it throws on, because a headline missing a letter is not
something you notice before it is published. Archivo and IBM Plex Mono come
with it under the OFL, the same two faces the site is set in.

The renderer moved to `scripts/raster.ts` so the card and the contact sheet
draw from the same code and cannot disagree about what a barrel looks like;
`render.ts` is now the command line over it, unchanged in what it does. Its
one new flag is `--ground`, a flat background instead of the per-cell
gradient: forty gradients side by side read as banding, and on the page's own
ink the models float on the card as one field instead of sitting on it as a
grey slab.

Ten columns by four, because 1.91:1 and 37 models want 40 cells and at that
shape the cells come out square, which is what lets a barrel look like a barrel
at 116 pixels. The last row is centred — three empty cells left flush is a
notch in the corner, and a short row centred is how a contact sheet ends.

Byte-identical across runs, so it does not churn the diff on every build.
This commit is contained in:
CRTkafa 2026-08-27 15:00:15 +07:00
parent dfee59381e
commit b29762a540
11 changed files with 1135 additions and 443 deletions

View file

@ -191,7 +191,10 @@ scripts/
zfight.ts coplanar overlap detection zfight.ts coplanar overlap detection
support.ts voxel connectivity — nothing may float support.ts voxel connectivity — nothing may float
audit.ts runs the support check across every configuration audit.ts runs the support check across every configuration
render.ts offline software rasteriser → PNG contact sheet raster.ts the software renderer: triangles in, PNG out
render.ts its command line — sheets, sweeps, turntables
text.ts a TrueType reader, so the renderer can set type
build-cover.ts the social card, with its numbers counted not typed
check-docs.ts documented counts against the models themselves check-docs.ts documented counts against the models themselves
reference-shots.ts one photographic reference per model, for comparison reference-shots.ts one photographic reference per model, for comparison
catalog-table.ts regenerates the model table in the registry README catalog-table.ts regenerates the model table in the registry README
@ -199,6 +202,8 @@ scripts/
media/ media/
kit.png the whole catalogue as one scene kit.png the whole catalogue as one scene
models.png the contact sheet, one cell per model models.png the contact sheet, one cell per model
cover.png the card a shared link shows; built, not drawn
fonts/ Archivo and IBM Plex Mono, under the OFL
models.json which registries this project resolves models.json which registries this project resolves
models.lock.json install receipt; `vibe3d diff` compares against it models.lock.json install receipt; `vibe3d diff` compares against it
``` ```

View file

@ -90,7 +90,10 @@ scripts/
verify-model.ts browserless conformance validation verify-model.ts browserless conformance validation
verify-glb.ts GLB round-trip validation verify-glb.ts GLB round-trip validation
zfight.ts coplanar face detection zfight.ts coplanar face detection
render.ts offline software rasterizer → PNG raster.ts the software renderer, no browser, no GPU
render.ts its command line: sheets, sweeps, turntables
text.ts TrueType outlines, filled by scanline
build-cover.ts media/cover.png, the card a link unfurls to
export-glb.ts exports the whole kit to GLB export-glb.ts exports the whole kit to GLB
catalog-table.ts generates the model table in REFERENCE.md catalog-table.ts generates the model table in REFERENCE.md
build-artifact.ts bundles the viewer into a single file build-artifact.ts bundles the viewer into a single file
@ -754,6 +757,8 @@ bun my-registry/build.ts # generate registry.json
bun scripts/verify-model.ts # full validation bun scripts/verify-model.ts # full validation
bun scripts/verify-glb.ts # GLB round-trip bun scripts/verify-glb.ts # GLB round-trip
bun scripts/render.ts [--one <id>] [--ids a,b] [--sweep "k=v1|v2"] [--size N] bun scripts/render.ts [--one <id>] [--ids a,b] [--sweep "k=v1|v2"] [--size N]
[--angles N] [--columns N] [--height N] [--ground <hex>]
bun scripts/build-cover.ts # media/cover.png
bun scripts/export-glb.ts [--one <id>] [--out dir] bun scripts/export-glb.ts [--one <id>] [--out dir]
bun scripts/catalog-table.ts # the document's table bun scripts/catalog-table.ts # the document's table

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 166 KiB

Before After
Before After

Binary file not shown.

Binary file not shown.

94
media/fonts/OFL.txt Normal file
View file

@ -0,0 +1,94 @@
Copyright 2020 The Archivo Project Authors (https://github.com/Omnibus-Type/Archivo)
Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

View file

@ -12,7 +12,8 @@
"registry:build": "bun my-registry/build.ts", "registry:build": "bun my-registry/build.ts",
"registry:validate": "vibe3d registry validate my-registry/dist/registry.json", "registry:validate": "vibe3d registry validate my-registry/dist/registry.json",
"viewer:build": "vite build --config vite.viewer.config.ts && bun scripts/build-artifact.ts", "viewer:build": "vite build --config vite.viewer.config.ts && bun scripts/build-artifact.ts",
"site:build": "bun run registry:build && bun run viewer:build && bun scripts/build-site.ts", "cover:build": "bun scripts/build-cover.ts",
"site:build": "bun run registry:build && bun run viewer:build && bun run cover:build && bun scripts/build-site.ts",
"site:ci": "bun install --frozen-lockfile && bun run site:build", "site:ci": "bun install --frozen-lockfile && bun run site:build",
"verify:glb": "bun scripts/verify-glb.ts", "verify:glb": "bun scripts/verify-glb.ts",
"render": "bun scripts/render.ts", "render": "bun scripts/render.ts",

129
scripts/build-cover.ts Normal file
View file

@ -0,0 +1,129 @@
/**
* Builds `media/cover.png`: the 1200×630 card that every shared link, search
* result and chat unfurl of https://medieval.crt.fyi/ shows.
*
* bun run cover:build
*
* It is a script and not a design file for one reason: the numbers on it are
* COUNTED, not typed. A card that says "37 models" is a picture of a number,
* and a picture cannot be checked the way `check-docs.ts` checks the READMEs —
* so it is built from the catalogue on every site build, and the day a model
* is added the card says so without anyone remembering to make it.
*
* Everything it draws comes from the pieces beside it: the models from
* `raster.ts`, which is the same renderer the contact sheet uses, so the card
* cannot disagree with it about what a barrel looks like; and the type from
* `text.ts`, reading the site's own two faces out of their `.ttf` files, so
* the card is set in the same Archivo and IBM Plex Mono as the page it
* advertises.
*/
import { writeFile } from 'node:fs/promises'
import { Mesh } from 'three/webgpu'
import { blit, encodePng, newFrame, renderOne, toLinear } from './raster.ts'
import { fillText, measure, readFont } from './text.ts'
import { MODEL_META } from '../my-registry/meta.ts'
import { CATALOG } from '@/catalog.ts'
/* ------------------------------------------------------------- the palette */
// src/viewer.css, so the card and the page it links to are the same object.
const INK = toLinear('0b0e12')
const RULE = toLinear('2a333e')
const TEXT = toLinear('c7d1db')
const DIM = toLinear('7a8899')
const AMBER = toLinear('f0a93c')
/* -------------------------------------------------------------- the layout */
const WIDTH = 1200 // 1.91:1, which is what every unfurl crops to
const HEIGHT = 630
const MARGIN = 20
const COLUMNS = 10
const CELL = 116
/* --------------------------------------------------------------- the models */
const ids = Object.keys(CATALOG).filter((id) =>
MODEL_META[id] !== undefined && id !== 'pressure-gauge' && id !== 'kit')
let triangles = 0
for (const id of ids) {
const built = CATALOG[id]!.build()
built.root.traverse((object) => {
if (!(object instanceof Mesh)) return
const index = object.geometry.getIndex()
triangles += (index ? index.count : object.geometry.getAttribute('position').count) / 3
})
built.dispose()
}
const card = newFrame(WIDTH, HEIGHT, INK)
/**
* Ten columns and four rows, because a card is 1.91:1 and 37 models want 40
* cells: at that shape the cells come out square, which is what lets a barrel
* look like a barrel at 116 pixels.
*
* The models are rendered on the card's own background rather than the contact
* sheet's per-cell gradient, so they float on it as one field instead of
* sitting on it as a grey slab — and the three cells the kit does not fill
* stop being a hole. The last row is centred for the same reason: a short row
* left flush with the others is a notch in the bottom right corner, and a
* short row centred is how a contact sheet is supposed to end.
*/
const rows = Math.ceil(ids.length / COLUMNS)
const gridTop = HEIGHT - MARGIN - rows * CELL
ids.forEach((id, index) => {
const row = Math.floor(index / COLUMNS)
const column = index % COLUMNS
const inRow = Math.min(COLUMNS, ids.length - row * COLUMNS)
const rowLeft = (WIDTH - inRow * CELL) / 2
blit(card, renderOne(id, { size: CELL, ground: INK }), rowLeft + column * CELL, gridTop + row * CELL)
console.log(` ${id}`)
})
/* ----------------------------------------------------------------- the type */
const archivo = readFont('media/fonts/Archivo-Bold.ttf')
const mono = readFont('media/fonts/IBMPlexMono-Regular.ttf')
const left = MARGIN + 20
const right = WIDTH - MARGIN - 20
fillText(card, archivo, '@medieval-kit', { x: left - 2, y: 60, size: 52, colour: TEXT })
fillText(card, mono, 'Procedural lowpoly props for three.js. Install the source, not the asset.', {
x: left, y: 92, size: 16, colour: DIM,
})
// The install line is the whole point of a source registry, so it is set as
// something you could type rather than as one more sentence about it.
const prompt = fillText(card, mono, '$ ', { x: left, y: 118, size: 16, colour: AMBER })
fillText(card, mono, `bunx vibe3d add @medieval-kit/${ids[0]}`, { x: prompt, y: 118, size: 16, colour: TEXT })
// Counted, never typed.
const count = `${ids.length} models`
fillText(card, mono, count, { x: right, y: 58, size: 22, colour: AMBER, align: 'right' })
fillText(card, mono, `${triangles.toLocaleString('en-US')} triangles`, {
x: right, y: 86, size: 16, colour: DIM, align: 'right',
})
fillText(card, mono, 'MIT licensed', { x: right, y: 110, size: 16, colour: DIM, align: 'right' })
// A hairline between the type and the models, held inside the margins so it
// reads as a rule rather than as the edge of a box.
for (let x = left; x < right; x += 1) {
const at = ((gridTop - 18) * WIDTH + x) * 3
card.colour[at] = RULE[0]; card.colour[at + 1] = RULE[1]; card.colour[at + 2] = RULE[2]
}
/* ---------------------------------------------------------------------- out */
const png = encodePng(card)
await writeFile('media/cover.png', png)
console.log(
`\nmedia/cover.png — ${WIDTH}×${HEIGHT}, ${Math.round(png.length / 1024)} KB`
+ `\n${count} · ${triangles.toLocaleString('en-US')} triangles`
+ `\nheadline ${Math.round(measure(archivo, '@medieval-kit', 52))} px wide`,
)

490
scripts/raster.ts Normal file
View file

@ -0,0 +1,490 @@
/**
* The software renderer: triangles in, PNG out. No browser, no GPU.
*
* Why it exists: every check the kit had until now was GEOMETRIC. Triangle
* count, winding order, coplanar faces, bounding box... all of them caught real
* bugs, but none of them could say "this shovel does not look like a shovel".
* To say that sentence you have to LOOK at the model.
*
* So there is a tiny software rasteriser here: it collects the triangles,
* projects them through a camera, fills them with a z-buffer and writes a PNG.
* The goal is not a pretty image but a READABLE SILHOUETTE — there is just
* enough shading to work out what the silhouette is, not a millimetre more.
*
* This is the library. `render.ts` is the command line over it and
* `build-cover.ts` is the social card; both draw the same models the same way,
* which is the point of the split — the card must not be able to disagree with
* the contact sheet about what a model looks like.
*/
import { deflateSync } from 'node:zlib'
import {
Box3,
Mesh,
PerspectiveCamera,
Sphere,
Vector3,
type Object3D,
} from 'three/webgpu'
import { CATALOG } from '@/catalog.ts'
/* ---------------------------------------------------------------- triangles */
interface Triangle {
readonly a: Vector3
readonly b: Vector3
readonly c: Vector3
/** Vertex colours, in LINEAR space. */
readonly ca: [number, number, number]
readonly cb: [number, number, number]
readonly cc: [number, number, number]
readonly metalness: number
readonly roughness: number
/** Unlit surface (flame). The vertex colour is the result directly. */
readonly unlit: boolean
readonly opacity: number
}
function collect(root: Object3D): Triangle[] {
root.updateMatrixWorld(true)
const out: Triangle[] = []
root.traverse((object) => {
if (!(object instanceof Mesh)) return
const geometry = object.geometry
const position = geometry.getAttribute('position')
if (!position) return
const colour = geometry.getAttribute('color')
const index = geometry.getIndex()
const count = index ? index.count : position.count
const material = object.material as {
metalness?: number
roughness?: number
opacity?: number
transparent?: boolean
isMeshBasicMaterial?: boolean
}
const unlit = material.isMeshBasicMaterial === true
const opacity = material.transparent ? (material.opacity ?? 1) : 1
const vertex = (i: number): { p: Vector3; c: [number, number, number] } => {
const v = index ? index.getX(i) : i
const p = new Vector3().fromBufferAttribute(position, v).applyMatrix4(object.matrixWorld)
const c: [number, number, number] = colour
? [colour.getX(v), colour.getY(v), colour.getZ(v)]
: [0.8, 0.8, 0.8]
return { p, c }
}
for (let i = 0; i < count; i += 3) {
const a = vertex(i), b = vertex(i + 1), c = vertex(i + 2)
out.push({
a: a.p, b: b.p, c: c.p,
ca: a.c, cb: b.c, cc: c.c,
metalness: material.metalness ?? 0,
roughness: material.roughness ?? 0.8,
unlit,
opacity,
})
}
})
return out
}
/* --------------------------------------------------------------------- colour */
/** Linear → sRGB. The palette colours are stored linear inside three. */
export function encode(value: number): number {
const v = Math.min(1, Math.max(0, value))
const s = v <= 0.0031308 ? v * 12.92 : 1.055 * Math.pow(v, 1 / 2.4) - 0.055
return Math.round(s * 255)
}
/** sRGB hex → linear, so `encode` puts the exact bytes back out again. */
export function toLinear(hex: string): [number, number, number] {
const n = Number.parseInt(hex.replace('#', ''), 16)
return [16, 8, 0].map((shift) => {
const v = ((n >> shift) & 0xff) / 255
return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4)
}) as [number, number, number]
}
/* -------------------------------------------------------------- rasterising */
const LIGHT = new Vector3(0.48, 0.82, 0.31).normalize()
const SKY: [number, number, number] = [0.42, 0.52, 0.68]
const GROUND: [number, number, number] = [0.24, 0.2, 0.16]
export interface Frame {
readonly width: number
readonly height: number
readonly colour: Float32Array // rgb, linear
readonly depth: Float32Array
}
/**
* @param ground A flat background, in linear space, instead of the gradient.
*
* The default gradient is right for a contact sheet, where every cell wants to
* be its own little photograph. It is wrong for the social card: forty cells
* each with their own top-to-bottom gradient come out as visible banding, and
* the sheet sits on the page as a grey slab rather than as part of it. Given
* the page's own background instead, the models float on the card as one field
* and the three cells the kit does not fill stop being a hole in the corner.
*/
export function newFrame(width: number, height: number, ground?: readonly number[]): Frame {
const colour = new Float32Array(width * height * 3)
if (ground) {
for (let i = 0; i < width * height; i += 1) {
colour[i * 3] = ground[0]!
colour[i * 3 + 1] = ground[1]!
colour[i * 3 + 2] = ground[2]!
}
return { width, height, colour, depth: new Float32Array(width * height).fill(Infinity) }
}
// Background: a calm grey-blue that darkens from top to bottom. A flat
// colour was the one thing that made the model's silhouette hard to read.
for (let y = 0; y < height; y += 1) {
const t = y / (height - 1)
const r = 0.052 + 0.028 * (1 - t)
const g = 0.058 + 0.034 * (1 - t)
const b = 0.068 + 0.046 * (1 - t)
for (let x = 0; x < width; x += 1) {
const i = (y * width + x) * 3
colour[i] = r; colour[i + 1] = g; colour[i + 2] = b
}
}
return { width, height, colour, depth: new Float32Array(width * height).fill(Infinity) }
}
interface Projected {
x: number
y: number
z: number
behind: boolean
}
function project(point: Vector3, camera: PerspectiveCamera, frame: Frame): Projected {
const v = point.clone().project(camera)
return {
x: (v.x * 0.5 + 0.5) * frame.width,
y: (1 - (v.y * 0.5 + 0.5)) * frame.height,
z: v.z,
// Vertices behind the camera flip sign when projected and fling the
// triangle to the opposite side of the screen. Instead of clipping we drop
// such triangles entirely — the viewer camera always frames the model, so
// this can only happen when something is wrong.
behind: v.z < -1 || v.z > 1,
}
}
function shade(tri: Triangle, normal: Vector3, albedo: [number, number, number]): [number, number, number] {
if (tri.unlit) return albedo
const ndl = Math.max(0, normal.dot(LIGHT))
// Hemisphere ambient: surfaces facing up see the sky, ones facing down see
// the ground. Metals are fed almost entirely from here — a metal with no
// environment map would otherwise come out pitch black.
const up = normal.y * 0.5 + 0.5
const ambient: [number, number, number] = [
GROUND[0] + (SKY[0] - GROUND[0]) * up,
GROUND[1] + (SKY[1] - GROUND[1]) * up,
GROUND[2] + (SKY[2] - GROUND[2]) * up,
]
const metal = tri.metalness
const diffuseStrength = (1 - metal * 0.85) * (0.28 + ndl * 1.05)
const envStrength = 0.35 + metal * 0.9
// Blinn-Phong highlight: the exponent is derived from the roughness.
const exponent = Math.pow(2, (1 - tri.roughness) * 10) + 1
const half = LIGHT.clone().add(new Vector3(0, 0, 1)).normalize()
const spec = Math.pow(Math.max(0, normal.dot(half)), exponent) * (1 - tri.roughness) * 1.6
return [0, 1, 2].map((i) => {
const base = albedo[i]!
const lit = base * diffuseStrength + base * ambient[i]! * envStrength
// On metal the reflection colour comes from albedo, on a dielectric white.
const tint = metal > 0.5 ? base : 1
return lit + spec * tint * (0.35 + metal * 0.9)
}) as [number, number, number]
}
function raster(frame: Frame, camera: PerspectiveCamera, triangles: readonly Triangle[]): void {
// Transparent triangles go last: they test depth but do NOT write depth,
// otherwise the wick behind the glass disappears.
const ordered = [...triangles].sort((a, b) => (a.opacity === b.opacity ? 0 : a.opacity < 1 ? 1 : -1))
for (const tri of ordered) {
const pa = project(tri.a, camera, frame)
const pb = project(tri.b, camera, frame)
const pc = project(tri.c, camera, frame)
if (pa.behind || pb.behind || pc.behind) continue
// Signed area in screen space: if negative the triangle has its back to
// us. Back-face culling MATTERS here — a model with a winding-order bug
// should look inside-out in the image, not be hidden.
const area = (pb.x - pa.x) * (pc.y - pa.y) - (pc.x - pa.x) * (pb.y - pa.y)
if (area >= 0) continue
const normal = new Vector3()
.subVectors(tri.b, tri.a)
.cross(new Vector3().subVectors(tri.c, tri.a))
.normalize()
const minX = Math.max(0, Math.floor(Math.min(pa.x, pb.x, pc.x)))
const maxX = Math.min(frame.width - 1, Math.ceil(Math.max(pa.x, pb.x, pc.x)))
const minY = Math.max(0, Math.floor(Math.min(pa.y, pb.y, pc.y)))
const maxY = Math.min(frame.height - 1, Math.ceil(Math.max(pa.y, pb.y, pc.y)))
for (let y = minY; y <= maxY; y += 1) {
for (let x = minX; x <= maxX; x += 1) {
const px = x + 0.5, py = y + 0.5
const w0 = ((pb.x - pa.x) * (py - pa.y) - (px - pa.x) * (pb.y - pa.y)) / area
const w1 = ((pc.x - pb.x) * (py - pb.y) - (px - pb.x) * (pc.y - pb.y)) / area
const w2 = 1 - w0 - w1
if (w0 < 0 || w1 < 0 || w2 < 0) continue
// w1 → a, w2 → b, w0 → c (opposite vertices of the edge functions)
const z = pa.z * w1 + pb.z * w2 + pc.z * w0
const at = y * frame.width + x
if (z >= frame.depth[at]!) continue
const albedo: [number, number, number] = [
tri.ca[0] * w1 + tri.cb[0] * w2 + tri.cc[0] * w0,
tri.ca[1] * w1 + tri.cb[1] * w2 + tri.cc[1] * w0,
tri.ca[2] * w1 + tri.cb[2] * w2 + tri.cc[2] * w0,
]
const rgb = shade(tri, normal, albedo)
const i = at * 3
const alpha = tri.opacity
frame.colour[i] = frame.colour[i]! * (1 - alpha) + rgb[0] * alpha
frame.colour[i + 1] = frame.colour[i + 1]! * (1 - alpha) + rgb[1] * alpha
frame.colour[i + 2] = frame.colour[i + 2]! * (1 - alpha) + rgb[2] * alpha
if (alpha >= 1) frame.depth[at] = z
}
}
}
}
/** Contact shadow: flatten the model onto the y=floor plane and draw it dark. */
function contactShadow(frame: Frame, camera: PerspectiveCamera, triangles: readonly Triangle[], floor: number): void {
for (const tri of triangles) {
if (tri.unlit) continue
const flat = (v: Vector3): Vector3 => new Vector3(v.x, floor + 0.0005, v.z)
const pa = project(flat(tri.a), camera, frame)
const pb = project(flat(tri.b), camera, frame)
const pc = project(flat(tri.c), camera, frame)
if (pa.behind || pb.behind || pc.behind) continue
const area = (pb.x - pa.x) * (pc.y - pa.y) - (pc.x - pa.x) * (pb.y - pa.y)
if (area === 0) continue
const minX = Math.max(0, Math.floor(Math.min(pa.x, pb.x, pc.x)))
const maxX = Math.min(frame.width - 1, Math.ceil(Math.max(pa.x, pb.x, pc.x)))
const minY = Math.max(0, Math.floor(Math.min(pa.y, pb.y, pc.y)))
const maxY = Math.min(frame.height - 1, Math.ceil(Math.max(pa.y, pb.y, pc.y)))
for (let y = minY; y <= maxY; y += 1) {
for (let x = minX; x <= maxX; x += 1) {
const px = x + 0.5, py = y + 0.5
const w0 = ((pb.x - pa.x) * (py - pa.y) - (px - pa.x) * (pb.y - pa.y)) / area
const w1 = ((pc.x - pb.x) * (py - pb.y) - (px - pb.x) * (pc.y - pb.y)) / area
const w2 = 1 - w0 - w1
if (w0 < 0 || w1 < 0 || w2 < 0) continue
const i = (y * frame.width + x) * 3
for (let k = 0; k < 3; k += 1) frame.colour[i + k] = frame.colour[i + k]! * 0.55
}
}
}
}
/* ---------------------------------------------------------------------- PNG */
const CRC_TABLE = (() => {
const table = new Uint32Array(256)
for (let n = 0; n < 256; n += 1) {
let c = n
for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
table[n] = c >>> 0
}
return table
})()
function crc32(bytes: Uint8Array): number {
let c = 0xffffffff
for (const byte of bytes) c = CRC_TABLE[(c ^ byte) & 0xff]! ^ (c >>> 8)
return (c ^ 0xffffffff) >>> 0
}
function chunk(type: string, data: Uint8Array): Uint8Array {
const body = new Uint8Array(4 + data.length)
for (let i = 0; i < 4; i += 1) body[i] = type.charCodeAt(i)
body.set(data, 4)
const out = new Uint8Array(8 + data.length + 4)
const view = new DataView(out.buffer)
view.setUint32(0, data.length)
out.set(body, 4)
view.setUint32(out.length - 4, crc32(body))
return out
}
export function encodePng(frame: Frame): Uint8Array {
const { width, height, colour } = frame
const raw = new Uint8Array((width * 3 + 1) * height)
for (let y = 0; y < height; y += 1) {
const row = y * (width * 3 + 1)
raw[row] = 0
for (let x = 0; x < width; x += 1) {
const from = (y * width + x) * 3
const to = row + 1 + x * 3
raw[to] = encode(colour[from]!)
raw[to + 1] = encode(colour[from + 1]!)
raw[to + 2] = encode(colour[from + 2]!)
}
}
const ihdr = new Uint8Array(13)
const view = new DataView(ihdr.buffer)
view.setUint32(0, width)
view.setUint32(4, height)
ihdr[8] = 8 // bit depth
ihdr[9] = 2 // colour type: truecolour
const parts = [
new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]),
chunk('IHDR', ihdr),
chunk('IDAT', new Uint8Array(deflateSync(raw))),
chunk('IEND', new Uint8Array(0)),
]
const total = parts.reduce((sum, part) => sum + part.length, 0)
const png = new Uint8Array(total)
let at = 0
for (const part of parts) { png.set(part, at); at += part.length }
return png
}
/* ------------------------------------------------------------------ framing */
/** Camera that fits the model into frame. Same framing as in the viewer. */
function frameCamera(root: Object3D, width: number, height: number): { camera: PerspectiveCamera; floor: number } {
const box = new Box3().setFromObject(root)
const sphere = box.getBoundingSphere(new Sphere())
const camera = new PerspectiveCamera(32, width / height, 0.01, 100)
// Three-quarter view: the one angle that shows two faces at once. Looking
// straight on hides depth completely.
const direction = new Vector3(0.78, 0.5, 1).normalize()
/**
* Fit the BOX to the frame, not the sphere to the frame's short side.
*
* A sphere fit is one number and it is wrong for anything that is not
* roughly round. The whole-kit scene is wide and flat: its bounding sphere
* is set by the horizontal extent and is far taller than the scene is, so
* fitting that sphere into the vertical field left the models occupying a
* band across the middle with empty air above and below. On a 1.91:1 social
* card it was most of the picture.
*
* The box fit is iterative because perspective is not linear in distance:
* put the camera somewhere, project the eight corners, see how far past the
* frame edge the worst one lands, and move by that ratio. Two passes is
* inside a pixel at these sizes, and it settles on whichever axis is
* actually tight rather than assuming it is the vertical one.
*/
let distance = (sphere.radius / Math.sin((camera.fov * Math.PI) / 360)) * 1.12
const corner = new Vector3()
for (let pass = 0; pass < 3; pass += 1) {
camera.position.copy(sphere.center).addScaledVector(direction, distance)
camera.lookAt(sphere.center)
camera.updateMatrixWorld(true)
camera.updateProjectionMatrix()
let worst = 0
for (let i = 0; i < 8; i += 1) {
corner.set(
i & 1 ? box.max.x : box.min.x,
i & 2 ? box.max.y : box.min.y,
i & 4 ? box.max.z : box.min.z,
).project(camera)
worst = Math.max(worst, Math.abs(corner.x), Math.abs(corner.y))
}
if (worst <= 0) break
// 0.9 of the frame, so nothing sits on the edge and a shadow has room.
distance *= worst / 0.9
}
camera.position.copy(sphere.center).addScaledVector(direction, distance)
camera.lookAt(sphere.center)
camera.updateMatrixWorld(true)
camera.updateProjectionMatrix()
return { camera, floor: box.min.y }
}
export interface RenderOptions {
readonly size: number
/**
* Frame height, when it is not the width.
*
* Everything here is square because a contact sheet is a grid, but a social
* card is 1.91:1 and cropping a square down to it either loses the model or
* leaves it small.
*/
readonly tall?: number
readonly patch?: Record<string, number>
/** Pre-rotation of the model around the Y axis (radians). For turntables. */
readonly spin?: number
readonly ground?: readonly number[]
}
export function renderOne(id: string, options: RenderOptions): Frame {
const { size, tall = options.size, patch, spin = 0, ground } = options
const entry = CATALOG[id]
if (!entry) throw new Error(`not in catalog: ${id}`)
const built = entry.build()
if (patch && built.params) built.params.apply(patch)
// Catch animated models mid-motion: a frozen flame does not show that the
// flame flickers.
built.update?.(0.42)
// We rotate the MODEL, not the camera: framing and the shadow computation
// stay in a fixed direction, so turntable frames compare one to one.
built.root.rotation.y = spin
const triangles = collect(built.root)
const frame = newFrame(size, tall, ground)
const { camera, floor } = frameCamera(built.root, size, tall)
contactShadow(frame, camera, triangles, floor)
raster(frame, camera, triangles)
built.dispose()
return frame
}
/** Lays the frames out on a grid. */
export function tile(list: readonly Frame[], size: number, columns: number, ground?: readonly number[]): Frame {
const rows = Math.ceil(list.length / columns)
const sheet = newFrame(columns * size, rows * size, ground)
list.forEach((frame, index) => {
const ox = (index % columns) * size
const oy = Math.floor(index / columns) * size
blit(sheet, frame, ox, oy)
})
return sheet
}
/** Copies one frame into another. Colour only — the card has no depth to keep. */
export function blit(
target: Frame,
source: Frame,
atX: number,
atY: number,
crop?: { x: number; y: number; width: number; height: number },
): void {
const { x = 0, y = 0, width = source.width, height = source.height } = crop ?? {}
for (let row = 0; row < height; row += 1) {
const ty = atY + row
if (ty < 0 || ty >= target.height) continue
for (let column = 0; column < width; column += 1) {
const tx = atX + column
if (tx < 0 || tx >= target.width) continue
const from = ((y + row) * source.width + x + column) * 3
const to = (ty * target.width + tx) * 3
target.colour[to] = source.colour[from]!
target.colour[to + 1] = source.colour[from + 1]!
target.colour[to + 2] = source.colour[from + 2]!
}
}
}

View file

@ -1,430 +1,24 @@
/** /**
* Offline model viewer — no browser, no GPU. * Offline model viewer — no browser, no GPU.
* *
* Why it exists: every check the kit had until now was GEOMETRIC. Triangle * The renderer itself lives in `raster.ts`; this is the command line over it,
* count, winding order, coplanar faces, bounding box... all of them caught real * and the place where the ways of looking at a model are defined: one large,
* bugs, but none of them could say "this shovel does not look like a shovel". * all of them on a contact sheet, one across a parameter sweep, one turning on
* To say that sentence you have to LOOK at the model. * the spot.
*
* So there is a tiny software rasteriser here: it collects the triangles,
* projects them through a camera, fills them with a z-buffer and writes a PNG.
* The goal is not a pretty image but a READABLE SILHOUETTE — there is just
* enough shading to work out what the silhouette is, not a millimetre more.
* *
* Usage: * Usage:
* bun scripts/render.ts → all of them + contact sheet * bun scripts/render.ts → all of them + contact sheet
* bun scripts/render.ts --one wooden-chest → one model, large * bun scripts/render.ts --one wooden-chest → one model, large
* bun scripts/render.ts --size 640 * bun scripts/render.ts --size 640
* bun scripts/render.ts --one hand-cart --angles 8 → turntable
* bun scripts/render.ts --one hoe --sweep bladeAngle=0.2|0.4|0.6
* bun scripts/render.ts --ground 0b0e12 → flat background, not the gradient
*/ */
import { deflateSync } from 'node:zlib'
import { mkdir, writeFile } from 'node:fs/promises' import { mkdir, writeFile } from 'node:fs/promises'
import { import { encodePng, renderOne, tile, toLinear, type Frame } from './raster.ts'
Box3,
Mesh,
PerspectiveCamera,
Sphere,
Vector3,
type Object3D,
} from 'three/webgpu'
import { CATALOG } from '@/catalog.ts' import { CATALOG } from '@/catalog.ts'
/* ---------------------------------------------------------------- triangles */
interface Triangle {
readonly a: Vector3
readonly b: Vector3
readonly c: Vector3
/** Vertex colours, in LINEAR space. */
readonly ca: [number, number, number]
readonly cb: [number, number, number]
readonly cc: [number, number, number]
readonly metalness: number
readonly roughness: number
/** Unlit surface (flame). The vertex colour is the result directly. */
readonly unlit: boolean
readonly opacity: number
}
function collect(root: Object3D): Triangle[] {
root.updateMatrixWorld(true)
const out: Triangle[] = []
root.traverse((object) => {
if (!(object instanceof Mesh)) return
const geometry = object.geometry
const position = geometry.getAttribute('position')
if (!position) return
const colour = geometry.getAttribute('color')
const index = geometry.getIndex()
const count = index ? index.count : position.count
const material = object.material as {
metalness?: number
roughness?: number
opacity?: number
transparent?: boolean
isMeshBasicMaterial?: boolean
}
const unlit = material.isMeshBasicMaterial === true
const opacity = material.transparent ? (material.opacity ?? 1) : 1
const vertex = (i: number): { p: Vector3; c: [number, number, number] } => {
const v = index ? index.getX(i) : i
const p = new Vector3().fromBufferAttribute(position, v).applyMatrix4(object.matrixWorld)
const c: [number, number, number] = colour
? [colour.getX(v), colour.getY(v), colour.getZ(v)]
: [0.8, 0.8, 0.8]
return { p, c }
}
for (let i = 0; i < count; i += 3) {
const a = vertex(i), b = vertex(i + 1), c = vertex(i + 2)
out.push({
a: a.p, b: b.p, c: c.p,
ca: a.c, cb: b.c, cc: c.c,
metalness: material.metalness ?? 0,
roughness: material.roughness ?? 0.8,
unlit,
opacity,
})
}
})
return out
}
/* -------------------------------------------------------------- rasterising */
const LIGHT = new Vector3(0.48, 0.82, 0.31).normalize()
const SKY: [number, number, number] = [0.42, 0.52, 0.68]
const GROUND: [number, number, number] = [0.24, 0.2, 0.16]
/** Linear → sRGB. The palette colours are stored linear inside three. */
function encode(value: number): number {
const v = Math.min(1, Math.max(0, value))
const s = v <= 0.0031308 ? v * 12.92 : 1.055 * Math.pow(v, 1 / 2.4) - 0.055
return Math.round(s * 255)
}
interface Frame {
readonly width: number
readonly height: number
readonly colour: Float32Array // rgb
readonly depth: Float32Array
}
function newFrame(width: number, height: number): Frame {
const colour = new Float32Array(width * height * 3)
// Background: a calm grey-blue that darkens from top to bottom. A flat
// colour was the one thing that made the model's silhouette hard to read.
for (let y = 0; y < height; y += 1) {
const t = y / (height - 1)
const r = 0.052 + 0.028 * (1 - t)
const g = 0.058 + 0.034 * (1 - t)
const b = 0.068 + 0.046 * (1 - t)
for (let x = 0; x < width; x += 1) {
const i = (y * width + x) * 3
colour[i] = r; colour[i + 1] = g; colour[i + 2] = b
}
}
return { width, height, colour, depth: new Float32Array(width * height).fill(Infinity) }
}
interface Projected {
x: number
y: number
z: number
behind: boolean
}
function project(point: Vector3, camera: PerspectiveCamera, frame: Frame): Projected {
const v = point.clone().project(camera)
return {
x: (v.x * 0.5 + 0.5) * frame.width,
y: (1 - (v.y * 0.5 + 0.5)) * frame.height,
z: v.z,
// Vertices behind the camera flip sign when projected and fling the
// triangle to the opposite side of the screen. Instead of clipping we drop
// such triangles entirely — the viewer camera always frames the model, so
// this can only happen when something is wrong.
behind: v.z < -1 || v.z > 1,
}
}
function shade(tri: Triangle, normal: Vector3, albedo: [number, number, number]): [number, number, number] {
if (tri.unlit) return albedo
const ndl = Math.max(0, normal.dot(LIGHT))
// Hemisphere ambient: surfaces facing up see the sky, ones facing down see
// the ground. Metals are fed almost entirely from here — a metal with no
// environment map would otherwise come out pitch black.
const up = normal.y * 0.5 + 0.5
const ambient: [number, number, number] = [
GROUND[0] + (SKY[0] - GROUND[0]) * up,
GROUND[1] + (SKY[1] - GROUND[1]) * up,
GROUND[2] + (SKY[2] - GROUND[2]) * up,
]
const metal = tri.metalness
const diffuseStrength = (1 - metal * 0.85) * (0.28 + ndl * 1.05)
const envStrength = 0.35 + metal * 0.9
// Blinn-Phong highlight: the exponent is derived from the roughness.
const exponent = Math.pow(2, (1 - tri.roughness) * 10) + 1
const half = LIGHT.clone().add(new Vector3(0, 0, 1)).normalize()
const spec = Math.pow(Math.max(0, normal.dot(half)), exponent) * (1 - tri.roughness) * 1.6
return [0, 1, 2].map((i) => {
const base = albedo[i]!
const lit = base * diffuseStrength + base * ambient[i]! * envStrength
// On metal the reflection colour comes from albedo, on a dielectric white.
const tint = metal > 0.5 ? base : 1
return lit + spec * tint * (0.35 + metal * 0.9)
}) as [number, number, number]
}
function raster(frame: Frame, camera: PerspectiveCamera, triangles: readonly Triangle[]): void {
// Transparent triangles go last: they test depth but do NOT write depth,
// otherwise the wick behind the glass disappears.
const ordered = [...triangles].sort((a, b) => (a.opacity === b.opacity ? 0 : a.opacity < 1 ? 1 : -1))
for (const tri of ordered) {
const pa = project(tri.a, camera, frame)
const pb = project(tri.b, camera, frame)
const pc = project(tri.c, camera, frame)
if (pa.behind || pb.behind || pc.behind) continue
// Signed area in screen space: if negative the triangle has its back to
// us. Back-face culling MATTERS here — a model with a winding-order bug
// should look inside-out in the image, not be hidden.
const area = (pb.x - pa.x) * (pc.y - pa.y) - (pc.x - pa.x) * (pb.y - pa.y)
if (area >= 0) continue
const normal = new Vector3()
.subVectors(tri.b, tri.a)
.cross(new Vector3().subVectors(tri.c, tri.a))
.normalize()
const minX = Math.max(0, Math.floor(Math.min(pa.x, pb.x, pc.x)))
const maxX = Math.min(frame.width - 1, Math.ceil(Math.max(pa.x, pb.x, pc.x)))
const minY = Math.max(0, Math.floor(Math.min(pa.y, pb.y, pc.y)))
const maxY = Math.min(frame.height - 1, Math.ceil(Math.max(pa.y, pb.y, pc.y)))
for (let y = minY; y <= maxY; y += 1) {
for (let x = minX; x <= maxX; x += 1) {
const px = x + 0.5, py = y + 0.5
const w0 = ((pb.x - pa.x) * (py - pa.y) - (px - pa.x) * (pb.y - pa.y)) / area
const w1 = ((pc.x - pb.x) * (py - pb.y) - (px - pb.x) * (pc.y - pb.y)) / area
const w2 = 1 - w0 - w1
if (w0 < 0 || w1 < 0 || w2 < 0) continue
// w1 → a, w2 → b, w0 → c (opposite vertices of the edge functions)
const z = pa.z * w1 + pb.z * w2 + pc.z * w0
const at = y * frame.width + x
if (z >= frame.depth[at]!) continue
const albedo: [number, number, number] = [
tri.ca[0] * w1 + tri.cb[0] * w2 + tri.cc[0] * w0,
tri.ca[1] * w1 + tri.cb[1] * w2 + tri.cc[1] * w0,
tri.ca[2] * w1 + tri.cb[2] * w2 + tri.cc[2] * w0,
]
const rgb = shade(tri, normal, albedo)
const i = at * 3
const alpha = tri.opacity
frame.colour[i] = frame.colour[i]! * (1 - alpha) + rgb[0] * alpha
frame.colour[i + 1] = frame.colour[i + 1]! * (1 - alpha) + rgb[1] * alpha
frame.colour[i + 2] = frame.colour[i + 2]! * (1 - alpha) + rgb[2] * alpha
if (alpha >= 1) frame.depth[at] = z
}
}
}
}
/** Contact shadow: flatten the model onto the y=floor plane and draw it dark. */
function contactShadow(frame: Frame, camera: PerspectiveCamera, triangles: readonly Triangle[], floor: number): void {
for (const tri of triangles) {
if (tri.unlit) continue
const flat = (v: Vector3): Vector3 => new Vector3(v.x, floor + 0.0005, v.z)
const pa = project(flat(tri.a), camera, frame)
const pb = project(flat(tri.b), camera, frame)
const pc = project(flat(tri.c), camera, frame)
if (pa.behind || pb.behind || pc.behind) continue
const area = (pb.x - pa.x) * (pc.y - pa.y) - (pc.x - pa.x) * (pb.y - pa.y)
if (area === 0) continue
const minX = Math.max(0, Math.floor(Math.min(pa.x, pb.x, pc.x)))
const maxX = Math.min(frame.width - 1, Math.ceil(Math.max(pa.x, pb.x, pc.x)))
const minY = Math.max(0, Math.floor(Math.min(pa.y, pb.y, pc.y)))
const maxY = Math.min(frame.height - 1, Math.ceil(Math.max(pa.y, pb.y, pc.y)))
for (let y = minY; y <= maxY; y += 1) {
for (let x = minX; x <= maxX; x += 1) {
const px = x + 0.5, py = y + 0.5
const w0 = ((pb.x - pa.x) * (py - pa.y) - (px - pa.x) * (pb.y - pa.y)) / area
const w1 = ((pc.x - pb.x) * (py - pb.y) - (px - pb.x) * (pc.y - pb.y)) / area
const w2 = 1 - w0 - w1
if (w0 < 0 || w1 < 0 || w2 < 0) continue
const i = (y * frame.width + x) * 3
for (let k = 0; k < 3; k += 1) frame.colour[i + k] = frame.colour[i + k]! * 0.55
}
}
}
}
/* ---------------------------------------------------------------------- PNG */
const CRC_TABLE = (() => {
const table = new Uint32Array(256)
for (let n = 0; n < 256; n += 1) {
let c = n
for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
table[n] = c >>> 0
}
return table
})()
function crc32(bytes: Uint8Array): number {
let c = 0xffffffff
for (const byte of bytes) c = CRC_TABLE[(c ^ byte) & 0xff]! ^ (c >>> 8)
return (c ^ 0xffffffff) >>> 0
}
function chunk(type: string, data: Uint8Array): Uint8Array {
const body = new Uint8Array(4 + data.length)
for (let i = 0; i < 4; i += 1) body[i] = type.charCodeAt(i)
body.set(data, 4)
const out = new Uint8Array(8 + data.length + 4)
const view = new DataView(out.buffer)
view.setUint32(0, data.length)
out.set(body, 4)
view.setUint32(out.length - 4, crc32(body))
return out
}
function encodePng(frame: Frame): Uint8Array {
const { width, height, colour } = frame
const raw = new Uint8Array((width * 3 + 1) * height)
for (let y = 0; y < height; y += 1) {
const row = y * (width * 3 + 1)
raw[row] = 0
for (let x = 0; x < width; x += 1) {
const from = (y * width + x) * 3
const to = row + 1 + x * 3
raw[to] = encode(colour[from]!)
raw[to + 1] = encode(colour[from + 1]!)
raw[to + 2] = encode(colour[from + 2]!)
}
}
const ihdr = new Uint8Array(13)
const view = new DataView(ihdr.buffer)
view.setUint32(0, width)
view.setUint32(4, height)
ihdr[8] = 8 // bit depth
ihdr[9] = 2 // colour type: truecolour
const parts = [
new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]),
chunk('IHDR', ihdr),
chunk('IDAT', new Uint8Array(deflateSync(raw))),
chunk('IEND', new Uint8Array(0)),
]
const total = parts.reduce((sum, part) => sum + part.length, 0)
const png = new Uint8Array(total)
let at = 0
for (const part of parts) { png.set(part, at); at += part.length }
return png
}
/* ------------------------------------------------------------------ framing */
/** Camera that fits the model into frame. Same framing as in the viewer. */
function frameCamera(root: Object3D, width: number, height: number): { camera: PerspectiveCamera; floor: number } {
const box = new Box3().setFromObject(root)
const sphere = box.getBoundingSphere(new Sphere())
const camera = new PerspectiveCamera(32, width / height, 0.01, 100)
// Three-quarter view: the one angle that shows two faces at once. Looking
// straight on hides depth completely.
const direction = new Vector3(0.78, 0.5, 1).normalize()
/**
* Fit the BOX to the frame, not the sphere to the frame's short side.
*
* A sphere fit is one number and it is wrong for anything that is not
* roughly round. The whole-kit scene is wide and flat: its bounding sphere
* is set by the horizontal extent and is far taller than the scene is, so
* fitting that sphere into the vertical field left the models occupying a
* band across the middle with empty air above and below. On a 1.91:1 social
* card it was most of the picture.
*
* The box fit is iterative because perspective is not linear in distance:
* put the camera somewhere, project the eight corners, see how far past the
* frame edge the worst one lands, and move by that ratio. Two passes is
* inside a pixel at these sizes, and it settles on whichever axis is
* actually tight rather than assuming it is the vertical one.
*/
let distance = (sphere.radius / Math.sin((camera.fov * Math.PI) / 360)) * 1.12
const corner = new Vector3()
for (let pass = 0; pass < 3; pass += 1) {
camera.position.copy(sphere.center).addScaledVector(direction, distance)
camera.lookAt(sphere.center)
camera.updateMatrixWorld(true)
camera.updateProjectionMatrix()
let worst = 0
for (let i = 0; i < 8; i += 1) {
corner.set(
i & 1 ? box.max.x : box.min.x,
i & 2 ? box.max.y : box.min.y,
i & 4 ? box.max.z : box.min.z,
).project(camera)
worst = Math.max(worst, Math.abs(corner.x), Math.abs(corner.y))
}
if (worst <= 0) break
// 0.9 of the frame, so nothing sits on the edge and a shadow has room.
distance *= worst / 0.9
}
camera.position.copy(sphere.center).addScaledVector(direction, distance)
camera.lookAt(sphere.center)
camera.updateMatrixWorld(true)
camera.updateProjectionMatrix()
return { camera, floor: box.min.y }
}
function renderOne(
id: string,
size: number,
patch?: Record<string, number>,
/** Pre-rotation of the model around the Y axis (radians). For turntables. */
spin = 0,
/**
* Frame height, when it is not the width.
*
* Everything here is square because a contact sheet is a grid, but a social
* card is 1.91:1 and cropping a square down to it either loses the model or
* leaves it small. `newFrame` and `frameCamera` both took a width and a
* height already; only this function was insisting they be the same.
*/
tall = size,
): Frame {
const entry = CATALOG[id]
if (!entry) throw new Error(`not in catalog: ${id}`)
const built = entry.build()
if (patch && built.params) built.params.apply(patch)
// Catch animated models mid-motion: a frozen flame does not show that the
// flame flickers.
built.update?.(0.42)
// We rotate the MODEL, not the camera: framing and the shadow computation
// stay in a fixed direction, so turntable frames compare one to one.
built.root.rotation.y = spin
const triangles = collect(built.root)
const frame = newFrame(size, tall)
const { camera, floor } = frameCamera(built.root, size, tall)
contactShadow(frame, camera, triangles, floor)
raster(frame, camera, triangles)
built.dispose()
return frame
}
/* -------------------------------------------------------------------- entry */
const args = process.argv.slice(2) const args = process.argv.slice(2)
const flag = (name: string): string | undefined => { const flag = (name: string): string | undefined => {
const at = args.indexOf(`--${name}`) const at = args.indexOf(`--${name}`)
@ -438,32 +32,15 @@ const tall = Number(flag('height') ?? size)
const only = flag('ids')?.split(',') const only = flag('ids')?.split(',')
const groundHex = flag('ground')
const ground = groundHex ? toLinear(groundHex) : undefined
await mkdir(outDir, { recursive: true }) await mkdir(outDir, { recursive: true })
function ids0(): string { function ids0(): string {
throw new Error('--sweep needs --one <model>') throw new Error('--sweep needs --one <model>')
} }
/** Lays the frames out on a grid. */
function tile(list: readonly Frame[], size: number, columns: number): Frame {
const rows = Math.ceil(list.length / columns)
const sheet = newFrame(columns * size, rows * size)
list.forEach((frame, index) => {
const ox = (index % columns) * size
const oy = Math.floor(index / columns) * size
for (let y = 0; y < size; y += 1) {
for (let x = 0; x < size; x += 1) {
const from = (y * size + x) * 3
const to = ((oy + y) * sheet.width + ox + x) * 3
sheet.colour[to] = frame.colour[from]!
sheet.colour[to + 1] = frame.colour[from + 1]!
sheet.colour[to + 2] = frame.colour[from + 2]!
}
}
})
return sheet
}
// Sweep: puts the same model side by side with different values of a single // Sweep: puts the same model side by side with different values of a single
// parameter. Picking a ratio by eye is far faster than changing the number and // parameter. Picking a ratio by eye is far faster than changing the number and
// looking at each one on its own — that is how I picked the hoe's blade angle. // looking at each one on its own — that is how I picked the hoe's blade angle.
@ -475,8 +52,8 @@ if (angles > 1) {
const target = one ?? (only?.[0]) const target = one ?? (only?.[0])
if (!target) throw new Error('--angles needs --one <model> or --ids') if (!target) throw new Error('--angles needs --one <model> or --ids')
const frames = Array.from({ length: angles }, (_, i) => const frames = Array.from({ length: angles }, (_, i) =>
renderOne(target, size, undefined, (i / angles) * Math.PI * 2)) renderOne(target, { size, ground, spin: (i / angles) * Math.PI * 2 }))
await writeFile(`${outDir}/_turntable.png`, encodePng(tile(frames, size, angles))) await writeFile(`${outDir}/_turntable.png`, encodePng(tile(frames, size, angles, ground)))
console.log(`${target} · ${angles} angles → ${outDir}/_turntable.png`) console.log(`${target} · ${angles} angles → ${outDir}/_turntable.png`)
process.exit(0) process.exit(0)
} }
@ -486,8 +63,8 @@ if (sweep) {
const [key, values] = sweep.split('=') const [key, values] = sweep.split('=')
const list = values!.split('|').map(Number) const list = values!.split('|').map(Number)
const target = one ?? ids0() const target = one ?? ids0()
const rendered = list.map((value) => renderOne(target, size, { [key!]: value })) const rendered = list.map((value) => renderOne(target, { size, ground, patch: { [key!]: value } }))
await writeFile(`${outDir}/_sweep.png`, encodePng(tile(rendered, size, list.length))) await writeFile(`${outDir}/_sweep.png`, encodePng(tile(rendered, size, list.length, ground)))
console.log(`${target} · ${key} = ${list.join(', ')} → ${outDir}/_sweep.png`) console.log(`${target} · ${key} = ${list.join(', ')} → ${outDir}/_sweep.png`)
process.exit(0) process.exit(0)
} }
@ -501,7 +78,7 @@ const ids = one ? [one]
const frames = new Map<string, Frame>() const frames = new Map<string, Frame>()
for (const id of ids) { for (const id of ids) {
const frame = renderOne(id, size, undefined, 0, tall) const frame = renderOne(id, { size, tall, ground })
frames.set(id, frame) frames.set(id, frame)
await writeFile(`${outDir}/${id}.png`, encodePng(frame)) await writeFile(`${outDir}/${id}.png`, encodePng(frame))
console.log(` ${id}`) console.log(` ${id}`)
@ -512,7 +89,7 @@ if (!one && frames.size > 1) {
// instead of opening them one by one exposes the scale and tone // instead of opening them one by one exposes the scale and tone
// inconsistencies between them — the kind of bug you miss looking at one. // inconsistencies between them — the kind of bug you miss looking at one.
const columns = Number(flag('columns') ?? 6) const columns = Number(flag('columns') ?? 6)
const sheet = tile([...frames.values()], size, columns) const sheet = tile([...frames.values()], size, columns, ground)
await writeFile(`${outDir}/_sheet.png`, encodePng(sheet)) await writeFile(`${outDir}/_sheet.png`, encodePng(sheet))
console.log(`\n${frames.size} models → ${outDir}/_sheet.png (${sheet.width}×${sheet.height})`) console.log(`\n${frames.size} models → ${outDir}/_sheet.png (${sheet.width}×${sheet.height})`)
} }

391
scripts/text.ts Normal file
View file

@ -0,0 +1,391 @@
/**
* Type, for the software renderer: a TrueType reader and a glyph filler.
*
* The social card needs a headline, and the renderer next door has no font in
* it — it draws triangles. The first version of the card got around that by
* being an HTML page screenshotted in a browser, which works exactly once and
* then rots: the model count on it is a picture of a number, and nobody can
* regenerate it without repeating the whole manual dance.
*
* So the card became `bun run cover:build`, and this is what let it. It reads
* the outlines out of a `.ttf` and fills them with a scanline pass, which is
* the same shape of code as the triangle rasteriser and the PNG encoder it
* sits beside — this repository already draws its own pictures and writes its
* own PNG chunks, so parsing its own glyphs is in character rather than a
* departure.
*
* It is deliberately partial. Only what the card actually asks for is here:
* the Basic Multilingual Plane through a format 4 `cmap`, simple and composite
* outlines, horizontal advances, and no kerning, hinting, ligatures or
* shaping. Anything it cannot draw it reports rather than silently dropping,
* because a headline missing a letter is the sort of thing you do not see
* until it is published.
*/
import { readFileSync } from 'node:fs'
export interface Point { readonly x: number; readonly y: number }
interface Glyph {
/** Closed polygons, in font units, y up. Already flattened from curves. */
readonly contours: readonly (readonly Point[])[]
readonly advance: number
}
export interface Face {
/** Font units per em. Every outline and advance is in these. */
readonly unitsPerEm: number
glyph(code: number): Glyph | undefined
}
/* ------------------------------------------------------------------ reading */
function tagAt(view: DataView, at: number): string {
return String.fromCharCode(view.getUint8(at), view.getUint8(at + 1), view.getUint8(at + 2), view.getUint8(at + 3))
}
export function readFont(path: string): Face {
const bytes = readFileSync(path)
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
const tables = new Map<string, number>()
const numTables = view.getUint16(4)
for (let i = 0; i < numTables; i += 1) {
const record = 12 + i * 16
tables.set(tagAt(view, record), view.getUint32(record + 8))
}
const need = (tag: string): number => {
const offset = tables.get(tag)
if (offset === undefined) throw new Error(`${path}: no ${tag} table`)
return offset
}
const head = need('head')
const unitsPerEm = view.getUint16(head + 18)
// 0 means the loca table holds half-offsets in uint16, 1 means whole ones in
// uint32. Reading it the wrong way gives outlines that are pure noise.
const longLoca = view.getInt16(head + 50) === 1
const numGlyphs = view.getUint16(need('maxp') + 4)
const numHMetrics = view.getUint16(need('hhea') + 34)
const hmtx = need('hmtx')
const loca = need('loca')
const glyf = need('glyf')
/* --- cmap: character → glyph id, through the (3,1) format 4 subtable ----- */
const cmap = need('cmap')
let format4 = -1
for (let i = 0; i < view.getUint16(cmap + 2); i += 1) {
const record = cmap + 4 + i * 8
const platform = view.getUint16(record)
const encoding = view.getUint16(record + 2)
const subtable = cmap + view.getUint32(record + 4)
// Windows/BMP first, Unicode/BMP as the fallback. Both are format 4 in
// every font this ships with, and format 4 covers everything a card in
// English can need.
if (view.getUint16(subtable) !== 4) continue
if (platform === 3 && encoding === 1) { format4 = subtable; break }
if (platform === 0 && format4 < 0) format4 = subtable
}
if (format4 < 0) throw new Error(`${path}: no format 4 cmap`)
const segments = view.getUint16(format4 + 6) / 2
const endCodes = format4 + 14
const startCodes = endCodes + segments * 2 + 2
const deltas = startCodes + segments * 2
const rangeOffsets = deltas + segments * 2
function glyphId(code: number): number {
for (let s = 0; s < segments; s += 1) {
if (view.getUint16(endCodes + s * 2) < code) continue
if (view.getUint16(startCodes + s * 2) > code) return 0
const delta = view.getInt16(deltas + s * 2)
const rangeOffset = view.getUint16(rangeOffsets + s * 2)
if (rangeOffset === 0) return (code + delta) & 0xffff
// The offset is measured from the slot it was read out of, which is the
// one genuinely strange thing in the format.
const at = rangeOffsets + s * 2 + rangeOffset + (code - view.getUint16(startCodes + s * 2)) * 2
const id = view.getUint16(at)
return id === 0 ? 0 : (id + delta) & 0xffff
}
return 0
}
/* --- glyf: the outlines ------------------------------------------------- */
const mid = (a: Point, b: Point): Point => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 })
/** Quadratic Bézier, flattened. Font units, so the step is generous. */
function quadratic(out: Point[], from: Point, control: Point, to: Point): void {
const span = Math.hypot(control.x - from.x, control.y - from.y)
+ Math.hypot(to.x - control.x, to.y - control.y)
const steps = Math.min(20, Math.max(3, Math.ceil(span / 25)))
for (let i = 1; i <= steps; i += 1) {
const t = i / steps
const u = 1 - t
out.push({
x: u * u * from.x + 2 * u * t * control.x + t * t * to.x,
y: u * u * from.y + 2 * u * t * control.y + t * t * to.y,
})
}
}
interface Vertex extends Point { readonly on: boolean }
/** One TrueType contour → one closed polygon. */
function flatten(points: readonly Vertex[]): Point[] {
const n = points.length
if (n === 0) return []
const first = points.findIndex((p) => p.on)
// A contour made entirely of off-curve points is legal: the start is then
// the midpoint between the last control point and the first.
const start: Point = first >= 0 ? points[first]! : mid(points[n - 1]!, points[0]!)
const walk = first >= 0
? [...points.slice(first + 1), ...points.slice(0, first)]
: [...points]
const out: Point[] = [start]
let control: Point | null = null
for (const point of walk) {
const here = out[out.length - 1]!
if (point.on) {
if (control) { quadratic(out, here, control, point); control = null } else out.push(point)
} else {
// Two control points in a row imply an on-curve point between them.
if (control) quadratic(out, here, control, mid(control, point))
control = point
}
}
if (control) quadratic(out, out[out.length - 1]!, control, start)
return out
}
function outline(id: number, depth = 0): Point[][] {
if (id >= numGlyphs || depth > 4) return []
const from = longLoca ? view.getUint32(loca + id * 4) : view.getUint16(loca + id * 2) * 2
const to = longLoca ? view.getUint32(loca + id * 4 + 4) : view.getUint16(loca + id * 2 + 2) * 2
if (to <= from) return [] // a blank glyph, such as the space
let at = glyf + from
const contourCount = view.getInt16(at)
at += 10 // past the bounding box
if (contourCount < 0) return composite(at, depth)
const ends: number[] = []
for (let i = 0; i < contourCount; i += 1) { ends.push(view.getUint16(at)); at += 2 }
const count = (ends[ends.length - 1] ?? -1) + 1
at += 2 + view.getUint16(at) // past the hinting instructions
const flags = new Uint8Array(count)
for (let i = 0; i < count;) {
const flag = view.getUint8(at); at += 1
flags[i] = flag; i += 1
if (flag & 8) { // repeat
let repeats = view.getUint8(at); at += 1
while (repeats > 0 && i < count) { flags[i] = flag; i += 1; repeats -= 1 }
}
}
// x then y, each stored as a delta that is one byte, two bytes, or absent
// entirely when it repeats the previous coordinate.
const read = (short: number, same: number): Int32Array => {
const values = new Int32Array(count)
let value = 0
for (let i = 0; i < count; i += 1) {
const flag = flags[i]!
if (flag & short) {
const delta = view.getUint8(at); at += 1
value += flag & same ? delta : -delta
} else if (!(flag & same)) {
value += view.getInt16(at); at += 2
}
values[i] = value
}
return values
}
const xs = read(2, 16)
const ys = read(4, 32)
const contours: Point[][] = []
let begin = 0
for (const end of ends) {
const points: Vertex[] = []
for (let i = begin; i <= end; i += 1) points.push({ x: xs[i]!, y: ys[i]!, on: (flags[i]! & 1) !== 0 })
const polygon = flatten(points)
if (polygon.length >= 3) contours.push(polygon)
begin = end + 1
}
return contours
}
/** A glyph built from other glyphs — the `@` in some faces, accents in all. */
function composite(start: number, depth: number): Point[][] {
let at = start
const contours: Point[][] = []
for (;;) {
const flags = view.getUint16(at); at += 2
const index = view.getUint16(at); at += 2
let dx: number, dy: number
if (flags & 1) { dx = view.getInt16(at); dy = view.getInt16(at + 2); at += 4 }
else { dx = view.getInt8(at); dy = view.getInt8(at + 1); at += 2 }
if (!(flags & 2)) { dx = 0; dy = 0 } // args are point numbers, not offsets
const f2dot14 = (offset: number): number => view.getInt16(offset) / 16384
let a = 1, b = 0, c = 0, d = 1
if (flags & 8) { a = d = f2dot14(at); at += 2 }
else if (flags & 0x40) { a = f2dot14(at); d = f2dot14(at + 2); at += 4 }
else if (flags & 0x80) {
a = f2dot14(at); b = f2dot14(at + 2); c = f2dot14(at + 4); d = f2dot14(at + 6); at += 8
}
for (const contour of outline(index, depth + 1)) {
contours.push(contour.map((p) => ({ x: a * p.x + c * p.y + dx, y: b * p.x + d * p.y + dy })))
}
if (!(flags & 0x20)) break // no more components
}
return contours
}
const cache = new Map<number, Glyph | undefined>()
return {
unitsPerEm,
glyph(code: number): Glyph | undefined {
if (cache.has(code)) return cache.get(code)
const id = glyphId(code)
const glyph = id === 0 ? undefined : {
contours: outline(id),
advance: view.getUint16(hmtx + Math.min(id, numHMetrics - 1) * 4),
}
cache.set(code, glyph)
return glyph
},
}
}
/* --------------------------------------------------------------- rendering */
export interface TextTarget {
readonly width: number
readonly height: number
/** rgb, linear, three floats per pixel. A `Frame` from raster.ts fits. */
readonly colour: Float32Array
}
export interface TextOptions {
readonly x: number
readonly y: number // the BASELINE, not the top
readonly size: number // px per em
readonly colour: readonly number[] // linear rgb
readonly align?: 'left' | 'right'
}
export function measure(face: Face, text: string, size: number): number {
const scale = size / face.unitsPerEm
let width = 0
for (const character of text) width += (face.glyph(character.codePointAt(0)!)?.advance ?? 0) * scale
return width
}
/**
* Draws a string and returns where the pen ended up, so a run in one colour
* can be continued in another without measuring it twice.
*
* Four sub-scanlines per row, with exact horizontal coverage along each of
* them. Sampling on a 4×4 grid instead would be less code and visibly worse:
* sixteen levels of grey is enough for a headline and not for 16px mono, which
* is most of the type on the card.
*/
export function fillText(target: TextTarget, face: Face, text: string, options: TextOptions): number {
const { x, y, size, colour, align = 'left' } = options
const scale = size / face.unitsPerEm
let pen = align === 'right' ? x - measure(face, text, size) : x
for (const character of text) {
const code = character.codePointAt(0)!
const glyph = face.glyph(code)
if (!glyph) {
if (character !== ' ') throw new Error(`no glyph for U+${code.toString(16).toUpperCase()} (${character})`)
continue
}
// Font units are y up and the frame is y down, which flips the winding of
// every contour. Non-zero fill does not care, as long as holes keep
// winding against their outlines — and they do, because both flip.
const polygons = glyph.contours.map((contour) =>
contour.map((p) => ({ x: pen + p.x * scale, y: y - p.y * scale })))
fill(target, polygons, colour)
pen += glyph.advance * scale
}
return pen
}
const SUB = 4
function fill(target: TextTarget, polygons: readonly (readonly Point[])[], colour: readonly number[]): void {
if (polygons.length === 0) return
let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity
for (const polygon of polygons) {
for (const p of polygon) {
minX = Math.min(minX, p.x); maxX = Math.max(maxX, p.x)
minY = Math.min(minY, p.y); maxY = Math.max(maxY, p.y)
}
}
const left = Math.max(0, Math.floor(minX))
const right = Math.min(target.width - 1, Math.ceil(maxX))
const top = Math.max(0, Math.floor(minY))
const bottom = Math.min(target.height - 1, Math.ceil(maxY))
if (right < left || bottom < top) return
const coverage = new Float32Array(right - left + 1)
const crossings: { x: number; winding: number }[] = []
for (let row = top; row <= bottom; row += 1) {
coverage.fill(0)
for (let sub = 0; sub < SUB; sub += 1) {
const scanline = row + (sub + 0.5) / SUB
crossings.length = 0
for (const polygon of polygons) {
for (let i = 0; i < polygon.length; i += 1) {
const a = polygon[i]!
const b = polygon[(i + 1) % polygon.length]!
// Half-open in y, so a vertex shared by two edges is counted once.
if ((a.y <= scanline) === (b.y <= scanline)) continue
const t = (scanline - a.y) / (b.y - a.y)
crossings.push({ x: a.x + t * (b.x - a.x), winding: b.y > a.y ? 1 : -1 })
}
}
if (crossings.length < 2) continue
crossings.sort((p, q) => p.x - q.x)
let winding = 0
for (let i = 0; i < crossings.length - 1; i += 1) {
winding += crossings[i]!.winding
if (winding !== 0) span(coverage, left, right, crossings[i]!.x, crossings[i + 1]!.x, 1 / SUB)
}
}
for (let column = left; column <= right; column += 1) {
const alpha = Math.min(1, coverage[column - left]!)
if (alpha <= 0) continue
const at = (row * target.width + column) * 3
for (let k = 0; k < 3; k += 1) {
target.colour[at + k] = target.colour[at + k]! * (1 - alpha) + colour[k]! * alpha
}
}
}
}
/** Adds a horizontal span's coverage, with the partial pixels at each end. */
function span(coverage: Float32Array, left: number, right: number, from: number, to: number, weight: number): void {
const x0 = Math.max(from, left)
const x1 = Math.min(to, right + 1)
if (x1 <= x0) return
const first = Math.floor(x0)
const last = Math.min(right, Math.floor(x1 - 1e-9))
if (first === last) {
coverage[first - left] = coverage[first - left]! + (x1 - x0) * weight
return
}
coverage[first - left] = coverage[first - left]! + (first + 1 - x0) * weight
for (let i = first + 1; i < last; i += 1) coverage[i - left] = coverage[i - left]! + weight
coverage[last - left] = coverage[last - left]! + (x1 - last) * weight
}