@kerf-js/keel 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +16 -0
- package/README.md +306 -2
- package/package.json +59 -3
- package/src/blend-inset.ts +79 -0
- package/src/blend.ts +120 -0
- package/src/client.d.ts +9 -0
- package/src/generate/bust.ts +24 -0
- package/src/generate/bust.worker.ts +4 -0
- package/src/generate/pack.ts +69 -0
- package/src/generate/plate.ts +51 -0
- package/src/generate/plate.worker.ts +4 -0
- package/src/generate/serve.ts +56 -0
- package/src/generate/surface.ts +16 -0
- package/src/generate/surface.worker.ts +4 -0
- package/src/generate.ts +133 -0
- package/src/governor.ts +87 -0
- package/src/index.d.ts +15 -0
- package/src/index.mjs +63 -0
- package/src/lit.d.ts +384 -0
- package/src/paint-live.ts +60 -0
- package/src/paint-recipe.d.mts +29 -0
- package/src/paint-recipe.mjs +29 -0
- package/src/paint-worker.mjs +20 -0
- package/src/paint.d.mts +37 -0
- package/src/paint.mjs +180 -0
- package/src/runtime.ts +35 -0
- package/src/scene.ts +289 -0
- package/src/stage.ts +192 -0
- package/vendor/LICENSE +21 -0
- package/vendor/LICENSE-modules +21 -0
- package/vendor/NOTICE +24 -0
- package/vendor/README.md +13 -0
- package/vendor/lit.d.mts +1 -0
- package/vendor/lit.mjs +2 -0
- package/vendor/lock.json +177 -0
- package/vendor/modules/band/events.d.ts +20 -0
- package/vendor/modules/band/index.d.ts +29 -0
- package/vendor/modules/band/player.d.ts +43 -0
- package/vendor/modules/band/roll.d.ts +14 -0
- package/vendor/modules/band/score.d.ts +45 -0
- package/vendor/modules/band/styles.data.d.ts +37 -0
- package/vendor/modules/band/voices.d.ts +33 -0
- package/vendor/modules/band.d.mts +1 -0
- package/vendor/modules/band.mjs +2 -0
- package/vendor/modules/butterflies/butterflies.glsl.d.ts +2 -0
- package/vendor/modules/butterflies/flight.d.ts +68 -0
- package/vendor/modules/butterflies/index.d.ts +79 -0
- package/vendor/modules/butterflies/wing.d.ts +38 -0
- package/vendor/modules/butterflies.d.mts +1 -0
- package/vendor/modules/butterflies.inputs.json +73 -0
- package/vendor/modules/butterflies.mjs +39 -0
- package/vendor/modules/camera-rail/index.d.ts +113 -0
- package/vendor/modules/camera-rail.d.mts +1 -0
- package/vendor/modules/camera-rail.mjs +2 -0
- package/vendor/modules/device-profile/index.d.ts +47 -0
- package/vendor/modules/device-profile.d.mts +1 -0
- package/vendor/modules/device-profile.mjs +2 -0
- package/vendor/modules/lit-finish/dress.d.ts +34 -0
- package/vendor/modules/lit-finish/finish.glsl.d.ts +15 -0
- package/vendor/modules/lit-finish/index.d.ts +33 -0
- package/vendor/modules/lit-finish/lit.d.ts +52 -0
- package/vendor/modules/lit-finish/pass.d.ts +35 -0
- package/vendor/modules/lit-finish/settings.d.ts +88 -0
- package/vendor/modules/lit-finish.d.mts +1 -0
- package/vendor/modules/lit-finish.inputs.json +200 -0
- package/vendor/modules/lit-finish.mjs +267 -0
- package/vendor/modules/look/index.d.ts +159 -0
- package/vendor/modules/look.d.mts +1 -0
- package/vendor/modules/look.inputs.json +23 -0
- package/vendor/modules/look.mjs +2 -0
- package/vendor/modules/motes/index.d.ts +83 -0
- package/vendor/modules/motes/motes.glsl.d.ts +9 -0
- package/vendor/modules/motes/place.d.ts +59 -0
- package/vendor/modules/motes.d.mts +1 -0
- package/vendor/modules/motes.inputs.json +116 -0
- package/vendor/modules/motes.mjs +68 -0
- package/vendor/modules/plate-painter/dab.d.ts +44 -0
- package/vendor/modules/plate-painter/exact.d.ts +19 -0
- package/vendor/modules/plate-painter/foliage.d.ts +4 -0
- package/vendor/modules/plate-painter/gpu.d.ts +65 -0
- package/vendor/modules/plate-painter/index.d.ts +14 -0
- package/vendor/modules/plate-painter/paint.glsl.d.ts +14 -0
- package/vendor/modules/plate-painter/plan.d.ts +42 -0
- package/vendor/modules/plate-painter/recipe.d.ts +136 -0
- package/vendor/modules/plate-painter/scene.d.ts +4 -0
- package/vendor/modules/plate-painter.d.mts +1 -0
- package/vendor/modules/plate-painter.inputs.json +50 -0
- package/vendor/modules/plate-painter.mjs +384 -0
- package/vendor/modules/portrait/body.d.ts +25 -0
- package/vendor/modules/portrait/bust.d.ts +67 -0
- package/vendor/modules/portrait/cap.d.ts +12 -0
- package/vendor/modules/portrait/compile.d.ts +8 -0
- package/vendor/modules/portrait/exact.d.ts +17 -0
- package/vendor/modules/portrait/hair.d.ts +26 -0
- package/vendor/modules/portrait/hand.d.ts +30 -0
- package/vendor/modules/portrait/head.d.ts +18 -0
- package/vendor/modules/portrait/index.d.ts +12 -0
- package/vendor/modules/portrait/mesh.d.ts +24 -0
- package/vendor/modules/portrait/parts.d.ts +33 -0
- package/vendor/modules/portrait/portrait.glsl.d.ts +4 -0
- package/vendor/modules/portrait/render.d.ts +125 -0
- package/vendor/modules/portrait/sdf.d.ts +75 -0
- package/vendor/modules/portrait/settings.d.ts +27 -0
- package/vendor/modules/portrait.d.mts +1 -0
- package/vendor/modules/portrait.inputs.json +111 -0
- package/vendor/modules/portrait.mjs +2 -0
- package/vendor/modules/quality/index.d.ts +130 -0
- package/vendor/modules/quality.d.mts +1 -0
- package/vendor/modules/quality.inputs.json +34 -0
- package/vendor/modules/quality.mjs +2 -0
- package/vendor/modules/scene-blend/blend.d.ts +54 -0
- package/vendor/modules/scene-blend/blend.glsl.d.ts +8 -0
- package/vendor/modules/scene-blend/index.d.ts +25 -0
- package/vendor/modules/scene-blend/lit.d.ts +61 -0
- package/vendor/modules/scene-blend/noise.d.ts +13 -0
- package/vendor/modules/scene-blend/settings.d.ts +63 -0
- package/vendor/modules/scene-blend.d.mts +1 -0
- package/vendor/modules/scene-blend.inputs.json +133 -0
- package/vendor/modules/scene-blend.mjs +2 -0
- package/vendor/modules/section-post/index.d.ts +23 -0
- package/vendor/modules/section-post/lit.d.ts +47 -0
- package/vendor/modules/section-post/noise.d.ts +14 -0
- package/vendor/modules/section-post/post.d.ts +31 -0
- package/vendor/modules/section-post/post.glsl.d.ts +8 -0
- package/vendor/modules/section-post/settings.d.ts +84 -0
- package/vendor/modules/section-post.d.mts +1 -0
- package/vendor/modules/section-post.inputs.json +107 -0
- package/vendor/modules/section-post.mjs +53 -0
- package/vendor/modules/surfaces/exact.d.ts +8 -0
- package/vendor/modules/surfaces/field.d.ts +7 -0
- package/vendor/modules/surfaces/gpu.d.ts +19 -0
- package/vendor/modules/surfaces/index.d.ts +17 -0
- package/vendor/modules/surfaces/paint.d.ts +28 -0
- package/vendor/modules/surfaces/plan.d.ts +39 -0
- package/vendor/modules/surfaces/print.d.ts +55 -0
- package/vendor/modules/surfaces/recipe.d.ts +143 -0
- package/vendor/modules/surfaces/surface.glsl.d.ts +4 -0
- package/vendor/modules/surfaces.d.mts +1 -0
- package/vendor/modules/surfaces.inputs.json +54 -0
- package/vendor/modules/surfaces.mjs +172 -0
- package/vendor/modules/tracks/index.d.ts +66 -0
- package/vendor/modules/tracks.d.mts +1 -0
- package/vendor/modules/tracks.mjs +2 -0
- package/vendor/modules/tree-growth/bend.d.ts +28 -0
- package/vendor/modules/tree-growth/frame.d.ts +60 -0
- package/vendor/modules/tree-growth/index.d.ts +23 -0
- package/vendor/modules/tree-growth/light.d.ts +13 -0
- package/vendor/modules/tree-growth/math.d.ts +19 -0
- package/vendor/modules/tree-growth/model.d.ts +100 -0
- package/vendor/modules/tree-growth/sectors.d.ts +10 -0
- package/vendor/modules/tree-growth/simulation.d.ts +58 -0
- package/vendor/modules/tree-growth/species.d.ts +117 -0
- package/vendor/modules/tree-growth/species.data.d.ts +2 -0
- package/vendor/modules/tree-growth/year.d.ts +38 -0
- package/vendor/modules/tree-growth.d.mts +1 -0
- package/vendor/modules/tree-growth.inputs.json +75 -0
- package/vendor/modules/tree-growth.mjs +2 -0
- package/vendor/modules/tree-render/features.d.ts +9 -0
- package/vendor/modules/tree-render/forest/bake.d.ts +41 -0
- package/vendor/modules/tree-render/forest/cards.d.ts +28 -0
- package/vendor/modules/tree-render/forest/forest.d.ts +156 -0
- package/vendor/modules/tree-render/index.d.ts +52 -0
- package/vendor/modules/tree-render/inputs.d.ts +260 -0
- package/vendor/modules/tree-render/instances.d.ts +66 -0
- package/vendor/modules/tree-render/math.d.ts +8 -0
- package/vendor/modules/tree-render/tree/bark.d.ts +20 -0
- package/vendor/modules/tree-render/tree/leaves.d.ts +29 -0
- package/vendor/modules/tree-render/tree/litter.d.ts +21 -0
- package/vendor/modules/tree-render/tree/ornaments.d.ts +36 -0
- package/vendor/modules/tree-render/tree/roots.d.ts +75 -0
- package/vendor/modules/tree-render/tree/shapes.d.ts +49 -0
- package/vendor/modules/tree-render/tree/tree.d.ts +239 -0
- package/vendor/modules/tree-render/tree/wood.d.ts +27 -0
- package/vendor/modules/tree-render/wind.d.ts +51 -0
- package/vendor/modules/tree-render.d.mts +1 -0
- package/vendor/modules/tree-render.inputs.json +45 -0
- package/vendor/modules/tree-render.mjs +2 -0
- package/vendor/modules/voxel-dither/dither.glsl.d.ts +9 -0
- package/vendor/modules/voxel-dither/index.d.ts +35 -0
- package/vendor/modules/voxel-dither/light.d.ts +33 -0
- package/vendor/modules/voxel-dither/lit.d.ts +86 -0
- package/vendor/modules/voxel-dither/pass.d.ts +46 -0
- package/vendor/modules/voxel-dither/screens.d.ts +21 -0
- package/vendor/modules/voxel-dither/settings.d.ts +307 -0
- package/vendor/modules/voxel-dither/signals.d.ts +35 -0
- package/vendor/modules/voxel-dither.d.mts +1 -0
- package/vendor/modules/voxel-dither.inputs.json +295 -0
- package/vendor/modules/voxel-dither.mjs +452 -0
- package/vendor/modules/world-light/index.d.ts +133 -0
- package/vendor/modules/world-light.d.mts +1 -0
- package/vendor/modules/world-light.inputs.json +68 -0
- package/vendor/modules/world-light.mjs +2 -0
package/src/paint.mjs
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// `import ground from './card.paint.json?paint'`: a surface painted from a seeded recipe at build time, handed on as a
|
|
2
|
+
// `?media&photo` image, so the page gets a media record (an AVIF ladder, a JPEG fallback and a placeholder with
|
|
3
|
+
// `media()`, the PNG alone without). Painting runs on the CPU on Node worker threads, with the arithmetic the GPU
|
|
4
|
+
// painter uses. A painted PNG is kept under `.kerf/cache/paint`, keyed by the plan's digest and the module's version: an unchanged recipe paints nothing.
|
|
5
|
+
import { createHash } from 'node:crypto'
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { basename, dirname, join, resolve } from 'node:path'
|
|
8
|
+
import { fileURLToPath } from 'node:url'
|
|
9
|
+
import { availableParallelism } from 'node:os'
|
|
10
|
+
import { Worker } from 'node:worker_threads'
|
|
11
|
+
import { crc32, deflateSync } from 'node:zlib'
|
|
12
|
+
import { recipeOf } from './paint-recipe.mjs'
|
|
13
|
+
|
|
14
|
+
const QUERY = /\?paint$/
|
|
15
|
+
const VIRTUAL = '\0keel-paint:'
|
|
16
|
+
// After the path, so the id ends in neither `.json` nor `.json?…` and the JSON plugin leaves it alone.
|
|
17
|
+
const END = ':paint.mjs'
|
|
18
|
+
const MODULE = fileURLToPath(new URL('../vendor/modules/surfaces.mjs', import.meta.url))
|
|
19
|
+
/** Moves when the PNG written for the same pixels would change. */
|
|
20
|
+
const ENCODING = 2
|
|
21
|
+
|
|
22
|
+
/** The module's version, from the header the vendor script writes. */
|
|
23
|
+
const versionOf = (source) => /^\/\/ surfaces@(\S+)/.exec(source)?.[1] ?? '0'
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Threads that paint: up to `size` at once, started when first asked and stopped by `close`. Each paint takes a
|
|
27
|
+
* second or so on the CPU, so a page's paints run side by side rather than one after another.
|
|
28
|
+
*/
|
|
29
|
+
export function createPaintPool(size = Math.max(1, Math.min(4, availableParallelism() - 1))) {
|
|
30
|
+
const idle = []
|
|
31
|
+
const all = []
|
|
32
|
+
const queue = []
|
|
33
|
+
const busy = new Map()
|
|
34
|
+
// An idle thread is unref'd, so a pool nobody closed never keeps Node running.
|
|
35
|
+
const give = (worker) => {
|
|
36
|
+
const job = queue.shift()
|
|
37
|
+
if (!job) {
|
|
38
|
+
worker.unref()
|
|
39
|
+
return idle.push(worker)
|
|
40
|
+
}
|
|
41
|
+
busy.set(worker, job)
|
|
42
|
+
worker.ref()
|
|
43
|
+
worker.postMessage(job.request)
|
|
44
|
+
}
|
|
45
|
+
const start = () => {
|
|
46
|
+
const worker = new Worker(new URL('./paint-worker.mjs', import.meta.url))
|
|
47
|
+
worker.on('message', ({ error, ...done }) => {
|
|
48
|
+
const job = busy.get(worker)
|
|
49
|
+
busy.delete(worker)
|
|
50
|
+
if (error === undefined) job?.resolve(done)
|
|
51
|
+
else job?.reject(new Error(error))
|
|
52
|
+
give(worker)
|
|
53
|
+
})
|
|
54
|
+
worker.on('error', (error) => {
|
|
55
|
+
busy.get(worker)?.reject(error)
|
|
56
|
+
busy.delete(worker)
|
|
57
|
+
all.splice(all.indexOf(worker), 1)
|
|
58
|
+
})
|
|
59
|
+
all.push(worker)
|
|
60
|
+
return worker
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
/** The PNG of a request, `{ bytes, width, height }`, painted on one of the threads. */
|
|
64
|
+
paint(request) {
|
|
65
|
+
return new Promise((done, fail) => {
|
|
66
|
+
queue.push({ request, resolve: done, reject: fail })
|
|
67
|
+
const worker = idle.pop() ?? (all.length < size ? start() : null)
|
|
68
|
+
if (worker) give(worker)
|
|
69
|
+
})
|
|
70
|
+
},
|
|
71
|
+
close: () => Promise.all(all.splice(0).map((w) => w.terminate())).then(() => {}),
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** RGBA rows as an RGB PNG, no filter, deflated: an albedo is opaque, so its alpha is left out. */
|
|
76
|
+
export function png(rgba, width, height) {
|
|
77
|
+
const chunk = (type, data) => {
|
|
78
|
+
const out = Buffer.alloc(12 + data.length)
|
|
79
|
+
out.writeUInt32BE(data.length, 0)
|
|
80
|
+
out.write(type, 4, 'latin1')
|
|
81
|
+
data.copy(out, 8)
|
|
82
|
+
out.writeUInt32BE(crc32(out.subarray(4, 8 + data.length)), 8 + data.length)
|
|
83
|
+
return out
|
|
84
|
+
}
|
|
85
|
+
const head = Buffer.alloc(13)
|
|
86
|
+
head.writeUInt32BE(width, 0)
|
|
87
|
+
head.writeUInt32BE(height, 4)
|
|
88
|
+
head.set([8, 2, 0, 0, 0], 8)
|
|
89
|
+
const row = width * 3
|
|
90
|
+
const raw = Buffer.alloc((row + 1) * height)
|
|
91
|
+
for (let y = 0, at = 0; y < height; y++) {
|
|
92
|
+
at++
|
|
93
|
+
for (let x = 0, i = y * width * 4; x < width; x++, i += 4) {
|
|
94
|
+
raw[at++] = rgba[i]
|
|
95
|
+
raw[at++] = rgba[i + 1]
|
|
96
|
+
raw[at++] = rgba[i + 2]
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return Buffer.concat([
|
|
100
|
+
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
|
|
101
|
+
chunk('IHDR', head),
|
|
102
|
+
chunk('IDAT', deflateSync(raw)),
|
|
103
|
+
chunk('IEND', Buffer.alloc(0)),
|
|
104
|
+
])
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The painted PNG for a recipe file, from the cache or painted now, on `pool`'s threads or else on this one. `log`
|
|
109
|
+
* hears how long a paint took.
|
|
110
|
+
*
|
|
111
|
+
* @returns The PNG's path and whether it was painted now.
|
|
112
|
+
*/
|
|
113
|
+
export async function paintFile(file, cacheDir, log = () => {}, pool = null) {
|
|
114
|
+
const surfaces = await import(MODULE)
|
|
115
|
+
const request = JSON.parse(readFileSync(file, 'utf8'))
|
|
116
|
+
const { recipe, settings } = recipeOf(request, surfaces)
|
|
117
|
+
const plan = surfaces.planSurface(recipe, settings)
|
|
118
|
+
const version = versionOf(readFileSync(MODULE, 'utf8').slice(0, 120))
|
|
119
|
+
const key = createHash('sha256')
|
|
120
|
+
.update(`${plan.digest}:surfaces@${version}:${ENCODING}`)
|
|
121
|
+
.digest('hex')
|
|
122
|
+
.slice(0, 16)
|
|
123
|
+
const stem = basename(file).replace(/\.paint\.json$|\.json$/, '')
|
|
124
|
+
// In a folder named by the key, so the file keeps the recipe's name and the media built from it is `<name>-<w>-…`.
|
|
125
|
+
const out = join(cacheDir, key, `${stem}.png`)
|
|
126
|
+
if (existsSync(out)) return { file: out, painted: false }
|
|
127
|
+
const started = performance.now()
|
|
128
|
+
const { bytes, width, height } = pool
|
|
129
|
+
? await pool.paint(request)
|
|
130
|
+
: (() => {
|
|
131
|
+
const surface = surfaces.paintPlan(plan)
|
|
132
|
+
const rgba = new Uint8Array(surface.buffers[0])
|
|
133
|
+
return { bytes: png(rgba, surface.width, surface.height), ...surface }
|
|
134
|
+
})()
|
|
135
|
+
mkdirSync(dirname(out), { recursive: true })
|
|
136
|
+
// Written aside and renamed, so a build stopped half-way leaves no torn file under the key.
|
|
137
|
+
writeFileSync(`${out}.part`, bytes)
|
|
138
|
+
renameSync(`${out}.part`, out)
|
|
139
|
+
log(`${basename(file)}: ${width}×${height} in ${Math.round(performance.now() - started)} ms`)
|
|
140
|
+
return { file: out, painted: true }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* The Vite plugin for `?paint` imports, beside kerf's own (which encodes the `?media` image it hands on).
|
|
145
|
+
*
|
|
146
|
+
* @param options `cacheDir`: where painted PNGs are kept, default `<root>/.kerf/cache/paint`. `threads`: how many
|
|
147
|
+
* paint at once, default one fewer than the cores up to 4; 0 paints on Vite's own thread.
|
|
148
|
+
*/
|
|
149
|
+
export function keelPaint(options = {}) {
|
|
150
|
+
let cacheDir = options.cacheDir
|
|
151
|
+
let say = () => {}
|
|
152
|
+
let pool = null
|
|
153
|
+
return {
|
|
154
|
+
name: 'keel:paint',
|
|
155
|
+
enforce: 'pre',
|
|
156
|
+
configResolved(config) {
|
|
157
|
+
cacheDir ??= join(config.root, '.kerf', 'cache', 'paint')
|
|
158
|
+
say = (line) => config.logger.info(`keel paint: ${line}`)
|
|
159
|
+
},
|
|
160
|
+
async resolveId(source, importer) {
|
|
161
|
+
if (!QUERY.test(source)) return null
|
|
162
|
+
const path = source.replace(QUERY, '')
|
|
163
|
+
const found = await this.resolve(path, importer, { skipSelf: true })
|
|
164
|
+
return `${VIRTUAL}${found?.id ?? resolve(dirname(importer ?? ''), path)}${END}`
|
|
165
|
+
},
|
|
166
|
+
async load(id) {
|
|
167
|
+
if (!id.startsWith(VIRTUAL)) return null
|
|
168
|
+
const file = id.slice(VIRTUAL.length, -END.length)
|
|
169
|
+
this.addWatchFile(file)
|
|
170
|
+
if (options.threads !== 0) pool ??= createPaintPool(options.threads)
|
|
171
|
+
const painted = await paintFile(file, cacheDir, say, pool)
|
|
172
|
+
// A painting is photographic: a JPEG fallback, not a lossless PNG one.
|
|
173
|
+
return `export { default } from ${JSON.stringify(`${painted.file}?media&photo`)}\n`
|
|
174
|
+
},
|
|
175
|
+
async buildEnd() {
|
|
176
|
+
await pool?.close()
|
|
177
|
+
pool = null
|
|
178
|
+
},
|
|
179
|
+
}
|
|
180
|
+
}
|
package/src/runtime.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// surface.renderer@1 for `keel-lit`. keel/lit owns the GL context; the surface adds the canvas, its size and its clock.
|
|
2
|
+
import type { SurfaceRenderer } from '@kerf-js/core/surface'
|
|
3
|
+
import * as lit from '../vendor/lit.mjs'
|
|
4
|
+
|
|
5
|
+
/** The surface.renderer@1 provider: `context` makes the surface's `s.lit` and `s.renderer`. */
|
|
6
|
+
export const renderer: SurfaceRenderer = {
|
|
7
|
+
context(canvas, def) {
|
|
8
|
+
let made: lit.LitRenderer
|
|
9
|
+
try {
|
|
10
|
+
made = lit.createLitRenderer({
|
|
11
|
+
canvas,
|
|
12
|
+
antialias: false,
|
|
13
|
+
alpha: false,
|
|
14
|
+
powerPreference: 'high-performance',
|
|
15
|
+
...def.context,
|
|
16
|
+
})
|
|
17
|
+
} catch {
|
|
18
|
+
return null
|
|
19
|
+
}
|
|
20
|
+
made.outputColorSpace = 'srgb'
|
|
21
|
+
made.shadowMap.enabled = true
|
|
22
|
+
made.shadowMap.type = 'pcf-soft'
|
|
23
|
+
return {
|
|
24
|
+
fields: { lit, renderer: made },
|
|
25
|
+
resize(width, height, dpr) {
|
|
26
|
+
made.setPixelRatio(dpr)
|
|
27
|
+
made.setSize(width, height, false)
|
|
28
|
+
},
|
|
29
|
+
dispose() {
|
|
30
|
+
made.dispose()
|
|
31
|
+
made.forceContextLoss()
|
|
32
|
+
},
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
}
|
package/src/scene.ts
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
// The scene contract: one section's scene, built on a page's shared `keel-lit` surface and driven by position.
|
|
2
|
+
// The page decides when a scene is built, where it stands and what it may spend; the scene only answers.
|
|
3
|
+
import type { SurfaceContext } from '@kerf-js/core/surface'
|
|
4
|
+
import type { LitCamera, LitNode, LitStage } from './lit'
|
|
5
|
+
import type { RailOptions } from '../vendor/modules/camera-rail.mjs'
|
|
6
|
+
import type { Levers } from '../vendor/modules/quality.mjs'
|
|
7
|
+
import type { Sampled, Track } from '../vendor/modules/tracks.mjs'
|
|
8
|
+
import type * as Band from '../vendor/modules/band.mjs'
|
|
9
|
+
import type * as ButterfliesModule from '../vendor/modules/butterflies.mjs'
|
|
10
|
+
import type * as CameraRail from '../vendor/modules/camera-rail.mjs'
|
|
11
|
+
import type * as DeviceProfile from '../vendor/modules/device-profile.mjs'
|
|
12
|
+
import type * as LitFinish from '../vendor/modules/lit-finish.mjs'
|
|
13
|
+
import type * as Look from '../vendor/modules/look.mjs'
|
|
14
|
+
import type * as MotesModule from '../vendor/modules/motes.mjs'
|
|
15
|
+
import type * as PlatePainterModule from '../vendor/modules/plate-painter.mjs'
|
|
16
|
+
import type * as PortraitModule from '../vendor/modules/portrait.mjs'
|
|
17
|
+
import type * as Quality from '../vendor/modules/quality.mjs'
|
|
18
|
+
import type * as SceneBlendModule from '../vendor/modules/scene-blend.mjs'
|
|
19
|
+
import type * as SectionPost from '../vendor/modules/section-post.mjs'
|
|
20
|
+
import type * as SurfacesModule from '../vendor/modules/surfaces.mjs'
|
|
21
|
+
import type * as Tracks from '../vendor/modules/tracks.mjs'
|
|
22
|
+
import type * as TreeGrowth from '../vendor/modules/tree-growth.mjs'
|
|
23
|
+
import type * as TreeRender from '../vendor/modules/tree-render.mjs'
|
|
24
|
+
import type * as VoxelDither from '../vendor/modules/voxel-dither.mjs'
|
|
25
|
+
import type * as WorldLight from '../vendor/modules/world-light.mjs'
|
|
26
|
+
|
|
27
|
+
/** The modules a scene can ask for, each loaded once, when the first scene that names it is built. */
|
|
28
|
+
export interface KeelModules {
|
|
29
|
+
band: typeof Band
|
|
30
|
+
butterflies: typeof ButterfliesModule
|
|
31
|
+
'camera-rail': typeof CameraRail
|
|
32
|
+
'device-profile': typeof DeviceProfile
|
|
33
|
+
'lit-finish': typeof LitFinish
|
|
34
|
+
look: typeof Look
|
|
35
|
+
motes: typeof MotesModule
|
|
36
|
+
'plate-painter': typeof PlatePainterModule
|
|
37
|
+
portrait: typeof PortraitModule
|
|
38
|
+
quality: typeof Quality
|
|
39
|
+
'scene-blend': typeof SceneBlendModule
|
|
40
|
+
'section-post': typeof SectionPost
|
|
41
|
+
surfaces: typeof SurfacesModule
|
|
42
|
+
tracks: typeof Tracks
|
|
43
|
+
'tree-growth': typeof TreeGrowth
|
|
44
|
+
'tree-render': typeof TreeRender
|
|
45
|
+
'voxel-dither': typeof VoxelDither
|
|
46
|
+
'world-light': typeof WorldLight
|
|
47
|
+
}
|
|
48
|
+
/** A module's id. */
|
|
49
|
+
export type ModuleId = keyof KeelModules
|
|
50
|
+
|
|
51
|
+
/** What a page lets its scenes spend: quality's page levers. The page owns them; a scene reads them in `setQuality`. */
|
|
52
|
+
export type { Levers }
|
|
53
|
+
|
|
54
|
+
/** What the page knows this frame. */
|
|
55
|
+
export interface SceneFrame {
|
|
56
|
+
/** The pointer over the stage, each axis in -1..1 with y up; null when it is away. */
|
|
57
|
+
readonly pointer: { readonly x: number; readonly y: number } | null
|
|
58
|
+
/** How fast the position moves, in units per second; 0 at rest. */
|
|
59
|
+
readonly velocity: number
|
|
60
|
+
/** The page's clock in seconds. It stands still under reduced motion. */
|
|
61
|
+
readonly time: number
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A section's pass over its scene: a paper panel's sweep and edge, and the darkening and blur under it. */
|
|
65
|
+
export interface ScenePost {
|
|
66
|
+
readonly progress?: number
|
|
67
|
+
readonly position?: number
|
|
68
|
+
readonly tear?: number
|
|
69
|
+
/** `#rrggbb`, or display values 0..1. */
|
|
70
|
+
readonly colour?: string | readonly [number, number, number]
|
|
71
|
+
readonly darken?: number
|
|
72
|
+
readonly blur?: number
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A scene as a finish draws it: its stage and camera, or a function that draws it onto the current target. */
|
|
76
|
+
export type SceneShot = { readonly scene: LitStage; readonly camera: LitCamera } | (() => void)
|
|
77
|
+
|
|
78
|
+
/** A scene built on the stage's surface, ready to draw. */
|
|
79
|
+
export interface LiveScene {
|
|
80
|
+
readonly stage: LitStage
|
|
81
|
+
readonly camera: LitCamera
|
|
82
|
+
/** Where it stands when the page holds scenes still (reduced motion, a low tier): its spec's `hold`, resolved. */
|
|
83
|
+
readonly hold?: number | undefined
|
|
84
|
+
/** What tracks on the `post` target gave at the last `at`; null without them. */
|
|
85
|
+
readonly post: ScenePost | null
|
|
86
|
+
/** Poses the scene at `position`, in viewports since its section began to enter (1 ≈ one viewport). */
|
|
87
|
+
at(position: number, frame: SceneFrame): void
|
|
88
|
+
setQuality(levers: Levers): void
|
|
89
|
+
/** Draws it to whatever the renderer targets. */
|
|
90
|
+
render(): void
|
|
91
|
+
/** The scene for a finish to draw, its camera fitted to the canvas: a function when the scene draws itself. */
|
|
92
|
+
shot(): SceneShot
|
|
93
|
+
/** Frees its geometry, materials and textures. */
|
|
94
|
+
dispose(): void
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** What the page hands a scene to build on. */
|
|
98
|
+
export interface SceneHost {
|
|
99
|
+
readonly surface: SurfaceContext<'keel-lit'>
|
|
100
|
+
readonly seed: number
|
|
101
|
+
readonly quality: Levers
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Draws every frame: a hand-over from `a` to `b` at `t`, or one scene with `a` = `b` and `t` = 1. */
|
|
105
|
+
export interface SceneBlend {
|
|
106
|
+
draw(a: LiveScene, b: LiveScene, t: number, options: BlendOptions): void
|
|
107
|
+
dispose?(): void
|
|
108
|
+
}
|
|
109
|
+
/** How a frame looks: the incoming scene's hand-over, the levers in force and the active section's pass. */
|
|
110
|
+
export interface BlendOptions {
|
|
111
|
+
readonly mode: 'noise' | 'radial' | 'fade'
|
|
112
|
+
readonly pointer: { readonly x: number; readonly y: number } | null
|
|
113
|
+
readonly centre: { readonly x: number; readonly y: number } | null
|
|
114
|
+
/** False under reduced motion, or when the scene fills in without line work. */
|
|
115
|
+
readonly lines: boolean
|
|
116
|
+
readonly levers: Levers
|
|
117
|
+
readonly post: ScenePost | null
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** What `build` gets: the host's surface, seed and levers, the scene's modules, and a sampler for its tracks. */
|
|
121
|
+
export interface SceneContext<M extends ModuleId> extends SceneHost {
|
|
122
|
+
readonly lit: SurfaceContext<'keel-lit'>['lit']
|
|
123
|
+
readonly renderer: SurfaceContext<'keel-lit'>['renderer']
|
|
124
|
+
readonly modules: Pick<KeelModules, M>
|
|
125
|
+
/** The scene's tracks at a position (and a time, for tracks driven by the clock). */
|
|
126
|
+
sample(position: number, time?: number): Sampled
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** What `build` returns: the scene root and camera, and anything the hooks need, reached there as `this`. */
|
|
130
|
+
export interface Built {
|
|
131
|
+
readonly stage: LitStage
|
|
132
|
+
readonly camera: LitCamera
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** A scene as its author writes it. */
|
|
136
|
+
export interface SceneSpec<M extends ModuleId, B extends Built> {
|
|
137
|
+
/** Loaded before `build`. `tracks`, and `camera-rail` when the tracks key a camera, come on their own. */
|
|
138
|
+
readonly modules?: readonly M[]
|
|
139
|
+
/**
|
|
140
|
+
* Keyed tracks in sequence units. A `camera` target drives the camera through `camera-rail`; a `post` target
|
|
141
|
+
* (`progress`, `position`, `tear`, `colour`, `darken`, `blur`) feeds the section's pass.
|
|
142
|
+
*/
|
|
143
|
+
readonly tracks?: readonly Track[]
|
|
144
|
+
/**
|
|
145
|
+
* Where the scene stands when the page holds scenes still, under reduced motion or on a low tier: a position, or the
|
|
146
|
+
* `first` or `last` key of its tracks.
|
|
147
|
+
*/
|
|
148
|
+
readonly hold?: number | 'first' | 'last'
|
|
149
|
+
/** The rail's pointer pan and tilt, default fov and path. */
|
|
150
|
+
readonly rail?: Omit<RailOptions<readonly Track[]>, 'tracks'>
|
|
151
|
+
build(ctx: SceneContext<M>): B | Promise<B>
|
|
152
|
+
/** After the rail: anything else the position moves. `values` are the tracks sampled there. */
|
|
153
|
+
at?(this: B, position: number, frame: SceneFrame, values: Sampled): void
|
|
154
|
+
setQuality?(this: B, levers: Levers): void
|
|
155
|
+
/** Draws through a finish of its own. Default: the renderer draws `stage` with `camera`. */
|
|
156
|
+
render?(this: B): void
|
|
157
|
+
/** Frees what the default does not: the stage's meshes are freed for it. */
|
|
158
|
+
dispose?(this: B): void
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** A scene a page can build: what `defineScene` returns. */
|
|
162
|
+
export interface SceneDef {
|
|
163
|
+
/** Fetches its modules, so a build later is quick. Safe to call again. */
|
|
164
|
+
load(): Promise<void>
|
|
165
|
+
build(host: SceneHost): Promise<LiveScene>
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const LOAD: { [K in ModuleId]: () => Promise<KeelModules[K]> } = {
|
|
169
|
+
band: () => import('../vendor/modules/band.mjs'),
|
|
170
|
+
butterflies: () => import('../vendor/modules/butterflies.mjs'),
|
|
171
|
+
'camera-rail': () => import('../vendor/modules/camera-rail.mjs'),
|
|
172
|
+
'device-profile': () => import('../vendor/modules/device-profile.mjs'),
|
|
173
|
+
'lit-finish': () => import('../vendor/modules/lit-finish.mjs'),
|
|
174
|
+
look: () => import('../vendor/modules/look.mjs'),
|
|
175
|
+
motes: () => import('../vendor/modules/motes.mjs'),
|
|
176
|
+
'plate-painter': () => import('../vendor/modules/plate-painter.mjs'),
|
|
177
|
+
portrait: () => import('../vendor/modules/portrait.mjs'),
|
|
178
|
+
quality: () => import('../vendor/modules/quality.mjs'),
|
|
179
|
+
'scene-blend': () => import('../vendor/modules/scene-blend.mjs'),
|
|
180
|
+
'section-post': () => import('../vendor/modules/section-post.mjs'),
|
|
181
|
+
surfaces: () => import('../vendor/modules/surfaces.mjs'),
|
|
182
|
+
tracks: () => import('../vendor/modules/tracks.mjs'),
|
|
183
|
+
'tree-growth': () => import('../vendor/modules/tree-growth.mjs'),
|
|
184
|
+
'tree-render': () => import('../vendor/modules/tree-render.mjs'),
|
|
185
|
+
'voxel-dither': () => import('../vendor/modules/voxel-dither.mjs'),
|
|
186
|
+
'world-light': () => import('../vendor/modules/world-light.mjs'),
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
type Freeable = { dispose?: () => void; isTexture?: boolean }
|
|
190
|
+
|
|
191
|
+
/** Frees every geometry, material and material texture under `root`. */
|
|
192
|
+
export function disposeTree(root: LitNode) {
|
|
193
|
+
root.traverse((node) => {
|
|
194
|
+
const { geometry, material } = node as { geometry?: Freeable; material?: Freeable | Freeable[] }
|
|
195
|
+
geometry?.dispose?.()
|
|
196
|
+
for (const m of ([] as Freeable[]).concat(material ?? [])) {
|
|
197
|
+
for (const value of Object.values(m) as unknown[])
|
|
198
|
+
if ((value as Freeable | null)?.isTexture) (value as Freeable).dispose?.()
|
|
199
|
+
m.dispose?.()
|
|
200
|
+
}
|
|
201
|
+
})
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** A hold as a position: as given, or the first or last key across the tracks (0 without any). */
|
|
205
|
+
function stop(hold: number | 'first' | 'last' | undefined, tracks: readonly Track[]) {
|
|
206
|
+
if (typeof hold !== 'string') return hold
|
|
207
|
+
const keys = tracks.flatMap((track) => track.keys.map((key) => key[0]))
|
|
208
|
+
if (!keys.length) return 0
|
|
209
|
+
return hold === 'first' ? Math.min(...keys) : Math.max(...keys)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function loadAll(ids: readonly ModuleId[]) {
|
|
213
|
+
const loaded = await Promise.all(ids.map((id) => LOAD[id]()))
|
|
214
|
+
return Object.fromEntries(ids.map((id, i) => [id, loaded[i]])) as Partial<KeelModules>
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Declares a section's scene: `defineScene({ tracks, build(ctx) { ... return { stage, camera } } })`.
|
|
219
|
+
* The page builds it when its section comes near, poses it with `at` each frame and disposes it when far.
|
|
220
|
+
*/
|
|
221
|
+
export function defineScene<M extends ModuleId = never, B extends Built = Built>(
|
|
222
|
+
spec: SceneSpec<M, B>,
|
|
223
|
+
): SceneDef {
|
|
224
|
+
const tracks = spec.tracks ?? []
|
|
225
|
+
const rides = tracks.some((track) => track.target === (spec.rail?.name ?? 'camera'))
|
|
226
|
+
const posts = tracks.some((track) => track.target === 'post')
|
|
227
|
+
const ids = [
|
|
228
|
+
...new Set<ModuleId>([
|
|
229
|
+
...(spec.modules ?? []),
|
|
230
|
+
'tracks',
|
|
231
|
+
...(rides ? ['camera-rail' as const] : []),
|
|
232
|
+
]),
|
|
233
|
+
]
|
|
234
|
+
let loading: Promise<Partial<KeelModules>> | undefined
|
|
235
|
+
const load = () => (loading ??= loadAll(ids))
|
|
236
|
+
return {
|
|
237
|
+
load: async () => void (await load()),
|
|
238
|
+
async build(host) {
|
|
239
|
+
const modules = await load()
|
|
240
|
+
const { sampleTracks } = modules.tracks!
|
|
241
|
+
const { lit, renderer } = host.surface
|
|
242
|
+
const sample = (position: number, time?: number) => sampleTracks(tracks, position, time)
|
|
243
|
+
const ctx = { ...host, lit, renderer, modules: modules as Pick<KeelModules, M>, sample }
|
|
244
|
+
const built = await spec.build(ctx)
|
|
245
|
+
const rail = rides
|
|
246
|
+
? modules['camera-rail']!.createCameraRail(sampleTracks, { ...spec.rail, tracks })
|
|
247
|
+
: null
|
|
248
|
+
const apply = modules['camera-rail']?.applyView
|
|
249
|
+
let aspect = 0
|
|
250
|
+
// The stage's surface resizes under the scene: its camera follows the canvas's shape.
|
|
251
|
+
const fit = () => {
|
|
252
|
+
const { width, height } = host.surface.size.value
|
|
253
|
+
if (!width || !height || width / height === aspect) return
|
|
254
|
+
aspect = width / height
|
|
255
|
+
built.camera.aspect = aspect
|
|
256
|
+
built.camera.updateProjectionMatrix()
|
|
257
|
+
}
|
|
258
|
+
const live: LiveScene & { post: ScenePost | null } = {
|
|
259
|
+
stage: built.stage,
|
|
260
|
+
camera: built.camera,
|
|
261
|
+
hold: stop(spec.hold, tracks),
|
|
262
|
+
post: null,
|
|
263
|
+
at(position, frame) {
|
|
264
|
+
if (rail && apply) apply(built.camera, rail.at(position, frame))
|
|
265
|
+
const values = sample(position, frame.time)
|
|
266
|
+
if (posts) live.post = values.post as ScenePost
|
|
267
|
+
spec.at?.call(built, position, frame, values)
|
|
268
|
+
},
|
|
269
|
+
setQuality: (levers) => spec.setQuality?.call(built, levers),
|
|
270
|
+
render() {
|
|
271
|
+
fit()
|
|
272
|
+
if (spec.render) spec.render.call(built)
|
|
273
|
+
else renderer.render(built.stage, built.camera)
|
|
274
|
+
},
|
|
275
|
+
shot() {
|
|
276
|
+
fit()
|
|
277
|
+
return spec.render
|
|
278
|
+
? () => spec.render!.call(built)
|
|
279
|
+
: { scene: built.stage, camera: built.camera }
|
|
280
|
+
},
|
|
281
|
+
dispose() {
|
|
282
|
+
spec.dispose?.call(built)
|
|
283
|
+
disposeTree(built.stage)
|
|
284
|
+
},
|
|
285
|
+
}
|
|
286
|
+
return live
|
|
287
|
+
},
|
|
288
|
+
}
|
|
289
|
+
}
|