lk3d 0.1.0 → 0.2.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.
Files changed (61) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +19 -6
  3. package/bin/lk3d.mjs +24 -13
  4. package/dist/lk3d-export.min.js +1 -1
  5. package/dist/lk3d.min.js +55 -23
  6. package/dist/lk3d.mjs +55 -23
  7. package/docs/api.md +105 -24
  8. package/docs/design.md +10 -7
  9. package/docs/performance.md +41 -10
  10. package/docs/scene-format.md +30 -29
  11. package/index.d.ts +49 -2
  12. package/package.json +1 -3
  13. package/scene.d.ts +96 -1
  14. package/schema/scene.schema.json +165 -1
  15. package/skill/lk3d/SKILL.md +11 -1
  16. package/src/ao.js +58 -0
  17. package/src/controls.js +21 -2
  18. package/src/element.js +111 -0
  19. package/src/figure/api.js +12 -2
  20. package/src/figure/camera.js +49 -9
  21. package/src/figure/context.d.ts +23 -1
  22. package/src/figure/idle.js +57 -19
  23. package/src/figure/input.js +81 -7
  24. package/src/figure/labels.js +12 -9
  25. package/src/figure/loop.js +6 -2
  26. package/src/figure/pick.js +19 -5
  27. package/src/figure/steps.js +143 -0
  28. package/src/flow.js +33 -2
  29. package/src/index.js +13 -2
  30. package/src/locales/en.js +6 -0
  31. package/src/locales/vi.js +6 -0
  32. package/src/renderer-gl.js +85 -15
  33. package/src/shaders.js +39 -1
  34. package/src/stylesheet.js +10 -2
  35. package/src/validate.js +50 -0
  36. package/docs/flow.png +0 -0
  37. package/docs/generator.png +0 -0
  38. package/docs/pen-blueprint.png +0 -0
  39. package/docs/pen-dark.png +0 -0
  40. package/docs/pen-ortho.png +0 -0
  41. package/docs/shapes/blade.png +0 -0
  42. package/docs/shapes/blob.png +0 -0
  43. package/docs/shapes/box.png +0 -0
  44. package/docs/shapes/capsule.png +0 -0
  45. package/docs/shapes/cylinder.png +0 -0
  46. package/docs/shapes/dna.png +0 -0
  47. package/docs/shapes/ellipsoid.png +0 -0
  48. package/docs/shapes/extrude.png +0 -0
  49. package/docs/shapes/helix.png +0 -0
  50. package/docs/shapes/lathe.png +0 -0
  51. package/docs/shapes/loop.png +0 -0
  52. package/docs/shapes/molecule.png +0 -0
  53. package/docs/shapes/orbit.png +0 -0
  54. package/docs/shapes/ring.png +0 -0
  55. package/docs/shapes/scatter.png +0 -0
  56. package/docs/shapes/shell.png +0 -0
  57. package/docs/shapes/sphere.png +0 -0
  58. package/docs/shapes/terrain.png +0 -0
  59. package/docs/shapes/torus.png +0 -0
  60. package/docs/shapes/tree.png +0 -0
  61. package/docs/shapes/tube.png +0 -0
