@liqweed/motion-kit 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/runtime/iso.mjs CHANGED
@@ -204,8 +204,16 @@ export function path3(points) {
204
204
  * `z1`. `fill` is the token of the top face; `sides` (default: `fill`) the
205
205
  * token of the side faces, which a layer of `shade` at 10–26 % darkens or
206
206
  * lightens by the face's turn from the light (screen left is lit). `shade:
207
- * null` leaves them flat. `stroke` outlines every face.
208
- * @typedef {Readonly<{ points: { x: number, y: number }[], z0: number, z1: number, fill: string, sides: string, shade: string | null, stroke: string, strokeWidth: number, opacity: number, id?: string }>} Solid
207
+ * null` leaves them flat. `stroke` outlines every face. `groups` (one number
208
+ * per footprint edge, edge i running from point i to point i + 1) names the
209
+ * shading faces: consecutive visible edges with the same number are one face,
210
+ * outlined once. With `smooth` the footprint's edges are samples of a curve
211
+ * and its sides are one continuous wall: the visible sides are outlined once as
212
+ * a whole, with no line where two faces meet, and only the shade changes from
213
+ * group to group (`roundedBox` sets both; a `prism` without them draws one
214
+ * outlined face per edge, as a polygon should). `top` is 2D content drawn on
215
+ * the top face (`TopContent`).
216
+ * @typedef {Readonly<{ points: { x: number, y: number }[], z0: number, z1: number, fill: string, sides: string, shade: string | null, stroke: string, strokeWidth: number, opacity: number, id?: string, groups?: readonly number[], smooth?: boolean, top?: Readonly<TopContent> }>} Solid
209
217
  */
210
218
 
211
219
  /**
@@ -219,9 +227,9 @@ function token(name) {
219
227
 
220
228
  /**
221
229
  * Footprint points counter-clockwise, or a throw for a footprint that is not a
222
- * convex polygon.
230
+ * convex polygon. `flipped` says the input wound clockwise and was reversed.
223
231
  * @param {{ x: number, y: number }[]} points
224
- * @returns {{ x: number, y: number }[]}
232
+ * @returns {{ points: { x: number, y: number }[], flipped: boolean }}
225
233
  */
226
234
  function convexCcw(points) {
227
235
  if (!Array.isArray(points) || points.length < 3) throw new Error("a solid's footprint needs at least three points");
@@ -233,12 +241,15 @@ function convexCcw(points) {
233
241
  area += a.x * b.y - b.x * a.y;
234
242
  }
235
243
  if (Math.abs(area) < 1e-9) throw new Error("a solid's footprint has no area");
244
+ // Any two vertices at one place, neighbours or not: a footprint that winds
245
+ // round twice has every turn and half-plane right, and draws each face twice.
236
246
  for (let i = 0; i < points.length; i++) {
237
- const a = points[i];
238
- const b = points[(i + 1) % points.length];
239
- if (Math.hypot(b.x - a.x, b.y - a.y) < 1e-9) throw new Error("a solid's footprint has a repeated point");
247
+ for (let j = i + 1; j < points.length; j++) {
248
+ if (Math.hypot(points[j].x - points[i].x, points[j].y - points[i].y) < 1e-9) throw new Error("a solid's footprint has a repeated point");
249
+ }
240
250
  }
241
- const ccw = area > 0 ? points.map((p) => ({ x: p.x, y: p.y })) : points.map((p) => ({ x: p.x, y: p.y })).reverse();
251
+ const flipped = area < 0;
252
+ const ccw = flipped ? points.map((p) => ({ x: p.x, y: p.y })).reverse() : points.map((p) => ({ x: p.x, y: p.y }));
242
253
  for (let i = 0; i < ccw.length; i++) {
243
254
  const a = ccw[i];
244
255
  const b = ccw[(i + 1) % ccw.length];
@@ -252,19 +263,29 @@ function convexCcw(points) {
252
263
  const b = ccw[(i + 1) % ccw.length];
253
264
  for (const p of ccw) if ((b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x) < -1e-9) throw new Error("a solid's footprint must be convex");
254
265
  }
255
- return ccw;
266
+ return { points: ccw, flipped };
256
267
  }
257
268
 
258
269
  /**
259
- * A prism: `points` extruded by `h` from the base height `z`.
260
- * @param {{ points: { x: number, y: number }[], h: number, z?: number, fill?: string, sides?: string, shade?: string | null, stroke?: string, strokeWidth?: number, opacity?: number, id?: string }} o
270
+ * A prism: `points` extruded by `h` from the base height `z`. `groups`,
271
+ * `smooth` and `top` are described at `Solid`; `groups` follows the winding of
272
+ * `points`.
273
+ * @param {{ points: { x: number, y: number }[], h: number, z?: number, fill?: string, sides?: string, shade?: string | null, stroke?: string, strokeWidth?: number, opacity?: number, id?: string, groups?: number[], smooth?: boolean, top?: TopContent }} o
261
274
  * @returns {Solid}
262
275
  */
263
- export function prism({ points, h, z = 0, fill = "surface", sides, shade = "ink", stroke = "line", strokeWidth = 1.5, opacity = 1, id }) {
276
+ export function prism({ points, h, z = 0, fill = "surface", sides, shade = "ink", stroke = "line", strokeWidth = 1.5, opacity = 1, id, groups, smooth = false, top }) {
264
277
  if (!finite(h) || h < 0) throw new Error(`a solid's height must be a number from 0 up, got ${h}`);
265
278
  if (!finite(z)) throw new Error(`a solid's base height must be finite, got ${z}`);
279
+ const foot = convexCcw(points);
280
+ const n = foot.points.length;
281
+ if (groups !== undefined && (!Array.isArray(groups) || groups.length !== n || !groups.every(finite))) throw new Error("a solid's groups need one number per footprint edge");
282
+ // Reversing the points turns edge i into edge n − 2 − i.
283
+ const edgeGroups = groups && Object.freeze(foot.flipped ? groups.map((_, i) => groups[(2 * n - 2 - i) % n]) : [...groups]);
266
284
  return Object.freeze({
267
- points: convexCcw(points),
285
+ points: foot.points,
286
+ ...(edgeGroups ? { groups: edgeGroups } : {}),
287
+ ...(smooth ? { smooth: true } : {}),
288
+ ...(top ? { top: Object.freeze(checkTop(top)) } : {}),
268
289
  z0: z,
269
290
  z1: z + h,
270
291
  fill: token(fill),
@@ -277,7 +298,7 @@ export function prism({ points, h, z = 0, fill = "surface", sides, shade = "ink"
277
298
  });
278
299
  }
279
300
 
280
- /** @typedef {Omit<Parameters<typeof prism>[0], "points" | "h">} SolidStyle */
301
+ /** @typedef {Omit<Parameters<typeof prism>[0], "points" | "h" | "groups" | "smooth">} SolidStyle */
281
302
 
282
303
  /**
283
304
  * A box: `w` along x, `d` along y, `h` up, its footprint centred on (x, y).
@@ -300,6 +321,68 @@ export function slab({ h = 0.25, ...rest }) {
300
321
  return box({ h, ...rest });
301
322
  }
302
323
 
324
+ /**
325
+ * A box with rounded vertical corners: `w` along x, `d` along y, `h` up, its
326
+ * footprint centred on (x, y), each corner an arc of `radius` sampled in
327
+ * `segments` straight pieces (default 8). The sampled footprint is an ordinary
328
+ * convex prism, so `orderSolids` orders it like any solid, but it is `smooth`:
329
+ * its visible sides draw as one wall, outlined once, with no line per sample or
330
+ * where an arc meets a straight side, however many segments there are. The wall
331
+ * is shaded per arc and per straight side (its `groups`). A `radius` of 0 is a `box`; at most half of the shorter side.
332
+ * @param {{ x: number, y: number, w: number, d: number, h: number, radius: number, segments?: number } & SolidStyle} o
333
+ * @returns {Solid}
334
+ */
335
+ export function roundedBox({ x, y, w, d, h, radius, segments = 8, ...style }) {
336
+ if (!(finite(w) && w > 0 && finite(d) && d > 0)) throw new Error("a rounded box needs a positive width and depth");
337
+ if (!finite(radius) || radius < 0 || radius > Math.min(w, d) / 2 + EPS) throw new Error(`a rounded box's radius must be from 0 to half its shorter side, got ${radius}`);
338
+ if (!Number.isInteger(segments) || segments < 1) throw new Error(`a rounded box needs at least 1 segment per corner, got ${segments}`);
339
+ if (radius <= EPS) return box({ x, y, w, d, h, ...style });
340
+ const hw = w / 2;
341
+ const hd = d / 2;
342
+ // Counter-clockwise from the south-east corner. A vertex remembers the arcs it
343
+ // ends or starts; one that two arcs share (the radius took the whole side
344
+ // between them) is one vertex, so no zero-length edge is made.
345
+ const corners = [
346
+ { cx: x + hw - radius, cy: y - hd + radius, from: -90 },
347
+ { cx: x + hw - radius, cy: y + hd - radius, from: 0 },
348
+ { cx: x - hw + radius, cy: y + hd - radius, from: 90 },
349
+ { cx: x - hw + radius, cy: y - hd + radius, from: 180 },
350
+ ];
351
+ const same = (/** @type {{ x: number, y: number }} */ a, /** @type {{ x: number, y: number }} */ b) => Math.hypot(a.x - b.x, a.y - b.y) < EPS;
352
+ const verts = /** @type {{ x: number, y: number, arcs: number[] }[]} */ ([]);
353
+ for (const [k, c] of corners.entries()) {
354
+ for (let j = 0; j <= segments; j++) {
355
+ const [s, co] = sincos(c.from + (90 * j) / segments);
356
+ const p = { x: c.cx + radius * co, y: c.cy + radius * s };
357
+ const last = verts[verts.length - 1];
358
+ if (last && same(p, last)) last.arcs.push(k);
359
+ else verts.push({ ...p, arcs: [k] });
360
+ }
361
+ }
362
+ if (same(verts[0], verts[verts.length - 1])) {
363
+ const tail = /** @type {{ arcs: number[] }} */ (verts.pop());
364
+ verts[0].arcs.push(...tail.arcs);
365
+ }
366
+ const points = verts.map(({ x, y }) => ({ x, y }));
367
+ // An edge between two vertices of one arc belongs to that arc (arcs sharing an endpoint keep their own shading); any other is a straight side, its own group.
368
+ const groups = verts.map((v, i) => {
369
+ const w = verts[(i + 1) % verts.length];
370
+ const shared = v.arcs.find((k) => w.arcs.includes(k));
371
+ return shared === undefined ? 4 + i : shared;
372
+ });
373
+ return prism({ points, h, groups, smooth: true, ...style });
374
+ }
375
+
376
+ /**
377
+ * A rounded slab: a `roundedBox` that is thin (`h` default 0.25), for a floor
378
+ * or a platform with rounded corners.
379
+ * @param {{ x: number, y: number, w: number, d: number, h?: number, radius: number, segments?: number } & SolidStyle} o
380
+ * @returns {Solid}
381
+ */
382
+ export function roundedSlab({ h = 0.25, ...rest }) {
383
+ return roundedBox({ h, ...rest });
384
+ }
385
+
303
386
  /**
304
387
  * The corners of a regular polygon of `n` sides and circumradius `r` centred on
305
388
  * (x, y), the first at `rotation` degrees from east: a footprint for `prism`.
@@ -320,35 +403,83 @@ export function regularPolygon(x, y, r, n, rotation = 0) {
320
403
 
321
404
  const EPS = 1e-9;
322
405
 
406
+ /**
407
+ * @typedef {{ kind: "side" | "top", points: { x: number, y: number }[], shade: number, layers?: { points: { x: number, y: number }[], shade: number }[] }} Face
408
+ */
409
+
323
410
  /**
324
411
  * The faces of `solid` that face the camera, as screen polygons. Sides first,
325
- * then the top: they never overlap, since the solid is convex.
412
+ * then the top: they never overlap, since the solid is convex. Consecutive
413
+ * visible edges of one group (`Solid.groups`) are one side face; without
414
+ * groups each edge is its own. A `smooth` solid's visible sides are one face
415
+ * whose `layers` are the groups, to shade apart.
326
416
  * @param {Solid} solid
327
417
  * @param {Camera} cam
328
- * @returns {{ kind: "side" | "top", points: { x: number, y: number }[], shade: number }[]}
418
+ * @returns {Face[]}
329
419
  */
330
420
  function visibleFaces(solid, cam) {
331
421
  const to = projector(cam);
332
422
  const [sa, ca] = sincos(cam.azimuth);
333
423
  const [se, ce] = sincos(cam.elevation);
334
- const faces = /** @type {{ kind: "side" | "top", points: { x: number, y: number }[], shade: number }[]} */ ([]);
424
+ const faces = /** @type {Face[]} */ ([]);
335
425
  const pts = solid.points;
426
+ const n = pts.length;
336
427
  if (solid.z1 - solid.z0 > EPS) {
337
- for (let i = 0; i < pts.length; i++) {
338
- const a = pts[i];
339
- const b = pts[(i + 1) % pts.length];
428
+ // turn: −1 faces screen left (lit), 1 faces screen right; null for an edge turned away.
429
+ const turns = pts.map((a, i) => {
430
+ const b = pts[(i + 1) % n];
340
431
  const len = Math.hypot(b.x - a.x, b.y - a.y);
341
432
  const nx = (b.y - a.y) / len;
342
433
  const ny = -(b.x - a.x) / len;
343
434
  // Toward the camera, horizontally, is (sin az, −cos az).
344
- if ((nx * sa - ny * ca) * ce <= EPS) continue;
345
- const turn = nx * ca + ny * sa; // −1 faces screen left (lit), 1 faces screen right
346
- faces.push({
347
- kind: "side",
348
- points: [to({ ...a, z: solid.z0 }), to({ ...b, z: solid.z0 }), to({ ...b, z: solid.z1 }), to({ ...a, z: solid.z1 })],
435
+ return (nx * sa - ny * ca) * ce <= EPS ? null : nx * ca + ny * sa;
436
+ });
437
+ const groups = solid.groups ?? pts.map((_, i) => i);
438
+ const wall = (/** @type {number} */ i) => (solid.smooth ? 0 : groups[i]);
439
+ // Start the walk where a run can begin (a change of wall, or after a turned-away edge), so a run never straddles the start.
440
+ let start = 0;
441
+ for (let i = 0; i < n; i++) {
442
+ const prev = (i + n - 1) % n;
443
+ if (wall(i) !== wall(prev) || turns[prev] === null) {
444
+ start = i;
445
+ break;
446
+ }
447
+ }
448
+ /** The side polygon over a run of consecutive edges, and its shade. */
449
+ const side = (/** @type {number[]} */ edges) => {
450
+ const chain = [...edges.map((i) => pts[i]), pts[(edges[edges.length - 1] + 1) % n]];
451
+ const turn = edges.reduce((sum, i) => sum + /** @type {number} */ (turns[i]), 0) / edges.length;
452
+ return {
453
+ points: [...chain.map((p) => to({ ...p, z: solid.z0 })), ...chain.map((p) => to({ ...p, z: solid.z1 })).reverse()],
349
454
  shade: Math.round((0.1 + 0.16 * ((turn + 1) / 2)) * 100) / 100,
350
- });
455
+ };
456
+ };
457
+ /** @type {number[]} */
458
+ let run = [];
459
+ const flush = () => {
460
+ if (!run.length) return;
461
+ if (solid.smooth) {
462
+ /** @type {number[][]} */
463
+ const parts = [];
464
+ for (const i of run) {
465
+ const last = parts[parts.length - 1];
466
+ if (last && groups[last[0]] === groups[i]) last.push(i);
467
+ else parts.push([i]);
468
+ }
469
+ const layers = parts.map(side);
470
+ faces.push({ kind: "side", ...side(run), layers });
471
+ } else faces.push({ kind: "side", ...side(run) });
472
+ run = [];
473
+ };
474
+ for (let k = 0; k < n; k++) {
475
+ const i = (start + k) % n;
476
+ if (turns[i] === null) flush();
477
+ else if (run.length && wall(run[0]) !== wall(i)) {
478
+ flush();
479
+ run = [i];
480
+ } else run.push(i);
351
481
  }
482
+ flush();
352
483
  }
353
484
  if (se > EPS) faces.push({ kind: "top", points: pts.map((p) => to({ ...p, z: solid.z1 })), shade: 0 });
354
485
  return faces;
@@ -360,7 +491,8 @@ const pathD = (points) => `${points.map((p, i) => `${i === 0 ? "M" : "L"}${num(p
360
491
  /**
361
492
  * Markup of one solid under a camera: only the faces that face the camera,
362
493
  * each a path in its token, the sides with a shade layer. Nothing is drawn for
363
- * a solid with zero opacity.
494
+ * a solid with zero opacity. A solid's `top` content is drawn over its top face,
495
+ * so it is ordered with the solid like any of its faces.
364
496
  * @param {Solid} solid
365
497
  * @param {Camera} cam
366
498
  * @returns {string}
@@ -369,9 +501,14 @@ export function drawSolid(solid, cam) {
369
501
  const paths = visibleFaces(solid, cam).map((face) => {
370
502
  const d = pathD(face.points);
371
503
  const base = el("path", { d, fill: tok(face.kind === "top" ? solid.fill : solid.sides), stroke: tok(solid.stroke), "stroke-width": solid.strokeWidth, "stroke-linejoin": "round" });
372
- return face.kind === "side" && solid.shade ? base + el("path", { d, fill: tok(solid.shade), opacity: face.shade }) : base;
504
+ if (face.kind === "top" || !solid.shade) return base;
505
+ // A smooth wall is shaded by its layers, unstroked, so no line shows where they meet.
506
+ const layers = face.layers ?? [face];
507
+ return base + layers.map((l) => el("path", { d: pathD(l.points), fill: tok(/** @type {string} */ (solid.shade)), opacity: l.shade })).join("");
373
508
  });
374
- return fade(solid.opacity, solid.id ? { "data-solid": solid.id } : {}, ...paths);
509
+ const [se] = sincos(cam.elevation);
510
+ const top = solid.top && se > EPS ? drawOnPlane(cam, topPlane(solid), solid.top.markup, solid.top.opacity ?? 1) : "";
511
+ return fade(solid.opacity, solid.id ? { "data-solid": solid.id } : {}, ...paths, top);
375
512
  }
376
513
 
377
514
  /**
@@ -491,6 +628,162 @@ export function drawSolids(solids, cam) {
491
628
  .join("");
492
629
  }
493
630
 
631
+ /* ------------------------------------------------- content on a horizontal plane */
632
+
633
+ /**
634
+ * 2D content for the top face of a solid. `markup` is ordinary SVG drawn in
635
+ * its own `view` (`{ width, height }`: the content's own units, origin at its
636
+ * top left, y down, so an icon on a 24 × 24 grid has the view 24 × 24); the view
637
+ * is fitted into the footprint's bounding box, centred, its aspect kept, less
638
+ * `inset` world units on every side. Stroke widths and font sizes are in the
639
+ * content's own units too. Colours are tokens, as anywhere.
640
+ * @typedef {{ markup: string, view: { width: number, height: number }, inset?: number, opacity?: number }} TopContent
641
+ */
642
+
643
+ /**
644
+ * A horizontal plane to draw 2D content on: a rectangle of `w` (east) by `d`
645
+ * (north) world units centred on (`x`, `y`) at height `z`, and the `view` the
646
+ * content is drawn in. The view is fitted into the rectangle, centred, its
647
+ * aspect kept.
648
+ * @typedef {{ x: number, y: number, z?: number, w: number, d: number, view: { width: number, height: number } }} Plane
649
+ */
650
+
651
+ /**
652
+ * @param {TopContent} top
653
+ * @returns {TopContent}
654
+ */
655
+ function checkTop(top) {
656
+ if (typeof top.markup !== "string") throw new Error("a solid's top content needs markup, a string of SVG");
657
+ if (!top.view || !(finite(top.view.width) && top.view.width > 0 && finite(top.view.height) && top.view.height > 0)) throw new Error("a solid's top content needs a view { width, height } above 0");
658
+ if (top.inset !== undefined && (!finite(top.inset) || top.inset < 0)) throw new Error(`a solid's top content inset must be 0 or more, got ${top.inset}`);
659
+ return { markup: top.markup, view: { width: top.view.width, height: top.view.height }, inset: top.inset ?? 0, opacity: top.opacity ?? 1 };
660
+ }
661
+
662
+ /**
663
+ * The plane of a solid's top face: its footprint's bounding box, less the inset.
664
+ * @param {Solid} solid
665
+ * @returns {Plane}
666
+ */
667
+ function topPlane(solid) {
668
+ const top = /** @type {Required<TopContent>} */ (solid.top);
669
+ const xs = solid.points.map((p) => p.x);
670
+ const ys = solid.points.map((p) => p.y);
671
+ const w = Math.max(...xs) - Math.min(...xs) - 2 * top.inset;
672
+ const d = Math.max(...ys) - Math.min(...ys) - 2 * top.inset;
673
+ if (!(w > 0 && d > 0)) throw new Error("a solid's top content inset leaves no room");
674
+ return { x: (Math.max(...xs) + Math.min(...xs)) / 2, y: (Math.max(...ys) + Math.min(...ys)) / 2, z: solid.z1, w, d, view: top.view };
675
+ }
676
+
677
+ /**
678
+ * The affine transform `[a, b, c, d, e, f]` (SVG `matrix`) that takes a plane's
679
+ * own coordinates to the screen under `cam`: (0, 0) is the view's top left
680
+ * (the plane's north-west corner), x runs east, y runs south. It is linear in
681
+ * the camera, so it follows a `lerpCamera` swivel. Content on a plane at 90°
682
+ * elevation is the same picture, scaled and panned; seen edge on (0°
683
+ * elevation) the plane has no area and the matrix is singular.
684
+ * @param {Camera} cam
685
+ * @param {Plane} plane
686
+ * @returns {[number, number, number, number, number, number]}
687
+ */
688
+ export function planeMatrix(cam, { x, y, z = 0, w, d, view }) {
689
+ if (!(finite(x) && finite(y) && finite(z))) throw new Error("a plane needs a finite position");
690
+ if (!(finite(w) && w > 0 && finite(d) && d > 0)) throw new Error("a plane needs a positive width and depth");
691
+ if (!view || !(finite(view.width) && view.width > 0 && finite(view.height) && view.height > 0)) throw new Error("a plane needs a view { width, height } above 0");
692
+ const k = Math.min(w / view.width, d / view.height); // world units per view unit
693
+ const x0 = x - (view.width * k) / 2;
694
+ const y0 = y + (view.height * k) / 2;
695
+ const to = projector(cam);
696
+ const o = to({ x: x0, y: y0, z });
697
+ const ex = to({ x: x0 + k, y: y0, z });
698
+ const ey = to({ x: x0, y: y0 - k, z });
699
+ return [ex.x - o.x, ex.y - o.y, ey.x - o.x, ey.y - o.y, o.x, o.y];
700
+ }
701
+
702
+ /**
703
+ * 2D `markup` drawn on a horizontal plane: the markup wrapped in the plane's
704
+ * transform (`planeMatrix`), so it follows the camera. Draw it right after the
705
+ * solid it sits on (or give the solid a `top`, which does so inside the solid's
706
+ * depth order); nothing is drawn when the plane is edge on or `opacity` is 0.
707
+ * @param {Camera} cam
708
+ * @param {Plane} plane
709
+ * @param {string} markup
710
+ * @param {number} [opacity]
711
+ * @returns {string}
712
+ */
713
+ export function drawOnPlane(cam, plane, markup, opacity = 1) {
714
+ const m = planeMatrix(cam, plane);
715
+ // Edge on: the two axes are parallel on the screen, whatever the scale of the view.
716
+ if (Math.abs(m[0] * m[3] - m[1] * m[2]) <= 1e-9 * Math.hypot(m[0], m[1]) * Math.hypot(m[2], m[3])) return "";
717
+ // What is serialised must not be singular either: a view so large that the scale rounds to 0 draws a point, so nothing.
718
+ const r = m.map((v) => Number(num(v, 4)));
719
+ if (r[0] * r[3] - r[1] * r[2] === 0) return "";
720
+ return fade(opacity, { transform: `matrix(${r.map((v) => num(v, 4)).join(" ")})` }, markup);
721
+ }
722
+
723
+ /* ------------------------------------------------------------ grid backdrop */
724
+
725
+ /**
726
+ * A backdrop of diamonds: grid lines every `step` world units along x and y in
727
+ * the floor plane at height `z`, out to `radius` from (`x`, `y`) (a segment of
728
+ * one `step` is kept when its middle is inside, so the edge is ragged: an end
729
+ * can lie up to half a step beyond `radius`), fading out
730
+ * radially, so it follows the camera (diamonds in isometric, squares in plan).
731
+ * The fade is `bands` steps of opacity, one `<path>` each, so the markup stays
732
+ * small and needs no gradient or id; the lines are `stroke` (a token) at up to
733
+ * `opacity`. Static: nothing moves while a step rests. Draw it first, under the
734
+ * solids; it has no depth and is never above one.
735
+ * @param {Camera} cam
736
+ * @param {{ radius: number, step?: number, x?: number, y?: number, z?: number, stroke?: string, strokeWidth?: number, opacity?: number, bands?: number }} o
737
+ * @returns {string}
738
+ */
739
+ export function drawGrid(cam, { radius, step = 1, x = 0, y = 0, z = 0, stroke = "line", strokeWidth = 1, opacity = 0.5, bands = 6 }) {
740
+ if (!(finite(radius) && radius > 0)) throw new Error(`a grid's radius must be above 0, got ${radius}`);
741
+ if (!(finite(step) && step > 0)) throw new Error(`a grid's step must be above 0, got ${step}`);
742
+ if (!(Number.isInteger(bands) && bands >= 1 && bands <= 64)) throw new Error(`a grid needs from 1 to 64 bands, got ${bands}`);
743
+ if (!(finite(x) && finite(y) && finite(z))) throw new Error("a grid needs a finite centre");
744
+ const colour = tok(token(stroke));
745
+ const to = projector(cam);
746
+ const cells = Math.ceil(radius / step);
747
+ if (cells > 200) throw new Error(`a grid of ${2 * cells} lines each way is too many: raise the step or lower the radius`);
748
+ // The band of the segment centred (cx, cy): from the edge in to the centre, or -1 outside.
749
+ const band = (/** @type {number} */ cx, /** @type {number} */ cy) => {
750
+ const f = 1 - Math.hypot(cx, cy) / radius;
751
+ return f <= 0 ? -1 : Math.min(bands - 1, Math.floor(f * bands));
752
+ };
753
+ const d = /** @type {string[]} */ (Array.from({ length: bands }, () => ""));
754
+ /** Add the segments of one line, joining neighbours of one band into one stroke. */
755
+ const line = (/** @type {number} */ fixed, /** @type {boolean} */ alongX) => {
756
+ /** @type {{ b: number, from: number, to: number } | null} */
757
+ let run = null;
758
+ const emit = () => {
759
+ if (!run) return;
760
+ const a = alongX ? to({ x: x + run.from, y: y + fixed, z }) : to({ x: x + fixed, y: y + run.from, z });
761
+ const b = alongX ? to({ x: x + run.to, y: y + fixed, z }) : to({ x: x + fixed, y: y + run.to, z });
762
+ d[run.b] += `M${num(a.x)} ${num(a.y)}L${num(b.x)} ${num(b.y)}`;
763
+ run = null;
764
+ };
765
+ for (let j = -cells; j < cells; j++) {
766
+ const from = j * step;
767
+ const b = alongX ? band(from + step / 2, fixed) : band(fixed, from + step / 2);
768
+ if (b < 0) emit();
769
+ else if (run && run.b === b) run.to = from + step;
770
+ else {
771
+ emit();
772
+ run = { b, from, to: from + step };
773
+ }
774
+ }
775
+ emit();
776
+ };
777
+ for (let i = -cells; i <= cells; i++) {
778
+ line(i * step, true);
779
+ line(i * step, false);
780
+ }
781
+ // The faintest ring first, so the brighter ones are over it where they meet.
782
+ return d
783
+ .map((path, b) => (path ? el("path", { d: path, fill: "none", stroke: colour, "stroke-width": strokeWidth, opacity: opacity * ((b + 1) / bands) }) : ""))
784
+ .join("");
785
+ }
786
+
494
787
  /* ----------------------------------------------------------- label anchors */
495
788
 
496
789
  /**
@@ -499,6 +792,23 @@ export function drawSolids(solids, cam) {
499
792
  * @typedef {{ id: string, x: number, y: number, width: number, height: number, stem?: { x1: number, y1: number, x2: number, y2: number }, opacity?: number }} LabelBox
500
793
  */
501
794
 
795
+ /** The line height of a label, as a multiple of its font size. */
796
+ const LINE_HEIGHT = 1.25;
797
+
798
+ /**
799
+ * The size of a label box: the longest line plus `padX` on each side, wide, and
800
+ * the lines at `LINE_HEIGHT` plus 5 px above and below.
801
+ * @param {string} id
802
+ * @param {string[]} lines
803
+ * @param {number} fontSize
804
+ * @param {number} padX
805
+ * @returns {{ width: number, height: number }}
806
+ */
807
+ function labelSize(id, lines, fontSize, padX) {
808
+ if (!lines.length) throw new Error(`label "${id}" has no text`);
809
+ return { width: Math.max(...lines.map((l) => estimateWidth(l, fontSize * 1.08))) + 2 * padX, height: lines.length * LINE_HEIGHT * fontSize + 2 * 5 };
810
+ }
811
+
502
812
  /**
503
813
  * A label on a point of the world, with a stem: a dot on the point, a vertical
504
814
  * stem `lift` pixels up, and the label's box at its top, placed in the
@@ -511,27 +821,53 @@ export function drawSolids(solids, cam) {
511
821
  * @returns {{ markup: string, box: LabelBox }}
512
822
  */
513
823
  export function labelAnchor(cam, { id, at, lines, fontSize = 14, lift = 40, side = "up", opacity = 1 }) {
514
- if (!lines.length) throw new Error(`label "${id}" has no text`);
515
824
  const p = project(cam, at);
516
- const padX = 8;
517
- const padY = 5;
518
- const lineHeight = 1.25;
519
- const width = Math.max(...lines.map((l) => estimateWidth(l, fontSize * 1.08))) + 2 * padX;
520
- const height = lines.length * lineHeight * fontSize + 2 * padY;
825
+ const { width, height } = labelSize(id, lines, fontSize, 8);
521
826
  const tipX = p.x;
522
827
  const tipY = p.y - lift;
523
828
  const x = side === "up" ? tipX - width / 2 : side === "right" ? tipX : tipX - width;
524
829
  const y = side === "up" ? tipY - height : tipY - height / 2;
525
830
  const stem = { x1: p.x, y1: p.y, x2: tipX, y2: tipY };
831
+ const r = drawn2;
832
+ const labelBox = { id, x: r(x), y: r(y), width: r(width), height: r(height), stem: { x1: r(stem.x1), y1: r(stem.y1), x2: r(stem.x2), y2: r(stem.y2) }, opacity };
526
833
  const markup = fade(
527
834
  opacity,
528
835
  { "data-label": id },
529
836
  el("line", { x1: stem.x1, y1: stem.y1, x2: stem.x2, y2: stem.y2, stroke: tok("line"), "stroke-width": 1.5 }),
530
837
  el("circle", { cx: p.x, cy: p.y, r: 3.5, fill: tok("ink"), stroke: tok("bg"), "stroke-width": 1.5 }),
531
838
  el("rect", { x, y, width, height, rx: 6, fill: tok("surface"), stroke: tok("line"), "stroke-width": 1.5 }),
532
- text({ x: x + width / 2, y: y + height / 2, "text-anchor": "middle", "dominant-baseline": "central", "font-size": fontSize, "font-weight": 600, fill: tok("ink") }, lines, lineHeight),
839
+ text({ x: x + width / 2, y: y + height / 2, "text-anchor": "middle", "dominant-baseline": "central", "font-size": fontSize, "font-weight": 600, fill: tok("ink") }, lines, LINE_HEIGHT),
533
840
  );
534
- return { markup, box: { id, x, y, width, height, stem, opacity } };
841
+ return { markup, box: labelBox };
842
+ }
843
+
844
+ /** A coordinate as the SVG attributes draw it: rounded to two decimals, which is what the gate checks. */
845
+ const drawn2 = (/** @type {number} */ n) => Number(num(n));
846
+
847
+ /**
848
+ * A pill: a stemless tag, a rounded box of text centred on the screen point
849
+ * (`x`, `y`), for the tags and badges that stand on their own. Its `box` goes
850
+ * to the scene's `labelBoxes` with the other labels, so the gate checks that
851
+ * it overlaps none and stays in the picture. To pin it to a point of the world,
852
+ * pass the projected point (`project(cam, at)`) with an offset. `fill`,
853
+ * `stroke` and `ink` are tokens (`ink` the text's: pick one that reads on
854
+ * `fill`, e.g. `onAccent` on `accent`). `lines` are already wrapped and
855
+ * localized, ≥ 14 px.
856
+ * @param {{ id: string, x: number, y: number, lines: string[], fontSize?: number, fill?: string, stroke?: string, ink?: string, opacity?: number }} o
857
+ * @returns {{ markup: string, box: LabelBox }}
858
+ */
859
+ export function labelPill({ id, x, y, lines, fontSize = 14, fill = "surface", stroke = "line", ink = "ink", opacity = 1 }) {
860
+ if (!(finite(x) && finite(y))) throw new Error(`pill "${id}" needs a finite position`);
861
+ const { width, height } = labelSize(id, lines, fontSize, 12);
862
+ const left = x - width / 2;
863
+ const top = y - height / 2;
864
+ const markup = fade(
865
+ opacity,
866
+ { "data-label": id },
867
+ el("rect", { x: left, y: top, width, height, rx: height / 2, fill: tok(token(fill)), stroke: tok(token(stroke)), "stroke-width": 1.5 }),
868
+ text({ x, y, "text-anchor": "middle", "dominant-baseline": "central", "font-size": fontSize, "font-weight": 600, fill: tok(token(ink)) }, lines, LINE_HEIGHT),
869
+ );
870
+ return { markup, box: { id, x: drawn2(left), y: drawn2(top), width: drawn2(width), height: drawn2(height), opacity } };
535
871
  }
536
872
 
537
873
  /**
@@ -561,22 +897,50 @@ function segmentHits(s, r) {
561
897
  * What is wrong with a set of drawn labels: two boxes closer than `gap`
562
898
  * pixels (overlapping), a stem running through another label, a box outside
563
899
  * the picture. Boxes with `opacity` 0 are not drawn and are skipped. Each
564
- * problem is one sentence; none for a clean set.
900
+ * problem is one sentence, and a repeated sentence is reported once; none for
901
+ * a clean set. It stops at `limit` problems (default: all; 0 returns none; a
902
+ * `limit` that is not a whole number from 0 or Infinity throws `RangeError`), so collection ends once it has
903
+ * that many; the collision scan can end early, after the boxes are filtered and indexed. Sentences in `ignore` are skipped
904
+ * and do not count towards the limit.
565
905
  * @param {LabelBox[]} boxes
566
- * @param {{ width: number, height: number, gap?: number }} view the picture's size
906
+ * @param {{ width: number, height: number, gap?: number, limit?: number, ignore?: Set<string> }} view the picture's size
567
907
  * @returns {string[]}
568
908
  */
569
- export function labelProblems(boxes, { width, height, gap = 4 }) {
909
+ export function labelProblems(boxes, { width, height, gap = 4, limit = Infinity, ignore }) {
910
+ if (!(limit === Infinity || (Number.isInteger(limit) && limit >= 0))) throw new RangeError(`labelProblems: limit must be a whole number from 0, or Infinity, got ${typeof limit === "number" ? limit : `a value of type ${typeof limit}`}`);
911
+ if (limit === 0) return [];
912
+ const eps = 1e-9; // rounded box edges that meet exactly must not fail on float noise
570
913
  // Drawn unless it fades out: `fade` drops an element whose opacity rounds to 0.
571
- const drawn = boxes.filter((b) => b.opacity === undefined || Math.round(b.opacity * 1000) > 0);
914
+ // Exact copies (same id, geometry and stem coordinates) all say the same sentences, and two
915
+ // of them already report an overlap with each other, so a third adds nothing:
916
+ // keep two, which bounds the work on a scene that repeats one box thousands of times.
917
+ /** @type {Map<string, number>} */
918
+ const copies = new Map();
919
+ const drawn = boxes.filter((b) => {
920
+ if (b.opacity !== undefined && Math.round(b.opacity * 1000) <= 0) return false;
921
+ const key = JSON.stringify([b.id, b.x, b.y, b.width, b.height, b.stem && [b.stem.x1, b.stem.y1, b.stem.x2, b.stem.y2]]);
922
+ const n = (copies.get(key) ?? 0) + 1;
923
+ copies.set(key, n);
924
+ return n <= 2;
925
+ });
926
+ /** @type {string[]} */
572
927
  const problems = [];
928
+ /** @type {Set<string>} */
929
+ const found = new Set();
930
+ /** @param {string} message @returns {boolean} whether the limit is reached */
931
+ const add = (message) => {
932
+ if (ignore?.has(message) || found.has(message)) return false;
933
+ found.add(message);
934
+ return problems.push(message) >= limit;
935
+ };
573
936
  for (const [i, a] of drawn.entries()) {
574
- if (a.x < 0 || a.y < 0 || a.x + a.width > width || a.y + a.height > height) problems.push(`label "${a.id}" is outside the picture`);
575
- for (const b of drawn.slice(i + 1)) {
576
- if (a.x < b.x + b.width + gap && b.x < a.x + a.width + gap && a.y < b.y + b.height + gap && b.y < a.y + a.height + gap) problems.push(`labels "${a.id}" and "${b.id}" overlap`);
937
+ if ((a.x < -eps || a.y < -eps || a.x + a.width > width + eps || a.y + a.height > height + eps) && add(`label "${a.id}" is outside the picture`)) return problems;
938
+ for (let j = i + 1; j < drawn.length; j++) {
939
+ const b = drawn[j];
940
+ if (a.x < b.x + b.width + gap - eps && b.x < a.x + a.width + gap - eps && a.y < b.y + b.height + gap - eps && b.y < a.y + a.height + gap - eps && add(`labels "${a.id}" and "${b.id}" overlap`)) return problems;
577
941
  }
578
942
  for (const b of drawn) {
579
- if (b !== a && b.stem && segmentHits(b.stem, a)) problems.push(`the stem of label "${b.id}" crosses label "${a.id}"`);
943
+ if (b !== a && b.stem && segmentHits(b.stem, a) && add(`the stem of label "${b.id}" crosses label "${a.id}"`)) return problems;
580
944
  }
581
945
  }
582
946
  return problems;
package/runtime/kit.mjs CHANGED
@@ -24,8 +24,8 @@
24
24
  import { DEFAULT_MOTION, ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, easings, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 } from "./motion.mjs";
25
25
  import { FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId } from "./scene.mjs";
26
26
  import { CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, contrastReport, cssVars, normalizeStyle, resolveTokens, sharedPairs, tok } from "./style.mjs";
27
- import { CAMERA_ISOMETRIC, CAMERA_PLAN, ISO_ELEVATION, box, camera, drawSolid, drawSolids, fitCamera, labelAnchor, labelProblems, lerpCamera, orderSolids, path3, prism, project, projector, regularPolygon, slab } from "./iso.mjs";
28
- import { attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, tokenPoints, tokensAlong, translate, trimSegment } from "./svg.mjs";
27
+ import { CAMERA_ISOMETRIC, CAMERA_PLAN, ISO_ELEVATION, box, camera, drawGrid, drawOnPlane, drawSolid, drawSolids, fitCamera, labelAnchor, labelPill, labelProblems, lerpCamera, orderSolids, path3, planeMatrix, prism, project, projector, regularPolygon, roundedBox, roundedSlab, slab } from "./iso.mjs";
28
+ import { attrString, blurReveal, cubic, dist, drawOn, el, esc, fade, highlightSweep, num, pointOnLine, polyline, scaleAbout, text, tokenPoints, tokensAlong, translate, trimSegment } from "./svg.mjs";
29
29
  import { PULSE_LAG, connectorPath, drawConnector, drawJunction, drawPulse, pulseEnd, pulseHead } from "./connectors.mjs";
30
30
  import { estimateWidth, wrapLabel } from "./wrap.mjs";
31
31
 
@@ -39,8 +39,8 @@ export const KIT = Object.freeze({
39
39
  ...{ DEFAULT_MOTION, ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, easings, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 },
40
40
  ...{ FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId },
41
41
  ...{ CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, contrastReport, cssVars, normalizeStyle, resolveTokens, sharedPairs, tok },
42
- ...{ attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, tokenPoints, tokensAlong, translate, trimSegment },
43
- ...{ CAMERA_ISOMETRIC, CAMERA_PLAN, ISO_ELEVATION, box, camera, drawSolid, drawSolids, fitCamera, labelAnchor, labelProblems, lerpCamera, orderSolids, path3, prism, project, projector, regularPolygon, slab },
42
+ ...{ attrString, blurReveal, cubic, dist, drawOn, el, esc, fade, highlightSweep, num, pointOnLine, polyline, scaleAbout, text, tokenPoints, tokensAlong, translate, trimSegment },
43
+ ...{ CAMERA_ISOMETRIC, CAMERA_PLAN, ISO_ELEVATION, box, camera, drawGrid, drawOnPlane, drawSolid, drawSolids, fitCamera, labelAnchor, labelPill, labelProblems, lerpCamera, orderSolids, path3, planeMatrix, prism, project, projector, regularPolygon, roundedBox, roundedSlab, slab },
44
44
  ...{ PULSE_LAG, connectorPath, drawConnector, drawJunction, drawPulse, pulseEnd, pulseHead },
45
45
  ...{ estimateWidth, wrapLabel },
46
46
  });