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
package/scene.d.ts CHANGED
@@ -109,13 +109,19 @@ export interface Scene {
109
109
  ground?: boolean;
110
110
  /**
111
111
  * The cut: a plane, or false to offer none. What lies on the side its normal points to, beyond offset along
112
- * it, is cut away; a page may move it (set({ section }))
112
+ * it, is cut away; while the model is cut open the reader moves the plane along its normal (dragging the cut
113
+ * face, or the slider) unless it is fixed, and a page may move it (set({ section }))
113
114
  */
114
115
  section?:
115
116
  | false
116
117
  | {
117
118
  normal?: Vec3;
118
119
  offset?: number;
120
+ /**
121
+ * true: the reader cannot move the cut (by dragging its face or its slider); the page still can. By default,
122
+ * while the model is cut open, the reader moves the plane along its normal.
123
+ */
124
+ fixed?: boolean;
119
125
  };
120
126
  /**
121
127
  * Parts that move together as one value goes along a range: a piston's stroke as the crank turns, a sleeve
@@ -156,6 +162,12 @@ export interface Scene {
156
162
  extras?: { [key: string]: unknown };
157
163
  /** The parts of the model, each a list of shapes with a name and a note. */
158
164
  parts: Part[];
165
+ /**
166
+ * Guided steps: the figure explained in order, each with its words and a state of the figure (where the camera
167
+ * looks, taken apart, cut open, labels, a part chosen, motions). The figure starts at the first; the reader
168
+ * goes through them with Back and Next under it, the page with fig.step().
169
+ */
170
+ steps?: Step[];
159
171
  }
160
172
 
161
173
  /** The first look: pen (near-white, thin lines; the default), studio (realistic) or ink (drawn). */
@@ -479,6 +491,89 @@ export interface Part {
479
491
  extras?: { [key: string]: unknown };
480
492
  }
481
493
 
494
+ /**
495
+ * A step of the figure's explanation: its words, and the figure's state while it is shown. What a step does
496
+ * not say goes back to the figure's start (put together, not cut, see-through off, labels as usual, nothing
497
+ * hidden or chosen, the motions at their start), so a step is the same picture however the reader came to it;
498
+ * only the camera stays where the reader left it unless the step says where (view, focus).
499
+ */
500
+ export type Step = Form<StepFields, 'title'> | Form<StepFields, 'text'>;
501
+
502
+ /** the fields of Step, each optional (Step says which are required, together) */
503
+ export interface StepFields {
504
+ /**
505
+ * Unique among the steps: what the page names it by (fig.step(id)).
506
+ * @minLength 1
507
+ */
508
+ id?: string;
509
+ /**
510
+ * The step's heading, a few words.
511
+ * @minLength 1
512
+ */
513
+ title?: string;
514
+ /**
515
+ * What the reader is to look at, and why: a sentence or two, with simple formatting (b i em strong sub sup br)
516
+ * as in a part's note.
517
+ * @minLength 1
518
+ */
519
+ text?: string;
520
+ /**
521
+ * Where the camera goes: a named view (home: the figure's first), or yaw and pitch (degrees), zoom (2: twice
522
+ * as close as the whole model) or dist, and target. Without view or focus the camera stays where it is.
523
+ */
524
+ view?:
525
+ | 'front'
526
+ | 'side'
527
+ | 'top'
528
+ | 'iso'
529
+ | 'home'
530
+ | {
531
+ yaw?: number;
532
+ pitch?: number;
533
+ /** @exclusiveMinimum 0 */
534
+ zoom?: number;
535
+ /** @exclusiveMinimum 0 */
536
+ dist?: number;
537
+ target?: Vec3;
538
+ };
539
+ /**
540
+ * Parts or groups to frame: the camera looks at their middle (as they are once the step has taken them apart)
541
+ * from far enough to see them all, from the view's angles if it gives them.
542
+ */
543
+ focus?: string[];
544
+ /**
545
+ * How far apart (0, the default: put together; 1: all the way).
546
+ * @minimum 0
547
+ * @maximum 1
548
+ */
549
+ explode?: number;
550
+ /** Cut open (true), or how far the plane has swept in (0 to 1); swept in as the step comes. */
551
+ cut?: boolean | number;
552
+ /** The cut's plane for this step (the scene's section by default). */
553
+ section?: {
554
+ normal?: Vec3;
555
+ offset?: number;
556
+ };
557
+ /** Casings see-through. */
558
+ xray?: boolean;
559
+ /**
560
+ * Which labels show: auto (the part pointed at or chosen, and all of them once the model is well apart; the
561
+ * default), all, none, or a list of parts and groups.
562
+ */
563
+ labels?: 'auto' | 'all' | 'none' | string[];
564
+ /** Parts or groups out of sight in this step. */
565
+ hide?: string[];
566
+ /**
567
+ * A part chosen, as if the reader had picked it: lit, with its name and note in the info box.
568
+ * @minLength 1
569
+ */
570
+ select?: string;
571
+ /** Motions' values by id (the others at their start). */
572
+ motion?: { [key: string]: number };
573
+ /** Motions played as the step comes, from the value it gives them. */
574
+ play?: string[];
575
+ }
576
+
482
577
  /** Parts that move one way: moved, turned, or both (moved, then turned). */
