@klex/mascot 0.4.0 → 0.5.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/README.md CHANGED
@@ -115,6 +115,19 @@ The minimal, flat-colored laptop floats in front of the body and gently bobs. Du
115
115
 
116
116
  `settings` accepts advanced movement settings such as `MOVEMENT_STYLES[n].settings`. A new settings object replaces a mode previously chosen by `moveTo`. Ordinary appearance updates preserve that mode. `movementMode` locks a character to `crawl`, `fly`, or `hop`: it picks that style's settings when `settings` is omitted, and `moveTo` ignores its mode argument.
117
117
 
118
+ ## Inflated look (experimental)
119
+
120
+ `appearance="inflated"` shades the body as a soft 3D form. The engine's deformed outline is rasterized each frame, a jump-flood distance field turns it into a height map, and a fragment shader lights it. Eyes, extras and the laptop stay SVG overlays. All characters on a page share one WebGL2 context and atlas, and each copies its tile into its own canvas, so z-order and clipping keep working.
121
+
122
+ ```tsx
123
+ <Klex appearance="inflated" material="plush" />
124
+ <Klex appearance="inflated" material="jelly" inflate={{ puffiness: 0.9, edgeProfile: 'gummy' }} />
125
+ ```
126
+
127
+ In this look the character behaves like a real 3D body: walking the other way turns it round with its nose towards the viewer, gaze turns mostly the head, "Turn away" shows its other side and "Spin" makes a full turn. Both sides carry the face. `turn={{ yaw, pitch, headYaw, headPitch, lookAround }}` (degrees) adds a turn of the whole body or only the head, and `lookAround` adds slow glances. `material` is `plush`, `rubber` or `jelly`. Shapes can set `puffiness` (0 = cookie, 1 = marshmallow), `edgeProfile` (`pillow`, `dome`, `gummy`) and up to four `bumps`; `inflate` overrides them per character. Without WebGL2 float render targets, with reduced motion, or in the `svg` layout, Klex falls back to the flat SVG. `klexSvg` is unaffected.
128
+
129
+ Klex Cloud compares the looks, materials and form settings at `/dev/klex`.
130
+
118
131
  ## Scenes
119
132
 
120
133
  Characters pause while offscreen. When a scene clips its characters, mark the clipping element with `data-klex-viewport`; every Klex inside then follows that element's visibility, so characters entering from outside the visible area keep animating.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@klex/mascot",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "The animated Klex mascot: a React component, its GSAP motion engine, body presets, and SVG helpers.",
5
5
  "type": "module",
6
6
  "license": "MIT AND CC-BY-4.0",
