@pretty-chitty/core 1.2.17 → 2.0.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.
Files changed (170) hide show
  1. package/dist/components/ClientTrustMatchViewer.d.ts +14 -1
  2. package/dist/components/ClientTrustMatchViewer.d.ts.map +1 -1
  3. package/dist/components/ClientTrustMatchViewer.js +25 -2
  4. package/dist/components/ClientTrustMatchViewer.js.map +1 -1
  5. package/dist/components/DemoWrapper.d.ts.map +1 -1
  6. package/dist/components/DemoWrapper.js +4 -11
  7. package/dist/components/DemoWrapper.js.map +1 -1
  8. package/dist/components/Gallery/BuiltItem.d.ts.map +1 -1
  9. package/dist/components/Gallery/BuiltItem.js +3 -0
  10. package/dist/components/Gallery/BuiltItem.js.map +1 -1
  11. package/dist/components/Gallery/GalleryController.d.ts.map +1 -1
  12. package/dist/components/Gallery/GalleryController.js +3 -1
  13. package/dist/components/Gallery/GalleryController.js.map +1 -1
  14. package/dist/components/PanelSpark.js +1 -1
  15. package/dist/components/PlayerImage.d.ts.map +1 -1
  16. package/dist/components/PlayerImage.js +21 -1
  17. package/dist/components/PlayerImage.js.map +1 -1
  18. package/dist/components/Playground.d.ts.map +1 -1
  19. package/dist/components/Playground.js +37 -11
  20. package/dist/components/Playground.js.map +1 -1
  21. package/dist/components/TokenizedMessage.d.ts +2 -6
  22. package/dist/components/TokenizedMessage.d.ts.map +1 -1
  23. package/dist/components/TokenizedMessage.js +1 -35
  24. package/dist/components/TokenizedMessage.js.map +1 -1
  25. package/dist/components/TopBarPlayers.d.ts.map +1 -1
  26. package/dist/components/TopBarPlayers.js +1 -1
  27. package/dist/components/TopBarPlayers.js.map +1 -1
  28. package/dist/game/Chit.js +2 -2
  29. package/dist/game/Chit.js.map +1 -1
  30. package/dist/game/ConnectionTransport.d.ts +3 -0
  31. package/dist/game/ConnectionTransport.d.ts.map +1 -1
  32. package/dist/game/ConnectionTransport.js +13 -4
  33. package/dist/game/ConnectionTransport.js.map +1 -1
  34. package/dist/game/Game.d.ts +8 -1
  35. package/dist/game/Game.d.ts.map +1 -1
  36. package/dist/game/Match.d.ts +66 -0
  37. package/dist/game/Match.d.ts.map +1 -1
  38. package/dist/game/Match.js +151 -3
  39. package/dist/game/Match.js.map +1 -1
  40. package/dist/game/MatchStorage.d.ts +8 -1
  41. package/dist/game/MatchStorage.d.ts.map +1 -1
  42. package/dist/game/MatchStorage.js +11 -3
  43. package/dist/game/MatchStorage.js.map +1 -1
  44. package/dist/game/Pick.d.ts +14 -0
  45. package/dist/game/Pick.d.ts.map +1 -1
  46. package/dist/game/Pick.js +15 -0
  47. package/dist/game/Pick.js.map +1 -1
  48. package/dist/game/PlayerChit.d.ts +4 -0
  49. package/dist/game/PlayerChit.d.ts.map +1 -1
  50. package/dist/game/PlayerChit.js +8 -2
  51. package/dist/game/PlayerChit.js.map +1 -1
  52. package/dist/game/PlayerInfo.d.ts +8 -0
  53. package/dist/game/PlayerInfo.d.ts.map +1 -1
  54. package/dist/game/PlayerInfo.js +6 -3
  55. package/dist/game/PlayerInfo.js.map +1 -1
  56. package/dist/game/PlayerPromptStatusChit.d.ts.map +1 -1
  57. package/dist/game/PlayerPromptStatusChit.js +3 -1
  58. package/dist/game/PlayerPromptStatusChit.js.map +1 -1
  59. package/dist/game/Turn.d.ts +11 -2
  60. package/dist/game/Turn.d.ts.map +1 -1
  61. package/dist/game/Turn.js +118 -68
  62. package/dist/game/Turn.js.map +1 -1
  63. package/dist/game/TurnState.d.ts +8 -0
  64. package/dist/game/TurnState.d.ts.map +1 -1
  65. package/dist/game/TurnState.js +7 -0
  66. package/dist/game/TurnState.js.map +1 -1
  67. package/dist/game/ai/AiClientPrompts.d.ts +160 -0
  68. package/dist/game/ai/AiClientPrompts.d.ts.map +1 -0
  69. package/dist/game/ai/AiClientPrompts.js +525 -0
  70. package/dist/game/ai/AiClientPrompts.js.map +1 -0
  71. package/dist/game/ai/AiLiveView.d.ts +2 -0
  72. package/dist/game/ai/AiLiveView.d.ts.map +1 -0
  73. package/dist/game/ai/AiLiveView.js +48 -0
  74. package/dist/game/ai/AiLiveView.js.map +1 -0
  75. package/dist/game/ai/AiPlayerView.d.ts +2 -0
  76. package/dist/game/ai/AiPlayerView.d.ts.map +1 -0
  77. package/dist/game/ai/AiPlayerView.js +89 -0
  78. package/dist/game/ai/AiPlayerView.js.map +1 -0
  79. package/dist/game/ai/connectAiPlayer.d.ts +43 -0
  80. package/dist/game/ai/connectAiPlayer.d.ts.map +1 -0
  81. package/dist/game/ai/connectAiPlayer.js +58 -0
  82. package/dist/game/ai/connectAiPlayer.js.map +1 -0
  83. package/dist/game/ai/defineAi.d.ts +119 -0
  84. package/dist/game/ai/defineAi.d.ts.map +1 -0
  85. package/dist/game/ai/defineAi.js +122 -0
  86. package/dist/game/ai/defineAi.js.map +1 -0
  87. package/dist/game/ai/simulateMatches.d.ts +62 -0
  88. package/dist/game/ai/simulateMatches.d.ts.map +1 -0
  89. package/dist/game/ai/simulateMatches.js +108 -0
  90. package/dist/game/ai/simulateMatches.js.map +1 -0
  91. package/dist/game/badAiTransport/BadAIClientPrompts.d.ts +3 -0
  92. package/dist/game/badAiTransport/BadAIClientPrompts.d.ts.map +1 -1
  93. package/dist/game/badAiTransport/BadAIClientPrompts.js +3 -0
  94. package/dist/game/badAiTransport/BadAIClientPrompts.js.map +1 -1
  95. package/dist/hooks/useTokenMap.d.ts +2 -4
  96. package/dist/hooks/useTokenMap.d.ts.map +1 -1
  97. package/dist/hooks/useTokenMap.js +2 -5
  98. package/dist/hooks/useTokenMap.js.map +1 -1
  99. package/dist/hooks/useWebGlRenderer.d.ts +1 -0
  100. package/dist/hooks/useWebGlRenderer.d.ts.map +1 -1
  101. package/dist/hooks/useWebGlRenderer.js +33 -21
  102. package/dist/hooks/useWebGlRenderer.js.map +1 -1
  103. package/dist/index.d.ts +21 -1
  104. package/dist/index.d.ts.map +1 -1
  105. package/dist/index.js +8 -1
  106. package/dist/index.js.map +1 -1
  107. package/dist/utilities/CanvasStack/CanvasOperations.d.ts +15 -1
  108. package/dist/utilities/CanvasStack/CanvasOperations.d.ts.map +1 -1
  109. package/dist/utilities/CanvasStack/CanvasOperations.js +65 -6
  110. package/dist/utilities/CanvasStack/CanvasOperations.js.map +1 -1
  111. package/dist/utilities/CanvasStack/CanvasStack.d.ts +18 -1
  112. package/dist/utilities/CanvasStack/CanvasStack.d.ts.map +1 -1
  113. package/dist/utilities/CanvasStack/CanvasStack.js +119 -6
  114. package/dist/utilities/CanvasStack/CanvasStack.js.map +1 -1
  115. package/dist/utilities/CanvasStack/PlayerCanvas.d.ts +2 -1
  116. package/dist/utilities/CanvasStack/PlayerCanvas.d.ts.map +1 -1
  117. package/dist/utilities/CanvasStack/PlayerCanvas.js +3 -2
  118. package/dist/utilities/CanvasStack/PlayerCanvas.js.map +1 -1
  119. package/dist/utilities/CanvasStack/ReactCanvas.d.ts +2 -1
  120. package/dist/utilities/CanvasStack/ReactCanvas.d.ts.map +1 -1
  121. package/dist/utilities/CanvasStack/ReactCanvas.js +2 -2
  122. package/dist/utilities/CanvasStack/ReactCanvas.js.map +1 -1
  123. package/dist/utilities/ParameterizedCanvas.d.ts +1 -0
  124. package/dist/utilities/ParameterizedCanvas.d.ts.map +1 -1
  125. package/dist/utilities/ParameterizedCanvas.js +4 -1
  126. package/dist/utilities/ParameterizedCanvas.js.map +1 -1
  127. package/dist/utilities/TokenizedText.d.ts +49 -0
  128. package/dist/utilities/TokenizedText.d.ts.map +1 -0
  129. package/dist/utilities/TokenizedText.js +47 -0
  130. package/dist/utilities/TokenizedText.js.map +1 -0
  131. package/package.json +1 -1
  132. package/src/library/components/ClientTrustMatchViewer.tsx +32 -2
  133. package/src/library/components/DemoWrapper.tsx +4 -12
  134. package/src/library/components/Gallery/BuiltItem.ts +4 -0
  135. package/src/library/components/Gallery/GalleryController.ts +3 -1
  136. package/src/library/components/PanelSpark.tsx +1 -1
  137. package/src/library/components/PlayerImage.tsx +26 -2
  138. package/src/library/components/Playground.tsx +77 -12
  139. package/src/library/components/TokenizedMessage.tsx +2 -63
  140. package/src/library/components/TopBarPlayers.tsx +6 -1
  141. package/src/library/game/Chit.ts +2 -2
  142. package/src/library/game/ConnectionTransport.ts +12 -3
  143. package/src/library/game/Game.ts +9 -1
  144. package/src/library/game/Match.ts +162 -3
  145. package/src/library/game/MatchStorage.ts +14 -4
  146. package/src/library/game/Pick.ts +20 -0
  147. package/src/library/game/PlayerChit.ts +10 -3
  148. package/src/library/game/PlayerInfo.ts +13 -3
  149. package/src/library/game/PlayerPromptStatusChit.ts +3 -1
  150. package/src/library/game/Turn.ts +131 -76
  151. package/src/library/game/TurnState.ts +8 -0
  152. package/src/library/game/ai/AI_GUIDE.md +434 -0
  153. package/src/library/game/ai/AiClientPrompts.ts +681 -0
  154. package/src/library/game/ai/AiLiveView.ts +63 -0
  155. package/src/library/game/ai/AiPlayerView.ts +112 -0
  156. package/src/library/game/ai/ai.test.ts +475 -0
  157. package/src/library/game/ai/connectAiPlayer.ts +88 -0
  158. package/src/library/game/ai/defineAi.ts +230 -0
  159. package/src/library/game/ai/simulateMatches.ts +172 -0
  160. package/src/library/game/badAiTransport/BadAIClientPrompts.ts +3 -0
  161. package/src/library/hooks/useTokenMap.ts +2 -6
  162. package/src/library/hooks/useWebGlRenderer.tsx +44 -24
  163. package/src/library/index.ts +34 -2
  164. package/src/library/utilities/CanvasStack/CanvasOperations.tsx +87 -17
  165. package/src/library/utilities/CanvasStack/CanvasStack.ts +119 -5
  166. package/src/library/utilities/CanvasStack/PlayerCanvas.tsx +5 -2
  167. package/src/library/utilities/CanvasStack/ReactCanvas.tsx +2 -2
  168. package/src/library/utilities/ParameterizedCanvas.ts +5 -1
  169. package/src/library/utilities/TokenizedText.test.ts +32 -0
  170. package/src/library/utilities/TokenizedText.ts +97 -0