483
578
  export type MotionTrack = Form<MotionTrackFields, 'move'> | Form<MotionTrackFields, 'turn'>;
484
579
 
@@ -152,7 +152,7 @@
152
152
  "description": "A shadow under the model (true by default)."
153
153
  },
154
154
  "section": {
155
- "description": "The cut: a plane, or false to offer none. What lies on the side its normal points to, beyond offset along it, is cut away; a page may move it (set({ section }))",
155
+ "description": "The cut: a plane, or false to offer none. What lies on the side its normal points to, beyond offset along it, is cut away; while the model is cut open the reader moves the plane along its normal (dragging the cut face, or the slider) unless it is fixed, and a page may move it (set({ section }))",
156
156
  "anyOf": [
157
157
  {
158
158
  "const": false
@@ -165,6 +165,10 @@
165
165
  },
166
166
  "offset": {
167
167
  "type": "number"
168
+ },
169
+ "fixed": {
170
+ "type": "boolean",
171
+ "description": "true: the reader cannot move the cut (by dragging its face or its slider); the page still can. By default, while the model is cut open, the reader moves the plane along its normal."
168
172
  }
169
173
  },
170
174
  "additionalProperties": false
@@ -265,6 +269,14 @@
265
269
  },
266
270
  "x-message": "a scene needs parts",
267
271
  "description": "The parts of the model, each a list of shapes with a name and a note."
272
+ },
273
+ "steps": {
274
+ "type": "array",
275
+ "minItems": 1,
276
+ "items": {
277
+ "$ref": "#/$defs/step"
278
+ },
279
+ "description": "Guided steps: the figure explained in order, each with its words and a state of the figure (where the camera looks, taken apart, cut open, labels, a part chosen, motions). The figure starts at the first; the reader goes through them with Back and Next under it, the page with fig.step()."
268
280
  }
269
281
  },
270
282
  "$defs": {
@@ -1960,6 +1972,158 @@
1960
1972
  }
1961
1973
  ],
1962
1974
  "x-message": "a joint turns its parts (turn) or slides them (slide)"