package/src/emotes.ts CHANGED
@@ -184,6 +184,7 @@ export const REST_EMOTE = {
184
184
  headSway: 0,
185
185
  headTilt: 0,
186
186
  turn: 0,
187
+ spin: 0,
187
188
  hideEyes: 0,
188
189
  melt: 0,
189
190
  puff: 0,
@@ -468,7 +469,8 @@ function gesturePose(kind: Gesture, t: number): typeof REST_EMOTE {
468
469
  compression: 0.09 * e * (1 - Math.cos(t * Math.PI * 8)),
469
470
  };
470
471
  case 'spin':
471
- return { ...REST_EMOTE, turn: e };
472
+ // Flat bodies mirror there and back; turned bodies make a full turn.
473
+ return { ...REST_EMOTE, turn: e, spin: smooth(t) };
472
474
  case 'peek':
473
475
  return { ...REST_EMOTE, nod: 1.4 * pulse(t), lookX: 2 * e, lookY: -e };
474
476
  case 'hide':
package/src/glide.ts CHANGED
@@ -281,6 +281,33 @@ export function klexBody(
281
281
  return roundedPath(bodyRig(displayPose, settings, shape, reaction).points);
282
282
  }
283
283
 
284
+ /** How the character turns this frame, for renderers that turn in depth. */
285
+ export type GlideTurn = {
286
+ /** Gaze in eye units, including what the head took over. */
287
+ lookX: number;
288
+ lookY: number;
289
+ /** 0 faces the viewer, 1 shows the back, as in "Turn away". */
290
+ turn: number;
291
+ /** Full turns completed by a spin, 0 to 1. */
292
+ spin: number;
293
+ /** Walking direction from -1 (left) to 1 (right), before emotes. */
294
+ facing: number;
295
+ };
296
+
297
+ /**
298
+ * Receives the deformed rig after each update, for renderers that draw the
299
+ * body themselves. `points` and `turn` are reused between frames.
300
+ */
301
+ export type GlideFrameListener = (
302
+ points: readonly (readonly [number, number])[],
303
+ faceX: number,
304
+ faceY: number,
305
+ faceAngle: number,
306
+ facing: number,
307
+ lift: number,
308
+ turn: GlideTurn,
309
+ ) => void;
310
+
284
311
  type GlideElements = {
285
312
  travel: HTMLDivElement | SVGGElement;
286
313
  actor: HTMLDivElement | SVGGElement;
@@ -288,11 +315,26 @@ type GlideElements = {
288
315
  body: SVGPathElement;
289
316
  eyes: SVGGElement;
290
317
  laptop?: SVGGElement;
318
+ onFrame?: GlideFrameListener;
319
+ /**
320
+ * True while the renderer turns the body in depth. Turning emotes then
321
+ * leave the outline facing forward instead of mirroring it.
322
+ */
323
+ turnsInDepth?: () => boolean;
291
324
  };
292
325
 
293
326
  // Keep one controller for the mounted figure, including interrupted moves.
294
327
  export function createGlide(
295
- { travel, actor, shadow, body, eyes, laptop }: GlideElements,
328
+ {
329
+ travel,
330
+ actor,
331
+ shadow,
332
+ body,
333
+ eyes,
334
+ laptop,
335
+ onFrame,
336
+ turnsInDepth,
337
+ }: GlideElements,
296
338
  onComplete: () => void,
297
339
  onEmoteComplete: () => void = () => {},
298
340
  onLookChange: (look: EmoteLook) => void = () => {},
@@ -315,6 +357,13 @@ export function createGlide(
315
357
  const setRotation = transformSetter(actor, 'rotation', 'deg');
316
358
  gsap.set(actor, { transformOrigin: '50% 90%' });
317
359
  const rigPoints: [number, number][] = [];
360
+ const frameTurn: GlideTurn = {
361
+ lookX: 0,
362
+ lookY: 0,
363
+ turn: 0,
364
+ spin: 0,
365
+ facing: 1,
366
+ };
318
367
  let settings = initialSettings;
319
368
  let shape: BodyShape = BODY_SHAPES[0];
320
369
  let scale = 1;
@@ -420,10 +469,30 @@ export function createGlide(
420
469
  lastLook = look;
421
470
  onLookChange(look);
422
471
  }
423
- const displayPose = {
424
- ...pose,
425
- facing: pose.facing * (1 - 2 * reaction.turn),
426
- };
472
+ // Turned in depth, the rig always draws the right-facing body and the
473
+ // renderer turns it round. Motion and gaze move into that body's frame.
474
+ const inDepth = turnsInDepth?.() ?? false;
475
+ const side = pose.facing < 0 ? -1 : 1;
476
+ const displayPose = inDepth
477
+ ? {
478
+ ...pose,
479
+ facing: 1,
480
+ look: 1 + (pose.look - pose.facing) * side,
481
+ lean: pose.lean * side,
482
+ drag: pose.drag * side,
483
+ }
484
+ : { ...pose, facing: pose.facing * (1 - 2 * reaction.turn) };
485
+ const rigReaction =
486
+ inDepth && side < 0
487
+ ? {
488
+ ...reaction,
489
+ lookX: -reaction.lookX,
490
+ gazeHeadX: -reaction.gazeHeadX,
491
+ // The renderer mirrors the face; keep winks on the same eye.
492
+ blinkLeft: reaction.blinkRight,
493
+ blinkRight: reaction.blinkLeft,
494
+ }
495
+ : reaction;
427
496
  const displayHeight = height + reaction.lift;
428
497
  setX(position);
429
498
  setGroundY(positionY);
@@ -444,39 +513,41 @@ export function createGlide(
444
513
  'opacity',
445
514
  String(0.12 * Math.max(0.15, 1 - displayHeight / 140)),
446
515
  );
447
- const rig = bodyRig(displayPose, settings, shape, reaction, rigPoints);
516
+ const rig = bodyRig(displayPose, settings, shape, rigReaction, rigPoints);
448
517
  setAttribute(body, 'd', roundedPath(rig.points));
449
518
  const head = rig.head;
450
519
  const [headX, headY] = head.point(
451
520
  80 +
452
521
  shape.eyeX * displayPose.facing +
453
- 3 * (pose.look - pose.facing) +
522
+ 3 * (inDepth ? displayPose.look - 1 : pose.look - pose.facing) +
454
523
  displayPose.facing * crawlReach(pose, settings) +
455
- settings.softness * pose.lean * 8,
524
+ settings.softness * displayPose.lean * 8,
456
525
  shape.eyeY + pose.crawl * settings.softness * pose.energy * 12,
457
526
  );
458
527
  const compressed = compressPoint(
459
528
  headX,
460
529
  headY,
461
- gsap.utils.clamp(-0.2, 0.45, pose.compression + reaction.compression),
530
+ gsap.utils.clamp(-0.2, 0.45, pose.compression + rigReaction.compression),
462
531
  );
463
532
  const [deformedX, deformedY] = deformPoint(
464
533
  ...compressed,
465
- reaction,
534
+ rigReaction,
466
535
  rig.bodyHeight,
467
536
  shape.eyeX * displayPose.facing,
468
537
  );
469
538
  const [eyeX, eyeY] = rotatePoint(
470
- deformedX * (1 - reaction.melt) +
471
- (80 + shape.eyeX * displayPose.facing * 0.3) * reaction.melt,
472
- deformedY * (1 - reaction.melt) + 116 * reaction.melt,
473
- reaction.roll * displayPose.facing,
539
+ deformedX * (1 - rigReaction.melt) +
540
+ (80 + shape.eyeX * displayPose.facing * 0.3) * rigReaction.melt,
541
+ deformedY * (1 - rigReaction.melt) + 116 * rigReaction.melt,
542
+ rigReaction.roll * displayPose.facing,
474
543
  );
475
544
  const faceX =
476
- 80 + (eyeX - rig.sideOffset - 80) * (1 + reaction.impact * 0.3);
477
- const faceY = 128 + (eyeY - rig.floorOffset - 128) * (1 - reaction.impact);
545
+ 80 + (eyeX - rig.sideOffset - 80) * (1 + rigReaction.impact * 0.3);
546
+ const faceY =
547
+ 128 + (eyeY - rig.floorOffset - 128) * (1 - rigReaction.impact);
478
548
  const faceAngle =
479
- head.angle * (1 - reaction.melt) + reaction.roll * displayPose.facing;
549
+ head.angle * (1 - rigReaction.melt) +
550
+ rigReaction.roll * displayPose.facing;
480
551
  setAttribute(
481
552
  eyes,
482
553
  'transform',
@@ -499,16 +570,32 @@ export function createGlide(
499
570
  const y = anchor.x * Math.sin(angle) + anchor.y * Math.cos(angle);
500
571
  setAttribute(attachment, 'transform', `translate(${x} ${y})`);
501
572
  }
573
+ if (onFrame) {
574
+ frameTurn.lookX = reaction.lookX + reaction.gazeHeadX;
575
+ frameTurn.lookY = reaction.lookY + reaction.gazeHeadY;
576
+ frameTurn.turn = reaction.turn;
577
+ frameTurn.facing = pose.facing;
578
+ frameTurn.spin = reaction.spin;
579
+ onFrame(
580
+ rig.points,
581
+ faceX,
582
+ faceY,
583
+ faceAngle,
584
+ displayPose.facing,
585
+ displayHeight,
586
+ frameTurn,
587
+ );
588
+ }
502
589
  setAttribute(eyes, 'opacity', String(1 - reaction.hideEyes));
503
590
  for (const [eye, closed, blink] of [
504
- [leftEye, leftClosed, reaction.blinkLeft],
505
- [rightEye, rightClosed, reaction.blinkRight],
591
+ [leftEye, leftClosed, rigReaction.blinkLeft],
592
+ [rightEye, rightClosed, rigReaction.blinkRight],
506
593
  ] as const) {
507
594
  const openness = Math.max(0, 1 - blink);
508
595
  setAttribute(
509
596
  eye,
510
597
  'transform',
511
- `translate(${reaction.lookX} ${reaction.lookY}) scale(1 ${openness})`,
598
+ `translate(${rigReaction.lookX} ${rigReaction.lookY}) scale(1 ${openness})`,
512
599
  );
513
600
  // Crossfade into a closed lid rather than making the eye disappear.
514
601
  const visible = Math.min(1, openness * 4);
@@ -517,7 +604,7 @@ export function createGlide(
517
604
  setAttribute(
518
605
  closed,
519
606
  'transform',
520
- `translate(${reaction.lookX} ${reaction.lookY})`,
607
+ `translate(${rigReaction.lookX} ${rigReaction.lookY})`,
521
608
  );
522
609
  }
523
610
  }
package/src/index.ts CHANGED
@@ -12,6 +12,15 @@ export { fitGaze, gazeRoom } from './gaze';
12
12
  export { phoneAnchor, waveAnchor } from './geometry';
13
13
  export { type KlexPosition, klexBody } from './glide';
14
14
  export { KlexGroundGrid } from './ground-grid';
15
+ export {
16
+ EDGE_PROFILES,
17
+ type InflateOptions,
18
+ type KlexMaterial,
19
+ MATERIALS,
20
+ resolveInflate,
21
+ } from './inflate/params';
22
+ export { chooseAppearance, type KlexAppearance } from './inflate/support';
23
+ export type { KlexTurn } from './inflate/turn';
15
24
  export {
16
25
  type EmoteId,
17
26
  Klex,
@@ -23,6 +32,8 @@ export {
23
32
  BODY_SHAPES,
24
33
  type BodyShape,
25
34
  DEFAULT_GLIDE,
35
+ type InflateBump,
36
+ type InflateProfile,
26
37
  type KlexPalette,
27
38
  MOVEMENT_STYLES,
28
39
  type MovementMode,
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The frame area each character renders, in the 160×140 rig units. Emotes
3
+ * such as puff, melt, roll and impact push the body past the resting frame.
4
+ */
5
+ export const REGION = { x: -30, y: -40, width: 220, height: 190 } as const;
6
+
7
+ /**
8
+ * Pixels per rig unit for the full-resolution mask and shading. Steps of 0.2
9
+ * keep both tile sides even, so the half-resolution height field lines up.
10
+ */
11
+ export function tileDensity(size: number, pixelRatio: number) {
12
+ const wanted = (size * pixelRatio) / 160;
13
+ return Math.min(2, Math.max(0.4, Math.ceil(wanted / 0.2 - 1e-9) * 0.2));
14
+ }
15
+
16
+ export type AtlasLayout = {
17
+ density: number;
18
+ tileWidth: number;
19
+ tileHeight: number;
20
+ columns: number;
21
+ rows: number;
22
+ width: number;
23
+ height: number;
24
+ capacity: number;
25
+ };
26
+
27
+ export function atlasLayout(
28
+ density: number,
29
+ tiles: number,
30
+ maxSize: number,
31
+ ): AtlasLayout {
32
+ const tileWidth = 2 * Math.round((REGION.width * density) / 2);
33
+ const tileHeight = 2 * Math.round((REGION.height * density) / 2);
34
+ // Browsers silently shrink larger drawing buffers, which shifts tiles.
35
+ const limit = Math.min(maxSize, 4096);
36
+ const columns = Math.max(
37
+ 1,
38
+ Math.min(Math.max(1, tiles), Math.floor(limit / tileWidth)),
39
+ );
40
+ const maxRows = Math.max(1, Math.floor(limit / tileHeight));
41
+ const rows = Math.min(maxRows, Math.max(1, Math.ceil(tiles / columns)));
42
+ return {
43
+ density,
44
+ tileWidth,
45
+ tileHeight,
46
+ columns,
47
+ rows,
48
+ width: columns * tileWidth,
49
+ height: rows * tileHeight,
50
+ capacity: columns * rows,
51
+ };
52
+ }
53
+
54
+ /** Hands out the lowest free tile so the atlas stays compact. */
55
+ export function createTileSlots() {
56
+ const used = new Set<number>();
57
+ return {
58
+ take() {
59
+ let slot = 0;
60
+ while (used.has(slot)) slot++;
61
+ used.add(slot);
62
+ return slot;
63
+ },
64
+ give(slot: number) {
65
+ used.delete(slot);
66
+ },
67
+ get count() {
68
+ return used.size;
69
+ },
70
+ get highest() {
71
+ return used.size ? Math.max(...used) + 1 : 0;
72
+ },
73
+ };
74
+ }
@@ -0,0 +1,302 @@
1
+ import { bodyContour } from '../geometry';
2
+ import type { BodyShape, InflateBump, InflateProfile } from '../presets';
3
+
4
+ export type KlexMaterial = 'plush' | 'rubber' | 'jelly';
5
+
6
+ export const MATERIALS = [
7
+ { id: 'plush', name: 'Plush', description: 'Velvet sheen and fine fur.' },
8
+ {
9
+ id: 'rubber',
10
+ name: 'Rubber',
11
+ description: 'Soft-touch with a broad gloss.',
12
+ },
13
+ {
14
+ id: 'jelly',
15
+ name: 'Jelly',
16
+ description: 'Glossy and slightly translucent.',
17
+ },
18
+ ] as const satisfies readonly {
19
+ id: KlexMaterial;
20
+ name: string;
21
+ description: string;
22
+ }[];
23
+
24
+ export const EDGE_PROFILES = [
25
+ { id: 'pillow', name: 'Pillow' },
26
+ { id: 'dome', name: 'Dome' },
27
+ { id: 'gummy', name: 'Gummy' },
28
+ ] as const satisfies readonly { id: InflateProfile; name: string }[];
29
+
30
+ /** Overrides for the shape's own inflate fields. */
31
+ export type InflateOptions = {
32
+ puffiness?: number;
33
+ edgeProfile?: InflateProfile;
34
+ bumps?: readonly InflateBump[];
35
+ };
36
+
37
+ export type ResolvedInflate = {
38
+ puffiness: number;
39
+ edgeProfile: InflateProfile;
40
+ bumps: readonly InflateBump[];
41
+ /** Largest inscribed radius of the rest outline. */
42
+ innerRadius: number;
43
+ /** Height at the plateau, in frame units. */
44
+ amplitude: number;
45
+ /** Distance from the edge where the profile reaches its plateau. */
46
+ edgeRadius: number;
47
+ };
48
+
49
+ export const MAX_BUMPS = 4;
50
+ const PROFILE_IDS: Record<InflateProfile, number> = {
51
+ dome: 0,
52
+ pillow: 1,
53
+ gummy: 2,
54
+ };
55
+ export const profileId = (profile: InflateProfile) => PROFILE_IDS[profile];
56
+
57
+ const lerp = (from: number, to: number, t: number) => from + (to - from) * t;
58
+ const clamp01 = (value: number) => Math.min(1, Math.max(0, value));
59
+
60
+ export function resolveInflate(
61
+ shape: BodyShape,
62
+ options: InflateOptions = {},
63
+ ): ResolvedInflate {
64
+ const puffiness = clamp01(options.puffiness ?? shape.puffiness ?? 0.6);
65
+ const edgeProfile = options.edgeProfile ?? shape.edgeProfile ?? 'dome';
66
+ const bumps = (options.bumps ?? shape.bumps ?? []).slice(0, MAX_BUMPS);
67
+ const innerRadius = inscribedRadius(shape);
68
+ // Domes and pillows rise over the whole body, so narrow parts stay thinner.
69
+ // A gummy keeps a flat face and only rounds a band along its edge.
70
+ const edgeRadius =
71
+ edgeProfile === 'gummy'
72
+ ? Math.min(innerRadius, lerp(4, 16, puffiness))
73
+ : innerRadius;
74
+ const amplitude =
75
+ edgeProfile === 'gummy'
76
+ ? edgeRadius * lerp(0.6, 1, puffiness)
77
+ : innerRadius *
78
+ (edgeProfile === 'dome'
79
+ ? lerp(0.2, 1.1, puffiness)
80
+ : lerp(0.15, 0.8, puffiness));
81
+ return { puffiness, edgeProfile, bumps, innerRadius, amplitude, edgeRadius };
82
+ }
83
+
84
+ /** Height over the distance from the edge, as the shader computes it. */
85
+ export function profileHeight(inflate: ResolvedInflate, distance: number) {
86
+ const t = clamp01(distance / inflate.edgeRadius);
87
+ const shape =
88
+ inflate.edgeProfile === 'pillow'
89
+ ? 1 - (1 - t) ** 3
90
+ : Math.sqrt(1 - (1 - t) ** 2);
91
+ return inflate.amplitude * shape;
92
+ }
93
+
94
+ const innerRadii = new WeakMap<BodyShape, number>();
95
+
96
+ // The largest inscribed circle normalizes the profile, so every form reaches
97
+ // the same roundness regardless of its size.
98
+ export function inscribedRadius(shape: BodyShape) {
99
+ const cached = innerRadii.get(shape);
100
+ if (cached !== undefined) return cached;
101
+ const contour = bodyContour(shape);
102
+ let minX = Infinity;
103
+ let maxX = -Infinity;
104
+ let minY = Infinity;
105
+ let maxY = -Infinity;
106
+ for (const [x = 0, y = 0] of contour) {
107
+ minX = Math.min(minX, x);
108
+ maxX = Math.max(maxX, x);
109
+ minY = Math.min(minY, y);
110
+ maxY = Math.max(maxY, y);
111
+ }
112
+ let best = 0;
113
+ const measure = (px: number, py: number) => {
114
+ let inside = false;
115
+ let nearest = Infinity;
116
+ for (let i = 0; i < contour.length; i++) {
117
+ const [ax = 0, ay = 0] = contour[i] ?? [];
118
+ const [bx = ax, by = ay] = contour[(i + 1) % contour.length] ?? [];
119
+ if (ay > py !== by > py && px < ax + ((py - ay) / (by - ay)) * (bx - ax))
120
+ inside = !inside;
121
+ const dx = bx - ax;
122
+ const dy = by - ay;
123
+ const t = clamp01(
124
+ ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy || 1),
125
+ );
126
+ nearest = Math.min(
127
+ nearest,
128
+ Math.hypot(px - ax - t * dx, py - ay - t * dy),
129
+ );
130
+ }
131
+ return inside ? nearest : 0;
132
+ };
133
+ // Coarse grid, then refine around the best candidate.
134
+ let bestX = (minX + maxX) / 2;
135
+ let bestY = (minY + maxY) / 2;
136
+ for (let y = minY; y <= maxY; y += 3) {
137
+ for (let x = minX; x <= maxX; x += 3) {
138
+ const radius = measure(x, y);
139
+ if (radius > best) {
140
+ best = radius;
141
+ bestX = x;
142
+ bestY = y;
143
+ }
144
+ }
145
+ }
146
+ for (let y = bestY - 3; y <= bestY + 3; y += 0.5) {
147
+ for (let x = bestX - 3; x <= bestX + 3; x += 0.5) {
148
+ best = Math.max(best, measure(x, y));
149
+ }
150
+ }
151
+ const radius = Math.max(1, best);
152
+ innerRadii.set(shape, radius);
153
+ return radius;
154
+ }
155
+
156
+ export type InflateFace = { x: number; y: number; angle: number };
157
+
158
+ /** The body turns about the center of its current bounds, at depth zero. */
159
+ export function turnPivot(points: readonly (readonly [number, number])[]) {
160
+ let minX = Infinity;
161
+ let maxX = -Infinity;
162
+ let minY = Infinity;
163
+ let maxY = -Infinity;
164
+ for (const [x, y] of points) {
165
+ minX = Math.min(minX, x);
166
+ maxX = Math.max(maxX, x);
167
+ minY = Math.min(minY, y);
168
+ maxY = Math.max(maxY, y);
169
+ }
170
+ return points.length
171
+ ? ([(minX + maxX) / 2, (minY + maxY) / 2] as const)
172
+ : ([80, 90] as const);
173
+ }
174
+
175
+ /**
176
+ * Rotate a body-space point (rig units, y down) into view space: yaw about
177
+ * the vertical axis, then pitch about the view's horizontal axis.
178
+ */
179
+ export function turnPoint(
180
+ [x, y, z]: readonly [number, number, number],
181
+ [pivotX, pivotY]: readonly [number, number],
182
+ yaw: number,
183
+ pitch: number,
184
+ ) {
185
+ const dx = x - pivotX;
186
+ const dy = y - pivotY;
187
+ const yawedX = dx * Math.cos(yaw) + z * Math.sin(yaw);
188
+ const yawedZ = -dx * Math.sin(yaw) + z * Math.cos(yaw);
189
+ return [
190
+ pivotX + yawedX,
191
+ pivotY + dy * Math.cos(pitch) - yawedZ * Math.sin(pitch),
192
+ dy * Math.sin(pitch) + yawedZ * Math.cos(pitch),
193
+ ] as const;
194
+ }
195
+
196
+ /**
197
+ * Move bumps from the rest outline onto the current frame. Face bumps follow
198
+ * the eyes; body bumps keep their relative place in the silhouette's bounds.
199
+ */
200
+ export function placeBumps(
201
+ shape: BodyShape,
202
+ bumps: readonly InflateBump[],
203
+ points: readonly (readonly [number, number])[],
204
+ face: InflateFace,
205
+ facing: number,
206
+ out: Float32Array,
207
+ offset: number,
208
+ ) {
209
+ let restMinX = Infinity;
210
+ let restMaxX = -Infinity;
211
+ let restMinY = Infinity;
212
+ for (const [x, y] of shape.outline) {
213
+ restMinX = Math.min(restMinX, x);
214
+ restMaxX = Math.max(restMaxX, x);
215
+ restMinY = Math.min(restMinY, y);
216
+ }
217
+ let minX = Infinity;
218
+ let maxX = -Infinity;
219
+ let minY = Infinity;
220
+ let maxY = -Infinity;
221
+ for (const [x, y] of points) {
222
+ minX = Math.min(minX, x);
223
+ maxX = Math.max(maxX, x);
224
+ minY = Math.min(minY, y);
225
+ maxY = Math.max(maxY, y);
226
+ }
227
+ const blend = (facing + 1) / 2;
228
+ const cos = Math.cos((face.angle * Math.PI) / 180);
229
+ const sin = Math.sin((face.angle * Math.PI) / 180);
230
+ for (let i = 0; i < MAX_BUMPS; i++) {
231
+ const bump = bumps[i];
232
+ const base = offset + i * 4;
233
+ if (!bump) {
234
+ out.fill(0, base, base + 4);
235
+ continue;
236
+ }
237
+ let x: number;
238
+ let y: number;
239
+ if (bump.anchor === 'face') {
240
+ const dx = (bump.x - (80 + shape.eyeX)) * (blend * 2 - 1);
241
+ const dy = bump.y - shape.eyeY;
242
+ x = face.x + dx * cos - dy * sin;
243
+ y = face.y + dx * sin + dy * cos;
244
+ } else {
245
+ const u = (bump.x - restMinX) / (restMaxX - restMinX || 1);
246
+ const v = (bump.y - restMinY) / (128 - restMinY || 1);
247
+ x = minX + (u * blend + (1 - u) * (1 - blend)) * (maxX - minX);
248
+ y = minY + v * (maxY - minY);
249
+ }
250
+ out[base] = x;
251
+ out[base + 1] = y;
252
+ out[base + 2] = bump.radius;
253
+ out[base + 3] = bump.height;
254
+ }
255
+ }
256
+
257
+ /** Sample the periodic B-spline the SVG body draws, as a flat vertex list. */
258
+ export function tessellate(
259
+ points: readonly (readonly [number, number])[],
260
+ out: Float32Array,
261
+ offset: number,
262
+ samples = segmentSamples(points.length),
263
+ ) {
264
+ const count = points.length;
265
+ let index = offset;
266
+ for (let i = 0; i < count; i++) {
267
+ const p0 = points[(i + count - 1) % count];
268
+ const p1 = points[i];
269
+ const p2 = points[(i + 1) % count];
270
+ const p3 = points[(i + 2) % count];
271
+ if (!p0 || !p1 || !p2 || !p3) continue;
272
+ for (let s = 0; s < samples; s++) {
273
+ const t = s / samples;
274
+ const t2 = t * t;
275
+ const t3 = t2 * t;
276
+ const w0 = (1 - t) ** 3 / 6;
277
+ const w1 = (3 * t3 - 6 * t2 + 4) / 6;
278
+ const w2 = (-3 * t3 + 3 * t2 + 3 * t + 1) / 6;
279
+ const w3 = t3 / 6;
280
+ out[index++] = p0[0] * w0 + p1[0] * w1 + p2[0] * w2 + p3[0] * w3;
281
+ out[index++] = p0[1] * w0 + p1[1] * w1 + p2[1] * w2 + p3[1] * w3;
282
+ }
283
+ }
284
+ return (index - offset) / 2;
285
+ }
286
+
287
+ /** Dense outlines need fewer samples per span for the same smoothness. */
288
+ export function segmentSamples(pointCount: number) {
289
+ return Math.min(8, Math.max(2, Math.ceil(128 / Math.max(1, pointCount))));
290
+ }
291
+
292
+ export function hexToLinear(color: string): [number, number, number] {
293
+ const match = /^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i.exec(color.trim());
294
+ const channels = match
295
+ ? [match[1], match[2], match[3]].map(
296
+ (hex) => Number.parseInt(hex ?? 'ff', 16) / 255,
297
+ )
298
+ : [1, 1, 1];
299
+ return channels.map((value) =>
300
+ value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4,
301
+ ) as [number, number, number];
302
+ }