@@ -11,6 +11,8 @@ export { Chit } from "./game/Chit";
11
11
  export { Turn } from "./game/Turn";
12
12
  /** @group Core Game Elements */
13
13
  export { Pick, ButtonPick, ChitPick, DragTarget, DragPick } from "./game/Pick";
14
+ /** @group Supporting Types */
15
+ export type { PickAiTag } from "./game/Pick";
14
16
  /** @group Core Game Elements */
15
17
  export { GameTheme } from "./game/GameTheme";
16
18
  /** @group Chits */
@@ -35,6 +37,31 @@ export { ChildOutlet, NonEditable, Ordered, Selectable } from "./utilities/Annot
35
37
  /** @group Chit Annotations */
36
38
  export type { SelectableChoice, SelectableConfig, SelectablePropertyInfo } from "./utilities/Annotations";
37
39
 
40
+ /** @group AI */
41
+ export { defineAi } from "./game/ai/defineAi";
42
+ /** @group AI */
43
+ export type {
44
+ GameAi,
45
+ AiRule,
46
+ AiScore,
47
+ AiContext,
48
+ AiOption,
49
+ AiChitOption,
50
+ AiDragOption,
51
+ AiButtonOption,
52
+ AiPickInfo,
53
+ } from "./game/ai/defineAi";
54
+ /** @group AI */
55
+ export { connectAiPlayer } from "./game/ai/connectAiPlayer";
56
+ /** @group AI */
57
+ export type { ConnectAiPlayerOptions, AiPlayerHandle } from "./game/ai/connectAiPlayer";
58
+ /** @group AI */
59
+ export type { AiPlayerOptions, AiPlayerStats, AiDecision, AiMemoryStore } from "./game/ai/AiClientPrompts";
60
+ /** @group AI */
61
+ export { simulateMatches } from "./game/ai/simulateMatches";
62
+ /** @group AI */
63
+ export type { SimulateMatchesOptions, SimulatedMatch, SimulationReport } from "./game/ai/simulateMatches";
64
+
38
65
  /** @group Buttons */