@@ -0,0 +1,143 @@
1
+ // @ts-check
2
+ // Guided steps (the scene's `steps`): the figure explained in order, each step a title and words and a state of the
3
+ // figure: where the camera looks, how far apart, the cut, see-through, which labels, parts hidden, a part chosen, the
4
+ // motions' values and which play. Going to a step sets all of that, and what a step does not say goes back to the
5
+ // figure's start, so a step is the same picture however the reader came to it (the camera moves only when the step
6
+ // says where). The reader still turns, takes apart and cuts as they like; the next step sets its own state again.
7
+ // Owns goToStep_ and stepAt_; reads spec_, opts_, words_, state_, built_, motions_, controls_ and stage_, and calls
8
+ // view_, viewAngles_, frame_, explodeNow_, tweenExplode_, setMotion_, stopMotion_, playMotion_, syncHandleInputs_,
9
+ // showInfo_, markDirty_ and kick_.
10
+ import { clock } from '../clock.js';
11
+ import { startOf } from '../motion.js';
12
+ import { safeHTML } from './dom.js';
13
+ import LK3D from '../namespace.js';
14
+
15
+ /** @param {import('./context').Ctx} c @param {string} buttonClass */
16
+ export function makeSteps(c, buttonClass) {
17
+ const steps = (c.spec_.steps || []).filter((step) => step && typeof step === 'object');
18
+ c.stepAt_ = -1;
19
+ c.goToStep_ = () => {};
20
+ if (!steps.length) return;
21
+
22
+ // ---- the cut, swept in (or out) as the explode and the camera glide, rather than appearing at once
23
+ /** @type {((now: number) => boolean) | null} */
24
+ let cutTween = null;
25
+ /** @param {boolean | number} to @param {number} ms */
26
+ const sweepCut = (to, ms) => {
27
+ if (cutTween) c.animations_.delete(cutTween);
28
+ cutTween = null;
29
+ const amount = (/** @type {boolean | number} */ cut) => (cut === true ? 1 : Math.max(0, Math.min(1, +cut || 0))),
30
+ from = amount(c.state_.cut),
31
+ target = amount(to);
32
+ if (!(ms > 0) || LK3D.reduce || from === target) return void (c.state_.cut = to);
33
+ const start = clock.now();
34
+ const tween = (cutTween = (now) => {
35
+ const progress = Math.max(0, Math.min(1, (now - start) / ms)),
36
+ eased = progress < 0.5 ? 4 * progress * progress * progress : 1 - Math.pow(-2 * progress + 2, 3) / 2;
37
+ c.state_.cut = progress >= 1 ? to : from + (target - from) * eased;
38
+ c.markDirty_();
39
+ if (progress < 1) return true;
40
+ c.animations_.delete(tween);
41
+ cutTween = null;
42
+ if (c.controls_.style) c.controls_.style(); // (the Cut button pressed once the cut is in, not while it sweeps)
43
+ return false;
44
+ });
45
+ c.animations_.add(tween);
46
+ };
47
+
48
+ // ---- the panel under the stage: the step's words, and Back and Next (unless the page drives the steps itself)
49
+ const panel = (c.opts_.steps ?? c.opts_.controls) !== false ? document.createElement('div') : null,
50
+ words = document.createElement('div'),
51
+ /** @type {HTMLButtonElement[]} */
52
+ buttons = [];
53
+ if (panel) {
54
+ panel.className = 'lk3d-steps';
55
+ panel.setAttribute('role', 'group');
56
+ panel.setAttribute('aria-label', c.words_.steps);
57
+ words.className = 'lk3d-step';
58
+ words.setAttribute('aria-live', 'polite'); // (each step's words are said aloud as the reader comes to it)
59
+ const nav = document.createElement('span');
60
+ nav.className = 'lk3d-step-nav';
61
+ for (const [label, by] of /** @type {[string, number][]} */ ([
62
+ [c.words_.back, -1],
63
+ [c.words_.next, 1],
64
+ ])) {
65
+ const button = document.createElement('button');
66
+ button.type = 'button';
67
+ button.className = buttonClass;
68
+ button.textContent = label;
69
+ // (at the first or last step it says so and does nothing, rather than being disabled: a disabled button would
70
+ // drop the keyboard's focus to the page)
71
+ button.addEventListener('click', () => {
72
+ const to = c.stepAt_ + by;
73
+ if (to < 0 || to >= steps.length) return;
74
+ c.goToStep_(to);
75
+ if (c.opts_.onStep) c.opts_.onStep(to, steps[to]);
76
+ });
77
+ nav.append(button);
78
+ buttons.push(button);
79
+ }
80
+ panel.append(words, nav);
81
+ c.stage_.after(panel);
82
+ // (before the first step, opts.step -1: no words yet, Next goes to the first)
83
+ buttons[0].setAttribute('aria-disabled', 'true');
84
+ buttons[1].setAttribute('aria-disabled', 'false');
85
+ }
86
+
87
+ // ---- going to a step: by its place (from 0) or its id; options.ms 0 sets it at once (no glides)
88
+ c.goToStep_ = (which, options = {}) => {
89
+ const index = typeof which === 'string' ? steps.findIndex((step) => step.id === which) : Math.round(+which);
90
+ const step = steps[index];
91
+ if (!step) return;
92
+ c.stepAt_ = index;
93
+ const atOnce = options.ms === 0,
94
+ listed = (/** @type {unknown} */ list) => (Array.isArray(list) ? list : []),
95
+ hidden = listed(step.hide);
96
+ // what shows, and how
97
+ for (const part of c.built_.parts)
98
+ part.hidden = part.hiddenByScene || hidden.includes(part.id) || hidden.includes(part.group);
99
+ c.syncHandleInputs_();
100
+ c.state_.xray = !!step.xray;
101
+ c.state_.labels = step.labels ?? c.opts_.labels ?? 'auto';
102
+ c.state_.section = { normal: [0, 0, 1], offset: 0, ...c.spec_.section, ...step.section };
103
+ const part = step.select != null && c.part_(step.select);
104
+ c.state_.selected = part && !part.hidden ? part.id : null;
105
+ // the motions: each at the step's value, else its start; those the step plays, played from there
106
+ for (const motion of c.motions_) {
107
+ c.stopMotion_(motion);
108
+ c.setMotion_(motion, step.motion?.[motion.id] ?? startOf(motion));
109
+ }
110
+ for (const id of listed(step.play)) {
111
+ const motion = c.motions_.find((each) => each.id === id);
112
+ if (motion) c.playMotion_(motion);
113
+ }
114
+ // taken apart, cut and looked at: glided there together
115
+ const explode = Math.max(0, Math.min(1, +(step.explode ?? 0) || 0));
116
+ if (atOnce) c.explodeNow_(explode);
117
+ else c.tweenExplode_(explode);
118
+ sweepCut(c.spec_.section === false ? false : (step.cut ?? false), atOnce ? 0 : 900);
119
+ const focus = listed(step.focus);
120
+ if (step.view === 'home') c.view_('home', options);
121
+ else if (step.view != null || focus.length) {
122
+ const view = typeof step.view === 'object' && step.view && !Array.isArray(step.view) ? step.view : {},
123
+ [yaw, pitch] = typeof step.view === 'string' ? c.viewAngles_(step.view) : [view.yaw, view.pitch],
124
+ framed = c.built_.parts.filter((each) => focus.includes(each.id) || focus.includes(each.group));
125
+ const framing = framed.length && !view.target ? c.frame_(framed, explode) : null;
126
+ const target = view.target || framing?.target,
127
+ dist = view.dist ?? (view.zoom ? undefined : framing?.dist);
128
+ c.view_({ yaw, pitch, target, dist, zoom: view.zoom }, options);
129
+ }
130
+ if (c.controls_.style) c.controls_.style(); // (the buttons show which toggles are on)
131
+ c.showInfo_();
132
+ if (panel) {
133
+ const count = c.words_.stepOf.replace('{n}', String(index + 1)).replace('{count}', String(steps.length));
134
+ words.innerHTML =
135
+ `<span class="lk3d-step-count">${safeHTML(count)}</span> ` +
136
+ (step.title ? `<b>${safeHTML(step.title)}</b> ` : '') +
137
+ safeHTML(step.text);
138
+ buttons[0].setAttribute('aria-disabled', String(index === 0));
139
+ buttons[1].setAttribute('aria-disabled', String(index === steps.length - 1));
140
+ }
141
+ c.kick_();
142
+ };
143
+ }
package/src/flow.js CHANGED
@@ -1,6 +1,8 @@
1
1
  // Flow: streaks that run along paths (air through an engine, blood along a vessel, water round a bend), each a thin