1975
+ },
1976
+ "step": {
1977
+ "type": "object",
1978
+ "description": "A step of the figure's explanation: its words, and the figure's state while it is shown. What a step does not say goes back to the figure's start (put together, not cut, see-through off, labels as usual, nothing hidden or chosen, the motions at their start), so a step is the same picture however the reader came to it; only the camera stays where the reader left it unless the step says where (view, focus).",
1979
+ "properties": {
1980
+ "id": {
1981
+ "type": "string",
1982
+ "minLength": 1,
1983
+ "description": "Unique among the steps: what the page names it by (fig.step(id))."
1984
+ },
1985
+ "title": {
1986
+ "type": "string",
1987
+ "minLength": 1,
1988
+ "description": "The step's heading, a few words."
1989
+ },
1990
+ "text": {
1991
+ "type": "string",
1992
+ "minLength": 1,
1993
+ "description": "What the reader is to look at, and why: a sentence or two, with simple formatting (b i em strong sub sup br) as in a part's note."
1994
+ },
1995
+ "view": {
1996
+ "description": "Where the camera goes: a named view (home: the figure's first), or yaw and pitch (degrees), zoom (2: twice as close as the whole model) or dist, and target. Without view or focus the camera stays where it is.",
1997
+ "anyOf": [
1998
+ {
1999
+ "enum": ["front", "side", "top", "iso", "home"]
2000
+ },
2001
+ {
2002
+ "type": "object",
2003
+ "properties": {
2004
+ "yaw": {
2005
+ "type": "number"
2006
+ },
2007
+ "pitch": {
2008
+ "type": "number"
2009
+ },
2010
+ "zoom": {
2011
+ "type": "number",
2012
+ "exclusiveMinimum": 0
2013
+ },
2014
+ "dist": {
2015
+ "type": "number",
2016
+ "exclusiveMinimum": 0
2017
+ },
2018
+ "target": {
2019
+ "$ref": "#/$defs/vec3"
2020
+ }
2021
+ },
2022
+ "additionalProperties": false
2023
+ }
2024
+ ]
2025
+ },
2026
+ "focus": {
2027
+ "type": "array",
2028
+ "items": {
2029
+ "type": "string",
2030
+ "minLength": 1
2031
+ },
2032
+ "minItems": 1,
2033
+ "description": "Parts or groups to frame: the camera looks at their middle (as they are once the step has taken them apart) from far enough to see them all, from the view's angles if it gives them."
2034
+ },
2035
+ "explode": {
2036
+ "type": "number",
2037
+ "minimum": 0,
2038
+ "maximum": 1,
2039
+ "description": "How far apart (0, the default: put together; 1: all the way)."
2040
+ },
2041
+ "cut": {
2042
+ "anyOf": [
2043
+ {
2044
+ "type": "boolean"
2045
+ },
2046
+ {
2047
+ "type": "number",
2048
+ "minimum": 0,
2049
+ "maximum": 1
2050
+ }
2051
+ ],
2052
+ "description": "Cut open (true), or how far the plane has swept in (0 to 1); swept in as the step comes."
2053
+ },
2054
+ "section": {
2055
+ "type": "object",
2056
+ "properties": {
2057
+ "normal": {
2058
+ "$ref": "#/$defs/vec3"
2059
+ },
2060
+ "offset": {
2061
+ "type": "number"
2062
+ }
2063
+ },
2064
+ "additionalProperties": false,
2065
+ "description": "The cut's plane for this step (the scene's section by default)."
2066
+ },
2067
+ "xray": {
2068
+ "type": "boolean",
2069
+ "description": "Casings see-through."
2070
+ },
2071
+ "labels": {
2072
+ "description": "Which labels show: auto (the part pointed at or chosen, and all of them once the model is well apart; the default), all, none, or a list of parts and groups.",
2073
+ "anyOf": [
2074
+ {
2075
+ "enum": ["auto", "all", "none"]
2076
+ },
2077
+ {
2078
+ "type": "array",
2079
+ "items": {
2080
+ "type": "string",
2081
+ "minLength": 1
2082
+ }
2083
+ }
2084
+ ]
2085
+ },
2086
+ "hide": {
2087
+ "type": "array",
2088
+ "items": {
2089
+ "type": "string",
2090
+ "minLength": 1
2091
+ },
2092
+ "minItems": 1,
2093
+ "description": "Parts or groups out of sight in this step."
2094
+ },
2095
+ "select": {
2096
+ "type": "string",
2097
+ "minLength": 1,
2098
+ "description": "A part chosen, as if the reader had picked it: lit, with its name and note in the info box."
2099
+ },
2100
+ "motion": {
2101
+ "type": "object",
2102
+ "additionalProperties": {
2103
+ "type": "number"
2104
+ },
2105
+ "description": "Motions' values by id (the others at their start)."
2106
+ },
2107
+ "play": {
2108
+ "type": "array",
2109
+ "items": {
2110
+ "type": "string",
2111
+ "minLength": 1
2112
+ },
2113
+ "minItems": 1,
2114
+ "description": "Motions played as the step comes, from the value it gives them."
2115
+ }
2116
+ },
2117
+ "anyOf": [
2118
+ {
2119
+ "required": ["title"]
2120
+ },
2121
+ {
2122
+ "required": ["text"]
2123
+ }
2124
+ ],
2125
+ "x-message": "a step needs its words: a title, text, or both",
2126
+ "additionalProperties": false
1963
2127
  }
