@liqweed/motion-kit 0.7.0 → 0.9.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.
@@ -0,0 +1,583 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · the isometric kit, for custom scenes (`kit`).
5
+ *
6
+ * A camera, solids, depth order and label anchors, as pure functions: the same
7
+ * camera and solids give the same markup, so a scene that draws a 3D view
8
+ * stays a function of time. Handed to custom scenes as part of `opts.kit`.
9
+ *
10
+ * World: x east, y north, z up, in any unit. The camera looks at it from
11
+ * `azimuth` (degrees turned about z; 0 = from the south) and `elevation`
12
+ * (degrees above the horizon). 90° elevation with azimuth 0 is the plan view, with north up;
13
+ * `ISO_ELEVATION` with a 45° azimuth is true isometric. The projection is
14
+ * orthographic, so it is linear and a swivel from one camera to another is an
15
+ * interpolation of the camera (`lerpCamera`).
16
+ *
17
+ * screen.x = pan.x + zoom · u
18
+ * screen.y = pan.y − zoom · (v·sin(elevation) + z·cos(elevation))
19
+ * with u = x·cos(az) + y·sin(az) and v = −x·sin(az) + y·cos(az)
20
+ *
21
+ * `pan` is where the world origin lands on the screen, in pixels, and `zoom`
22
+ * is pixels per world unit. Colours are token names (`"surface"`), never
23
+ * literals: faces take `tok(name)`, the sides shaded by a translucent layer of
24
+ * a second token. Labels are boxes the gate checks (`labelProblems`).
25
+ *
26
+ * Imports stay single-line named imports: lib/bundle.mjs inlines only that form.
27
+ */
28
+ import { estimateWidth } from "./wrap.mjs";
29
+ import { tok } from "./style.mjs";
30
+ import { el, fade, num, text } from "./svg.mjs";
31
+
32
+ /** The elevation, in degrees, of true isometric: atan(1/√2), about 35.264°. */
33
+ export const ISO_ELEVATION = (Math.atan(Math.SQRT1_2) * 180) / Math.PI;
34
+
35
+ /** @typedef {{ x: number, y: number, z?: number }} Point3 */
36
+ /**
37
+ * A camera: where it looks from, and the pan and zoom of the picture.
38
+ * @typedef {Readonly<{ azimuth: number, elevation: number, zoom: number, pan: { x: number, y: number } }>} Camera
39
+ */
40
+ /**
41
+ * A projected point: its screen position, and `depth`, how near it is to the
42
+ * viewer (larger is nearer).
43
+ * @typedef {{ x: number, y: number, depth: number }} Projected
44
+ */
45
+
46
+ /**
47
+ * Sine and cosine of an angle in degrees, exact at multiples of 90°, so the
48
+ * plan view (90° elevation) projects without trigonometric noise.
49
+ * @param {number} deg
50
+ * @returns {[number, number]} [sin, cos]
51
+ */
52
+ function sincos(deg) {
53
+ const r = ((deg % 360) + 360) % 360;
54
+ if (r % 90 === 0) return /** @type {[number, number]} */ ([[0, 1], [1, 0], [0, -1], [-1, 0]][r / 90]);
55
+ const rad = (deg * Math.PI) / 180;
56
+ return [Math.sin(rad), Math.cos(rad)];
57
+ }
58
+
59
+ /** @param {number} n */
60
+ const finite = (n) => typeof n === "number" && Number.isFinite(n);
61
+
62
+ /**
63
+ * A camera. Defaults: true isometric (45° azimuth, `ISO_ELEVATION`), zoom 1,
64
+ * the world origin at the screen origin.
65
+ * @param {{ azimuth?: number, elevation?: number, zoom?: number, pan?: { x: number, y: number } }} [opts]
66
+ * @returns {Camera}
67
+ */
68
+ export function camera({ azimuth = 45, elevation = ISO_ELEVATION, zoom = 1, pan = { x: 0, y: 0 } } = {}) {
69
+ if (!finite(azimuth)) throw new Error(`camera: azimuth must be a finite number of degrees, got ${azimuth}`);
70
+ if (!finite(elevation) || elevation < 0 || elevation > 90) throw new Error(`camera: elevation must be from 0 to 90 degrees, got ${elevation}`);
71
+ if (!finite(zoom) || zoom <= 0) throw new Error(`camera: zoom must be a positive number, got ${zoom}`);
72
+ if (!pan || !finite(pan.x) || !finite(pan.y)) throw new Error("camera: pan must be { x, y } in finite pixels");
73
+ return Object.freeze({ azimuth, elevation, zoom, pan: Object.freeze({ x: pan.x, y: pan.y }) });
74
+ }
75
+
76
+ /** The plan view: straight down, north up. */
77
+ export const CAMERA_PLAN = camera({ azimuth: 0, elevation: 90 });
78
+ /** True isometric. */
79
+ export const CAMERA_ISOMETRIC = camera({ azimuth: 45, elevation: ISO_ELEVATION });
80
+
81
+ /**
82
+ * The camera `p` of the way from `a` to `b`: every field interpolated
83
+ * linearly, so a swivel is `lerpCamera(plan, iso, progress(t, …))`. At 0 and
84
+ * 1 it is `a` and `b` themselves.
85
+ * @param {Camera} a
86
+ * @param {Camera} b
87
+ * @param {number} p 0..1
88
+ * @returns {Camera}
89
+ */
90
+ export function lerpCamera(a, b, p) {
91
+ if (p <= 0) return a;
92
+ if (p >= 1) return b;
93
+ const mix = (/** @type {number} */ x, /** @type {number} */ y) => x + (y - x) * p;
94
+ return camera({
95
+ azimuth: mix(a.azimuth, b.azimuth),
96
+ elevation: mix(a.elevation, b.elevation),
97
+ zoom: mix(a.zoom, b.zoom),
98
+ pan: { x: mix(a.pan.x, b.pan.x), y: mix(a.pan.y, b.pan.y) },
99
+ });
100
+ }
101
+
102
+ /**
103
+ * The projection of a camera as a function of a world point.
104
+ * @param {Camera} cam
105
+ * @returns {(p: Point3) => Projected}
106
+ */
107
+ export function projector(cam) {
108
+ const [sa, ca] = sincos(cam.azimuth);
109
+ const [se, ce] = sincos(cam.elevation);
110
+ const { zoom, pan } = cam;
111
+ return ({ x, y, z = 0 }) => {
112
+ const u = x * ca + y * sa;
113
+ const v = -x * sa + y * ca;
114
+ return { x: pan.x + zoom * u, y: pan.y - zoom * (v * se + z * ce), depth: -v * ce + z * se };
115
+ };
116
+ }
117
+
118
+ /**
119
+ * One world point on the screen.
120
+ * @param {Camera} cam
121
+ * @param {Point3} p
122
+ * @returns {Projected}
123
+ */
124
+ export function project(cam, p) {
125
+ return projector(cam)(p);
126
+ }
127
+
128
+ /**
129
+ * `cam` with the zoom and pan that fit `points` (world points: a scene's
130
+ * floor corners and tallest heights) into a `width` × `height` picture, centred
131
+ * in the area the margins leave. Fitting each frame's camera keeps the whole
132
+ * scene in view through a swivel; `cam`'s own zoom and pan are replaced.
133
+ * @param {Point3[]} points
134
+ * @param {Camera} cam
135
+ * @param {{ width: number, height: number, margin?: number | { top?: number, right?: number, bottom?: number, left?: number } }} area
136
+ * @returns {Camera}
137
+ */
138
+ export function fitCamera(points, cam, { width, height, margin = 0 }) {
139
+ if (!points.length) throw new Error("fitCamera: needs at least one point");
140
+ const m = typeof margin === "number" ? { top: margin, right: margin, bottom: margin, left: margin } : margin;
141
+ const top = m.top ?? 0;
142
+ const right = m.right ?? 0;
143
+ const bottom = m.bottom ?? 0;
144
+ const left = m.left ?? 0;
145
+ const free = { w: width - left - right, h: height - top - bottom };
146
+ if (!(free.w > 0 && free.h > 0)) throw new Error("fitCamera: the margins leave no room");
147
+ const unit = projector(camera({ azimuth: cam.azimuth, elevation: cam.elevation }));
148
+ let minX = Infinity;
149
+ let maxX = -Infinity;
150
+ let minY = Infinity;
151
+ let maxY = -Infinity;
152
+ for (const p of points) {
153
+ const s = unit(p);
154
+ minX = Math.min(minX, s.x);
155
+ maxX = Math.max(maxX, s.x);
156
+ minY = Math.min(minY, s.y);
157
+ maxY = Math.max(maxY, s.y);
158
+ }
159
+ const w = maxX - minX;
160
+ const h = maxY - minY;
161
+ const zoom = Math.min(w > 0 ? free.w / w : Infinity, h > 0 ? free.h / h : Infinity);
162
+ if (!Number.isFinite(zoom)) throw new Error("fitCamera: the points have no extent");
163
+ return camera({
164
+ azimuth: cam.azimuth,
165
+ elevation: cam.elevation,
166
+ zoom,
167
+ pan: { x: left + free.w / 2 - ((minX + maxX) / 2) * zoom, y: top + free.h / 2 - ((minY + maxY) / 2) * zoom },
168
+ });
169
+ }
170
+
171
+ /**
172
+ * A polyline through world points with its length, so a token travels it at a
173
+ * constant speed in world units, whatever the camera does, when its progress is
174
+ * linear (`ease: linear`).
175
+ * @param {Point3[]} points
176
+ * @returns {{ length: number, points: Point3[], at: (f: number) => { x: number, y: number, z: number } }}
177
+ */
178
+ export function path3(points) {
179
+ if (points.length < 2) throw new Error("path3: needs at least two points");
180
+ const pts = points.map((p) => ({ x: p.x, y: p.y, z: p.z ?? 0 }));
181
+ const starts = [0];
182
+ for (let i = 1; i < pts.length; i++) starts.push(starts[i - 1] + Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y, pts[i].z - pts[i - 1].z));
183
+ const length = starts[starts.length - 1];
184
+ return {
185
+ length,
186
+ points: pts,
187
+ at(f) {
188
+ const target = Math.min(Math.max(f, 0), 1) * length;
189
+ let i = 1;
190
+ while (i < pts.length - 1 && target > starts[i]) i++;
191
+ const a = pts[i - 1];
192
+ const b = pts[i];
193
+ const span = starts[i] - starts[i - 1];
194
+ const k = span === 0 ? 0 : (target - starts[i - 1]) / span;
195
+ return { x: a.x + (b.x - a.x) * k, y: a.y + (b.y - a.y) * k, z: a.z + (b.z - a.z) * k };
196
+ },
197
+ };
198
+ }
199
+
200
+ /* ------------------------------------------------------------------ solids */
201
+
202
+ /**
203
+ * An extruded convex polygon: a footprint in the x-y plane, from `z0` up to
204
+ * `z1`. `fill` is the token of the top face; `sides` (default: `fill`) the
205
+ * token of the side faces, which a layer of `shade` at 10–26 % darkens or
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
209
+ */
210
+
211
+ /**
212
+ * @param {string} name a token name
213
+ * @returns {string}
214
+ */
215
+ function token(name) {
216
+ tok(name); // throws for an unknown token
217
+ return name;
218
+ }
219
+
220
+ /**
221
+ * Footprint points counter-clockwise, or a throw for a footprint that is not a
222
+ * convex polygon.
223
+ * @param {{ x: number, y: number }[]} points
224
+ * @returns {{ x: number, y: number }[]}
225
+ */
226
+ function convexCcw(points) {
227
+ if (!Array.isArray(points) || points.length < 3) throw new Error("a solid's footprint needs at least three points");
228
+ for (const p of points) if (!p || !finite(p.x) || !finite(p.y)) throw new Error("a solid's footprint points must be finite { x, y }");
229
+ let area = 0;
230
+ for (let i = 0; i < points.length; i++) {
231
+ const a = points[i];
232
+ const b = points[(i + 1) % points.length];
233
+ area += a.x * b.y - b.x * a.y;
234
+ }
235
+ if (Math.abs(area) < 1e-9) throw new Error("a solid's footprint has no area");
236
+ 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");
240
+ }
241
+ const ccw = area > 0 ? points.map((p) => ({ x: p.x, y: p.y })) : points.map((p) => ({ x: p.x, y: p.y })).reverse();
242
+ for (let i = 0; i < ccw.length; i++) {
243
+ const a = ccw[i];
244
+ const b = ccw[(i + 1) % ccw.length];
245
+ const c = ccw[(i + 2) % ccw.length];
246
+ if ((b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x) < -1e-9) throw new Error("a solid's footprint must be convex");
247
+ }
248
+ // Consecutive turns alone pass a star that winds twice: every vertex must also
249
+ // lie on the inner side of every edge.
250
+ for (let i = 0; i < ccw.length; i++) {
251
+ const a = ccw[i];
252
+ const b = ccw[(i + 1) % ccw.length];
253
+ 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
+ }
255
+ return ccw;
256
+ }
257
+
258
+ /**
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
261
+ * @returns {Solid}
262
+ */
263
+ export function prism({ points, h, z = 0, fill = "surface", sides, shade = "ink", stroke = "line", strokeWidth = 1.5, opacity = 1, id }) {
264
+ if (!finite(h) || h < 0) throw new Error(`a solid's height must be a number from 0 up, got ${h}`);
265
+ if (!finite(z)) throw new Error(`a solid's base height must be finite, got ${z}`);
266
+ return Object.freeze({
267
+ points: convexCcw(points),
268
+ z0: z,
269
+ z1: z + h,
270
+ fill: token(fill),
271
+ sides: token(sides ?? fill),
272
+ shade: shade === null ? null : token(shade),
273
+ stroke: token(stroke),
274
+ strokeWidth,
275
+ opacity,
276
+ id,
277
+ });
278
+ }
279
+
280
+ /** @typedef {Omit<Parameters<typeof prism>[0], "points" | "h">} SolidStyle */
281
+
282
+ /**
283
+ * A box: `w` along x, `d` along y, `h` up, its footprint centred on (x, y).
284
+ * @param {{ x: number, y: number, w: number, d: number, h: number } & SolidStyle} o
285
+ * @returns {Solid}
286
+ */
287
+ export function box({ x, y, w, d, h, ...style }) {
288
+ if (!(finite(w) && w > 0 && finite(d) && d > 0)) throw new Error("a box needs a positive width and depth");
289
+ const hw = w / 2;
290
+ const hd = d / 2;
291
+ return prism({ points: [{ x: x - hw, y: y - hd }, { x: x + hw, y: y - hd }, { x: x + hw, y: y + hd }, { x: x - hw, y: y + hd }], h, ...style });
292
+ }
293
+
294
+ /**
295
+ * A slab: a box that is thin (`h` default 0.25), for a floor or a platform.
296
+ * @param {{ x: number, y: number, w: number, d: number, h?: number } & SolidStyle} o
297
+ * @returns {Solid}
298
+ */
299
+ export function slab({ h = 0.25, ...rest }) {
300
+ return box({ h, ...rest });
301
+ }
302
+
303
+ /**
304
+ * The corners of a regular polygon of `n` sides and circumradius `r` centred on
305
+ * (x, y), the first at `rotation` degrees from east: a footprint for `prism`.
306
+ * @param {number} x
307
+ * @param {number} y
308
+ * @param {number} r
309
+ * @param {number} n
310
+ * @param {number} [rotation]
311
+ * @returns {{ x: number, y: number }[]}
312
+ */
313
+ export function regularPolygon(x, y, r, n, rotation = 0) {
314
+ if (!Number.isInteger(n) || n < 3) throw new Error(`a regular polygon needs at least 3 sides, got ${n}`);
315
+ return Array.from({ length: n }, (_, i) => {
316
+ const [s, c] = sincos(rotation + (360 * i) / n);
317
+ return { x: x + r * c, y: y + r * s };
318
+ });
319
+ }
320
+
321
+ const EPS = 1e-9;
322
+
323
+ /**
324
+ * 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.
326
+ * @param {Solid} solid
327
+ * @param {Camera} cam
328
+ * @returns {{ kind: "side" | "top", points: { x: number, y: number }[], shade: number }[]}
329
+ */
330
+ function visibleFaces(solid, cam) {
331
+ const to = projector(cam);
332
+ const [sa, ca] = sincos(cam.azimuth);
333
+ const [se, ce] = sincos(cam.elevation);
334
+ const faces = /** @type {{ kind: "side" | "top", points: { x: number, y: number }[], shade: number }[]} */ ([]);
335
+ const pts = solid.points;
336
+ 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];
340
+ const len = Math.hypot(b.x - a.x, b.y - a.y);
341
+ const nx = (b.y - a.y) / len;
342
+ const ny = -(b.x - a.x) / len;
343
+ // 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 })],
349
+ shade: Math.round((0.1 + 0.16 * ((turn + 1) / 2)) * 100) / 100,
350
+ });
351
+ }
352
+ }
353
+ if (se > EPS) faces.push({ kind: "top", points: pts.map((p) => to({ ...p, z: solid.z1 })), shade: 0 });
354
+ return faces;
355
+ }
356
+
357
+ /** @param {{ x: number, y: number }[]} points */
358
+ const pathD = (points) => `${points.map((p, i) => `${i === 0 ? "M" : "L"}${num(p.x)} ${num(p.y)}`).join(" ")} Z`;
359
+
360
+ /**
361
+ * Markup of one solid under a camera: only the faces that face the camera,
362
+ * each a path in its token, the sides with a shade layer. Nothing is drawn for
363
+ * a solid with zero opacity.
364
+ * @param {Solid} solid
365
+ * @param {Camera} cam
366
+ * @returns {string}
367
+ */
368
+ export function drawSolid(solid, cam) {
369
+ const paths = visibleFaces(solid, cam).map((face) => {
370
+ const d = pathD(face.points);
371
+ 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;
373
+ });
374
+ return fade(solid.opacity, solid.id ? { "data-solid": solid.id } : {}, ...paths);
375
+ }
376
+
377
+ /**
378
+ * Whether the solids can be told apart in depth on the screen: the bounding
379
+ * boxes of their projections overlap.
380
+ * @param {{ min: { x: number, y: number }, max: { x: number, y: number } }} a
381
+ * @param {{ min: { x: number, y: number }, max: { x: number, y: number } }} b
382
+ */
383
+ const screenOverlap = (a, b) => a.min.x < b.max.x - EPS && b.min.x < a.max.x - EPS && a.min.y < b.max.y - EPS && b.min.y < a.max.y - EPS;
384
+
385
+ /**
386
+ * Which of two solids is drawn first, by the axes that separate them: -1 when
387
+ * `a` lies behind `b`, 1 when it lies in front, 0 when no axis, or two that
388
+ * disagree, decide (the solids then cannot hide one another).
389
+ * @param {Solid} a
390
+ * @param {Solid} b
391
+ * @param {number} sa sin of the azimuth
392
+ * @param {number} ca cos of the azimuth
393
+ * @param {number} se sin of the elevation
394
+ * @returns {-1 | 0 | 1}
395
+ */
396
+ function behind(a, b, sa, ca, se) {
397
+ let vote = 0;
398
+ let conflict = false;
399
+ /** @param {-1 | 1} v */
400
+ const cast = (v) => {
401
+ if (vote !== 0 && vote !== v) conflict = true;
402
+ vote = v;
403
+ };
404
+ // Footprints: a separating line between two convex polygons lies along an edge of one.
405
+ for (const poly of [a.points, b.points]) {
406
+ for (let i = 0; i < poly.length; i++) {
407
+ const p = poly[i];
408
+ const q = poly[(i + 1) % poly.length];
409
+ const len = Math.hypot(q.x - p.x, q.y - p.y);
410
+ const nx = (q.y - p.y) / len;
411
+ const ny = -(q.x - p.x) / len;
412
+ const range = (/** @type {Solid} */ s) => {
413
+ const d = s.points.map((pt) => pt.x * nx + pt.y * ny);
414
+ return [Math.min(...d), Math.max(...d)];
415
+ };
416
+ const [a0, a1] = range(a);
417
+ const [b0, b1] = range(b);
418
+ const facing = nx * sa - ny * ca; // how much this axis points toward the camera
419
+ if (Math.abs(facing) <= EPS) continue;
420
+ if (a1 <= b0 + EPS) cast(facing > 0 ? -1 : 1); // b is on the positive side
421
+ else if (b1 <= a0 + EPS) cast(facing > 0 ? 1 : -1);
422
+ }
423
+ }
424
+ // Heights: from above, the higher solid is nearer.
425
+ if (se > EPS) {
426
+ if (a.z1 <= b.z0 + EPS) cast(-1);
427
+ else if (b.z1 <= a.z0 + EPS) cast(1);
428
+ }
429
+ return conflict ? 0 : vote === 0 ? 0 : /** @type {-1 | 1} */ (vote);
430
+ }
431
+
432
+ /**
433
+ * The solids in drawing order, farthest first, for `cam`. Two solids are
434
+ * ordered by the axes that separate them (footprint edges and height), only
435
+ * when they overlap on the screen; the rest is a topological sort, ties and
436
+ * cycles broken by how near each solid's centre is, then by input order. The
437
+ * same input always gives the same order.
438
+ * @template {Solid} S
439
+ * @param {S[]} solids
440
+ * @param {Camera} cam
441
+ * @returns {S[]}
442
+ */
443
+ export function orderSolids(solids, cam) {
444
+ const to = projector(cam);
445
+ const [sa, ca] = sincos(cam.azimuth);
446
+ const [se] = sincos(cam.elevation);
447
+ const info = solids.map((s) => {
448
+ const corners = s.points.flatMap((p) => [to({ ...p, z: s.z0 }), to({ ...p, z: s.z1 })]);
449
+ const xs = corners.map((c) => c.x);
450
+ const ys = corners.map((c) => c.y);
451
+ const cx = s.points.reduce((n, p) => n + p.x, 0) / s.points.length;
452
+ const cy = s.points.reduce((n, p) => n + p.y, 0) / s.points.length;
453
+ return { min: { x: Math.min(...xs), y: Math.min(...ys) }, max: { x: Math.max(...xs), y: Math.max(...ys) }, near: to({ x: cx, y: cy, z: (s.z0 + s.z1) / 2 }).depth };
454
+ });
455
+ const after = solids.map(() => /** @type {number[]} */ ([])); // after[i]: drawn after i
456
+ const waiting = solids.map(() => 0);
457
+ for (let i = 0; i < solids.length; i++) {
458
+ for (let j = i + 1; j < solids.length; j++) {
459
+ if (!screenOverlap(info[i], info[j])) continue;
460
+ const order = behind(solids[i], solids[j], sa, ca, se);
461
+ if (order === 0) continue;
462
+ const [first, second] = order < 0 ? [i, j] : [j, i];
463
+ after[first].push(second);
464
+ waiting[second]++;
465
+ }
466
+ }
467
+ const done = solids.map(() => false);
468
+ const out = /** @type {S[]} */ ([]);
469
+ /** @param {number} i @param {number} j */
470
+ const nearer = (i, j) => info[i].near < info[j].near - EPS || (Math.abs(info[i].near - info[j].near) <= EPS && i < j);
471
+ while (out.length < solids.length) {
472
+ let pick = -1;
473
+ for (let i = 0; i < solids.length; i++) if (!done[i] && waiting[i] === 0 && (pick < 0 || nearer(i, pick))) pick = i;
474
+ if (pick < 0) for (let i = 0; i < solids.length; i++) if (!done[i] && (pick < 0 || nearer(i, pick))) pick = i; // a cycle
475
+ done[pick] = true;
476
+ out.push(solids[pick]);
477
+ for (const next of after[pick]) waiting[next]--;
478
+ }
479
+ return out;
480
+ }
481
+
482
+ /**
483
+ * Markup of several solids, depth ordered for `cam`.
484
+ * @param {Solid[]} solids
485
+ * @param {Camera} cam
486
+ * @returns {string}
487
+ */
488
+ export function drawSolids(solids, cam) {
489
+ return orderSolids(solids, cam)
490
+ .map((s) => drawSolid(s, cam))
491
+ .join("");
492
+ }
493
+
494
+ /* ----------------------------------------------------------- label anchors */
495
+
496
+ /**
497
+ * What the gate checks of a label: its box in the picture (top left, size), its
498
+ * stem, and whether it is drawn (`opacity` above 0).
499
+ * @typedef {{ id: string, x: number, y: number, width: number, height: number, stem?: { x1: number, y1: number, x2: number, y2: number }, opacity?: number }} LabelBox
500
+ */
501
+
502
+ /**
503
+ * A label on a point of the world, with a stem: a dot on the point, a vertical
504
+ * stem `lift` pixels up, and the label's box at its top, placed in the
505
+ * projected view, so it follows the camera. `side` puts the box above the
506
+ * stem (`"up"`, centred), or beside its top (`"right"` or `"left"`).
507
+ * `lines` are the label's (already wrapped, localized) lines. Returns the
508
+ * markup and the box for the scene's `labelBoxes`.
509
+ * @param {Camera} cam
510
+ * @param {{ id: string, at: Point3, lines: string[], fontSize?: number, lift?: number, side?: "up" | "right" | "left", opacity?: number }} o
511
+ * @returns {{ markup: string, box: LabelBox }}
512
+ */
513
+ 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
+ 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;
521
+ const tipX = p.x;
522
+ const tipY = p.y - lift;
523
+ const x = side === "up" ? tipX - width / 2 : side === "right" ? tipX : tipX - width;
524
+ const y = side === "up" ? tipY - height : tipY - height / 2;
525
+ const stem = { x1: p.x, y1: p.y, x2: tipX, y2: tipY };
526
+ const markup = fade(
527
+ opacity,
528
+ { "data-label": id },
529
+ el("line", { x1: stem.x1, y1: stem.y1, x2: stem.x2, y2: stem.y2, stroke: tok("line"), "stroke-width": 1.5 }),
530
+ el("circle", { cx: p.x, cy: p.y, r: 3.5, fill: tok("ink"), stroke: tok("bg"), "stroke-width": 1.5 }),
531
+ 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),
533
+ );
534
+ return { markup, box: { id, x, y, width, height, stem, opacity } };
535
+ }
536
+
537
+ /**
538
+ * Whether the segment crosses the rectangle (Liang–Barsky).
539
+ * @param {{ x1: number, y1: number, x2: number, y2: number }} s
540
+ * @param {{ x: number, y: number, width: number, height: number }} r
541
+ */
542
+ function segmentHits(s, r) {
543
+ let t0 = 0;
544
+ let t1 = 1;
545
+ const dx = s.x2 - s.x1;
546
+ const dy = s.y2 - s.y1;
547
+ for (const [p, q] of [[-dx, s.x1 - r.x], [dx, r.x + r.width - s.x1], [-dy, s.y1 - r.y], [dy, r.y + r.height - s.y1]]) {
548
+ if (p === 0) {
549
+ if (q < 0) return false;
550
+ } else {
551
+ const k = q / p;
552
+ if (p < 0) t0 = Math.max(t0, k);
553
+ else t1 = Math.min(t1, k);
554
+ if (t0 > t1) return false;
555
+ }
556
+ }
557
+ return true;
558
+ }
559
+
560
+ /**
561
+ * What is wrong with a set of drawn labels: two boxes closer than `gap`
562
+ * pixels (overlapping), a stem running through another label, a box outside
563
+ * the picture. Boxes with `opacity` 0 are not drawn and are skipped. Each
564
+ * problem is one sentence; none for a clean set.
565
+ * @param {LabelBox[]} boxes
566
+ * @param {{ width: number, height: number, gap?: number }} view the picture's size
567
+ * @returns {string[]}
568
+ */
569
+ export function labelProblems(boxes, { width, height, gap = 4 }) {
570
+ // 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);
572
+ const problems = [];
573
+ 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`);
577
+ }
578
+ 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}"`);
580
+ }
581
+ }
582
+ return problems;
583
+ }
package/runtime/kit.mjs CHANGED
@@ -21,23 +21,25 @@
21
21
  * from `motion-kit build` calls the factory the same way, with the bundled
