@klex/mascot 0.4.0 → 0.6.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/src/glide.ts CHANGED
@@ -9,7 +9,13 @@ import {
9
9
  REST_EMOTE,
10
10
  } from './emotes';
11
11
  import { fitGaze, gazeRoom } from './gaze';
12
- import { mirroredOutline, phoneAnchor, waveAnchor } from './geometry';
12
+ import {
13
+ bookPenPoint,
14
+ bookPlacement,
15
+ mirroredOutline,
16
+ phoneAnchor,
17
+ waveAnchor,
18
+ } from './geometry';
13
19
  import { BODY_SHAPES, type BodyShape, DEFAULT_GLIDE } from './presets';
14
20
  import { roundedPath } from './svg';
15
21
 
@@ -281,6 +287,33 @@ export function klexBody(
281
287
  return roundedPath(bodyRig(displayPose, settings, shape, reaction).points);
282
288
  }
283
289
 
290
+ /** How the character turns this frame, for renderers that turn in depth. */
291
+ export type GlideTurn = {
292
+ /** Gaze in eye units, including what the head took over. */
293
+ lookX: number;
294
+ lookY: number;
295
+ /** 0 faces the viewer, 1 shows the back, as in "Turn away". */
296
+ turn: number;
297
+ /** Full turns completed by a spin, 0 to 1. */
298
+ spin: number;
299
+ /** Walking direction from -1 (left) to 1 (right), before emotes. */
300
+ facing: number;
301
+ };
302
+
303
+ /**
304
+ * Receives the deformed rig after each update, for renderers that draw the
305
+ * body themselves. `points` and `turn` are reused between frames.
306
+ */
307
+ export type GlideFrameListener = (
308
+ points: readonly (readonly [number, number])[],
309
+ faceX: number,
310
+ faceY: number,
311
+ faceAngle: number,
312
+ facing: number,
313
+ lift: number,
314
+ turn: GlideTurn,
315
+ ) => void;
316
+
284
317
  type GlideElements = {
285
318
  travel: HTMLDivElement | SVGGElement;
286
319
  actor: HTMLDivElement | SVGGElement;
@@ -288,11 +321,28 @@ type GlideElements = {
288
321
  body: SVGPathElement;
289
322
  eyes: SVGGElement;
290
323
  laptop?: SVGGElement;
324
+ book?: SVGGElement;
325
+ onFrame?: GlideFrameListener;
326
+ /**
327
+ * True while the renderer turns the body in depth. Turning emotes then
328
+ * leave the outline facing forward instead of mirroring it.
329
+ */
330
+ turnsInDepth?: () => boolean;
291
331
  };
292
332
 
293
333
  // Keep one controller for the mounted figure, including interrupted moves.
294
334
  export function createGlide(
295
- { travel, actor, shadow, body, eyes, laptop }: GlideElements,
335
+ {
336
+ travel,
337
+ actor,
338
+ shadow,
339
+ body,
340
+ eyes,
341
+ laptop,
342
+ book,
343
+ onFrame,
344
+ turnsInDepth,
345
+ }: GlideElements,
296
346
  onComplete: () => void,
297
347
  onEmoteComplete: () => void = () => {},
298
348
  onLookChange: (look: EmoteLook) => void = () => {},
@@ -315,6 +365,13 @@ export function createGlide(
315
365
  const setRotation = transformSetter(actor, 'rotation', 'deg');
316
366
  gsap.set(actor, { transformOrigin: '50% 90%' });
317
367
  const rigPoints: [number, number][] = [];
368
+ const frameTurn: GlideTurn = {
369
+ lookX: 0,
370
+ lookY: 0,
371
+ turn: 0,
372
+ spin: 0,
373
+ facing: 1,
374
+ };
318
375
  let settings = initialSettings;
319
376
  let shape: BodyShape = BODY_SHAPES[0];
320
377
  let scale = 1;
@@ -349,6 +406,10 @@ export function createGlide(
349
406
  );
350
407
  let hand = eyes.querySelector('[data-wave-anchor]');
351
408
  let phone = eyes.querySelector('[data-phone-anchor]');
409
+ const bookInk = [...(book?.querySelectorAll('[data-book-ink] > path') ?? [])];
410
+ const bookPen = book?.querySelector('[data-book-pen]');
411
+ const bookTurn = book?.querySelector('[data-book-turn]');
412
+ const bookTurnInk = book?.querySelector('[data-book-turn-ink]');
352
413
  let hop: {
353
414
  from: number;
354
415
  to: number;
@@ -360,6 +421,44 @@ export function createGlide(
360
421
  load: number;
361
422
  } | null = null;
362
423
 
424
+ function renderBook() {
425
+ if (!book) return;
426
+ const bookScale = reducedMotion
427
+ ? Number(activity === 'learning')
428
+ : activityMotion.bookScale;
429
+ const { x, y, scale: size } = bookPlacement(shape);
430
+ const pivotY = y + 26 * size;
431
+ setAttribute(
432
+ book,
433
+ 'transform',
434
+ `translate(${shape.eyeX * 0.3 * (pose.facing - 1)} ${reducedMotion ? 0 : activityMotion.learningBob}) translate(${x} ${pivotY}) scale(${bookScale}) translate(${-x} ${-pivotY})`,
435
+ );
436
+ setAttribute(book, 'opacity', String(Number(bookScale > 0)));
437
+ if (bookScale === 0) return;
438
+ const { ink, pen, turn } = activityMotion.learning;
439
+ // A turning page already shows the fresh one beneath it.
440
+ const written = reducedMotion ? 2.6 : turn > 0 ? 0 : ink;
441
+ for (const [index, line] of bookInk.entries())
442
+ setAttribute(
443
+ line,
444
+ 'stroke-dashoffset',
445
+ (1 - Math.min(1, Math.max(0, written - index))).toFixed(3),
446
+ );
447
+ const tip = reducedMotion
448
+ ? bookPenPoint(2, 0.6, 1)
449
+ : bookPenPoint(pen.line, pen.x, 1 - pen.lift);
450
+ setAttribute(
451
+ bookPen,
452
+ 'transform',
453
+ `translate(${tip.x.toFixed(2)} ${tip.y.toFixed(2)})`,
454
+ );
455
+ // The full page folds over the spine onto the left; its back is blank.
456
+ const fold = Math.cos(Math.PI * turn * turn * (3 - 2 * turn));
457
+ setAttribute(bookTurn, 'opacity', String(Number(turn > 0 && turn < 1)));
458
+ setAttribute(bookTurn, 'transform', `scale(${fold.toFixed(3)} 1)`);
459
+ setAttribute(bookTurnInk, 'opacity', String(Number(fold > 0)));
460
+ }
461
+
363
462
  function render() {
364
463
  const laptopScale = reducedMotion
365
464
  ? Number(activity === 'working')
@@ -372,6 +471,7 @@ export function createGlide(
372
471
  `translate(${shape.eyeX * 0.4 * (pose.facing - 1)} ${reducedMotion ? 0 : activityMotion.workingBob}) translate(${laptopX} ${laptopY}) scale(${laptopScale}) translate(${-laptopX} ${-laptopY})`,
373
472
  );
374
473
  setAttribute(laptop, 'opacity', String(Number(laptopScale > 0)));
474
+ renderBook();
375
475
  const resting = !busy && !transitioning && !emote;
376
476
  const restingPose = activityMotion.pose(
377
477
  reducedMotion ? activity : undefined,
@@ -395,24 +495,37 @@ export function createGlide(
395
495
  );
396
496
  const look: EmoteLook = emote
397
497
  ? emoteLook(emote.action.id, emote.time / emote.action.duration)
398
- : resting && activity === 'working'
498
+ : resting && activity === 'recalling'
399
499
  ? {
400
- expression: 'neutral',
401
- extra:
402
- !reducedMotion && activityMotion.thinking
403
- ? 'question'
404
- : undefined,
500
+ extra: 'thought',
501
+ expression: reducedMotion
502
+ ? 'neutral'
503
+ : activityMotion.recallingExpression,
405
504
  }
406
- : resting && activity === 'calling'
505
+ : resting && activity === 'learning'
407
506
  ? {
408
- extra: 'phone',
409
507
  expression: reducedMotion
410
- ? 'neutral'
411
- : activityMotion.callingExpression,
508
+ ? 'focused'
509
+ : activityMotion.learningExpression,
412
510
  }
413
- : resting && activity === 'sleeping'
414
- ? { extra: 'sleep' }
415
- : {};
511
+ : resting && activity === 'working'
512
+ ? {
513
+ expression: 'neutral',
514
+ extra:
515
+ !reducedMotion && activityMotion.thinking
516
+ ? 'question'
517
+ : undefined,
518
+ }
519
+ : resting && activity === 'calling'
520
+ ? {
521
+ extra: 'phone',
522
+ expression: reducedMotion
523
+ ? 'neutral'
524
+ : activityMotion.callingExpression,
525
+ }
526
+ : resting && activity === 'sleeping'
527
+ ? { extra: 'sleep' }
528
+ : {};
416
529
  if (
417
530
  look.expression !== lastLook.expression ||
418
531
  look.extra !== lastLook.extra
@@ -420,10 +533,30 @@ export function createGlide(
420
533
  lastLook = look;
421
534
  onLookChange(look);
422
535
  }
423
- const displayPose = {
424
- ...pose,
425
- facing: pose.facing * (1 - 2 * reaction.turn),
426
- };
536
+ // Turned in depth, the rig always draws the right-facing body and the
537
+ // renderer turns it round. Motion and gaze move into that body's frame.
538
+ const inDepth = turnsInDepth?.() ?? false;
539
+ const side = pose.facing < 0 ? -1 : 1;
540
+ const displayPose = inDepth
541
+ ? {
542
+ ...pose,
543
+ facing: 1,
544
+ look: 1 + (pose.look - pose.facing) * side,
545
+ lean: pose.lean * side,
546
+ drag: pose.drag * side,
547
+ }
548
+ : { ...pose, facing: pose.facing * (1 - 2 * reaction.turn) };
549
+ const rigReaction =
550
+ inDepth && side < 0
551
+ ? {
552
+ ...reaction,
553
+ lookX: -reaction.lookX,
554
+ gazeHeadX: -reaction.gazeHeadX,
555
+ // The renderer mirrors the face; keep winks on the same eye.
556
+ blinkLeft: reaction.blinkRight,
557
+ blinkRight: reaction.blinkLeft,
558
+ }
559
+ : reaction;
427
560
  const displayHeight = height + reaction.lift;
428
561
  setX(position);
429
562
  setGroundY(positionY);
@@ -444,39 +577,41 @@ export function createGlide(
444
577
  'opacity',
445
578
  String(0.12 * Math.max(0.15, 1 - displayHeight / 140)),
446
579
  );
447
- const rig = bodyRig(displayPose, settings, shape, reaction, rigPoints);
580
+ const rig = bodyRig(displayPose, settings, shape, rigReaction, rigPoints);
448
581
  setAttribute(body, 'd', roundedPath(rig.points));
449
582
  const head = rig.head;
450
583
  const [headX, headY] = head.point(
451
584
  80 +
452
585
  shape.eyeX * displayPose.facing +
453
- 3 * (pose.look - pose.facing) +
586
+ 3 * (inDepth ? displayPose.look - 1 : pose.look - pose.facing) +
454
587
  displayPose.facing * crawlReach(pose, settings) +
455
- settings.softness * pose.lean * 8,
588
+ settings.softness * displayPose.lean * 8,
456
589
  shape.eyeY + pose.crawl * settings.softness * pose.energy * 12,
457
590
  );
458
591
  const compressed = compressPoint(
459
592
  headX,
460
593
  headY,
461
- gsap.utils.clamp(-0.2, 0.45, pose.compression + reaction.compression),
594
+ gsap.utils.clamp(-0.2, 0.45, pose.compression + rigReaction.compression),
462
595
  );
463
596
  const [deformedX, deformedY] = deformPoint(
464
597
  ...compressed,
465
- reaction,
598
+ rigReaction,
466
599
  rig.bodyHeight,
467
600
  shape.eyeX * displayPose.facing,
468
601
  );
469
602
  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,
603
+ deformedX * (1 - rigReaction.melt) +
604
+ (80 + shape.eyeX * displayPose.facing * 0.3) * rigReaction.melt,
605
+ deformedY * (1 - rigReaction.melt) + 116 * rigReaction.melt,
606
+ rigReaction.roll * displayPose.facing,
474
607
  );
475
608
  const faceX =
476
- 80 + (eyeX - rig.sideOffset - 80) * (1 + reaction.impact * 0.3);
477
- const faceY = 128 + (eyeY - rig.floorOffset - 128) * (1 - reaction.impact);
609
+ 80 + (eyeX - rig.sideOffset - 80) * (1 + rigReaction.impact * 0.3);
610
+ const faceY =
611
+ 128 + (eyeY - rig.floorOffset - 128) * (1 - rigReaction.impact);
478
612
  const faceAngle =
479
- head.angle * (1 - reaction.melt) + reaction.roll * displayPose.facing;
613
+ head.angle * (1 - rigReaction.melt) +
614
+ rigReaction.roll * displayPose.facing;
480
615
  setAttribute(
481
616
  eyes,
482
617
  'transform',
@@ -499,16 +634,32 @@ export function createGlide(
499
634
  const y = anchor.x * Math.sin(angle) + anchor.y * Math.cos(angle);
500
635
  setAttribute(attachment, 'transform', `translate(${x} ${y})`);
501
636
  }
637
+ if (onFrame) {
638
+ frameTurn.lookX = reaction.lookX + reaction.gazeHeadX;
639
+ frameTurn.lookY = reaction.lookY + reaction.gazeHeadY;
640
+ frameTurn.turn = reaction.turn;
641
+ frameTurn.facing = pose.facing;
642
+ frameTurn.spin = reaction.spin;
643
+ onFrame(
644
+ rig.points,
645
+ faceX,
646
+ faceY,
647
+ faceAngle,
648
+ displayPose.facing,
649
+ displayHeight,
650
+ frameTurn,
651
+ );
652
+ }
502
653
  setAttribute(eyes, 'opacity', String(1 - reaction.hideEyes));
503
654
  for (const [eye, closed, blink] of [
504
- [leftEye, leftClosed, reaction.blinkLeft],
505
- [rightEye, rightClosed, reaction.blinkRight],
655
+ [leftEye, leftClosed, rigReaction.blinkLeft],
656
+ [rightEye, rightClosed, rigReaction.blinkRight],
506
657
  ] as const) {
507
658
  const openness = Math.max(0, 1 - blink);
508
659
  setAttribute(
509
660
  eye,
510
661
  'transform',
511
- `translate(${reaction.lookX} ${reaction.lookY}) scale(1 ${openness})`,
662
+ `translate(${rigReaction.lookX} ${rigReaction.lookY}) scale(1 ${openness})`,
512
663
  );
513
664
  // Crossfade into a closed lid rather than making the eye disappear.
514
665
  const visible = Math.min(1, openness * 4);
@@ -517,7 +668,7 @@ export function createGlide(
517
668
  setAttribute(
518
669
  closed,
519
670
  'transform',
520
- `translate(${reaction.lookX} ${reaction.lookY})`,
671
+ `translate(${rigReaction.lookX} ${rigReaction.lookY})`,
521
672
  );
522
673
  }
523
674
  }
@@ -815,7 +966,7 @@ export function createGlide(
815
966
  settings = next;
816
967
  reducedMotion = reduced;
817
968
  activity = nextActivity === 'idle' && !nextIdle ? false : nextActivity;
818
- if (reduced) activityMotion.snapLaptop(activity === 'working');
969
+ if (reduced) activityMotion.snapProps(activity);
819
970
  if (reduced && emote) {
820
971
  emote = null;
821
972
  onEmoteComplete();
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
+ }