2
2
  // ribbon that fades from its head to its tail and takes its colour from a ramp along the path (cool at the intake,
3
- // hot at the exhaust). Their geometry is made here on the CPU, every frame they move; a renderer only widens them on
3
+ // hot at the exhaust). On WebGL 2 the renderer places them on the GPU from what is here (each path as a table of its
4
+ // points, each streak's fixed numbers: gpuData), sending only the time travelled each frame; elsewhere (WebGL 1, the 2D
5
+ // fallback) their geometry is made here on the CPU, every frame they move (update), and a renderer only widens them on
4
6
  // screen and blends them. pathOf() is also what particles along a path use.
5
7
  import { sub, mulv, len, rgb } from './math.js';
6
8
 
@@ -32,6 +34,11 @@ export function pathOf(points, closed = false) {
32
34
  };
33
35
  return {
34
36
  total,
37
+ // each point and its distance along the path, [x, y, z, distance], the closing point too for a closed path
38
+ table: [
39
+ ...segments.map(([start, , , startDistance]) => [...start, startDistance]),
40
+ [...path[segments.length % path.length], total],
41
+ ],
35
42
  into,
36
43
  at(distance) {
37
44
  const point = [0, 0, 0];
@@ -115,7 +122,9 @@ export function makeFlow(options = {}) {
115
122
  drawnCount: 0,
116
123
  vertices: new Float32Array(count * STREAK_POINTS * 2 * STRIDE),
117
124
  // each streak: its path, where it starts, how fast it goes, and how it wanders round the path
125
+ paths,
118
126
  seeds: Array.from({ length: count }, (_, i) => ({
127
+ row: i % paths.length,
119
128
  path: paths[i % paths.length],
120
129
  start: random(i, 1),
121
130
  pace: 0.8 + 0.4 * random(i, 2),
@@ -127,8 +136,12 @@ export function makeFlow(options = {}) {
127
136
  step(dt) {
128
137
  flow.travelled += flow.speed * dt;
129
138
  },
139
+ // how many streaks show: count × amount
140
+ drawn() {
141
+ return (flow.drawnCount = Math.round(flow.count * Math.max(0, Math.min(1, flow.amount))));
142
+ },
130
143
  update(m) {
131
- const drawnCount = (flow.drawnCount = Math.round(flow.count * Math.max(0, Math.min(1, flow.amount)))),
144
+ const drawnCount = flow.drawn(),
132
145
  vertices = flow.vertices,
133
146
  points = new Float64Array(STREAK_POINTS * 3), // (one small array a frame: nothing a streak)
134
147
  point = new Float64Array(3);
@@ -188,3 +201,21 @@ export function flowIndices(streakCount) {
188
201
  }
189
202
  return indices;
190
203
  }
204
+
205
+ // What the GPU places a flow's streaks from (WebGL 2): its paths as a texture of 4 floats a texel, a row a path (the
206
+ // first texel its point count and length, then each point and its distance along), and each streak's fixed numbers,
207
+ // 12 floats a streak (the path's row, where it starts, its pace, its phase; its offset from the path and its turns; how
208
+ // it wanders). The shader in shaders.js (FLOW_VS, GPU) works out what update() does from them.
209
+ export function gpuData(flow) {
210
+ const width = 1 + Math.max(...flow.paths.map((path) => path.table.length)),
211
+ table = new Float32Array(width * flow.paths.length * 4),
212
+ seeds = new Float32Array(flow.count * 12);
213
+ flow.paths.forEach((path, row) => {
214
+ table.set([path.table.length, path.total, 0, 0], row * width * 4);
215
+ path.table.forEach((point, k) => table.set(point, (row * width + 1 + k) * 4));
216
+ });
217
+ flow.seeds.forEach((seed, i) =>
218
+ seeds.set([seed.row, seed.start, seed.pace, seed.phase, ...seed.offset, seed.turns, ...seed.wobble, 0], i * 12),
219
+ );
220
+ return { width, height: flow.paths.length, table, seeds };
221
+ }
package/src/index.js CHANGED
@@ -32,6 +32,7 @@ import { makeIdle } from './figure/idle.js';
32
32
  import { makeInput } from './figure/input.js';
33
33
  import { makeAdditions } from './figure/additions.js';
34
34
  import { makeApi } from './figure/api.js';
35
+ import { makeSteps } from './figure/steps.js';
35
36
  import { M, D2R } from './math.js';
36
37
  import { buildFitting } from './geometry.js';
37
38
  import { guard } from './guard.js';
@@ -40,6 +41,8 @@ import { controls } from './controls.js';
40
41
  import { clock, refreshFrom } from './clock.js';
41
42
  import LK3D, { FORMAT } from './namespace.js';
42
43
  import en from './locales/en.js';
44
+ import { defineElement } from './element.js';
45
+ import { serveAO } from './ao.js';
43
46
 
44
47
  let warned = false;
45
48
 
@@ -47,7 +50,7 @@ let warned = false;
47
50
  // and timers are made in): the WebGL context · where parts are (pose) · liquids and gases · the camera · the elements ·
48
51
  // the renderer (WebGL 2 or 1, else Canvas 2D) · the frame loop · the look · labels · picking and the idle work (trees,
49
52
  // crease shading, edges) · the pointer, keys and handles · what a page adds · the API · the built-in controls
50
- // (controls.js) · handles as range inputs · watching size, visibility and the screen's density.
53
+ // (controls.js) · handles as range inputs · guided steps · watching size, visibility and the screen's density.
51
54
  /**
52
55
  * @param {HTMLElement & { lk3d?: any }} el
53
56
  * @param {import('../scene').Scene} spec
@@ -71,7 +74,7 @@ function mount(el, spec, opts = {}) {
71
74
  const pageButtonClass = opts.buttonClass ?? defaults.buttonClass,
72
75
  buttonClass = 'lk3d-btn ' + (pageButtonClass || 'lk3d-plain');
73
76
  const mountedAt = performance.now(),
74
- stats = { setupMs: 0, firstFrameMs: null, treesMs: null, aoMs: null, refreshMs: null };
77
+ stats = { setupMs: 0, firstFrameMs: null, treesMs: null, aoMs: null, refreshMs: null, aoWorker: false };
75
78
  const state = {
76
79
  style: opts.style || spec.style || 'pen',
77
80
  theme: opts.theme || spec.theme || null,
@@ -160,11 +163,16 @@ function mount(el, spec, opts = {}) {
160
163
  explodable: built.parts.some((part) => part.explode.some((offset) => offset !== 0)),
161
164
  motions: c.motions_.filter((motion) => motion.name),
162
165
  cuttable: spec.section !== false && c.renderer_ && c.renderer_.kind !== '2d',
166
+ cutRange: c.cutRange_,
167
+ moveCut: spec.section && spec.section.fixed ? null : c.moveCut_,
163
168
  seeThrough: built.parts.some((part) => part.xray),
164
169
  }),
165
170
  );
166
171
  }
167
172
  makeHandleInputs();
173
+ // ---- guided steps (the scene's steps): their panel under the stage, and the first one (opts.step) set at once
174
+ makeSteps(c, buttonClass);
175
+ c.goToStep_(opts.step ?? 0, { ms: 0 });
168
176
  startWatching();
169
177
  c.showInfo_();
170
178
  stats.setupMs = performance.now() - mountedAt;
@@ -173,6 +181,9 @@ function mount(el, spec, opts = {}) {
173
181
 
174
182
  LK3D.mount = mount;
175
183
  if (typeof window !== 'undefined') window.LK3D = LK3D;
184
+ defineElement(mount); // <lk3d-figure>, for pages that write no script
185
+ // (this script run as the page's crease-shading worker, ao.js: it answers its jobs and draws nothing)
186
+ if (typeof self !== 'undefined' && /** @type {any} */ (self).lk3dAO) serveAO();
176
187
  export default LK3D;
177
188
  export const { build, reduce, version, locales, defaults, themes, format } = LK3D; // (the same objects: setting defaults here sets them for LK3D; reduce is read once, at load)
178
189
  export { mount, M, refreshFrom, clock, safeHTML };
package/src/locales/en.js CHANGED
@@ -18,6 +18,8 @@ export default {
18
18
  cut: 'Cut open',
19
19
  cutTitle: 'Cut the model in half to see inside',
20
20
  xray: 'See through',
21
+ cutAt: 'Cut at',
22
+ cutAtLabel: 'Move the cut through the model',
21
23
  xrayTitle: 'Make the casing transparent',
22
24
  labels: 'Labels',
23
25
  labelsTitle: 'Show all labels',
@@ -29,5 +31,9 @@ export default {
29
31
  side: 'Side',
30
32
  top: 'Top',
31
33
  home: 'Reset',
34
+ steps: 'Steps',
35
+ back: 'Back',
36
+ next: 'Next',
37
+ stepOf: 'Step {n} of {count}',
32
38
  decimal: '.',
33
39
  };
package/src/locales/vi.js CHANGED
@@ -17,6 +17,8 @@ export default {
17
17
  cut: 'Cắt dọc',
18
18
  cutTitle: 'Cắt đôi mô hình để xem bên trong',
19
19
  xray: 'Nhìn xuyên',
20
+ cutAt: 'Mặt cắt',
21
+ cutAtLabel: 'Dời mặt cắt qua mô hình',
20
22
  xrayTitle: 'Làm vỏ trong suốt',
21
23
  labels: 'Nhãn',
22
24
  labelsTitle: 'Hiện tất cả nhãn',
@@ -28,5 +30,9 @@ export default {
28
30
  side: 'Bên',
29
31
  top: 'Trên',
30
32
  home: 'Ban đầu',
33
+ steps: 'Các bước',
34
+ back: 'Bước trước',
35
+ next: 'Bước tiếp',
36
+ stepOf: 'Bước {n}/{count}',
31
37
  decimal: ',',
32
38
  };
@@ -3,7 +3,7 @@
3
3
  // ({kind, hifi, draw(frame), setAO(batch), dispose()}), so another backend (WebGPU) can be added beside it.
4
4
  import * as shaders from './shaders.js';
5
5
  import { M, sub, len, mulv, add, norm, dot } from './math.js';
6
- import { flowIndices, STRIDE, MAX_STREAKS } from './flow.js';
6
+ import { flowIndices, gpuData, STRIDE, MAX_STREAKS } from './flow.js';
7
7
  import * as changed from './changed.js';
8
8
 
9
9
  // (uViewD: in ortho, the distance every point is drawn as from; 0 in perspective, where nearer points are larger)
@@ -195,8 +195,8 @@ function glRenderer(gl, scene, options = {}) {
195
195
  (programs[name] = Object.assign(
196
196
  name === 'points'
197
197
  ? makeProgram(POINT_VS, POINT_FS)
198
- : name === 'flow'
199
- ? makeProgram(shaders.FLOW_VS, shaders.FLOW_FS)
198
+ : name === 'flow' || name === 'flowGPU'
199
+ ? makeProgram(shaders.FLOW_VS, shaders.FLOW_FS, name === 'flowGPU' ? ['GPU'] : [])
200
200
  : name === 'edge'
201
201
  ? makeProgram(shaders.EDGE_VS, shaders.EDGE_FS)
202
202
  : name === 'stream'
@@ -423,6 +423,38 @@ function glRenderer(gl, scene, options = {}) {
423
423
  return [texture, framebuffer];
424
424
  };
425
425
  const flowBuffers = new WeakMap(); // each flow's vertex buffer, made once at its full size and refilled in place
426
+ // flows placed on the GPU (WebGL 2): each flow's paths as a float texture and its streaks' fixed numbers as instance
427
+ // attributes, made once (flow.js gpuData), so a frame sends only the time travelled. A flow whose paths have more
428
+ // points than a texture is wide, or every flow once the program does not link, is placed on the CPU (flow.js update)
429
+ const flowsOnGPU = new WeakMap(),
430
+ maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
431
+ /** @type {{ corners: WebGLBuffer, indices: WebGLBuffer } | null} (a streak's 8 corners and 18 triangle corners) */
432
+ let streakTemplate = null;
433
+ const placesFlow = (flow) =>
434
+ gl2 &&
435
+ !(programs.flowGPU && programs.flowGPU.failed) &&
436
+ !!flow.seeds &&
437
+ (flow.tableWidth ??= 1 + Math.max(...flow.paths.map((path) => path.table.length))) <= maxTextureSize;
438
+ function gpuFlowOf(flow) {
439
+ let held = flowsOnGPU.get(flow);
440
+ if (!held) {
441
+ const data = gpuData(flow),
442
+ texture = gl.createTexture();
443
+ gl.activeTexture(gl.TEXTURE8);
444
+ gl.bindTexture(gl.TEXTURE_2D, texture);
445
+ for (const [name, value] of [
446
+ [gl.TEXTURE_MIN_FILTER, gl.NEAREST],
447
+ [gl.TEXTURE_MAG_FILTER, gl.NEAREST],
448
+ [gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE],
449
+ [gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE],
450
+ ])
451
+ gl.texParameteri(gl.TEXTURE_2D, name, value);
452
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, data.width, data.height, 0, gl.RGBA, gl.FLOAT, data.table);
453
+ gl.activeTexture(gl.TEXTURE0);
454
+ flowsOnGPU.set(flow, (held = { texture, seeds: makeBuffer(data.seeds) }));
455
+ }
456
+ return held;
457
+ }
426
458
 
427
459
  // a vertex array, described once: a shape's buffers (or its edges' segments) and its copies' placements, 16
428
460
  // numbers a copy (a batch's own), or 24 with the part's state (a group of parts alike: see groupsOf); bound with
@@ -828,6 +860,7 @@ function glRenderer(gl, scene, options = {}) {
828
860
  upload,
829
861
  instances,
830
862
  edges,
863
+ placesFlow,
831
864
  get pending() {
832
865
  return pending;
833
866
  },
@@ -852,7 +885,7 @@ function glRenderer(gl, scene, options = {}) {
852
885
  ...(shadowsOn ? [programs.depth] : []),
853
886
  ...(pointSets.length ? [optionalProgram('points')] : []),
854
887
  ...(ballSets.length ? [optionalProgram('balls')] : []),
855
- ...(flows.length ? [optionalProgram('flow')] : []),
888
+ ...flows.map((flow) => optionalProgram(placesFlow(flow) ? 'flowGPU' : 'flow')),
856
889
  ...(frame.edges ? [optionalProgram('edge')] : []),
857
890
  ...(frame.streams && frame.streams.length ? [optionalProgram('stream'), optionalProgram('copy')] : []),
858
891
  ];
@@ -1229,20 +1262,54 @@ function glRenderer(gl, scene, options = {}) {
1229
1262
  }
1230
1263
  // 6b. flow streaks: hidden by solid parts, not hiding anything themselves; ink over a light page (never added,
1231
1264
  // which would wash out into the paper), light added on a dark one
1232
- if (flows.length && can('flow')) {
1233
- const flowProgram = optionalProgram('flow'),
1234
- attributes = flowProgram.attributes;
1235
- common(flowProgram, frame);
1236
- gl.uniform2f(flowProgram.uniforms.uView, width / 2, height / 2);
1265
+ if (flows.length) {
1237
1266
  gl.enable(gl.BLEND);
1238
1267
  if (frame.look.dark) gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
1239
1268
  else gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
1240
1269
  gl.depthMask(false);
1241
1270
  gl.disable(gl.CULL_FACE);
1242
- if (!flowIndexBuffer) flowIndexBuffer = makeBuffer(flowIndices(MAX_STREAKS), gl.ELEMENT_ARRAY_BUFFER);
1243
- gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, flowIndexBuffer);
1244
- enableOnly([attributes.aPos, attributes.aDir, attributes.aA]);
1245
1271
  for (const flow of flows) {
1272
+ const onGPU = placesFlow(flow),
1273
+ name = onGPU ? 'flowGPU' : 'flow';
1274
+ if (!can(name)) continue;
1275
+ const flowProgram = programs[name],
1276
+ { attributes, uniforms } = flowProgram;
1277
+ common(flowProgram, frame);
1278
+ gl.uniform2f(uniforms.uView, width / 2, height / 2);
1279
+ flow.colors.forEach((color, i) => gl.uniform3fv(uniforms['uC' + i], color));
1280
+ gl.uniform1f(uniforms.uAlpha, flow.opacity);
1281
+ gl.uniform1f(uniforms.uWidth, (Math.max(1.25, flow.width) / 2 + 0.5) * frame.dpr);
1282
+ if (onGPU) {
1283
+ // one streak drawn as many times as there are: its corners, each copy with its streak's fixed numbers
1284
+ const held = gpuFlowOf(flow),
1285
+ seeds = [attributes.aSeedA, attributes.aSeedB, attributes.aSeedC];
1286
+ streakTemplate ??= {
1287
+ corners: makeBuffer(new Float32Array([0, -1, 0, 1, 1, -1, 1, 1, 2, -1, 2, 1, 3, -1, 3, 1])),
1288
+ indices: makeBuffer(flowIndices(1), gl.ELEMENT_ARRAY_BUFFER),
1289
+ };
1290
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, streakTemplate.indices);
1291
+ enableOnly([attributes.aCorner, ...seeds]);
1292
+ gl.bindBuffer(gl.ARRAY_BUFFER, streakTemplate.corners);
1293
+ gl.vertexAttribPointer(attributes.aCorner, 2, gl.FLOAT, false, 0, 0);
1294
+ instancing.setDivisor(attributes.aCorner, 0);
1295
+ gl.bindBuffer(gl.ARRAY_BUFFER, held.seeds);
1296
+ seeds.forEach((location, k) => {
1297
+ gl.vertexAttribPointer(location, k < 2 ? 4 : 3, gl.FLOAT, false, 48, 16 * k);
1298
+ instancing.setDivisor(location, 1);
1299
+ });
1300
+ gl.activeTexture(gl.TEXTURE8);
1301
+ gl.bindTexture(gl.TEXTURE_2D, held.texture);
1302
+ gl.activeTexture(gl.TEXTURE0);
1303
+ gl.uniform1i(uniforms.uPaths, 8);
1304
+ gl.uniformMatrix4fv(uniforms.uM, false, flow.owner ? flow.owner.matrix : IDENTITY);
1305
+ gl.uniform4f(uniforms.uFlow, flow.travelled, flow.length, flow.spread, flow.closed ? 1 : 0);
1306
+ instancing.drawElements(gl.TRIANGLES, 18, gl.UNSIGNED_SHORT, 0, flow.drawnCount);
1307
+ for (const location of seeds) instancing.setDivisor(location, 0);
1308
+ continue;
1309
+ }
1310
+ if (!flowIndexBuffer) flowIndexBuffer = makeBuffer(flowIndices(MAX_STREAKS), gl.ELEMENT_ARRAY_BUFFER);
1311
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, flowIndexBuffer);
1312
+ enableOnly([attributes.aPos, attributes.aDir, attributes.aA]);
1246
1313
  let flowBuffer = flowBuffers.get(flow);
1247
1314
  if (!flowBuffer)
1248
1315
  flowBuffers.set(flow, (flowBuffer = makeBuffer(flow.vertices, gl.ARRAY_BUFFER, gl.DYNAMIC_DRAW)));
@@ -1252,9 +1319,6 @@ function glRenderer(gl, scene, options = {}) {
1252
1319
  gl.vertexAttribPointer(attributes.aDir, 4, gl.FLOAT, false, STRIDE * 4, 16);
1253
1320
  gl.vertexAttribPointer(attributes.aA, 1, gl.FLOAT, false, STRIDE * 4, 32);
1254
1321
  for (const location of [attributes.aPos, attributes.aDir, attributes.aA]) instancing.setDivisor(location, 0);
1255
- flow.colors.forEach((color, i) => gl.uniform3fv(flowProgram.uniforms['uC' + i], color));
1256
- gl.uniform1f(flowProgram.uniforms.uAlpha, flow.opacity);
1257
- gl.uniform1f(flowProgram.uniforms.uWidth, (Math.max(1.25, flow.width) / 2 + 0.5) * frame.dpr);
1258
1322
  gl.drawElements(gl.TRIANGLES, flow.drawnCount * 18, gl.UNSIGNED_SHORT, 0);
1259
1323
  }
1260
1324
  gl.depthMask(true);
@@ -1455,6 +1519,12 @@ function glRenderer(gl, scene, options = {}) {
1455
1519
  // what a removed thing held on the GPU: a ball set's buffer, a stream's hull, a flow's streaks, or a batch of its
1456
1520
  // own (lines: never shared with another)
1457
1521
  release(thing) {
1522
+ const placed = flowsOnGPU.get(thing); // (a flow placed on the GPU: its paths' texture and its streaks' numbers)
1523
+ if (placed) {
1524
+ gl.deleteTexture(placed.texture);
1525
+ gl.deleteBuffer(placed.seeds);
1526
+ flowsOnGPU.delete(thing);
1527
+ }
1458
1528
  for (const cache of [ballBuffers, hullBuffers, flowBuffers]) {
1459
1529
  const held = cache.get(thing);
1460
1530
  if (held)
package/src/shaders.js CHANGED
@@ -329,10 +329,48 @@ void main() {
329
329
  // in pixels; alpha fades from head to tail and across the width, with a little dither against banding, and the
330
330
  // colour comes from a ramp of four stops along the path. Written premultiplied: over the picture on a light page,
331
331
  // added to it on a dark one (the blending decides).
332
- const FLOW_VS = `attribute vec4 aPos; attribute vec4 aDir; attribute float aA;
332
+ // With GPU (WebGL 2), each vertex places itself as flow.js update() would, from the flow's paths (a float texture: a
333
+ // row a path, its point count and length in the first texel, then each point and its distance along) and its streak's
334
+ // fixed numbers (instance attributes): the head where the time travelled puts it, a point a third of the streak's
335
+ // length behind the last, wandering round the path, through the part's matrix; nothing is sent each frame but the time.
336
+ const FLOW_VS = `
337
+ #ifdef GPU
338
+ attribute vec2 aCorner; attribute vec4 aSeedA; attribute vec4 aSeedB; attribute vec3 aSeedC;
339
+ uniform highp sampler2D uPaths; uniform mat4 uM; uniform vec4 uFlow; // travelled, length (a share of the path), spread, closed
340
+ // the point at distance d along path row r of n points: the last point at or before d, towards the next
341
+ vec3 at(int r, int n, float d) {
342
+ int lo = 1, hi = n;
343
+ for (int i = 0; i < 16; i++) {
344
+ if (lo >= hi) break;
345
+ int m = (lo + hi + 1) / 2;
346
+ if (texelFetch(uPaths, ivec2(m, r), 0).w <= d) lo = m; else hi = m - 1;
347
+ }
348
+ vec4 a = texelFetch(uPaths, ivec2(lo, r), 0), b = texelFetch(uPaths, ivec2(min(lo + 1, n), r), 0);
349
+ return mix(a.xyz, b.xyz, b.w > a.w ? clamp((d - a.w) / (b.w - a.w), 0.0, 1.0) : 0.0);
350
+ }
351
+ // point k of the streak (0 its head, 3 its tail): where it is, in the scene, and how far along the path (w)
352
+ vec4 point(float k) {
353
+ int r = int(aSeedA.x);
354
+ vec4 info = texelFetch(uPaths, ivec2(0, r), 0);
355
+ float L = info.y, d = mod(aSeedA.y * L + uFlow.x * aSeedA.z, max(L, 1e-9)) - uFlow.y * L * k / 3.0;
356
+ d = uFlow.w > 0.5 ? mod(d, max(L, 1e-9)) : max(d, 0.0);
357
+ float along = L > 0.0 ? d / L : 0.0;
358
+ vec3 p = at(r, int(info.x), d) + (aSeedB.xyz + aSeedC * sin(aSeedA.w + 6.2832 * aSeedB.w * along)) * uFlow.z;
359
+ return vec4((uM * vec4(p, 1.0)).xyz, along);
360
+ }
361
+ #else
362
+ attribute vec4 aPos; attribute vec4 aDir; attribute float aA;
363
+ #endif
333
364
  uniform mat4 uVP; uniform vec2 uView; uniform float uWidth; varying float vA; varying float vSide; varying float vT;
334
365
  varying vec3 vW;
335
366
  void main() {
367
+ #ifdef GPU
368
+ float k = aCorner.x;
369
+ vec4 here = point(k), behind = point(max(k - 1.0, 0.0)), ahead = point(min(k + 1.0, 3.0));
370
+ float ends = uFlow.w > 0.5 ? 1.0 : clamp(min(here.w, 1.0 - here.w) / 0.06, 0.0, 1.0);
371
+ vec4 aPos = vec4(here.xyz, aCorner.y), aDir = vec4(behind.xyz - ahead.xyz, here.w);
372
+ float aA = (1.0 - k / 3.0) * ends;
373
+ #endif
336
374
  vec4 a = uVP * vec4(aPos.xyz, 1.0), b = uVP * vec4(aPos.xyz + aDir.xyz, 1.0);
337
375
  vW = aPos.xyz;
338
376
  vec2 d = (b.xy / b.w - a.xy / a.w) * uView;
package/src/stylesheet.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // The figure's stylesheet, added to the page once. A page themes it with CSS variables (set on :root or any ancestor):
2
2
  // --lk3d-ink (lines, text, borders) · --lk3d-paper (label and button backgrounds) · --lk3d-muted (hints, credits)
3
- // --lk3d-accent (focus ring) · --lk3d-warn (the "not to scale" note) · --lk3d-highlight (pressed buttons)
3
+ // --lk3d-accent (focus ring) · --lk3d-warn (the "not to scale" note) · --lk3d-highlight (pressed buttons) and
4
+ // --lk3d-highlight-ink (their words: dark, for the light highlight; a page with a dark highlight sets it light)
4
5
  // --lk3d-font (labels in the drawn look) · --lk3d-line (leader lines and label borders under a theme)
5
6
  // A theme (LK3D.themes) sets these on the stage itself, so the words on a themed figure follow its theme.
6
7
  function css() {
@@ -8,7 +9,9 @@ function css() {
8
9
  const style = document.createElement('style');
9
10
  style.id = 'lk3d-css';
10
11
  style.textContent = `
12
+ lk3d-figure{display:block}
11
13
  .lk3d{position:relative; margin:24px 0 6px}
14
+ .lk3d-info{font-size:15.5px; line-height:1.45; min-height:1.45em; margin:8px 0 0}
12
15
  .lk3d-stage{position:relative; width:100%; overflow:hidden; border-radius:6px; touch-action:pan-y; user-select:none; -webkit-user-select:none}
13
16
  .lk3d-active .lk3d-stage{touch-action:none}
14
17
  .lk3d-sr{position:absolute; width:1px; height:1px; overflow:hidden; clip:rect(0 0 0 0); white-space:nowrap}
@@ -44,12 +47,17 @@ function css() {
44
47
  .lk3d-stage.lk3d-kbd{box-shadow:0 0 0 2px var(--lk3d-accent, #2f5fb3)}
45
48
  .lk3d-credit{font-size:13px; color:var(--lk3d-muted, #6b6670); margin:6px 0 0}
46
49
  .lk3d-bar{display:flex; flex-wrap:wrap; gap:8px 10px; align-items:center; margin-top:10px}
47
- .lk3d-bar .lk3d-btn.on{background:var(--lk3d-highlight, #f3d78f)}
50
+ .lk3d-bar .lk3d-btn.on{background:var(--lk3d-highlight, #f3d78f); color:var(--lk3d-highlight-ink, #1d1a1e)}
48
51
  .lk3d-plain{font:inherit; font-size:14px; line-height:1.3; padding:3px 10px; border:1.2px solid var(--lk3d-ink, #1d1a1e); border-radius:5px; background:var(--lk3d-paper, #f7f5ef); color:var(--lk3d-ink, #1d1a1e); cursor:pointer}
49
52
  .lk3d-plain:hover{filter:brightness(.96)} .lk3d-plain:focus-visible{outline:2px solid var(--lk3d-accent, #2f5fb3); outline-offset:1px}
50
53
  .lk3d-range{display:flex; gap:8px; align-items:center; font-size:15.5px}
51
54
  .lk3d-range input{width:120px; accent-color:var(--lk3d-ink, #1d1a1e)}
52
55
  .lk3d-views{display:inline-flex; gap:6px; flex-wrap:wrap}
56
+ .lk3d-steps{display:flex; flex-wrap:wrap; gap:8px 12px; align-items:flex-start; margin-top:10px; padding:2px 0 2px 12px; border-left:3px solid var(--lk3d-accent, #2f5fb3)}
57
+ .lk3d-step{flex:1 1 18em; min-width:0; font-size:15.5px; line-height:1.45}
58
+ .lk3d-step-count{color:var(--lk3d-muted, #6b6670); font-size:13px; white-space:nowrap}
59
+ .lk3d-step-nav{display:inline-flex; gap:6px} .lk3d-step-nav [aria-disabled=true]{opacity:.45; cursor:default}
60
+ @media print{.lk3d-bar, .lk3d-hint, .lk3d-step-nav{display:none}}
53
61
  @media (max-width:520px){.lk3d-tag{font-size:12px; line-height:17px; padding:0 5px} .lk3d-scale{font-size:11.5px; top:6px; bottom:auto; right:6px}}`;
54
62
  document.head.append(style);
55
63
  }
package/src/validate.js CHANGED
@@ -284,6 +284,7 @@ function links(scene, out) {
284
284
  if (joint && typeof joint === 'object' && !visit.has(joint.id) && loop(joint))
285
285
  out.push({ path: `joints[${i}]`, message: `${say(joint.id)} reads itself through other joints (a loop)` });
286
286
  });
287
+ steps(scene, out, names, parts);
287
288
  // motions: one id each; tracks that move parts that exist, with keys in order and within the range
288
289
  const seenMotions = new Set();
289
290
  (Array.isArray(scene.motions) ? scene.motions : []).forEach((motion, i) => {
@@ -315,6 +316,55 @@ function links(scene, out) {
315
316
  });
316
317
  }
317
318
 
319
+ // guided steps: one id each; what they name exists (parts and groups, motions within their range; a part labelled has
320
+ // a label); a cut only where
321
+ // the scene offers one; a part chosen or labelled that the same step does not hide; home, the figure's first view, not
322
+ // given parts to frame as well (it has its own target)
323
+ function steps(scene, out, names, parts) {
324
+ const motions = new Map(
325
+ (Array.isArray(scene.motions) ? scene.motions : [])
326
+ .filter((motion) => motion)
327
+ .map((motion) => [motion.id, motion]),
328
+ ),
329
+ seen = new Set(),
330
+ list = (value) => (Array.isArray(value) ? value : []);
331
+ (Array.isArray(scene.steps) ? scene.steps : []).forEach((step, i) => {
332
+ if (!step || typeof step !== 'object') return;
333
+ const bad = (field, message) => out.push({ path: `steps[${i}].${field}`, message });
334
+ if (step.id != null) {
335
+ if (seen.has(step.id)) bad('id', `${say(step.id)} is used by two steps`);
336
+ seen.add(step.id);
337
+ }
338
+ const hidden = list(step.hide),
339
+ hides = (name) => {
340
+ const part = parts.find((each) => each.id === name);
341
+ return hidden.includes(name) || (part && hidden.includes(part.group));
342
+ };
343
+ for (const field of ['focus', 'hide', 'labels'])
344
+ for (const name of list(step[field]))
345
+ if (!names.has(name)) bad(field, `names ${say(name)}, which is no part or group`);
346
+ else if (field !== 'hide' && hides(name)) bad(field, `names ${say(name)}, which this step hides`);
347
+ else if (field === 'labels' && parts.some((part) => part.id === name && (part.label === false || !part.name)))
348
+ bad(field, `names ${say(name)}, which has no label (no name, or label: false)`);
349
+ if (step.select != null && typeof step.select === 'string') {
350
+ if (!parts.some((part) => part.id === step.select)) bad('select', `${say(step.select)} is no part`);
351
+ else if (hides(step.select)) bad('select', `${say(step.select)} is hidden by this step`);
352
+ }
353
+ if (step.view === 'home' && list(step.focus).length)
354
+ bad('focus', 'frames parts, but the view is home (the first view, with its own target): give angles instead');
355
+ if (step.cut && scene.section === false) bad('cut', 'cuts, but the scene offers no cut (section: false)');
356
+ const valued = step.motion && typeof step.motion === 'object' ? step.motion : {};
357
+ for (const [id, value] of Object.entries(valued)) {
358
+ const motion = motions.get(id),
359
+ [start, end] = (motion && Array.isArray(motion.range) && motion.range) || [];
360
+ if (!motion) bad(`motion.${id}`, `${say(id)} is no motion`);
361
+ else if (!motion.loop && typeof value === 'number' && (value < start || value > end))
362
+ bad(`motion.${id}`, `${value} is outside its range [${start}, ${end}]`);
363
+ }
364
+ for (const id of list(step.play)) if (!motions.has(id)) bad('play', `${say(id)} is no motion`);
365
+ });
366
+ }
367
+
318
368
  export function validate(scene) {
319
369
  const out = values(scene); // (a scene that holds itself, or is nested past reason: said first, and only that)
320
370
  if (out.length) return out;
package/docs/flow.png DELETED
Binary file
Binary file
Binary file
package/docs/pen-dark.png DELETED
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file