lk3d 0.1.0 → 0.2.1

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 (63) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +28 -7
  3. package/bin/lk3d.mjs +24 -13
  4. package/dist/lk3d-export.min.js +1 -1
  5. package/dist/lk3d.min.js +73 -35
  6. package/dist/lk3d.mjs +72 -34
  7. package/docs/api.md +132 -51
  8. package/docs/design.md +12 -7
  9. package/docs/handles-and-lines.md +27 -0
  10. package/docs/performance.md +42 -10
  11. package/docs/scene-format.md +31 -29
  12. package/index.d.ts +53 -2
  13. package/package.json +2 -3
  14. package/scene.d.ts +200 -1
  15. package/schema/scene.schema.json +329 -1
  16. package/skill/lk3d/SKILL.md +14 -1
  17. package/src/ao.js +58 -0
  18. package/src/controls.js +21 -2
  19. package/src/element.js +111 -0
  20. package/src/figure/api.js +18 -3
  21. package/src/figure/camera.js +57 -9
  22. package/src/figure/context.d.ts +37 -2
  23. package/src/figure/dimensions.js +140 -0
  24. package/src/figure/idle.js +57 -19
  25. package/src/figure/input.js +105 -7
  26. package/src/figure/labels.js +26 -8
  27. package/src/figure/loop.js +8 -2
  28. package/src/figure/pick.js +24 -8
  29. package/src/figure/steps.js +144 -0
  30. package/src/flow.js +33 -2
  31. package/src/index.js +16 -2
  32. package/src/locales/en.js +7 -0
  33. package/src/locales/vi.js +7 -0
  34. package/src/renderer-gl.js +88 -16
  35. package/src/shaders.js +63 -17
  36. package/src/stylesheet.js +14 -4
  37. package/src/validate.js +89 -0
  38. package/docs/flow.png +0 -0
  39. package/docs/generator.png +0 -0
  40. package/docs/pen-blueprint.png +0 -0
  41. package/docs/pen-dark.png +0 -0
  42. package/docs/pen-ortho.png +0 -0
  43. package/docs/shapes/blade.png +0 -0
  44. package/docs/shapes/blob.png +0 -0
  45. package/docs/shapes/box.png +0 -0
  46. package/docs/shapes/capsule.png +0 -0
  47. package/docs/shapes/cylinder.png +0 -0
  48. package/docs/shapes/dna.png +0 -0
  49. package/docs/shapes/ellipsoid.png +0 -0
  50. package/docs/shapes/extrude.png +0 -0
  51. package/docs/shapes/helix.png +0 -0
  52. package/docs/shapes/lathe.png +0 -0
  53. package/docs/shapes/loop.png +0 -0
  54. package/docs/shapes/molecule.png +0 -0
  55. package/docs/shapes/orbit.png +0 -0
  56. package/docs/shapes/ring.png +0 -0
  57. package/docs/shapes/scatter.png +0 -0
  58. package/docs/shapes/shell.png +0 -0
  59. package/docs/shapes/sphere.png +0 -0
  60. package/docs/shapes/terrain.png +0 -0
  61. package/docs/shapes/torus.png +0 -0
  62. package/docs/shapes/tree.png +0 -0
  63. package/docs/shapes/tube.png +0 -0
@@ -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
@@ -714,7 +746,8 @@ function glRenderer(gl, scene, options = {}) {
714
746
  changed.put(frame.cut && part.cut);
715
747
  changed.put(part.batches.reduce((sum, batch) => sum + (batch.version || 0), 0));
716
748
  }
717
- for (const value of [...frame.plane, frame.bounds.radius, frame.cut, loaded, ...extra]) changed.put(value);
749
+ for (const value of [...frame.plane, ...(frame.plane2 || []), frame.bounds.radius, frame.cut, loaded, ...extra])
750
+ changed.put(value);
718
751
  return changed.end();
719
752
  }
720
753
  // the glow: emission drawn at half resolution, blurred at a quarter, added onto the picture