1964
2128
  },
1965
2129
  "additionalProperties": false
@@ -97,7 +97,17 @@ every number in scene units with one scale for the whole object, and say what is
97
97
  - A `theme` (`light`, `dark`, `blueprint`, `sepia`) only if the page around it asks for one.
98
98
  - The object fills about 55–65% of the stage, with air around it.
99
99
 
100
- ## 6. Look like a critic, then hand over
100
+ ## 6. Steps, when the figure explains something in order
101
+
102
+ When the figure is to explain (how a machine works, what happens in turn), give it `steps`: three to six, each a
103
+ `title` of a few words and a sentence or two of `text` saying what to look at and why, with the state that shows it
104
+ (`view` or `focus`, `explode`, `cut`, `xray`, `labels`, `select`, `motion`, `play`). Start from the whole object and
105
+ end where the idea is. A step says everything it needs: what it leaves out goes back to the start (put together, not
106
+ cut, nothing hidden), so write each as if the reader came straight to it. Label only what the step's words name.
107
+ `check` catches steps that name what does not exist or hide what they label; `render` draws each step
108
+ (`name-look-step1.png`, …): look at each as the reader will, with its words beside it.
109
+
110
+ ## 7. Look like a critic, then hand over
101
111
 
102
112
  Render rest, apart and cut in at least two looks, and at a narrow width (`--width 390`). For each picture ask:
103
113
  does it read at a glance? Is every part where it should be, resting on something? Does anything pass through