22
22
  * runtime as `kit`, after the CLI built it here once.
23
23
  */
24
- import { ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 } from "./motion.mjs";
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, cssVars, normalizeStyle, resolveTokens, tok } from "./style.mjs";
27
- import { attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, translate, trimSegment } from "./svg.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";
28
29
  import { estimateWidth, wrapLabel } from "./wrap.mjs";
29
30
 
30
31
  /**
31
32
  * The runtime, flat, handed to custom scene modules as `opts.kit`: the exports
32
- * of motion, scene, style, svg and wrap (not the scene types or the player).
33
+ * of motion, scene, style, svg, iso and wrap (not the scene types or the player).
33
34
  * Named imports, because lib/bundle.mjs inlines only that form; a new export
34
35
  * in one of those modules is added here (test/runtime.test.mjs checks).
35
36
  */
36
37
  export const KIT = Object.freeze({
37
- ...{ ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 },
38
+ ...{ DEFAULT_MOTION, ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, easings, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 },
38
39
  ...{ FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId },
39
40
  ...{ CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, cssVars, normalizeStyle, resolveTokens, tok },
40
- ...{ attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, translate, trimSegment },
41
+ ...{ attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, tokenPoints, tokensAlong, translate, trimSegment },
42
+ ...{ CAMERA_ISOMETRIC, CAMERA_PLAN, ISO_ELEVATION, box, camera, drawSolid, drawSolids, fitCamera, labelAnchor, labelProblems, lerpCamera, orderSolids, path3, prism, project, projector, regularPolygon, slab },
41
43
  ...{ estimateWidth, wrapLabel },
42
44
  });