39
66
  export { GameButton, DynamicGameButton, ToggleGalleryButton } from "./game/GameButton";
40
67
 
@@ -42,6 +69,9 @@ export { GameButton, DynamicGameButton, ToggleGalleryButton } from "./game/GameB
42
69
  export { ParameterizedCanvas } from "./utilities/ParameterizedCanvas";
43
70
  /** @group 2D Rendering */
44
71
  export { StaticImage } from "./utilities/StaticImage";
72
+
73
+ export { tokenizedMessageToText, buildTokenMap, parseMessageTokens } from "./utilities/TokenizedText";
74
+ export type { TokenDefinition, TokenMap } from "./utilities/TokenizedText";
45
75
  /** @group 2D Rendering */
46
76
  export * as ReactCanvas from "./utilities/CanvasStack/ReactCanvas";
47
77
  /** @group 2D Rendering */
@@ -81,7 +111,7 @@ export type { Stage } from "./game/GameDeckChit";
81
111
  /** @group Supporting Types */
82
112
  export { PlayerInfo } from "./game/PlayerInfo";
83
113
  /** @group Supporting Types */
84
- export type { IPlayerInfo } from "./game/PlayerInfo";
114
+ export type { IPlayerInfo, AiSeatInfo } from "./game/PlayerInfo";
85
115
  /** @internal */
86
116
  /** @group Supporting Types */
87
117
  export { MatchViewer } from "./components/MatchViewer";
@@ -90,7 +120,9 @@ export { MatchViewer } from "./components/MatchViewer";
90
120
  export { DemoWrapper } from "./components/DemoWrapper";