package/src/ao.js ADDED
@@ -0,0 +1,58 @@
1
+ // @ts-check
2
+ // Crease shading (ambient occlusion: bvh.js aoJob) in a Web Worker, so the page's main thread stays free while it is
3
+ // worked out (seconds of rays on a slow phone). One worker for the page, made of lk3d's own script, nothing more to
4
+ // ship: the file a <script src> loaded (imported into the worker), or the text of an inline <script> (a built lesson's).
5
+ // Marked so (self.lk3dAO), the script answers jobs instead of drawing. Where no worker can be made (lk3d imported as a
6
+ // module, a page whose policy forbids one), shadeAway says so and the figure shades in idle slices on the page.
7
+ import { buildBVH, aoJob } from './bvh.js';
8
+
9
+ // (where this script came from: read while it first runs, the only time document.currentScript is this script)
10
+ const script =
11
+ typeof document !== 'undefined' ? /** @type {HTMLScriptElement | null} */ (document.currentScript) : null,
12
+ source = script ? (script.src ? `importScripts(${JSON.stringify(script.src)})` : script.textContent) : '';
13
+ /** @type {Worker | null} */
14
+ let worker = null,
15
+ failed = !source,
16
+ jobs = 0;
17
+ const waiting = new Map(); // a job's id → [resolve, reject]
18
+
19
+ // in the worker: each mesh sent shaded, its shading sent back
20
+ export function serveAO() {
21
+ self.onmessage = ({ data }) => {
22
+ const job = aoJob(data.mesh, buildBVH(data.mesh), data.reach);
23
+ job.step(Infinity);
24
+ self.postMessage({ id: data.id, out: job.out }, /** @type {any} */ ([job.out.buffer]));
25
+ };
26
+ }
27
+
28
+ // on the page: a mesh's shading, worked out in the worker (a promise of its Uint8Array), or null where there is none
29
+ /** @param {{ positions: Float32Array, normals: Float32Array, indices: any, count: number }} mesh @param {number} reach */
30
+ export function shadeAway(mesh, reach) {
31
+ if (failed) return null;
32
+ try {
33
+ if (!worker) {
34
+ worker = new Worker(URL.createObjectURL(new Blob(['self.lk3dAO=1;' + source], { type: 'text/javascript' })));
35
+ worker.onmessage = ({ data }) => {
36
+ const [resolve] = waiting.get(data.id) || [];
37
+ waiting.delete(data.id);
38
+ if (resolve) resolve(data.out);
39
+ };
40
+ // (a worker that cannot load or breaks: its jobs, and every one after, done on the page)
41
+ worker.onerror = (event) => {
42
+ event.preventDefault();
43
+ failed = true;
44
+ for (const [, [, reject]] of waiting) reject(new Error('lk3d: the crease-shading worker stopped'));
45
+ waiting.clear();
46
+ if (worker) worker.terminate();
47
+ worker = null;
48
+ };
49
+ }
50
+ const id = ++jobs,
51
+ { positions, normals, indices, count } = mesh;
52
+ worker.postMessage({ id, mesh: { positions, normals, indices, count }, reach });
53
+ return new Promise((resolve, reject) => waiting.set(id, [resolve, reject]));
54
+ } catch {
55
+ failed = true; // (no Worker, no Blob URLs, or a policy that forbids them)
56
+ return null;
57
+ }
58
+ }
package/src/controls.js CHANGED
@@ -1,5 +1,5 @@
1
- // The built-in controls under a figure: take apart (a slider and a button), cut open, see through, show all labels,
2
- // go round the looks, and the four views. They act through the figure's own API (fig.set, fig.view), so a page that
1
+ // The built-in controls under a figure: take apart (a slider and a button), cut open (and, while it is, where the cut
2
+ // is: a slider), see through, show all labels, go round the looks, and the four views. They act through the figure's own API (fig.set, fig.view), so a page that
3
3
  // passes `controls: false` and builds its own buttons gets exactly the same behaviour.