43
45
 
@@ -152,3 +152,64 @@ export function splitEdge(t, start, duration, lag = 0.07, ease = easeStandard) {
152
152
  export function stagger(count, start, gap) {
153
153
  return Array.from({ length: count }, (_, i) => start + i * gap);
154
154
  }
155
+
156
+ /* ----------------------------------------------------- style curves */
157
+
158
+ /**
159
+ * The two curves a style may name: `enter` for entrances, `move` for movement
160
+ * between two visible states, each as the four numbers of a CSS
161
+ * `cubic-bezier(x1, y1, x2, y2)`. The defaults are `easeOut` and `easeStandard`.
162
+ * @typedef {{ enter: readonly [number, number, number, number], move: readonly [number, number, number, number] }} Motion
163
+ */
164
+ /** @type {Readonly<Motion>} */
165
+ export const DEFAULT_MOTION = Object.freeze({
166
+ enter: Object.freeze(/** @type {[number, number, number, number]} */ ([0, 0, 0.2, 1])),
167
+ move: Object.freeze(/** @type {[number, number, number, number]} */ ([0.4, 0, 0.2, 1])),
168
+ });
169
+
170
+ /**
171
+ * A step frame must equal the frame 1 ms before it (the gate's settled-frame
172
+ * rule), and the shortest built-in move lasts about 0.2 s, so a curve has to be
173
+ * within rounding of 1 at 0.5 % of its duration before the end. The defaults are
174
+ * (about 1e-5 short of 1 there); a linear curve is 5e-3 short.
175
+ */
176
+ const SETTLE_PROBE = 0.005;
177
+ const SETTLE_TOLERANCE = 2e-5;
178
+ /** Share of a curve's duration held at 1 when the curve does not settle by itself. */
179
+ const SETTLE_WINDOW = 0.05;
180
+
181
+ /**
182
+ * `curve` as it is, when it ends flat enough to settle on its own; otherwise
183
+ * the same curve finished in the first 95 % of its duration, so the last 5 % is
184
+ * held at exactly 1 and every step frame is settled whatever the curve.
185
+ * @param {(p: number) => number} curve
186
+ * @returns {(p: number) => number}
187
+ */
188
+ function settled(curve) {
189
+ if (1 - curve(1 - SETTLE_PROBE) <= SETTLE_TOLERANCE) return curve;
190
+ return (p) => curve(Math.min(1, p / (1 - SETTLE_WINDOW)));
191
+ }
192
+
193
+ /** @type {Map<string, { easeOut: (p: number) => number, easeStandard: (p: number) => number }>} */
194
+ const easingCache = new Map();
195
+
196
+ /**
197
+ * The entrance and movement curves of a style's `motion` (or the defaults).
198
+ * Scene types call this with `style.motion` once per frame, so a diagram moves
199
+ * on the page's own curve. The result is cached by curve. The endpoints stay
200
+ * fixed, and a curve that does not end flat (a linear one) finishes in the first
201
+ * 95 % of each move, so step frames are settled for every permitted curve.
202
+ * @param {Motion} [motion]
203
+ * @returns {{ easeOut: (p: number) => number, easeStandard: (p: number) => number }}
204
+ */
205
+ export function easings(motion = DEFAULT_MOTION) {
206
+ if (motion === DEFAULT_MOTION) return { easeOut, easeStandard };
207
+ const key = `${motion.enter.join()}|${motion.move.join()}`;
208
+ let found = easingCache.get(key);
209
+ if (!found) {
210
+ if (easingCache.size >= 32) easingCache.clear();
211
+ found = { easeOut: settled(cubicBezier(...motion.enter)), easeStandard: settled(cubicBezier(...motion.move)) };
212
+ easingCache.set(key, found);
213
+ }
214
+ return found;
215
+ }