@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
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// A generator's result as one buffer for Cache Storage, and back: the JSON of its plain parts, then each typed array's
|
|
2
|
+
// bytes, 8-aligned. And the buffers a result can hand over to another thread without a copy.
|
|
3
|
+
|
|
4
|
+
type Typed =
|
|
5
|
+
| Float32Array
|
|
6
|
+
| Float64Array
|
|
7
|
+
| Uint8Array
|
|
8
|
+
| Uint8ClampedArray
|
|
9
|
+
| Uint16Array
|
|
10
|
+
| Uint32Array
|
|
11
|
+
| Int32Array
|
|
12
|
+
const KINDS = {
|
|
13
|
+
Float32Array,
|
|
14
|
+
Float64Array,
|
|
15
|
+
Uint8Array,
|
|
16
|
+
Uint8ClampedArray,
|
|
17
|
+
Uint16Array,
|
|
18
|
+
Uint32Array,
|
|
19
|
+
Int32Array,
|
|
20
|
+
}
|
|
21
|
+
type Kind = keyof typeof KINDS
|
|
22
|
+
|
|
23
|
+
const typed = (value: unknown): value is Typed =>
|
|
24
|
+
ArrayBuffer.isView(value) && !(value instanceof DataView)
|
|
25
|
+
|
|
26
|
+
/** Each typed array's buffer under `value`, once. */
|
|
27
|
+
export function transferables(value: unknown, out = new Set<ArrayBuffer>()): ArrayBuffer[] {
|
|
28
|
+
if (typed(value)) {
|
|
29
|
+
if (value.buffer instanceof ArrayBuffer) out.add(value.buffer)
|
|
30
|
+
} else if (value && typeof value === 'object')
|
|
31
|
+
for (const v of Object.values(value)) transferables(v, out)
|
|
32
|
+
return [...out]
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** `value` as one buffer: a length, the JSON with each typed array as `{ $: kind, at, n }`, then their bytes. */
|
|
36
|
+
export function pack(value: unknown): ArrayBuffer {
|
|
37
|
+
const parts: Typed[] = []
|
|
38
|
+
let at = 0
|
|
39
|
+
const json = JSON.stringify(value, (_key, v: unknown) => {
|
|
40
|
+
if (!typed(v)) return v
|
|
41
|
+
const ref = { $: v.constructor.name as Kind, at, n: v.length }
|
|
42
|
+
parts.push(v)
|
|
43
|
+
at += Math.ceil(v.byteLength / 8) * 8
|
|
44
|
+
return ref
|
|
45
|
+
})
|
|
46
|
+
const head = new TextEncoder().encode(json)
|
|
47
|
+
const start = Math.ceil((4 + head.length) / 8) * 8
|
|
48
|
+
const out = new Uint8Array(start + at)
|
|
49
|
+
new DataView(out.buffer).setUint32(0, head.length)
|
|
50
|
+
out.set(head, 4)
|
|
51
|
+
let offset = start
|
|
52
|
+
for (const p of parts) {
|
|
53
|
+
out.set(new Uint8Array(p.buffer, p.byteOffset, p.byteLength), offset)
|
|
54
|
+
offset += Math.ceil(p.byteLength / 8) * 8
|
|
55
|
+
}
|
|
56
|
+
return out.buffer
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** What `pack` wrote, its typed arrays as views on `buffer`. */
|
|
60
|
+
export function unpack<T>(buffer: ArrayBuffer): T {
|
|
61
|
+
const length = new DataView(buffer).getUint32(0)
|
|
62
|
+
const json = new TextDecoder().decode(new Uint8Array(buffer, 4, length))
|
|
63
|
+
const start = Math.ceil((4 + length) / 8) * 8
|
|
64
|
+
return JSON.parse(json, (_key, v: { $?: Kind; at: number; n: number } | null) =>
|
|
65
|
+
v && typeof v === 'object' && v.$ && v.$ in KINDS
|
|
66
|
+
? new KINDS[v.$](buffer, start + v.at, v.n)
|
|
67
|
+
: v,
|
|
68
|
+
) as T
|
|
69
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// A painted plate at a frame's size: planned, painted on a WebGL2 `OffscreenCanvas` and read back as pixels.
|
|
2
|
+
import {
|
|
3
|
+
coverCrop,
|
|
4
|
+
createPlatePainter,
|
|
5
|
+
LAKE_VALLEY,
|
|
6
|
+
planPlate,
|
|
7
|
+
type BackdropView,
|
|
8
|
+
type PlatePainter,
|
|
9
|
+
type PlatePlan,
|
|
10
|
+
type PlateRecipe,
|
|
11
|
+
type PlateSettings,
|
|
12
|
+
type PlateView,
|
|
13
|
+
} from '../../vendor/modules/plate-painter.mjs'
|
|
14
|
+
|
|
15
|
+
/** What to paint: a recipe (the module's own by default) and settings, at a size, of the crop that covers it. */
|
|
16
|
+
export interface PlateJob {
|
|
17
|
+
readonly recipe?: PlateRecipe
|
|
18
|
+
readonly settings?: PlateSettings
|
|
19
|
+
readonly width: number
|
|
20
|
+
readonly height: number
|
|
21
|
+
/** The plate's part to paint; default the crop covering `width` × `height`, placed by `cover`. */
|
|
22
|
+
readonly view?: PlateView
|
|
23
|
+
readonly cover?: Omit<BackdropView, 'width' | 'height'>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The plate's pixels, rows from the top: `new lit.DataTexture(data, width, height)`. */
|
|
27
|
+
export interface PlateResult {
|
|
28
|
+
readonly digest: string
|
|
29
|
+
readonly width: number
|
|
30
|
+
readonly height: number
|
|
31
|
+
readonly view: PlateView
|
|
32
|
+
readonly data: Uint8ClampedArray
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const plans = new Map<string, PlatePlan>()
|
|
36
|
+
let painter: PlatePainter | undefined
|
|
37
|
+
|
|
38
|
+
export function run(job: PlateJob): PlateResult {
|
|
39
|
+
const recipe = job.recipe ?? LAKE_VALLEY
|
|
40
|
+
const key = JSON.stringify([recipe, job.settings ?? {}])
|
|
41
|
+
let plan = plans.get(key)
|
|
42
|
+
if (!plan) plans.set(key, (plan = planPlate(recipe, job.settings)))
|
|
43
|
+
const gl = painter ? null : new OffscreenCanvas(1, 1).getContext('webgl2')
|
|
44
|
+
if (!painter && !gl) throw new Error('keel generate: plates need WebGL2 on an OffscreenCanvas')
|
|
45
|
+
painter ??= createPlatePainter(gl!)
|
|
46
|
+
const view = job.view ?? coverCrop(plan.aspect, job.width / job.height, job.cover)
|
|
47
|
+
const plate = painter.paint(plan, { width: job.width, height: job.height, view })
|
|
48
|
+
const still = painter.read(plate)
|
|
49
|
+
painter.release(plate)
|
|
50
|
+
return { digest: plate.digest, width: still.width, height: still.height, view, data: still.data }
|
|
51
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// A generator's worker side: runs one job per message and hands the result back, its buffers transferred. In a
|
|
2
|
+
// secure context, results are kept in Cache Storage under the worker's own (content-hashed) URL and the job's key,
|
|
3
|
+
// so a repeat visit reads the bytes instead of generating them.
|
|
4
|
+
import { pack, transferables, unpack } from './pack'
|
|
5
|
+
|
|
6
|
+
/** A request from `generate`. */
|
|
7
|
+
export interface Request {
|
|
8
|
+
readonly id: number
|
|
9
|
+
readonly key: string
|
|
10
|
+
readonly args: unknown
|
|
11
|
+
/** Keep the result in Cache Storage for the next visit. */
|
|
12
|
+
readonly store: boolean
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const DEV = (import.meta as { env?: { DEV?: boolean } }).env?.DEV !== false
|
|
16
|
+
const CACHE = 'keel-generate'
|
|
17
|
+
|
|
18
|
+
/** The cache entry's URL: the worker's path, so a new build (a new worker file) misses, then the job's key. */
|
|
19
|
+
const entry = (key: string) =>
|
|
20
|
+
`${self.location.origin}/.keel-generate${self.location.pathname}/${encodeURIComponent(key)}`
|
|
21
|
+
|
|
22
|
+
async function cached(key: string): Promise<unknown> {
|
|
23
|
+
if (DEV || typeof caches === 'undefined') return undefined
|
|
24
|
+
try {
|
|
25
|
+
const hit = await (await caches.open(CACHE)).match(entry(key))
|
|
26
|
+
return hit ? unpack(await hit.arrayBuffer()) : undefined
|
|
27
|
+
} catch {
|
|
28
|
+
return undefined
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function keep(key: string, value: unknown) {
|
|
33
|
+
if (DEV || typeof caches === 'undefined') return
|
|
34
|
+
const body = pack(value)
|
|
35
|
+
void caches
|
|
36
|
+
.open(CACHE)
|
|
37
|
+
.then((cache) => cache.put(entry(key), new Response(body)))
|
|
38
|
+
.catch(() => {})
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Answers `generate`'s messages with `run`. */
|
|
42
|
+
export function serve(run: (args: never) => unknown) {
|
|
43
|
+
self.onmessage = async ({ data }: MessageEvent<Request>) => {
|
|
44
|
+
try {
|
|
45
|
+
let result = data.store ? await cached(data.key) : undefined
|
|
46
|
+
if (result === undefined) {
|
|
47
|
+
result = await run(data.args as never)
|
|
48
|
+
// Packed before the transfer below takes the buffers away.
|
|
49
|
+
if (data.store) keep(data.key, result)
|
|
50
|
+
}
|
|
51
|
+
self.postMessage({ id: data.id, result }, { transfer: transferables(result) })
|
|
52
|
+
} catch (error) {
|
|
53
|
+
self.postMessage({ id: data.id, error: (error as Error)?.message ?? String(error) })
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// A surface's albedo and relief: on a WebGL2 `OffscreenCanvas` where there is one, else on the CPU. Same pixels.
|
|
2
|
+
import { recipeOf, type PaintRecipe } from '../paint-recipe.mjs'
|
|
3
|
+
import * as surfaces from '../../vendor/modules/surfaces.mjs'
|
|
4
|
+
|
|
5
|
+
let painter: surfaces.SurfacePainter | null | undefined
|
|
6
|
+
|
|
7
|
+
export function run(request: PaintRecipe): surfaces.Surface {
|
|
8
|
+
const { recipe, settings } = recipeOf(request, surfaces)
|
|
9
|
+
const plan = surfaces.planSurface(recipe, settings)
|
|
10
|
+
if (painter === undefined) {
|
|
11
|
+
const gl =
|
|
12
|
+
typeof OffscreenCanvas === 'undefined' ? null : new OffscreenCanvas(1, 1).getContext('webgl2')
|
|
13
|
+
painter = gl && surfaces.createSurfacePainter(gl)
|
|
14
|
+
}
|
|
15
|
+
return painter ? painter.paintPlan(plan) : surfaces.paintPlan(plan)
|
|
16
|
+
}
|
package/src/generate.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// Generators off the main thread: `await generate('bust', recipe)` meshes a portrait's bust in a worker, and
|
|
2
|
+
// 'plate' and 'surface' paint there on an `OffscreenCanvas`. Results come back as `{ digest, buffers }`-shaped plain
|
|
3
|
+
// data with their buffers transferred, kept by the job's key for the page's life (and across visits in Cache Storage),
|
|
4
|
+
// so asking twice costs nothing. Without workers (a test, a server) the job runs here, after an `import()`.
|
|
5
|
+
import type { Surface } from '../vendor/modules/surfaces.mjs'
|
|
6
|
+
import type { BustJob, BustResult } from './generate/bust'
|
|
7
|
+
import type { PlateJob, PlateResult } from './generate/plate'
|
|
8
|
+
import type { Request } from './generate/serve'
|
|
9
|
+
import type { PaintRecipe } from './paint-recipe.mjs'
|
|
10
|
+
|
|
11
|
+
export type { BustJob, BustResult, PlateJob, PlateResult, PaintRecipe }
|
|
12
|
+
|
|
13
|
+
/** Each job: what it takes and what it gives. */
|
|
14
|
+
export interface GenerateJobs {
|
|
15
|
+
/** portrait's `buildBust`, from settings or a recipe: then `createPortrait(lit, bust, bust.palette)` here. */
|
|
16
|
+
bust: { args: BustJob; result: BustResult }
|
|
17
|
+
/** plate-painter's plate at a frame's size, read back: `new lit.DataTexture(data, width, height)`. */
|
|
18
|
+
plate: { args: PlateJob; result: PlateResult }
|
|
19
|
+
/** A surface's albedo and relief, as `paintLive` and `?paint` take it. */
|
|
20
|
+
surface: { args: PaintRecipe; result: Surface }
|
|
21
|
+
}
|
|
22
|
+
/** A job's name: `bust`, `plate` or `surface`. */
|
|
23
|
+
export type GenerateJob = keyof GenerateJobs
|
|
24
|
+
|
|
25
|
+
/** How long a result is kept. */
|
|
26
|
+
export interface GenerateOptions {
|
|
27
|
+
/** For the page's life, so asking again costs nothing. Default true, false for `plate` (one per canvas size). */
|
|
28
|
+
readonly keep?: boolean
|
|
29
|
+
/** In Cache Storage too, for the next visit (secure contexts, built pages). Default as `keep`. */
|
|
30
|
+
readonly store?: boolean
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
type Answer = { id: number; result?: unknown; error?: string }
|
|
34
|
+
|
|
35
|
+
const kept = new Map<string, Promise<unknown>>()
|
|
36
|
+
const workers = new Map<GenerateJob, Worker | null>()
|
|
37
|
+
const waiting = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>()
|
|
38
|
+
let next = 0
|
|
39
|
+
|
|
40
|
+
/** Each worker named in full, so the bundler finds and builds it. */
|
|
41
|
+
function spawn(job: GenerateJob): Worker {
|
|
42
|
+
if (job === 'bust')
|
|
43
|
+
return new Worker(new URL('./generate/bust.worker.ts', import.meta.url), {
|
|
44
|
+
type: 'module',
|
|
45
|
+
name: 'keel-bust',
|
|
46
|
+
})
|
|
47
|
+
if (job === 'plate')
|
|
48
|
+
return new Worker(new URL('./generate/plate.worker.ts', import.meta.url), {
|
|
49
|
+
type: 'module',
|
|
50
|
+
name: 'keel-plate',
|
|
51
|
+
})
|
|
52
|
+
return new Worker(new URL('./generate/surface.worker.ts', import.meta.url), {
|
|
53
|
+
type: 'module',
|
|
54
|
+
name: 'keel-surface',
|
|
55
|
+
})
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function workerFor(job: GenerateJob): Worker | null {
|
|
59
|
+
if (!workers.has(job)) {
|
|
60
|
+
const worker = typeof Worker === 'undefined' ? null : spawn(job)
|
|
61
|
+
worker?.addEventListener('message', ({ data }: MessageEvent<Answer>) => {
|
|
62
|
+
const wait = waiting.get(data.id)
|
|
63
|
+
waiting.delete(data.id)
|
|
64
|
+
if (data.error === undefined) wait?.resolve(data.result)
|
|
65
|
+
else wait?.reject(new Error(data.error))
|
|
66
|
+
})
|
|
67
|
+
workers.set(job, worker)
|
|
68
|
+
}
|
|
69
|
+
return workers.get(job)!
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** In this thread: for a page with no workers, and the fallback when a worker can't (a plate without WebGL2 there). */
|
|
73
|
+
async function here(job: GenerateJob, args: unknown): Promise<unknown> {
|
|
74
|
+
const jobs = {
|
|
75
|
+
bust: () => import('./generate/bust'),
|
|
76
|
+
plate: () => import('./generate/plate'),
|
|
77
|
+
surface: () => import('./generate/surface'),
|
|
78
|
+
}
|
|
79
|
+
const { run } = await jobs[job]()
|
|
80
|
+
return (run as (a: unknown) => unknown)(args)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The same JSON for the same value, whatever order its keys were written in. */
|
|
84
|
+
export function keyOf(job: GenerateJob, args: unknown): string {
|
|
85
|
+
const sorted = (v: unknown): unknown =>
|
|
86
|
+
v && typeof v === 'object' && !Array.isArray(v)
|
|
87
|
+
? Object.fromEntries(
|
|
88
|
+
Object.keys(v)
|
|
89
|
+
.sort((a, b) => a.localeCompare(b))
|
|
90
|
+
.map((k) => [k, sorted((v as Record<string, unknown>)[k])]),
|
|
91
|
+
)
|
|
92
|
+
: Array.isArray(v)
|
|
93
|
+
? v.map(sorted)
|
|
94
|
+
: v
|
|
95
|
+
return `${job}:${JSON.stringify(sorted(args))}`
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Runs a generator in its worker: `const bust = await generate('bust', recipe)`. The same job and args give the same
|
|
100
|
+
* promise for the page's life; `forget(job, args)` drops it. Data only: upload textures and geometry here.
|
|
101
|
+
*/
|
|
102
|
+
export function generate<J extends GenerateJob>(
|
|
103
|
+
job: J,
|
|
104
|
+
args: GenerateJobs[J]['args'],
|
|
105
|
+
options: GenerateOptions = {},
|
|
106
|
+
): Promise<GenerateJobs[J]['result']> {
|
|
107
|
+
const key = keyOf(job, args)
|
|
108
|
+
const keep = options.keep ?? job !== 'plate'
|
|
109
|
+
let result = kept.get(key)
|
|
110
|
+
if (!result) {
|
|
111
|
+
const worker = workerFor(job)
|
|
112
|
+
const store = options.store ?? keep
|
|
113
|
+
result = worker
|
|
114
|
+
? new Promise((resolve, reject) => {
|
|
115
|
+
const id = next++
|
|
116
|
+
waiting.set(id, { resolve, reject })
|
|
117
|
+
worker.postMessage({ id, key, args, store } satisfies Request)
|
|
118
|
+
}).catch(() => here(job, args))
|
|
119
|
+
: here(job, args)
|
|
120
|
+
// A failed job is not kept, so asking again tries again; one not to keep is shared only while it runs.
|
|
121
|
+
void result.then(
|
|
122
|
+
() => keep || kept.delete(key),
|
|
123
|
+
() => kept.delete(key),
|
|
124
|
+
)
|
|
125
|
+
kept.set(key, result)
|
|
126
|
+
}
|
|
127
|
+
return result as Promise<GenerateJobs[J]['result']>
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Drops a kept result, so its buffers can be freed once nothing else holds them. */
|
|
131
|
+
export function forget<J extends GenerateJob>(job: J, args: GenerateJobs[J]['args']) {
|
|
132
|
+
kept.delete(keyOf(job, args))
|
|
133
|
+
}
|
package/src/governor.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// The page's frame governor on KEEL's own modules: device-profile reads the device once, quality picks the level and
|
|
2
|
+
// its page levers from the tier and lowers the render scale while frames run slow; the tier sets the fps and ratio caps.
|
|
3
|
+
import type { Levers } from './scene'
|
|
4
|
+
import type { DeviceSignals, DeviceTier } from '../vendor/modules/device-profile.mjs'
|
|
5
|
+
import type { Quality } from '../vendor/modules/quality.mjs'
|
|
6
|
+
|
|
7
|
+
/** Options for `keelGovernor`. */
|
|
8
|
+
export interface GovernorOptions {
|
|
9
|
+
/** The frame time to hold, in ms. Default 1000 / 60. */
|
|
10
|
+
target?: number
|
|
11
|
+
/** A recorded device instead of this browser's: a test, or a page that pins a tier. */
|
|
12
|
+
signals?: DeviceSignals
|
|
13
|
+
/**
|
|
14
|
+
* A media query under which scenes hold too, whatever the tier: `'(max-width: 767px)'` stands a phone's scenes at
|
|
15
|
+
* their `hold` without a camera of their own for it. Read every frame, so turning a tablet moves it.
|
|
16
|
+
*/
|
|
17
|
+
hold?: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A governor for `<Stage governor={...}>`. */
|
|
21
|
+
export interface KeelGovernor {
|
|
22
|
+
start(): Promise<void>
|
|
23
|
+
frame(ms: number): void
|
|
24
|
+
readonly levers: Levers
|
|
25
|
+
readonly fps: number
|
|
26
|
+
pixelRatio(width: number): number
|
|
27
|
+
/** True on a low tier or under `hold`'s query: scenes with a `hold` stand there rather than move with the scroll. */
|
|
28
|
+
readonly hold: boolean
|
|
29
|
+
/** The device's tier once `start` resolved; `high` before. */
|
|
30
|
+
readonly tier: DeviceTier
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Everything at full, until the device is read. */
|
|
34
|
+
const FULL: Levers = { renderScale: 1, bloom: 1, motes: 1, blendScale: 1, taa: true, density: 1 }
|
|
35
|
+
|
|
36
|
+
/** What each tier's frames may cost: low draws at 30 fps, and a narrower canvas on a weaker device. */
|
|
37
|
+
const PACE: Record<DeviceTier, { fps: number; widest: number }> = {
|
|
38
|
+
high: { fps: 60, widest: 3840 },
|
|
39
|
+
mid: { fps: 60, widest: 1920 },
|
|
40
|
+
low: { fps: 30, widest: 1280 },
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The frame governor a stage asks each frame: `<Stage governor={keelGovernor()}>`. Its modules load in `start`.
|
|
45
|
+
* The render scale is quality's, relative to where quality starts, so a device that keeps up draws at full scale.
|
|
46
|
+
*/
|
|
47
|
+
export function keelGovernor(options: GovernorOptions = {}): KeelGovernor {
|
|
48
|
+
let tier: DeviceTier = 'high'
|
|
49
|
+
let device = 2
|
|
50
|
+
let quality: Quality | null = null
|
|
51
|
+
let start = 1
|
|
52
|
+
let levers = FULL
|
|
53
|
+
const narrow = options.hold && typeof matchMedia === 'function' ? matchMedia(options.hold) : null
|
|
54
|
+
return {
|
|
55
|
+
async start() {
|
|
56
|
+
const [profile, governor] = await Promise.all([
|
|
57
|
+
import('../vendor/modules/device-profile.mjs'),
|
|
58
|
+
import('../vendor/modules/quality.mjs'),
|
|
59
|
+
])
|
|
60
|
+
const known = profile.profileOf(options.signals ?? profile.readSignals())
|
|
61
|
+
tier = known.tier
|
|
62
|
+
device = known.pixelRatio
|
|
63
|
+
quality = governor.createQuality({ level: 'auto', tier, target: options.target ?? 1000 / 60 })
|
|
64
|
+
start = quality.scale
|
|
65
|
+
levers = { ...quality.levers, renderScale: 1 }
|
|
66
|
+
},
|
|
67
|
+
frame(ms) {
|
|
68
|
+
if (!quality) return
|
|
69
|
+
quality.frame(ms)
|
|
70
|
+
const scale = Math.round((quality.scale / start) * 100) / 100
|
|
71
|
+
if (scale !== levers.renderScale) levers = { ...levers, renderScale: scale }
|
|
72
|
+
},
|
|
73
|
+
get levers() {
|
|
74
|
+
return levers
|
|
75
|
+
},
|
|
76
|
+
get fps() {
|
|
77
|
+
return PACE[tier].fps
|
|
78
|
+
},
|
|
79
|
+
get tier() {
|
|
80
|
+
return tier
|
|
81
|
+
},
|
|
82
|
+
get hold() {
|
|
83
|
+
return tier === 'low' || !!narrow?.matches
|
|
84
|
+
},
|
|
85
|
+
pixelRatio: (width) => Math.min(device, 2, PACE[tier].widest / Math.max(width, 1)),
|
|
86
|
+
}
|
|
87
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { PluginEntry } from '@kerf-js/core/config'
|
|
2
|
+
import type * as lit from './lit'
|
|
3
|
+
|
|
4
|
+
/** The plugin for `kerf.config.ts`: adds the `keel-lit` surface kind. */
|
|
5
|
+
export declare const keel: () => PluginEntry
|
|
6
|
+
|
|
7
|
+
/** The KEEL modules this package ships: `@kerf-js/keel/modules/<id>`. */
|
|
8
|
+
export declare const MODULES: readonly string[]
|
|
9
|
+
|
|
10
|
+
declare module '@kerf-js/core/surface' {
|
|
11
|
+
interface SurfaceKinds {
|
|
12
|
+
/** `s.lit`: the keel/lit namespace. `s.renderer`: its renderer, bound to the surface's canvas. */
|
|
13
|
+
'keel-lit': { lit: typeof lit; renderer: lit.LitRenderer }
|
|
14
|
+
}
|
|
15
|
+
}
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// KEEL's renderer and modules stay behind `import()`: only a page that mounts a `keel-lit` surface loads them.
|
|
2
|
+
import { definePlugin, defineSlot, provide } from '@kerf-js/core/plugin'
|
|
3
|
+
|
|
4
|
+
const renderer = defineSlot({
|
|
5
|
+
id: 'surface.renderer',
|
|
6
|
+
version: 1,
|
|
7
|
+
cardinality: 'keyed',
|
|
8
|
+
sides: ['client'],
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
/** The KEEL modules this package ships, each loaded on its own: `@kerf-js/keel/modules/<id>`. */
|
|
12
|
+
export const MODULES = [
|
|
13
|
+
'band',
|
|
14
|
+
'butterflies',
|
|
15
|
+
'camera-rail',
|
|
16
|
+
'device-profile',
|
|
17
|
+
'lit-finish',
|
|
18
|
+
'look',
|
|
19
|
+
'motes',
|
|
20
|
+
'plate-painter',
|
|
21
|
+
'portrait',
|
|
22
|
+
'quality',
|
|
23
|
+
'scene-blend',
|
|
24
|
+
'section-post',
|
|
25
|
+
'surfaces',
|
|
26
|
+
'tracks',
|
|
27
|
+
'tree-growth',
|
|
28
|
+
'tree-render',
|
|
29
|
+
'voxel-dither',
|
|
30
|
+
'world-light',
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
export const keel = definePlugin({
|
|
34
|
+
name: '@kerf-js/keel',
|
|
35
|
+
version: '0.1.4',
|
|
36
|
+
kerf: '*',
|
|
37
|
+
namespace: 'keel/',
|
|
38
|
+
contribute: () => ({
|
|
39
|
+
provides: [
|
|
40
|
+
provide(renderer, {
|
|
41
|
+
key: 'keel-lit',
|
|
42
|
+
sides: { client: { module: '@kerf-js/keel/runtime', export: 'renderer' } },
|
|
43
|
+
}),
|
|
44
|
+
],
|
|
45
|
+
agents: {
|
|
46
|
+
title: 'KEEL generation (@kerf-js/keel)',
|
|
47
|
+
text: [
|
|
48
|
+
"- `kind: 'keel-lit'`: `s.lit` is keel/lit (WebGL2 scene graph, PBR, soft shadows), `s.renderer` its renderer.",
|
|
49
|
+
"- `keelStage(s, { prefer: 'realism' | 'pixel' })` from `@kerf-js/keel/stage` gives `scene`, `camera`, `sun`, `sky`, `setLook()`, `light()` and `render()`. Call `stage.render()` inside `s.frame`.",
|
|
50
|
+
'- Generators load lazily: `await import("@kerf-js/keel/modules/tree-growth")` (also tree-render, world-light, quality, device-profile, tracks, camera-rail, scene-blend, section-post, motes, butterflies, plate-painter, portrait, surfaces). Same seed, same result.',
|
|
51
|
+
'- Music: `createBand(audioContext)` and `scoreOf({ seed, style })` from `@kerf-js/keel/modules/band` (ambient, lofi, synthwave, chiptune, house, cinematic, folk, dream). `band.setEnergy(0..1)` layers parts. Start it from a click.',
|
|
52
|
+
'- Scrub a scene with `timeline()` and `progress()` from `@kerf-js/scroll/timeline`.',
|
|
53
|
+
].join('\n'),
|
|
54
|
+
},
|
|
55
|
+
catalog: [
|
|
56
|
+
{
|
|
57
|
+
name: 'keel',
|
|
58
|
+
import: '@kerf-js/keel',
|
|
59
|
+
summary: 'surface.renderer: keel-lit; KEEL generators (trees, looks, light)',
|
|
60
|
+
},
|
|
61
|
+
],
|
|
62
|
+
}),
|
|
63
|
+
})
|