4
4
  export function controls({
5
5
  el,
@@ -12,6 +12,8 @@ export function controls({
12
12
  seeThrough,
13
13
  tweenExplode,
14
14
  motions,
15
+ cutRange,
16
+ moveCut,
15
17
  }) {
16
18
  const bar = document.createElement('div');
17
19
  bar.className = 'lk3d-bar';
@@ -87,6 +89,23 @@ export function controls({
87
89
  () => fig.set({ cut: !state.cut }),
88
90
  () => state.cut,
89
91
  );
92
+ // where the cut is, while it is on (unless the scene fixes it): a slider across the parts it cuts, from one end to
93
+ // the other (the same as dragging the cut face; the keys move it too)
94
+ if (cuttable && moveCut) {
95
+ const cutSlider = slider(words.cutAt, words.cutAtLabel, 0, 1, 0.005, 0),
96
+ row = /** @type {HTMLElement} */ (cutSlider.parentElement);
97
+ cutSlider.addEventListener('input', () => {
98
+ const [from, to] = cutRange();
99
+ moveCut(from + (to - from) * +cutSlider.value);
100
+ });
101
+ const sync = () => {
102
+ row.style.display = state.cut ? '' : 'none'; // (not the hidden attribute: the row's own display would win)
103
+ const [from, to] = cutRange();
104
+ cutSlider.value = String((state.section.offset - from) / (to - from || 1));
105
+ };
106
+ toggles.push(sync);
107
+ sync();
108
+ }
90
109
  if (seeThrough)
91
110
  toggle(
92
111
  words.xray,
package/src/element.js ADDED
@@ -0,0 +1,111 @@
1
+ // @ts-check
2
+ // <lk3d-figure>: a figure as an HTML element, for a page that writes no script of its own (Markdown, a content
3
+ // system, any framework). The scene comes from `src` (its address) or from a JSON script inside the element:
4
+ // <lk3d-figure src="generator.json" look="pen" locale="vi"></lk3d-figure>
5
+ // <lk3d-figure><script type="application/json">{ "parts": [ … ] }</script></lk3d-figure>
6
+ // Attributes: look, theme, labels (auto, all, none), step (a place from 0, or an id) change the figure as they change;
7
+ // src, locale, controls="false", steps="false", info="false" (no line for the part's name and note under it) and
8
+ // transparent mount it again. A script reaches the figure's API as `element.figure` (null until mounted; a new one
9
+ // each time it is mounted again) and `element.ready` (resolves with the first, once complete); the reader's moves come as events that bubble: lk3d-pick
10
+ // ({ id }), lk3d-handle ({ id, value }), lk3d-step ({ index, step }), lk3d-section ({ normal, offset }); a scene that
11
+ // cannot be read or drawn, as lk3d-error ({ message }), its words shown in the element.
12
+
13
+ /** @param {(el: HTMLElement, scene: any, opts?: any) => any} mount */
14
+ export function defineElement(mount) {
15
+ if (typeof customElements === 'undefined' || customElements.get('lk3d-figure')) return;
16
+ const LIVE = ['look', 'theme', 'labels', 'step'],
17
+ MOUNTED = ['src', 'locale', 'controls', 'steps', 'info', 'transparent'];
18
+ class Lk3dFigure extends HTMLElement {
19
+ // (a getter, not a static field: the bundle is built for ES2020, which would bring a helper for the field)
20
+ static get observedAttributes() {
21
+ return [...LIVE, ...MOUNTED];
22
+ }
23
+ constructor() {
24
+ super();
25
+ /** @type {any} the figure's API, once mounted */
26
+ this.figure = null;
27
+ /** @type {any} the scene, read once (a JSON script inside is gone once the figure is drawn in its place) */
28
+ this.scene = null;
29
+ this.loads = 0; // (each load counted: one that finishes after a newer one began is dropped)
30
+ /** @type {(figure: any) => void} */
31
+ let resolve = () => {};
32
+ /** @type {Promise<any>} */
33
+ this.ready = new Promise((done) => (resolve = done));
34
+ this.resolveReady = resolve;
35
+ }
36
+ connectedCallback() {
37
+ if (!this.figure) this.load();
38
+ }
39
+ disconnectedCallback() {
40
+ if (this.figure) this.figure.destroy();
41
+ this.figure = null;
42
+ }
43
+ /** @param {string} name @param {string | null} before @param {string | null} now */
44
+ attributeChangedCallback(name, before, now) {
45
+ if (!this.figure || before === now) return;
46
+ if (name === 'src') this.scene = null;
47
+ if (!LIVE.includes(name)) return void this.load();
48
+ if (name === 'step') this.figure.step(/^-?\d+$/.test(now || '') ? +(now || 0) : now);
49
+ else this.figure.set({ [name === 'look' ? 'style' : name]: now || (name === 'labels' ? 'auto' : null) });
50
+ }
51
+ /** @param {string} type @param {object} detail */
52
+ say(type, detail) {
53
+ this.dispatchEvent(new CustomEvent('lk3d-' + type, { detail, bubbles: true }));
54
+ }
55
+ async load() {
56
+ const load = ++this.loads,
57
+ attribute = (/** @type {string} */ name) => this.getAttribute(name),
58
+ off = (/** @type {string} */ name) => attribute(name) === 'false';
59
+ try {
60
+ if (!this.scene) {
61
+ const inside = this.querySelector('script[type="application/json"]'),
62
+ src = attribute('src');
63
+ if (src) {
64
+ // (a page opened from a file may not fetch others: said so, with what to do, not as "Failed to fetch")
65
+ const response = await fetch(src).catch((/** @type {Error} */ error) => {
66
+ throw new Error(
67
+ `lk3d: ${src} could not be fetched (${error.message})` +
68
+ (location.protocol === 'file:' ? ': a page opened from a file cannot fetch; serve it over http' : ''),
69
+ );
70
+ });
71
+ if (!response.ok) throw new Error(`lk3d: ${src}: ${response.status} ${response.statusText}`);
72
+ this.scene = await response.json();
73
+ } else if (inside) this.scene = JSON.parse(inside.textContent || '');
74
+ else throw new Error('lk3d: <lk3d-figure> needs a scene: src="scene.json", or a JSON script inside');
75
+ }
76
+ if (load !== this.loads || !this.isConnected) return;
77
+ if (this.figure) this.figure.destroy();
78
+ const info = off('info') ? null : document.createElement('p'),
79
+ step = attribute('step');
80
+ if (info) info.className = 'lk3d-info';
81
+ this.figure = mount(this, this.scene, {
82
+ style: attribute('look') || undefined,
83
+ theme: attribute('theme') || undefined,
84
+ labels: attribute('labels') || undefined,
85
+ locale: attribute('locale') || undefined,
86
+ controls: !off('controls'),
87
+ steps: attribute('steps') == null ? undefined : !off('steps'),
88
+ step: step == null ? undefined : /^-?\d+$/.test(step) ? +step : step,
89
+ transparent: this.hasAttribute('transparent') && !off('transparent'),
90
+ info,
91
+ onPick: (/** @type {any} */ part) => this.say('pick', { id: part ? part.id : null }),
92
+ onHandle: (/** @type {string} */ id, /** @type {number} */ value) => this.say('handle', { id, value }),
93
+ onStep: (/** @type {number} */ index, /** @type {any} */ stepShown) =>
94
+ this.say('step', { index, step: stepShown }),
95
+ onSection: (/** @type {any} */ section) => this.say('section', section),
96
+ });
97
+ // (the name and note of the part pointed at, under the figure and its steps' words)
98
+ if (info) (this.querySelector('.lk3d-steps') || this.querySelector('.lk3d-stage'))?.after(info);
99
+ const figure = this.figure;
100
+ figure.ready.then(() => this.figure === figure && this.resolveReady(figure));
101
+ } catch (error) {
102
+ const message = String(/** @type {Error} */ (error).message || error);
103
+ this.figure = null;
104
+ this.textContent = message;
105
+ console.error(message);
106
+ this.say('error', { message });
107
+ }
108
+ }
109
+ }
110
+ customElements.define('lk3d-figure', Lk3dFigure);
111
+ }
package/src/figure/api.js CHANGED
@@ -57,6 +57,10 @@ export function makeApi(c) {
57
57
  get timeScale() {
58
58
  return c.state_.timeScale;
59
59
  },
60
+ // the cut's plane now: where the scene, a step, the page or the reader put it
61
+ get section() {
62
+ return { normal: c.state_.section.normal.slice(), offset: c.state_.section.offset };
63
+ },
60
64
  _state: c.state_, // the engine's own state: not an API, it may change
61
65
  set(changes) {
62
66
  if ('explode' in changes) c.explodeNow_(changes.explode); // (the page's own value wins over a running tween)
@@ -252,12 +256,18 @@ export function makeApi(c) {
252
256
  }
253
257
  );
254
258
  },
259
+ // the scene's guided steps: go to one by its place (from 0) or id ({ ms: 0 }: at once), and which is shown (-1:
260
+ // none). The figure starts at the first (or mount's opts.step); moving through them does not call onStep
261
+ steps: c.spec_.steps || [],
262
+ step: (which, options) => c.goToStep_(which, options),
263
+ get currentStep() {
264
+ return c.stepAt_;
265
+ },
255
266
  // frame some parts (ids or groups): the camera looks at their middle, from far enough to see them all
256
267
  focus(ids, options = {}) {
257
268
  const parts = c.built_.parts.filter((part) => ids.includes(part.id) || ids.includes(part.group));
258
269
  if (!parts.length) return;
259
- const box = c.boxOf_(parts);
260
- c.view_({ ...options, target: box.center, dist: box.radius * 2.6 }, options);
270
+ c.view_({ ...options, ...c.frame_(parts) }, options);
261
271
  },
262
272
  get refreshMs() {
263
273
  return c.refreshMs_;