91
121
  /** @internal */
92
122
  /** @group Supporting Types */
93
- export { Match } from "./game/Match";
123
+ export { Match, MatchAiControls } from "./game/Match";
124
+ /** @group AI */
125
+ export type { SeatAiPlayersOptions } from "./game/Match";
94
126
  /** @internal */
95
127
  /** @group Supporting Types */
96
128
  export { Connection } from "./game/Connection";
@@ -16,6 +16,8 @@ export abstract class CanvasOperation {
16
16
  getImage: GetImage,
17
17
  reportOutlet: ReportOutlet,
18
18
  ): void;
19
+
20
+ abstract benefitsFromMipMap(): boolean;
19
21
  }
20
22
 
21
23
  export type RenderCallback = (context: CanvasRenderingContext2D, x: number, y: number, w: number, h: number) => void;
@@ -25,6 +27,10 @@ export class LayeredCanvasOperation extends CanvasOperation {
25
27
  super();
26
28
  }
27
29
 
30
+ override benefitsFromMipMap() {
31
+ return this.layers.some((l) => l.benefitsFromMipMap());
32
+ }
33
+
28
34
  override render(
29
35
  context: CanvasRenderingContext2D,
30
36
  bounds: RenderBounds,
@@ -43,6 +49,10 @@ export class ColorCanvasOperation extends CanvasOperation {
43
49
  super();
44
50
  }
45
51
 
52
+ override benefitsFromMipMap() {
53
+ return false;
54
+ }
55
+
46
56
  override render(
47
57
  context: CanvasRenderingContext2D,
48
58
  bounds: RenderBounds,
@@ -67,6 +77,10 @@ export class VerticalStackCanvasOperation extends CanvasOperation {
67
77
  super();
68
78
  }
69
79
 
80
+ override benefitsFromMipMap() {
81
+ return this.items.some((i) => i.layer?.benefitsFromMipMap() ?? false);
82
+ }
83
+
70
84
  override render(
71
85
  context: CanvasRenderingContext2D,
72
86
  bounds: RenderBounds,
@@ -90,6 +104,10 @@ export class HorizontalStackCanvasOperation extends CanvasOperation {
90
104
  super();
91
105
  }
92
106
 
107
+ override benefitsFromMipMap() {
108
+ return this.items.some((i) => i.layer?.benefitsFromMipMap() ?? false);
109
+ }
110
+
93
111
  override render(
94
112
  context: CanvasRenderingContext2D,
95
113
  bounds: RenderBounds,
@@ -116,6 +134,10 @@ export class OutletCanvasOperation extends CanvasOperation {
116
134
  super();
117
135
  }
118
136
 
137
+ override benefitsFromMipMap() {
138
+ return this.child.benefitsFromMipMap();
139
+ }
140
+
119
141
  override render(
120
142
  context: CanvasRenderingContext2D,
121
143
  bounds: RenderBounds,
@@ -142,6 +164,10 @@ export class PadCanvasOperation extends CanvasOperation {
142
164
  super();
143
165
  }
144
166
 
167
+ override benefitsFromMipMap() {
168
+ return this.item.benefitsFromMipMap();
169
+ }
170
+
145
171
  override render(
146
172
  context: CanvasRenderingContext2D,
147
173
  bounds: RenderBounds,
@@ -190,6 +216,10 @@ export class MarkdownCanvasOperation extends CanvasOperation {
190
216
  super();
191
217
  }
192
218
 
219
+ override benefitsFromMipMap() {
220
+ return true;
221
+ }
222
+
193
223
  public height = 0;
194
224
  override render(context: CanvasRenderingContext2D, bounds: RenderBounds, getImage: GetImage) {
195
225
  const iconMap: {
@@ -252,6 +282,10 @@ export class TextCanvasOperation extends CanvasOperation {
252
282
  super();
253
283
  }
254
284
 
285
+ override benefitsFromMipMap() {
286
+ return true;
287
+ }
288
+
255
289
  private makeFont(): string {
256
290
  const fontSize = this.options.fontSize ?? 16;
257
291
  const fontFamily = this.options.fontFamily ?? GameTheme.defaultFontFamily;
@@ -381,6 +415,10 @@ export class ImageCanvasOperation extends CanvasOperation {
381
415
  super();
382
416
  }
383
417
 
418
+ override benefitsFromMipMap() {
419
+ return false;
420
+ }
421
+
384
422
  draw(
385
423
  context: CanvasRenderingContext2D,
386
424
  bounds: RenderBounds,
@@ -554,17 +592,7 @@ export class ImageCanvasOperation extends CanvasOperation {
554
592
  if (swiF > inset * 2 && shiF > inset * 2) {
555
593
  const prevSmoothing = context.imageSmoothingEnabled;
556
594
  context.imageSmoothingEnabled = false;
557
- context.drawImage(
558
- source as any,
559
- sxiF + inset,
560
- syiF + inset,
561
- swiF - inset * 2,
562
- shiF - inset * 2,
563
- x,
564
- y,
565
- w,
566
- h,
567
- );
595
+ context.drawImage(source as any, sxiF + inset, syiF + inset, swiF - inset * 2, shiF - inset * 2, x, y, w, h);
568
596
  context.imageSmoothingEnabled = prevSmoothing;
569
597
  }
570
598
  }
@@ -592,10 +620,17 @@ export class ImageCanvasOperation extends CanvasOperation {
592
620
  }
593
621
 
594
622
  export class PlayerCanvasOperation extends CanvasOperation {
595
- constructor(private player: PlayerChit) {
623
+ constructor(
624
+ private player: PlayerChit,
625
+ private colorBlend: number = 0,
626
+ ) {
596
627
  super();
597
628
  }
598
629
 
630
+ override benefitsFromMipMap() {
631
+ return false;
632
+ }
633
+
599
634
  drawFill(context: CanvasRenderingContext2D, bounds: RenderBounds, sourceImage: HTMLImageElement) {
600
635
  const x = bounds.x,
601
636
  y = bounds.y,
@@ -611,17 +646,44 @@ export class PlayerCanvasOperation extends CanvasOperation {
611
646
  sh = sourceImage.height;
612
647
 
613
648
  if (targetAspect > sourceAspect) {
614
- // Target is wider than source; adjust source height and y to maintain aspect ratio
615
649
  sh = sw / targetAspect;
616
- sy += (sourceImage.height - sh) / 2; // Center vertically in source
650
+ sy += (sourceImage.height - sh) / 2;
617
651
  } else {
618
- // Target is taller than source; adjust source width and x to maintain aspect ratio
619
652
  sw = sh * targetAspect;
620
- sx += (sourceImage.width - sw) / 2; // Center horizontally in source
653
+ sx += (sourceImage.width - sw) / 2;
654
+ }
655
+
656
+ if (this.colorBlend < 1) {
657
+ context.globalAlpha = 1 - this.colorBlend;
658
+ context.drawImage(sourceImage, sx, sy, sw, sh, x, y, w, h);
621
659
  }
622
660
 
661
+ if (this.colorBlend <= 0) return;
662
+
663
+ // Build tinted version on an offscreen canvas using composite blend modes
664
+ const pw = Math.ceil(w),
665
+ ph = Math.ceil(h);
666
+ const offscreen = document.createElement("canvas");
667
+ offscreen.width = pw;
668
+ offscreen.height = ph;
669
+ const offCtx = offscreen.getContext("2d")!;
670
+
671
+ // Grayscale + slight contrast boost via CSS filter
672
+ offCtx.filter = "grayscale(1) contrast(2)";
673
+ offCtx.drawImage(sourceImage, sx, sy, sw, sh, 0, 0, pw, ph);
674
+ offCtx.filter = "none";
675
+
676
+ // For dark player colors, screen blend makes dark areas take the color while whites stay white.
677
+ // For light player colors, multiply blend makes white areas take the color while blacks stay black.
678
+ offCtx.globalCompositeOperation = Colors.default(this.player.color).lightness() < 40 ? "screen" : "multiply";
679
+ offCtx.fillStyle = this.player.color;
680
+ offCtx.fillRect(0, 0, pw, ph);
681
+ offCtx.globalCompositeOperation = "source-over";
682
+
683
+ // Overlay the tinted version at colorBlend strength
684
+ context.globalAlpha = this.colorBlend;
685
+ context.drawImage(offscreen, x, y, w, h);
623
686
  context.globalAlpha = 1;
624
- context.drawImage(sourceImage, sx, sy, sw, sh, x, y, w, h);
625
687
  }
626
688
 
627
689
  override render(
@@ -648,6 +710,10 @@ export class CallbackCanvasOperation extends CanvasOperation {
648
710
  super();
649
711
  }
650
712
 
713
+ override benefitsFromMipMap() {
714
+ return false;
715
+ }
716
+
651
717
  override render(
652
718
  context: CanvasRenderingContext2D,
653
719
  bounds: RenderBounds,
@@ -670,6 +736,10 @@ export class RoundedRectCanvasOperation extends CanvasOperation {
670
736
  super();
671
737
  }
672
738
 
739
+ override benefitsFromMipMap() {
740
+ return this.children.some((c) => c.benefitsFromMipMap());
741
+ }
742
+
673
743
  override render(
674
744
  context: CanvasRenderingContext2D,
675
745
  bounds: RenderBounds,
@@ -39,6 +39,9 @@ export class CanvasStack implements IUpdatingCanvas {
39
39
  private static imageCache = new ImageCache(50); // 50? Is that good? No idea.
40
40
  private _outlets: { [id: string]: Coord } = {};
41
41
 
42
+ private _mipCanvases: HTMLCanvasElement[] = [];
43
+ private _mipContexts: CanvasRenderingContext2D[] = [];
44
+
42
45
  public createdAt = Date.now();
43
46
 
44
47
  public get hasBuiltTexture(): boolean {
@@ -90,6 +93,7 @@ export class CanvasStack implements IUpdatingCanvas {
90
93
  this._outlets[id] = coords;
91
94
  },
92
95
  );
96
+ this._renderMipCanvases();
93
97
  this.cbs.forEach((cb) => cb());
94
98
  }
95
99
 
@@ -98,7 +102,10 @@ export class CanvasStack implements IUpdatingCanvas {
98
102
  this.canvas!.title = `Disposed, mat ${this._material?.uuid} texture ${this._texture?.uuid}`;
99
103
  this.canvas = undefined;
100
104
  this.context = undefined;
105
+ this._mipCanvases = [];
106
+ this._mipContexts = [];
101
107
  CanvasStack._liveStacks.delete(this);
108
+ CanvasStack._pendingMips.delete(this);
102
109
 
103
110
  if (this._material) {
104
111
  this._material.dispose();
@@ -114,6 +121,7 @@ export class CanvasStack implements IUpdatingCanvas {
114
121
  public width: number,
115
122
  public height: number,
116
123
  public operation: CanvasOperation,
124
+ private _mipLevelsOverride?: number,
117
125
  ) {
118
126
  this.canvas = document.createElement("canvas");
119
127
  this.canvas.width = width;
@@ -129,6 +137,113 @@ export class CanvasStack implements IUpdatingCanvas {
129
137
  CanvasStack.ensureContextRestoreSubscription();
130
138
 
131
139
  this.render();
140
+ if (this.mipMaps > 0) CanvasStack.scheduleMips(this);
141
+ }
142
+
143
+ get mipMaps(): number {
144
+ if (this._mipLevelsOverride !== undefined) return this._mipLevelsOverride;
145
+ return this.operation.benefitsFromMipMap() ? 2 : 0;
146
+ }
147
+
148
+ // Faces with text get hand-drawn mip levels: text rasterised at the small size is sharper than GPU box-filtering.
149
+ // Building that chain (a canvas per level, down to 1×1) for every face while the table loads is what stalled
150
+ // phones — Safari queues 2D drawing in its GPU process and the first texture upload waits for all of it (8 s on an
151
+ // iPhone for ~950 canvases). So every texture starts with GPU-generated mipmaps, and once canvas creation has gone
152
+ // quiet the faces that benefit get their custom chain a few per frame, swapped in by a re-upload. Plain images
153
+ // (mipMaps 0) never used the chain: the GPU builds theirs.
154
+ private static _pendingMips = new Set<CanvasStack>();
155
+ private static _mipTimer: ReturnType<typeof setTimeout> | undefined;
156
+ private static _firstPendingAt = 0;
157
+ private static readonly MIP_QUIET_MS = 1000; // build once no new canvas has appeared for this long…
158
+ private static readonly MIP_MAX_WAIT_MS = 5000; // …or this long after the first one started waiting
159
+ private static readonly MIP_FRAME_BUDGET_MS = 6;
160
+
161
+ private static scheduleMips(stack: CanvasStack) {
162
+ if (CanvasStack._pendingMips.size === 0) CanvasStack._firstPendingAt = Date.now();
163
+ CanvasStack._pendingMips.add(stack);
164
+ if (CanvasStack._mipTimer) clearTimeout(CanvasStack._mipTimer);
165
+ const waited = Date.now() - CanvasStack._firstPendingAt;
166
+ const delay = Math.max(0, Math.min(CanvasStack.MIP_QUIET_MS, CanvasStack.MIP_MAX_WAIT_MS - waited));
167
+ CanvasStack._mipTimer = setTimeout(() => {
168
+ CanvasStack._mipTimer = undefined;
169
+ requestAnimationFrame(CanvasStack.buildPendingMips);
170
+ }, delay);
171
+ }
172
+
173
+ private static buildPendingMips = () => {
174
+ const start = performance.now();
175
+ for (const stack of CanvasStack._pendingMips) {
176
+ CanvasStack._pendingMips.delete(stack);
177
+ if (stack.canvas) stack._buildMips();
178
+ if (performance.now() - start > CanvasStack.MIP_FRAME_BUDGET_MS) break;
179
+ }
180
+ if (CanvasStack._pendingMips.size > 0) requestAnimationFrame(CanvasStack.buildPendingMips);
181
+ };
182
+
183
+ private _buildMips() {
184
+ this._initMipCanvases();
185
+ if (this._texture) {
186
+ this._applyMipmaps(this._texture);
187
+ this._texture.needsUpdate = true;
188
+ CanvasStack.disposer.notifyChange(this._texture.uuid);
189
+ }
190
+ }
191
+
192
+ /** Custom levels once the chain is built (same level count as GPU generation, so the re-upload reuses the storage). */
193
+ private _applyMipmaps(texture: Texture) {
194
+ if (this._mipCanvases.length > 0) {
195
+ texture.generateMipmaps = false;
196
+ // mipmaps[i] is uploaded as WebGL level i. Level 0 must be the base
197
+ // canvas; levels 1..N are the custom-rendered smaller canvases.
198
+ texture.mipmaps = [this.canvas!, ...this._mipCanvases];
199
+ } else {
200
+ texture.generateMipmaps = true;
201
+ texture.mipmaps = [];
202
+ }
203
+ }
204
+
205
+ private _initMipCanvases() {
206
+ this._mipCanvases = [];
207
+ this._mipContexts = [];
208
+ // Build the full mipmap chain down to 1×1. WebGL requires a complete chain
209
+ // when using a mipmap filter — a partial chain makes the texture incomplete
210
+ // and WebGL renders it as transparent.
211
+ let w = this.width;
212
+ let h = this.height;
213
+ while (w > 1 || h > 1) {
214
+ w = Math.max(1, Math.floor(w / 2));
215
+ h = Math.max(1, Math.floor(h / 2));
216
+ const c = document.createElement("canvas");
217
+ c.width = w;
218
+ c.height = h;
219
+ this._mipCanvases.push(c);
220
+ this._mipContexts.push(c.getContext("2d")!);
221
+ }
222
+ this._renderMipCanvases();
223
+ }
224
+
225
+ private _renderMipCanvases() {
226
+ const noop = () => {};
227
+ const numCustomLevels = this.mipMaps;
228
+ for (let i = 0; i < this._mipCanvases.length; i++) {
229
+ const ctx = this._mipContexts[i];
230
+ const c = this._mipCanvases[i];
231
+ if (i < numCustomLevels) {
232
+ // Custom render: canvas scale so text is rasterized natively at the
233
+ // smaller effective size rather than downsampled from the base canvas.
234
+ const scale = c.width / this.width;
235
+ ctx.save();
236
+ ctx.scale(scale, scale);
237
+ ctx.clearRect(0, 0, this.width, this.height);
238
+ this.operation.render(ctx, { x: 0, y: 0, w: this.width, h: this.height }, this.loadUrl.bind(this), noop);
239
+ ctx.restore();
240
+ } else {
241
+ // Complete the chain by box-filtering down from the previous level.
242
+ const prev = i === 0 ? this.canvas! : this._mipCanvases[i - 1];
243
+ ctx.clearRect(0, 0, c.width, c.height);
244
+ ctx.drawImage(prev, 0, 0, c.width, c.height);
245
+ }
246
+ }
132
247
  }
133
248
 
134
249
  private static _liveStacks: Set<CanvasStack> = new Set();
@@ -175,18 +290,17 @@ export class CanvasStack implements IUpdatingCanvas {
175
290
  }
176
291
 
177
292
  if (!this._texture) {
178
- // WebGL1 only supports mipmaps on power-of-two textures, and these
179
- // canvases are arbitrarily sized. Skip mipmap generation outside WebGL2.
180
- const useMipmaps = getWebGlRendererInstance()?.isWebGL2 ?? false;
293
+ const wrapper = getWebGlRendererInstance();
181
294
  this._texture = new Texture(
182
295
  this.canvas,
183
296
  UVMapping,
184
297
  ClampToEdgeWrapping,
185
298
  ClampToEdgeWrapping,
186
299
  LinearFilter,
187
- useMipmaps ? LinearMipmapLinearFilter : LinearFilter,
300
+ LinearMipmapLinearFilter,
188
301
  );
189
- this._texture.generateMipmaps = useMipmaps;
302
+ this._applyMipmaps(this._texture);
303
+ this._texture.anisotropy = wrapper?.maxAnisotropy ?? 1;
190
304
  this._texture.needsUpdate = true;
191
305
  this._texture.colorSpace = SRGBColorSpace;
192
306
 
@@ -7,11 +7,14 @@ export class PlayerCanvas extends ParameterizedCanvas {
7
7
  width = 50;
8
8
  height = 50;
9
9
 
10
- constructor(private player: PlayerChit) {
10
+ constructor(
11
+ private player: PlayerChit,
12
+ private colorBlend?: number,
13
+ ) {
11
14
  super();
12
15
  }
13
16
 
14
17
  protected render() {
15
- return <Player player={this.player} />;
18
+ return <Player player={this.player} colorBlend={this.colorBlend} />;
16
19
  }
17
20
  }
@@ -206,8 +206,8 @@ export function Image({
206
206
  * @param args
207
207
  * @returns
208
208
  */
209
- export function Player({ player }: { player: PlayerChit }) {
210
- return <WrappedCanvasOperation operation={new PlayerCanvasOperation(player)} />;
209
+ export function Player({ player, colorBlend }: { player: PlayerChit; colorBlend?: number }) {
210
+ return <WrappedCanvasOperation operation={new PlayerCanvasOperation(player, colorBlend)} />;
211
211
  }
212
212
 
213
213
  /**
@@ -40,6 +40,10 @@ export abstract class ParameterizedCanvas extends ObjectWithProps {
40
40
  .join("___")}`;
41
41
  }
42
42
 
43
+ protected get mipLevels(): number | undefined {
44
+ return undefined;
45
+ }
46
+
43
47
  get(): IUpdatingCanvas {
44
48
  const signature = this.signature();
45
49
  let result = ParameterizedCanvas.lu[signature];
@@ -48,7 +52,7 @@ export abstract class ParameterizedCanvas extends ObjectWithProps {
48
52
  result = ParameterizedCanvas.lu[signature] = (() => {
49
53
  try {
50
54
  const ops = this.render();
51
- return new CanvasStack(this.width, this.height, unwrapCanvasNode(ops));
55
+ return new CanvasStack(this.width, this.height, unwrapCanvasNode(ops), this.mipLevels);
52
56
  } catch (e) {
53
57
  console.error(e);
54
58
  return new CanvasStack(this.width, this.height, new LayeredCanvasOperation([]));
@@ -0,0 +1,32 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { buildTokenMap, parseMessageTokens, tokenizedMessageToText } from "./TokenizedText";
3
+
4
+ describe("tokenizedMessageToText", () => {
5
+ const tokenMap = buildTokenMap(
6
+ { gold: { image: "gold.png", text: "gold" }, vp: { label: "VP", color: "#fff" }, iconOnly: { image: "x.png" } },
7
+ [{ playerId: "player0", name: "Josh", color: "#f00", imageUrl: "josh.png" }],
8
+ );
9
+
10
+ it("replaces player tokens with the player's name", () => {
11
+ expect(tokenizedMessageToText("Follow :player0:'s action", tokenMap)).toBe("Follow Josh's action");
12
+ });
13
+
14
+ it("prefers text, then label, and keeps unknown or image-only tokens as-is", () => {
15
+ expect(tokenizedMessageToText("Pay 2 :gold: for 1 :vp:", tokenMap)).toBe("Pay 2 gold for 1 VP");
16
+ expect(tokenizedMessageToText(":iconOnly: and :nope:", tokenMap)).toBe(":iconOnly: and :nope:");
17
+ });
18
+
19
+ it("gives the warning token a text form", () => {
20
+ expect(tokenizedMessageToText(":warning: Last round", tokenMap)).toBe("Warning: Last round");
21
+ });
22
+
23
+ it("leaves plain messages untouched", () => {
24
+ expect(tokenizedMessageToText("Waiting for turn to complete", tokenMap)).toBe("Waiting for turn to complete");
25
+ expect(tokenizedMessageToText("", tokenMap)).toBe("");
26
+ });
27
+
28
+ it("parses text runs and tokens in order", () => {
29
+ const parts = parseMessageTokens("a :player0: b", tokenMap);
30
+ expect(parts.map((p) => p.type)).toEqual(["text", "token", "text"]);
31
+ });
32
+ });
@@ -0,0 +1,97 @@
1
+ import { ImageSpec } from "./CanvasStack/CanvasOperations";
2
+
3
+ /**
4
+ * A `:token:` that can appear in game messages (prompts, log lines, etc.).
5
+ *
6
+ * `image`, `label` and `color` drive the "pretty" rendering in the UI. `text` is the plain-text stand-in used anywhere
7
+ * a message has to be pure text (match storage, match lists, notifications). When `text` is omitted the `label` is
8
+ * used, and when there is no label either the raw `:token:` is kept.
9
+ */
10
+ export interface TokenDefinition {
11
+ image?: string | ImageSpec;
12
+ label?: string;
13
+ color?: string;
14
+ /** Plain-text representation of this token, for places that cannot render images or styling. */
15
+ text?: string;
16
+ }
17
+
18
+ export type TokenMap = Record<string, TokenDefinition>;
19
+
20
+ export interface ParsedToken {
21
+ type: "token";
22
+ name: string;
23
+ definition?: TokenDefinition;
24
+ key: string;
25
+ }
26
+
27
+ export interface ParsedText {
28
+ type: "text";
29
+ content: string;
30
+ key: string;
31
+ }
32
+
33
+ export type ParsedElement = ParsedToken | ParsedText;
34
+
35
+ const TOKEN_REGEX = /:([a-zA-Z0-9_-]+):/g;
36
+
37
+ /** Splits a message into literal text runs and `:token:` references. */
38
+ export function parseMessageTokens(message: string, tokenMap: TokenMap): ParsedElement[] {
39
+ const elements: ParsedElement[] = [];
40
+ const regex = new RegExp(TOKEN_REGEX.source, "g");
41
+ let lastIndex = 0;
42
+ let match;
43
+
44
+ while ((match = regex.exec(message)) !== null) {
45
+ const tokenName = match[1];
46
+
47
+ if (match.index > lastIndex) {
48
+ elements.push({ type: "text", content: message.substring(lastIndex, match.index), key: `text-${lastIndex}` });
49
+ }
50
+
51
+ elements.push({ type: "token", name: tokenName, definition: tokenMap[tokenName], key: `token-${match.index}` });
52
+
53
+ lastIndex = match.index + match[0].length;
54
+ }
55
+
56
+ if (lastIndex < message.length) {
57
+ elements.push({ type: "text", content: message.substring(lastIndex), key: `text-${lastIndex}` });
58
+ }
59
+
60
+ return elements;
61
+ }
62
+
63
+ /** The plain-text form of a single token. */
64
+ export function tokenToText(name: string, definition?: TokenDefinition): string {
65
+ return definition?.text ?? definition?.label ?? `:${name}:`;
66
+ }
67
+
68
+ /**
69
+ * Converts a tokenized message into plain text by replacing every `:token:` with its text representation.
70
+ * Unknown tokens are left as-is.
71
+ */
72
+ export function tokenizedMessageToText(message: string, tokenMap: TokenMap): string {
73
+ return parseMessageTokens(message, tokenMap)
74
+ .map((el) => (el.type === "token" ? tokenToText(el.name, el.definition) : el.content))
75
+ .join("");
76
+ }
77
+
78
+ export interface TokenMapPlayer {
79
+ playerId: string;
80
+ name?: string;
81
+ color?: string;
82
+ imageUrl?: string;
83
+ }
84
+
85
+ /**
86
+ * Builds the full token map for a match: the game's own tokens plus one token per player (keyed by player id) and the
87
+ * built-in `:warning:` token. Shared by the UI hook and by server-side code so both agree on what a token means.
88
+ */
89
+ export function buildTokenMap(gameTokenMap: TokenMap | undefined, players: TokenMapPlayer[], defaultColor?: string): TokenMap {
90
+ const tokenMap: TokenMap = { ...(gameTokenMap ?? {}) };
91
+ players.forEach((p) => {
92
+ const name = p.name ?? "??";
93
+ tokenMap[p.playerId] = { label: name, text: name, color: p.color ?? defaultColor, image: p.imageUrl };
94
+ });
95
+ tokenMap["warning"] = { label: "⚠️", text: "Warning:" };
96
+ return tokenMap;
97
+ }