@@ -806,6 +839,7 @@ function glRenderer(gl, scene, options = {}) {
806
839
  if (uniforms.uVP) gl.uniformMatrix4fv(uniforms.uVP, false, viewProjection || frame.viewProjection);
807
840
  if (uniforms.uEye) gl.uniform3fv(uniforms.uEye, frame.eye);
808
841
  if (uniforms.uPlane) gl.uniform4fv(uniforms.uPlane, frame.plane);
842
+ if (uniforms.uPlane2) gl.uniform4fv(uniforms.uPlane2, frame.plane2 || [0, 0, 0, 1]); // (none: always beyond it)
809
843
  if (uniforms.uCut) gl.uniform1f(uniforms.uCut, frame.cut ? 1 : 0);
810
844
  if (uniforms.uOutline) gl.uniform1f(uniforms.uOutline, 0);
811
845
  if (uniforms.uViewD) gl.uniform1f(uniforms.uViewD, frame.viewDistance || 0);
@@ -828,6 +862,7 @@ function glRenderer(gl, scene, options = {}) {
828
862
  upload,
829
863
  instances,
830
864
  edges,
865
+ placesFlow,
831
866
  get pending() {
832
867
  return pending;
833
868
  },
@@ -852,7 +887,7 @@ function glRenderer(gl, scene, options = {}) {
852
887
  ...(shadowsOn ? [programs.depth] : []),
853
888
  ...(pointSets.length ? [optionalProgram('points')] : []),
854
889
  ...(ballSets.length ? [optionalProgram('balls')] : []),
855
- ...(flows.length ? [optionalProgram('flow')] : []),
890
+ ...flows.map((flow) => optionalProgram(placesFlow(flow) ? 'flowGPU' : 'flow')),
856
891
  ...(frame.edges ? [optionalProgram('edge')] : []),
857
892
  ...(frame.streams && frame.streams.length ? [optionalProgram('stream'), optionalProgram('copy')] : []),
858
893
  ];
@@ -1229,20 +1264,54 @@ function glRenderer(gl, scene, options = {}) {
1229
1264
  }
1230
1265
  // 6b. flow streaks: hidden by solid parts, not hiding anything themselves; ink over a light page (never added,
1231
1266
  // 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);
1267
+ if (flows.length) {
1237
1268
  gl.enable(gl.BLEND);
1238
1269
  if (frame.look.dark) gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
1239
1270
  else gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
1240
1271
  gl.depthMask(false);
1241
1272
  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
1273
  for (const flow of flows) {
1274
+ const onGPU = placesFlow(flow),
1275
+ name = onGPU ? 'flowGPU' : 'flow';
1276
+ if (!can(name)) continue;
1277
+ const flowProgram = programs[name],
1278
+ { attributes, uniforms } = flowProgram;
1279
+ common(flowProgram, frame);
1280
+ gl.uniform2f(uniforms.uView, width / 2, height / 2);
1281
+ flow.colors.forEach((color, i) => gl.uniform3fv(uniforms['uC' + i], color));
1282
+ gl.uniform1f(uniforms.uAlpha, flow.opacity);
1283
+ gl.uniform1f(uniforms.uWidth, (Math.max(1.25, flow.width) / 2 + 0.5) * frame.dpr);
1284
+ if (onGPU) {
1285
+ // one streak drawn as many times as there are: its corners, each copy with its streak's fixed numbers
1286
+ const held = gpuFlowOf(flow),
1287
+ seeds = [attributes.aSeedA, attributes.aSeedB, attributes.aSeedC];
1288
+ streakTemplate ??= {
1289
+ corners: makeBuffer(new Float32Array([0, -1, 0, 1, 1, -1, 1, 1, 2, -1, 2, 1, 3, -1, 3, 1])),
1290
+ indices: makeBuffer(flowIndices(1), gl.ELEMENT_ARRAY_BUFFER),
1291
+ };
1292
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, streakTemplate.indices);
1293
+ enableOnly([attributes.aCorner, ...seeds]);
1294
+ gl.bindBuffer(gl.ARRAY_BUFFER, streakTemplate.corners);
1295
+ gl.vertexAttribPointer(attributes.aCorner, 2, gl.FLOAT, false, 0, 0);
1296
+ instancing.setDivisor(attributes.aCorner, 0);
1297
+ gl.bindBuffer(gl.ARRAY_BUFFER, held.seeds);
1298
+ seeds.forEach((location, k) => {
1299
+ gl.vertexAttribPointer(location, k < 2 ? 4 : 3, gl.FLOAT, false, 48, 16 * k);
1300
+ instancing.setDivisor(location, 1);
1301
+ });
1302
+ gl.activeTexture(gl.TEXTURE8);
1303
+ gl.bindTexture(gl.TEXTURE_2D, held.texture);
1304
+ gl.activeTexture(gl.TEXTURE0);
1305
+ gl.uniform1i(uniforms.uPaths, 8);
1306
+ gl.uniformMatrix4fv(uniforms.uM, false, flow.owner ? flow.owner.matrix : IDENTITY);
1307
+ gl.uniform4f(uniforms.uFlow, flow.travelled, flow.length, flow.spread, flow.closed ? 1 : 0);
1308
+ instancing.drawElements(gl.TRIANGLES, 18, gl.UNSIGNED_SHORT, 0, flow.drawnCount);
1309
+ for (const location of seeds) instancing.setDivisor(location, 0);
1310
+ continue;
1311
+ }
1312
+ if (!flowIndexBuffer) flowIndexBuffer = makeBuffer(flowIndices(MAX_STREAKS), gl.ELEMENT_ARRAY_BUFFER);
1313
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, flowIndexBuffer);
1314
+ enableOnly([attributes.aPos, attributes.aDir, attributes.aA]);
1246
1315
  let flowBuffer = flowBuffers.get(flow);
1247
1316
  if (!flowBuffer)
1248
1317
  flowBuffers.set(flow, (flowBuffer = makeBuffer(flow.vertices, gl.ARRAY_BUFFER, gl.DYNAMIC_DRAW)));
@@ -1252,9 +1321,6 @@ function glRenderer(gl, scene, options = {}) {
1252
1321
  gl.vertexAttribPointer(attributes.aDir, 4, gl.FLOAT, false, STRIDE * 4, 16);
1253
1322
  gl.vertexAttribPointer(attributes.aA, 1, gl.FLOAT, false, STRIDE * 4, 32);
1254
1323
  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
1324
  gl.drawElements(gl.TRIANGLES, flow.drawnCount * 18, gl.UNSIGNED_SHORT, 0);
1259
1325
  }
1260
1326
  gl.depthMask(true);
@@ -1455,6 +1521,12 @@ function glRenderer(gl, scene, options = {}) {
1455
1521
  // 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
1522
  // own (lines: never shared with another)
1457
1523
  release(thing) {
1524
+ const placed = flowsOnGPU.get(thing); // (a flow placed on the GPU: its paths' texture and its streaks' numbers)
1525
+ if (placed) {
1526
+ gl.deleteTexture(placed.texture);
1527
+ gl.deleteBuffer(placed.seeds);
1528
+ flowsOnGPU.delete(thing);
1529
+ }
1458
1530
  for (const cache of [ballBuffers, hullBuffers, flowBuffers]) {
1459
1531
  const held = cache.get(thing);
1460
1532
  if (held)
package/src/shaders.js CHANGED
@@ -64,7 +64,7 @@ void main() {
64
64
  // way back towards the wall: where two parts' sections overlap, the nearer wall's wins, steadily.
65
65
  const PART_FS = `
66
66
  uniform vec3 uColor; uniform float uAlpha; uniform float uFlat; uniform vec3 uMat; // (uColor: the outline's)
67
- uniform vec3 uLight; uniform vec3 uEye; uniform vec4 uPlane; uniform vec3 uCap;
67
+ uniform vec3 uLight; uniform vec3 uEye; uniform vec4 uPlane; uniform vec4 uPlane2; uniform vec3 uCap;
68
68
  // (a cap's hatching lies on the cut's plane, every uHatch units: uFwd and uOrtho give the ray from the eye)
69
69
  uniform vec3 uFwd; uniform float uOrtho; uniform float uHatch;
70
70
  uniform float uDpr; uniform float uAOk; uniform vec3 uPaper; uniform vec3 uSolid;
@@ -139,7 +139,7 @@ vec2 envBRDF(float NoV, float r) { // the split-sum environment term, as Karis
139
139
  #endif
140
140
  void main() {
141
141
  float cut = step(1.5, vIE.w), hi = step(0.5, vIE.w - 2.0 * cut);
142
- if (cut > 0.5 && dot(uPlane.xyz, vW) + uPlane.w > 0.0) discard;
142
+ if (cut > 0.5 && dot(uPlane.xyz, vW) + uPlane.w > 0.0 && dot(uPlane2.xyz, vW) + uPlane2.w > 0.0) discard; // (beyond both planes: one, when uPlane2 is (0, 0, 0, 1))
143
143
  #ifdef CUTS
144
144
  if (uTex.x > 0.5 && texture2D(uBase, vUV).a < uTex.w) discard; // a cut-out's clear texels
145
145
  #endif
@@ -151,10 +151,18 @@ void main() {
151
151
  // behind open space, a bore, is hidden by the nearer wall), hatched where the ray to it crosses the cut's plane,
152
152
  // in the plane's own coordinates: the hatching stays put on the section as the camera drifts
153
153
  vec3 rd = uOrtho > 0.5 ? uFwd : vW - uEye;
154
- float den = dot(uPlane.xyz, rd);
155
- vec3 P = abs(den) > 1e-6 ? vW - rd * ((dot(uPlane.xyz, vW) + uPlane.w) / den) : vW;
156
- vec3 ax = normalize(cross(uPlane.xyz, abs(uPlane.y) < 0.9 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0)));
157
- float hs = (dot(P, ax) + dot(P, cross(uPlane.xyz, ax))) / max(uHatch, 1e-4), h = step(0.55, fract(hs));
154
+ vec4 pl = uPlane;
155
+ float den = dot(pl.xyz, rd);
156
+ vec3 P = abs(den) > 1e-6 ? vW - rd * ((dot(pl.xyz, vW) + pl.w) / den) : vW;
157
+ // (a quarter cut: the face the ray left the cut-away wedge through; the second plane's where the first's crossing
158
+ // lies outside the wedge)
159
+ if (dot(uPlane2.xyz, P) + uPlane2.w < 0.0) {
160
+ pl = uPlane2;
161
+ den = dot(pl.xyz, rd);
162
+ P = abs(den) > 1e-6 ? vW - rd * ((dot(pl.xyz, vW) + pl.w) / den) : vW;
163
+ }
164
+ vec3 ax = normalize(cross(pl.xyz, abs(pl.y) < 0.9 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0)));
165
+ float hs = (dot(P, ax) + dot(P, cross(pl.xyz, ax))) / max(uHatch, 1e-4), h = step(0.55, fract(hs));
158
166
  #ifdef GL2
159
167
  h = mix(h, 0.45, smoothstep(0.15, 0.4, fwidth(hs))); // (lines too fine for the pixels: their even tone, no moiré)
160
168
  #endif
@@ -275,12 +283,12 @@ void main() {
275
283
  }`;
276
284
 
277
285
  // ---- depth only, for the shadow map (and a cut-out's clear texels casting none)
278
- const DEPTH_FS = `uniform vec4 uPlane; varying vec3 vW; varying vec4 vIE;
286
+ const DEPTH_FS = `uniform vec4 uPlane; uniform vec4 uPlane2; varying vec3 vW; varying vec4 vIE;
279
287
  #ifdef CUTS
280
288
  uniform sampler2D uBase; uniform vec4 uTex; varying vec2 vUV;
281
289
  #endif
282
290
  void main() {
283
- if (vIE.w > 1.5 && dot(uPlane.xyz, vW) + uPlane.w > 0.0) discard;
291
+ if (vIE.w > 1.5 && dot(uPlane.xyz, vW) + uPlane.w > 0.0 && dot(uPlane2.xyz, vW) + uPlane2.w > 0.0) discard;
284
292
  #ifdef CUTS
285
293
  if (uTex.x > 0.5 && texture2D(uBase, vUV).a < uTex.w) discard;
286
294
  #endif
@@ -288,8 +296,8 @@ void main() {
288
296
  }`;
289
297
 
290
298
  // ---- emission only, for the glow
291
- const GLOW_FS = `uniform vec4 uPlane; varying vec3 vW; varying vec4 vIE;
292
- void main() { if (vIE.w > 1.5 && dot(uPlane.xyz, vW) + uPlane.w > 0.0) discard; gl_FragColor = vec4(vIE.rgb, 1.0); }`;
299
+ const GLOW_FS = `uniform vec4 uPlane; uniform vec4 uPlane2; varying vec3 vW; varying vec4 vIE;
300
+ void main() { if (vIE.w > 1.5 && dot(uPlane.xyz, vW) + uPlane.w > 0.0 && dot(uPlane2.xyz, vW) + uPlane2.w > 0.0) discard; gl_FragColor = vec4(vIE.rgb, 1.0); }`;
293
301
 
294
302
  // ---- the ground: a disc under the model that only shows the shadow (and a soft contact shadow)
295
303
  const GROUND_VS = `attribute vec4 aPos; uniform mat4 uVP; uniform vec3 uCenter; uniform float uRadius; uniform float uY;
@@ -329,10 +337,48 @@ void main() {
329
337
  // in pixels; alpha fades from head to tail and across the width, with a little dither against banding, and the
330
338
  // colour comes from a ramp of four stops along the path. Written premultiplied: over the picture on a light page,
331
339
  // added to it on a dark one (the blending decides).
332
- const FLOW_VS = `attribute vec4 aPos; attribute vec4 aDir; attribute float aA;
340
+ // With GPU (WebGL 2), each vertex places itself as flow.js update() would, from the flow's paths (a float texture: a
341
+ // row a path, its point count and length in the first texel, then each point and its distance along) and its streak's
342
+ // fixed numbers (instance attributes): the head where the time travelled puts it, a point a third of the streak's
343
+ // length behind the last, wandering round the path, through the part's matrix; nothing is sent each frame but the time.
344
+ const FLOW_VS = `
345
+ #ifdef GPU
346
+ attribute vec2 aCorner; attribute vec4 aSeedA; attribute vec4 aSeedB; attribute vec3 aSeedC;
347
+ uniform highp sampler2D uPaths; uniform mat4 uM; uniform vec4 uFlow; // travelled, length (a share of the path), spread, closed
348
+ // the point at distance d along path row r of n points: the last point at or before d, towards the next
349
+ vec3 at(int r, int n, float d) {
350
+ int lo = 1, hi = n;
351
+ for (int i = 0; i < 16; i++) {
352
+ if (lo >= hi) break;
353
+ int m = (lo + hi + 1) / 2;
354
+ if (texelFetch(uPaths, ivec2(m, r), 0).w <= d) lo = m; else hi = m - 1;
355
+ }
356
+ vec4 a = texelFetch(uPaths, ivec2(lo, r), 0), b = texelFetch(uPaths, ivec2(min(lo + 1, n), r), 0);
357
+ return mix(a.xyz, b.xyz, b.w > a.w ? clamp((d - a.w) / (b.w - a.w), 0.0, 1.0) : 0.0);
358
+ }
359
+ // point k of the streak (0 its head, 3 its tail): where it is, in the scene, and how far along the path (w)
360
+ vec4 point(float k) {
361
+ int r = int(aSeedA.x);
362
+ vec4 info = texelFetch(uPaths, ivec2(0, r), 0);
363
+ float L = info.y, d = mod(aSeedA.y * L + uFlow.x * aSeedA.z, max(L, 1e-9)) - uFlow.y * L * k / 3.0;
364
+ d = uFlow.w > 0.5 ? mod(d, max(L, 1e-9)) : max(d, 0.0);
365
+ float along = L > 0.0 ? d / L : 0.0;
366
+ vec3 p = at(r, int(info.x), d) + (aSeedB.xyz + aSeedC * sin(aSeedA.w + 6.2832 * aSeedB.w * along)) * uFlow.z;
367
+ return vec4((uM * vec4(p, 1.0)).xyz, along);
368
+ }
369
+ #else
370
+ attribute vec4 aPos; attribute vec4 aDir; attribute float aA;
371
+ #endif
333
372
  uniform mat4 uVP; uniform vec2 uView; uniform float uWidth; varying float vA; varying float vSide; varying float vT;
334
373
  varying vec3 vW;
335
374
  void main() {
375
+ #ifdef GPU
376
+ float k = aCorner.x;
377
+ vec4 here = point(k), behind = point(max(k - 1.0, 0.0)), ahead = point(min(k + 1.0, 3.0));
378
+ float ends = uFlow.w > 0.5 ? 1.0 : clamp(min(here.w, 1.0 - here.w) / 0.06, 0.0, 1.0);
379
+ vec4 aPos = vec4(here.xyz, aCorner.y), aDir = vec4(behind.xyz - ahead.xyz, here.w);
380
+ float aA = (1.0 - k / 3.0) * ends;
381
+ #endif
336
382
  vec4 a = uVP * vec4(aPos.xyz, 1.0), b = uVP * vec4(aPos.xyz + aDir.xyz, 1.0);
337
383
  vW = aPos.xyz;
338
384
  vec2 d = (b.xy / b.w - a.xy / a.w) * uView;
@@ -341,9 +387,9 @@ void main() {
341
387
  gl_Position = a; vA = aA; vSide = aPos.w; vT = aDir.w;
342
388
  }`;
343
389
  const FLOW_FS = `uniform vec3 uC0; uniform vec3 uC1; uniform vec3 uC2; uniform vec3 uC3; uniform float uAlpha;
344
- uniform vec4 uPlane; uniform float uCut; varying float vA; varying float vSide; varying float vT; varying vec3 vW;
390
+ uniform vec4 uPlane; uniform vec4 uPlane2; uniform float uCut; varying float vA; varying float vSide; varying float vT; varying vec3 vW;
345
391
  void main() {
346
- if (uCut > 0.5 && dot(uPlane.xyz, vW) + uPlane.w > 0.0) discard; // cut away with the parts it flows through
392
+ if (uCut > 0.5 && dot(uPlane.xyz, vW) + uPlane.w > 0.0 && dot(uPlane2.xyz, vW) + uPlane2.w > 0.0) discard; // cut away with the parts it flows through
347
393
  float x = clamp(vT, 0.0, 1.0) * 3.0;
348
394
  vec3 c = x < 1.0 ? mix(uC0, uC1, x) : x < 2.0 ? mix(uC1, uC2, x - 1.0) : mix(uC2, uC3, x - 2.0);
349
395
  float a = uAlpha * vA * (1.0 - smoothstep(0.3, 1.0, abs(vSide)));
@@ -367,10 +413,10 @@ void main() {
367
413
  gl_Position = a; vSide = aPos.w; vW = w.xyz; vLit = dot(normalize(mat3(m) * aFace), uLight);
368
414
  vTint = aIC.a; vCut = aIE.w;
369
415
  }`;
370
- const EDGE_FS = `uniform vec3 uColor; uniform vec3 uLit; uniform float uAlpha; uniform vec4 uPlane;
416
+ const EDGE_FS = `uniform vec3 uColor; uniform vec3 uLit; uniform float uAlpha; uniform vec4 uPlane; uniform vec4 uPlane2;
371
417
  varying float vSide; varying vec3 vW; varying float vLit; varying float vTint; varying float vCut;
372
418
  void main() {
373
- if (vCut > 1.5 && dot(uPlane.xyz, vW) + uPlane.w > 0.0) discard;
419
+ if (vCut > 1.5 && dot(uPlane.xyz, vW) + uPlane.w > 0.0 && dot(uPlane2.xyz, vW) + uPlane2.w > 0.0) discard;
374
420
  // a lit part's edges light (an accent, a glowing one, the one chosen: as if catching the light); and an edge whose
375
421
  // faces turn to the light lighter, one turned away darker (a bevel catching the light)
376
422
  vec3 c = vTint > 0.5 ? uLit : uColor;
@@ -389,7 +435,7 @@ const STREAM_FS = `uniform vec4 uPts[16]; uniform vec3 uTab[24]; uniform int uN;
389
435
  uniform vec3 uC0; uniform vec3 uC1; uniform vec3 uC2; uniform vec3 uC3;
390
436
  uniform vec3 uEye; uniform vec3 uFwd; uniform float uOrtho; uniform mat4 uVP;
391
437
  uniform sampler2D uDepth; uniform float uHasDepth; uniform vec2 uView;
392
- uniform vec4 uF; uniform vec3 uG; uniform float uDen; uniform vec4 uPlane; uniform float uCut; uniform vec3 uLo; uniform vec3 uHi;
438
+ uniform vec4 uF; uniform vec3 uG; uniform float uDen; uniform vec4 uPlane; uniform vec4 uPlane2; uniform float uCut; uniform vec3 uLo; uniform vec3 uHi;
393
439
  varying vec3 vW; // uF: how far the air has travelled, the field's scale along the path, reach (how far a ray crosses),
394
440
  // turbulence; uG: swirl, the path's length, where it fades; uTab: inner and outer radius and travel time along the path
395
441
  float h3(vec3 p) { p = fract(p * 0.1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); }
@@ -437,7 +483,7 @@ void main() {
437
483
  vec4 acc = vec4(0.0);
438
484
  for (int i = 0; i < 48; i++) {
439
485
  vec3 p = vW - dir * st * (float(i) + j);
440
- if (uCut > 0.5 && dot(uPlane.xyz, p) + uPlane.w > 0.0) continue;
486
+ if (uCut > 0.5 && dot(uPlane.xyz, p) + uPlane.w > 0.0 && dot(uPlane2.xyz, p) + uPlane2.w > 0.0) continue;
441
487
  vec4 cp = uVP * vec4(p, 1.0);
442
488
  if (cp.z / cp.w * 0.5 + 0.5 > zs) continue;
443
489
  float a = min(1.0, dens(p, f) * st * 2.0 * uDen);
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}
@@ -19,13 +22,15 @@ function css() {
19
22
  .lk3d-lines{position:absolute; inset:0; width:100%; height:100%; pointer-events:none; overflow:visible}
20
23
  .lk3d-lines line{stroke:var(--lk3d-ink, #1d1a1e); stroke-width:1.1}
21
24
  .lk3d-lines circle{fill:var(--lk3d-ink, #1d1a1e)}
25
+ .lk3d-lines path.lk3d-dim{fill:none; stroke:var(--lk3d-ink, #1d1a1e); stroke-width:1}
26
+ .lk3d-dimtext{position:absolute; left:0; top:0; font:12.5px/1.25 system-ui, sans-serif; color:var(--lk3d-ink, #1d1a1e); background:var(--lk3d-paper, #f7f5ef); padding:0 3px; border-radius:3px; white-space:nowrap}
22
27
  .lk3d-tags{position:absolute; inset:0; pointer-events:none}
23
28
  .lk3d-tag{position:absolute; left:0; top:0; will-change:transform; white-space:nowrap; font-family:var(--lk3d-font, system-ui, sans-serif); font-size:14px; line-height:20px; padding:0 7px;
24
29
  background:var(--lk3d-paper, #f7f5ef); color:var(--lk3d-ink, #1d1a1e); border:1.2px solid var(--lk3d-ink, #1d1a1e); border-radius:4px 7px 5px 6px}
25
30
  .lk3d-tag.on{background:#f3d78f}
26
31
  .lk3d-stage[data-look="studio"] .lk3d-tag{background:rgba(14,18,24,.82); color:#eef2f7; border-color:rgba(255,255,255,.35); font-family:system-ui, sans-serif; font-size:12.5px; letter-spacing:.02em}
27
32
  .lk3d-stage[data-look="studio"] .lk3d-tag.on{background:rgba(232,150,60,.9); color:#111}
28
- .lk3d-stage[data-look="studio"] .lk3d-lines line{stroke:rgba(255,255,255,.55)} .lk3d-stage[data-look="studio"] .lk3d-lines circle{fill:#fff}
33
+ .lk3d-stage[data-look="studio"] .lk3d-lines line, .lk3d-stage[data-look="studio"] .lk3d-lines path.lk3d-dim{stroke:rgba(255,255,255,.7)} .lk3d-stage[data-look="studio"] .lk3d-dimtext{background:rgba(20,22,26,.75); color:#fff} .lk3d-stage[data-look="studio"] .lk3d-lines circle{fill:#fff}
29
34
  .lk3d-hint{position:absolute; left:10px; bottom:8px; font-size:13px; color:var(--lk3d-muted, #6b6670); background:rgba(247,245,239,.85); padding:1px 7px; border-radius:4px; pointer-events:none; transition:opacity .4s}
30
35
  .lk3d-stage[data-look="studio"] .lk3d-hint{color:#c9d1dc; background:rgba(10,12,16,.6)}
31
36
  .lk3d-hint.gone{opacity:0}
@@ -37,19 +42,24 @@ function css() {
37
42
  .lk3d-stage[data-look="studio"] .lk3d-scale{color:#eef2f7} .lk3d-stage[data-look="studio"] .lk3d-note{background:rgba(10,12,16,.7); color:#ffb38a}
38
43
  .lk3d-stage[data-theme] .lk3d-tag{background:var(--lk3d-paper); color:var(--lk3d-ink); border:1px solid var(--lk3d-line); font-family:system-ui, sans-serif; font-size:12.5px}
39
44
  .lk3d-stage[data-theme] .lk3d-tag.on{background:var(--lk3d-highlight); color:var(--lk3d-ink)}
40
- .lk3d-stage[data-theme] .lk3d-lines line{stroke:var(--lk3d-line); stroke-width:.8} .lk3d-stage[data-theme] .lk3d-lines circle{fill:var(--lk3d-line)}
45
+ .lk3d-stage[data-theme] .lk3d-lines line{stroke:var(--lk3d-line); stroke-width:.8} .lk3d-stage[data-theme] .lk3d-lines path.lk3d-dim{stroke:var(--lk3d-line)} .lk3d-stage[data-theme] .lk3d-dimtext{background:var(--lk3d-paper); color:var(--lk3d-ink)} .lk3d-stage[data-theme] .lk3d-lines circle{fill:var(--lk3d-line)}
41
46
  .lk3d-stage[data-theme] .lk3d-hint{color:var(--lk3d-muted); background:var(--lk3d-paper)} .lk3d-stage[data-theme] .lk3d-mark{color:var(--lk3d-muted)}
42
47
  .lk3d-stage[data-theme] .lk3d-scale{color:var(--lk3d-ink)} .lk3d-stage[data-theme] .lk3d-note{background:var(--lk3d-paper); color:var(--lk3d-warn)}
43
48
  .lk3d-sr{position:absolute; width:1px; height:1px; margin:-1px; padding:0; border:0; overflow:hidden; clip:rect(0 0 0 0); white-space:nowrap}
44
49
  .lk3d-stage.lk3d-kbd{box-shadow:0 0 0 2px var(--lk3d-accent, #2f5fb3)}
45
50
  .lk3d-credit{font-size:13px; color:var(--lk3d-muted, #6b6670); margin:6px 0 0}
46
51
  .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)}
52
+ .lk3d-bar .lk3d-btn.on{background:var(--lk3d-highlight, #f3d78f); color:var(--lk3d-highlight-ink, #1d1a1e)}
48
53
  .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
54
  .lk3d-plain:hover{filter:brightness(.96)} .lk3d-plain:focus-visible{outline:2px solid var(--lk3d-accent, #2f5fb3); outline-offset:1px}
50
55
  .lk3d-range{display:flex; gap:8px; align-items:center; font-size:15.5px}
51
56
  .lk3d-range input{width:120px; accent-color:var(--lk3d-ink, #1d1a1e)}
52
57
  .lk3d-views{display:inline-flex; gap:6px; flex-wrap:wrap}
58
+ .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)}
59
+ .lk3d-step{flex:1 1 18em; min-width:0; font-size:15.5px; line-height:1.45}
60
+ .lk3d-step-count{color:var(--lk3d-muted, #6b6670); font-size:13px; white-space:nowrap}
61
+ .lk3d-step-nav{display:inline-flex; gap:6px} .lk3d-step-nav [aria-disabled=true]{opacity:.45; cursor:default}
62
+ @media print{.lk3d-bar, .lk3d-hint, .lk3d-step-nav{display:none}}
53
63
  @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
64
  document.head.append(style);
55
65
  }
package/src/validate.js CHANGED
@@ -139,6 +139,8 @@ function links(scene, out) {
139
139
  const section = scene.section;
140
140
  if (section && typeof section === 'object' && zero(section.normal))
141
141
  out.push({ path: 'section.normal', message: NO_WAY });
142
+ if (section && typeof section === 'object' && section.second && zero(section.second.normal))
143
+ out.push({ path: 'section.second.normal', message: NO_WAY });
142
144
  const names = new Set(parts.flatMap((part) => [part.id, part.group].filter(Boolean))),
143
145
  seen = new Set(),
144
146
  models = scene.models || {};
@@ -284,6 +286,8 @@ function links(scene, out) {
284
286
  if (joint && typeof joint === 'object' && !visit.has(joint.id) && loop(joint))
285
287
  out.push({ path: `joints[${i}]`, message: `${say(joint.id)} reads itself through other joints (a loop)` });
286
288
  });
289
+ dimensions(scene, out, parts);
290
+ steps(scene, out, names, parts);
287
291
  // motions: one id each; tracks that move parts that exist, with keys in order and within the range
288
292
  const seenMotions = new Set();
289
293
  (Array.isArray(scene.motions) ? scene.motions : []).forEach((motion, i) => {
@@ -315,6 +319,91 @@ function links(scene, out) {
315
319
  });
316
320
  }
317
321
 
322
+ // dimensions: one id each; the parts their points ride on exist; a length between two places, an angle with arms
323
+ function dimensions(scene, out, parts) {
324
+ const seen = new Set(),
325
+ isPart = (id) => parts.some((part) => part.id === id);
326
+ (Array.isArray(scene.dimensions) ? scene.dimensions : []).forEach((dimension, i) => {
327
+ if (!dimension || typeof dimension !== 'object') return;
328
+ const bad = (field, message) => out.push({ path: `dimensions[${i}]${field}`, message });
329
+ if (dimension.id != null) {
330
+ if (seen.has(dimension.id)) bad('.id', `${say(dimension.id)} is used by two dimensions`);
331
+ seen.add(dimension.id);
332
+ }
333
+ const points = [
334
+ ['.from', dimension.from],
335
+ ['.to', dimension.to],
336
+ ...(Array.isArray(dimension.angle) ? dimension.angle.map((point, k) => [`.angle[${k}]`, point]) : []),
337
+ ];
338
+ for (const [field, point] of points)
339
+ if (point && typeof point === 'object' && !Array.isArray(point) && point.part != null && !isPart(point.part))
340
+ bad(`${field}.part`, `${say(point.part)} is no part`);
341
+ // (the same place twice, where neither rides on a part: nothing to measure)
342
+ const same = (a, b) => Array.isArray(a) && Array.isArray(b) && a.every((value, k) => value === b[k]);
343
+ if (same(dimension.from, dimension.to)) bad('.to', 'is where from is: a length needs two places');
344
+ if (
345
+ Array.isArray(dimension.angle) &&
346
+ (same(dimension.angle[0], dimension.angle[1]) || same(dimension.angle[2], dimension.angle[1]))
347
+ )
348
+ bad('.angle', 'has an arm of no length: its points are a point on each arm, and the vertex between them');
349
+ if (dimension.from && dimension.angle) bad('', 'is a length (from, to) or an angle, not both');
350
+ if (dimension.unit && !scene.unit)
351
+ bad('.unit', `converts to ${say(dimension.unit)}, but the scene has no unit to convert from`);
352
+ });
353
+ }
354
+
355
+ // guided steps: one id each; what they name exists (parts and groups, motions within their range; a part labelled has
356
+ // a label); a cut only where
357
+ // the scene offers one; a part chosen or labelled that the same step does not hide; home, the figure's first view, not
358
+ // given parts to frame as well (it has its own target)
359
+ function steps(scene, out, names, parts) {
360
+ const motions = new Map(
361
+ (Array.isArray(scene.motions) ? scene.motions : [])
362
+ .filter((motion) => motion)
363
+ .map((motion) => [motion.id, motion]),
364
+ ),
365
+ seen = new Set(),
366
+ list = (value) => (Array.isArray(value) ? value : []);
367
+ (Array.isArray(scene.steps) ? scene.steps : []).forEach((step, i) => {
368
+ if (!step || typeof step !== 'object') return;
369
+ const bad = (field, message) => out.push({ path: `steps[${i}].${field}`, message });
370
+ if (step.id != null) {
371
+ if (seen.has(step.id)) bad('id', `${say(step.id)} is used by two steps`);
372
+ seen.add(step.id);
373
+ }
374
+ const hidden = list(step.hide),
375
+ hides = (name) => {
376
+ const part = parts.find((each) => each.id === name);
377
+ return hidden.includes(name) || (part && hidden.includes(part.group));
378
+ };
379
+ for (const field of ['focus', 'hide', 'labels'])
380
+ for (const name of list(step[field]))
381
+ if (!names.has(name)) bad(field, `names ${say(name)}, which is no part or group`);
382
+ else if (field !== 'hide' && hides(name)) bad(field, `names ${say(name)}, which this step hides`);
383
+ else if (field === 'labels' && parts.some((part) => part.id === name && (part.label === false || !part.name)))
384
+ bad(field, `names ${say(name)}, which has no label (no name, or label: false)`);
385
+ if (step.select != null && typeof step.select === 'string') {
386
+ if (!parts.some((part) => part.id === step.select)) bad('select', `${say(step.select)} is no part`);
387
+ else if (hides(step.select)) bad('select', `${say(step.select)} is hidden by this step`);
388
+ }
389
+ if (step.view === 'home' && list(step.focus).length)
390
+ bad('focus', 'frames parts, but the view is home (the first view, with its own target): give angles instead');
391
+ if (step.cut && scene.section === false) bad('cut', 'cuts, but the scene offers no cut (section: false)');
392
+ const valued = step.motion && typeof step.motion === 'object' ? step.motion : {};
393
+ for (const [id, value] of Object.entries(valued)) {
394
+ const motion = motions.get(id),
395
+ [start, end] = (motion && Array.isArray(motion.range) && motion.range) || [];
396
+ if (!motion) bad(`motion.${id}`, `${say(id)} is no motion`);
397
+ else if (!motion.loop && typeof value === 'number' && (value < start || value > end))
398
+ bad(`motion.${id}`, `${value} is outside its range [${start}, ${end}]`);
399
+ }
400
+ for (const id of list(step.play)) if (!motions.has(id)) bad('play', `${say(id)} is no motion`);
401
+ const dimensionIds = new Set(list(scene.dimensions).map((dimension) => dimension && dimension.id));
402
+ for (const id of list(step.dimensions))
403
+ if (!dimensionIds.has(id)) bad('dimensions', `${say(id)} is no dimension (give it an id)`);
404
+ });
405
+ }
406
+
318
407
  export function validate(scene) {
319
408
  const out = values(scene); // (a scene that holds itself, or is nested past reason: said first, and only that)
320
409
  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
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file