@pretty-chitty/core 1.2.10 → 1.2.16

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 (165) hide show
  1. package/README.md +17 -3
  2. package/dist/components/DemoWrapper.js +1 -1
  3. package/dist/components/DemoWrapper.js.map +1 -1
  4. package/dist/components/FullScreenGalleryDisplay.d.ts.map +1 -1
  5. package/dist/components/FullScreenGalleryDisplay.js +5 -1
  6. package/dist/components/FullScreenGalleryDisplay.js.map +1 -1
  7. package/dist/components/Gallery/AnimationController.d.ts +1 -0
  8. package/dist/components/Gallery/AnimationController.d.ts.map +1 -1
  9. package/dist/components/Gallery/AnimationController.js +9 -0
  10. package/dist/components/Gallery/AnimationController.js.map +1 -1
  11. package/dist/components/Gallery/BuiltItem.d.ts +2 -1
  12. package/dist/components/Gallery/BuiltItem.d.ts.map +1 -1
  13. package/dist/components/Gallery/BuiltItem.js +15 -3
  14. package/dist/components/Gallery/BuiltItem.js.map +1 -1
  15. package/dist/components/Gallery/GalleryController.d.ts +1 -0
  16. package/dist/components/Gallery/GalleryController.d.ts.map +1 -1
  17. package/dist/components/Gallery/GalleryController.js +15 -4
  18. package/dist/components/Gallery/GalleryController.js.map +1 -1
  19. package/dist/components/Gallery/GalleryViewer.d.ts +2 -1
  20. package/dist/components/Gallery/GalleryViewer.d.ts.map +1 -1
  21. package/dist/components/Gallery/GalleryViewer.js +13 -4
  22. package/dist/components/Gallery/GalleryViewer.js.map +1 -1
  23. package/dist/components/InlineGalleryDisplay.d.ts.map +1 -1
  24. package/dist/components/InlineGalleryDisplay.js +5 -1
  25. package/dist/components/InlineGalleryDisplay.js.map +1 -1
  26. package/dist/components/Playground.d.ts.map +1 -1
  27. package/dist/components/Playground.js +59 -21
  28. package/dist/components/Playground.js.map +1 -1
  29. package/dist/components/ServerTrustMatchViewer.d.ts.map +1 -1
  30. package/dist/components/ServerTrustMatchViewer.js +10 -2
  31. package/dist/components/ServerTrustMatchViewer.js.map +1 -1
  32. package/dist/components/SparkLineChart.d.ts.map +1 -1
  33. package/dist/components/SparkLineChart.js +62 -22
  34. package/dist/components/SparkLineChart.js.map +1 -1
  35. package/dist/components/Viewer.d.ts.map +1 -1
  36. package/dist/components/Viewer.js +15 -6
  37. package/dist/components/Viewer.js.map +1 -1
  38. package/dist/game/Chit.d.ts +10 -1
  39. package/dist/game/Chit.d.ts.map +1 -1
  40. package/dist/game/Chit.js +125 -4
  41. package/dist/game/Chit.js.map +1 -1
  42. package/dist/game/Connection.d.ts +1 -0
  43. package/dist/game/Connection.d.ts.map +1 -1
  44. package/dist/game/Connection.js +27 -8
  45. package/dist/game/Connection.js.map +1 -1
  46. package/dist/game/ConnectionTransport.d.ts +5 -0
  47. package/dist/game/ConnectionTransport.d.ts.map +1 -1
  48. package/dist/game/ConnectionTransport.js +32 -0
  49. package/dist/game/ConnectionTransport.js.map +1 -1
  50. package/dist/game/GalleryItemChitChildrenSource.d.ts.map +1 -1
  51. package/dist/game/GalleryItemChitChildrenSource.js +9 -1
  52. package/dist/game/GalleryItemChitChildrenSource.js.map +1 -1
  53. package/dist/game/Game.d.ts +6 -0
  54. package/dist/game/Game.d.ts.map +1 -1
  55. package/dist/game/OrderedOutlet.d.ts +4 -1
  56. package/dist/game/OrderedOutlet.d.ts.map +1 -1
  57. package/dist/game/OrderedOutlet.js +25 -4
  58. package/dist/game/OrderedOutlet.js.map +1 -1
  59. package/dist/game/Pick.d.ts +1 -0
  60. package/dist/game/Pick.d.ts.map +1 -1
  61. package/dist/game/Pick.js +40 -1
  62. package/dist/game/Pick.js.map +1 -1
  63. package/dist/game/Prompt.d.ts +11 -1
  64. package/dist/game/Prompt.d.ts.map +1 -1
  65. package/dist/game/Prompt.js +34 -1
  66. package/dist/game/Prompt.js.map +1 -1
  67. package/dist/game/Turn.d.ts +17 -0
  68. package/dist/game/Turn.d.ts.map +1 -1
  69. package/dist/game/Turn.js +114 -63
  70. package/dist/game/Turn.js.map +1 -1
  71. package/dist/game/badAiTransport/BadAIClientPrompts.d.ts +3 -1
  72. package/dist/game/badAiTransport/BadAIClientPrompts.d.ts.map +1 -1
  73. package/dist/game/badAiTransport/BadAIClientPrompts.js +31 -5
  74. package/dist/game/badAiTransport/BadAIClientPrompts.js.map +1 -1
  75. package/dist/game/clientTransport/ClientPrompts.d.ts +2 -0
  76. package/dist/game/clientTransport/ClientPrompts.d.ts.map +1 -1
  77. package/dist/game/clientTransport/ClientPrompts.js +48 -16
  78. package/dist/game/clientTransport/ClientPrompts.js.map +1 -1
  79. package/dist/game/clientTransport/ClientTime.d.ts.map +1 -1
  80. package/dist/game/clientTransport/ClientTime.js +58 -52
  81. package/dist/game/clientTransport/ClientTime.js.map +1 -1
  82. package/dist/game/serverTransport/ServerPrompts.d.ts +1 -1
  83. package/dist/game/serverTransport/ServerPrompts.d.ts.map +1 -1
  84. package/dist/game/serverTransport/ServerPrompts.js +14 -3
  85. package/dist/game/serverTransport/ServerPrompts.js.map +1 -1
  86. package/dist/game/serverTransport/ServerStatus.d.ts.map +1 -1
  87. package/dist/game/serverTransport/ServerStatus.js +6 -2
  88. package/dist/game/serverTransport/ServerStatus.js.map +1 -1
  89. package/dist/game/serverTransport/ServerTime.d.ts.map +1 -1
  90. package/dist/game/serverTransport/ServerTime.js +6 -2
  91. package/dist/game/serverTransport/ServerTime.js.map +1 -1
  92. package/dist/hooks/useTimeController.d.ts.map +1 -1
  93. package/dist/hooks/useTimeController.js +3 -0
  94. package/dist/hooks/useTimeController.js.map +1 -1
  95. package/dist/hooks/useWebGlRenderer.d.ts +27 -1
  96. package/dist/hooks/useWebGlRenderer.d.ts.map +1 -1
  97. package/dist/hooks/useWebGlRenderer.js +191 -7
  98. package/dist/hooks/useWebGlRenderer.js.map +1 -1
  99. package/dist/index.d.ts +1 -1
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +1 -1
  102. package/dist/index.js.map +1 -1
  103. package/dist/rendering/ChitGalleryItemInstance.js +1 -1
  104. package/dist/rendering/ChitGalleryItemInstance.js.map +1 -1
  105. package/dist/rendering/ChitRenderInstance.d.ts.map +1 -1
  106. package/dist/rendering/ChitRenderInstance.js +30 -9
  107. package/dist/rendering/ChitRenderInstance.js.map +1 -1
  108. package/dist/rendering/ChitRenderSpec.js +1 -1
  109. package/dist/rendering/ChitRenderSpec.js.map +1 -1
  110. package/dist/rendering/outline/IDBasedOutlinePass.d.ts.map +1 -1
  111. package/dist/rendering/outline/IDBasedOutlinePass.js +6 -2
  112. package/dist/rendering/outline/IDBasedOutlinePass.js.map +1 -1
  113. package/dist/rendering/outline/passes/InterMeshEdgeDetectionPass.d.ts.map +1 -1
  114. package/dist/rendering/outline/passes/InterMeshEdgeDetectionPass.js +7 -3
  115. package/dist/rendering/outline/passes/InterMeshEdgeDetectionPass.js.map +1 -1
  116. package/dist/utilities/CanvasStack/CanvasOperations.d.ts.map +1 -1
  117. package/dist/utilities/CanvasStack/CanvasOperations.js +34 -13
  118. package/dist/utilities/CanvasStack/CanvasOperations.js.map +1 -1
  119. package/dist/utilities/CanvasStack/CanvasStack.d.ts +9 -0
  120. package/dist/utilities/CanvasStack/CanvasStack.d.ts.map +1 -1
  121. package/dist/utilities/CanvasStack/CanvasStack.js +37 -2
  122. package/dist/utilities/CanvasStack/CanvasStack.js.map +1 -1
  123. package/dist/utilities/CanvasStack/RichTextRenderer.d.ts +2 -0
  124. package/dist/utilities/CanvasStack/RichTextRenderer.d.ts.map +1 -1
  125. package/dist/utilities/CanvasStack/RichTextRenderer.js +47 -4
  126. package/dist/utilities/CanvasStack/RichTextRenderer.js.map +1 -1
  127. package/package.json +1 -1
  128. package/src/library/components/DemoWrapper.tsx +1 -1
  129. package/src/library/components/FullScreenGalleryDisplay.tsx +5 -0
  130. package/src/library/components/Gallery/AnimationController.ts +10 -0
  131. package/src/library/components/Gallery/BuiltItem.ts +16 -3
  132. package/src/library/components/Gallery/GalleryController.ts +15 -4
  133. package/src/library/components/Gallery/GalleryViewer.tsx +17 -3
  134. package/src/library/components/InlineGalleryDisplay.tsx +5 -0
  135. package/src/library/components/Playground.tsx +76 -20
  136. package/src/library/components/ServerTrustMatchViewer.tsx +10 -2
  137. package/src/library/components/SparkLineChart.tsx +85 -24
  138. package/src/library/components/Viewer.tsx +15 -6
  139. package/src/library/game/Chit.test.ts +91 -0
  140. package/src/library/game/Chit.ts +122 -9
  141. package/src/library/game/Connection.ts +27 -8
  142. package/src/library/game/ConnectionTransport.ts +38 -0
  143. package/src/library/game/GalleryItemChitChildrenSource.ts +9 -1
  144. package/src/library/game/Game.ts +7 -0
  145. package/src/library/game/OrderedOutlet.ts +27 -4
  146. package/src/library/game/Pick.ts +46 -4
  147. package/src/library/game/Prompt.ts +43 -3
  148. package/src/library/game/Turn.ts +127 -78
  149. package/src/library/game/badAiTransport/BadAIClientPrompts.ts +33 -4
  150. package/src/library/game/clientTransport/ClientPrompts.ts +50 -16
  151. package/src/library/game/clientTransport/ClientTime.ts +61 -56
  152. package/src/library/game/serverTransport/ServerPrompts.ts +25 -7
  153. package/src/library/game/serverTransport/ServerStatus.ts +6 -2
  154. package/src/library/game/serverTransport/ServerTime.ts +6 -2
  155. package/src/library/hooks/useTimeController.tsx +3 -0
  156. package/src/library/hooks/useWebGlRenderer.tsx +225 -7
  157. package/src/library/index.ts +1 -1
  158. package/src/library/rendering/ChitGalleryItemInstance.ts +1 -1
  159. package/src/library/rendering/ChitRenderInstance.ts +32 -9
  160. package/src/library/rendering/ChitRenderSpec.ts +1 -1
  161. package/src/library/rendering/outline/IDBasedOutlinePass.ts +6 -2
  162. package/src/library/rendering/outline/passes/InterMeshEdgeDetectionPass.ts +7 -3
  163. package/src/library/utilities/CanvasStack/CanvasOperations.tsx +44 -13
  164. package/src/library/utilities/CanvasStack/CanvasStack.ts +38 -1
  165. package/src/library/utilities/CanvasStack/RichTextRenderer.ts +66 -5
@@ -76,6 +76,9 @@ export function TimeControllerProvider({ children }: { children: ReactNode }) {
76
76
 
77
77
  if (!clientTime || clientTime.connection !== connection) {
78
78
  clientTime?.dispose();
79
+ if (clientTime?.clientPrompt) {
80
+ clientTime.clientPrompt.disconnect();
81
+ }
79
82
 
80
83
  const newClientTime = new ClientTime(connection, game, clientTimeState);
81
84
  connection.register(newClientTime);
@@ -26,13 +26,21 @@ class WebGLRendererWrapper {
26
26
  private renderer: WebGLRenderer;
27
27
  private composerPool = new Map<string, ComposerEntry>();
28
28
  private memoryExtension: any;
29
+ private loseContextExt: WEBGL_lose_context | null = null;
29
30
  private currentWidth = 0;
30
31
  private currentHeight = 0;
31
32
  public pixelRatio = Math.max(1.5, typeof window !== "undefined" ? window.devicePixelRatio : 1.5);
32
33
  private maxComposers = 8;
34
+ private _contextLost = false;
35
+ private _restoreScheduled = false;
36
+ private _lastLossAt = 0;
37
+ private _lastRestoreAttemptAt = 0;
38
+ private static RESTORE_BACKOFF_MS = 250;
39
+ private _dirtyCallbacks = new Set<() => void>();
40
+ public readonly isWebGL2: boolean;
33
41
 
34
42
  constructor() {
35
- this.renderer = new WebGLRenderer({ alpha: true, antialias: true });
43
+ this.renderer = new WebGLRenderer({ alpha: true, antialias: true, preserveDrawingBuffer: true });
36
44
 
37
45
  // Check if WebGL context is available
38
46
  if (!this.renderer.getContext()) {
@@ -42,6 +50,10 @@ class WebGLRendererWrapper {
42
50
  // Get memory extension for GPU memory monitoring
43
51
  const gl = this.renderer.getContext();
44
52
  this.memoryExtension = gl.getExtension("WEBGL_debug_renderer_info");
53
+ this.loseContextExt = gl.getExtension("WEBGL_lose_context");
54
+ this.isWebGL2 =
55
+ typeof WebGL2RenderingContext !== "undefined" &&
56
+ gl instanceof WebGL2RenderingContext;
45
57
 
46
58
  this.renderer.setPixelRatio(this.pixelRatio);
47
59
  this.renderer.shadowMap.enabled = true;
@@ -49,6 +61,134 @@ class WebGLRendererWrapper {
49
61
 
50
62
  // Enable scissor test for partial rendering
51
63
  this.renderer.setScissorTest(true);
64
+
65
+ // Handle WebGL context loss and restoration
66
+ const canvas = this.renderer.domElement;
67
+ canvas.addEventListener(
68
+ "webglcontextlost",
69
+ (e) => {
70
+ e.preventDefault(); // allows context to be restored
71
+ this.handleContextLost("event");
72
+ },
73
+ false,
74
+ );
75
+
76
+ canvas.addEventListener(
77
+ "webglcontextrestored",
78
+ () => {
79
+ this.handleContextRestored();
80
+ },
81
+ false,
82
+ );
83
+ }
84
+
85
+ private handleContextLost(source: "event" | "silent") {
86
+ const wasLost = this._contextLost;
87
+ this._contextLost = true;
88
+ this._lastLossAt = Date.now();
89
+ console.warn(
90
+ `[WebGLRenderer] Context lost (source=${source}, alreadyLost=${wasLost}, size=${this.currentWidth}x${this.currentHeight}, composers=${this.composerPool.size})`,
91
+ );
92
+
93
+ // All render targets are invalid — drop them so we don't keep using stale ones
94
+ for (const entry of this.composerPool.values()) {
95
+ entry.composer.dispose();
96
+ entry.outlinePass.dispose();
97
+ }
98
+ this.composerPool.clear();
99
+
100
+ // If the loss was silent (no event from the browser), the matching `restored`
101
+ // event also won't fire on its own. Schedule a forced restore so rendering
102
+ // resumes without requiring the user to switch panels. The "event" path is
103
+ // expected to recover on its own; if it doesn't, render() will reschedule.
104
+ if (source === "silent") {
105
+ this.maybeScheduleRestore();
106
+ }
107
+ }
108
+
109
+ private handleContextRestored() {
110
+ const downMs = this._lastLossAt ? Date.now() - this._lastLossAt : -1;
111
+ console.warn(
112
+ `[WebGLRenderer] Context restored (downMs=${downMs}, size=${this.currentWidth}x${this.currentHeight})`,
113
+ );
114
+ this._contextLost = false;
115
+ this._restoreScheduled = false;
116
+
117
+ // Re-apply renderer state
118
+ this.renderer.setPixelRatio(this.pixelRatio);
119
+ this.renderer.shadowMap.enabled = true;
120
+ this.renderer.setClearColor(0xffffff, 1.0);
121
+ this.renderer.setScissorTest(true);
122
+
123
+ // Composer pool was cleared on loss; reset size tracking so the next
124
+ // render call rebuilds the backing framebuffer at the right dimensions.
125
+ this.currentWidth = 0;
126
+ this.currentHeight = 0;
127
+
128
+ // Notify all active viewers to re-render
129
+ for (const cb of this._dirtyCallbacks) {
130
+ cb();
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Throttled scheduler for forceRestore(). Call this any time we observe the
136
+ * context is still lost and want to try recovery — it dedupes against an
137
+ * already-pending attempt and enforces a backoff so we don't spin.
138
+ */
139
+ private maybeScheduleRestore() {
140
+ if (!this._contextLost) return;
141
+ if (this._restoreScheduled) return;
142
+ const sinceLastAttempt = Date.now() - this._lastRestoreAttemptAt;
143
+ if (this._lastRestoreAttemptAt > 0 && sinceLastAttempt < WebGLRendererWrapper.RESTORE_BACKOFF_MS) {
144
+ // Defer until backoff elapses
145
+ const wait = WebGLRendererWrapper.RESTORE_BACKOFF_MS - sinceLastAttempt;
146
+ this._restoreScheduled = true;
147
+ setTimeout(() => {
148
+ this._restoreScheduled = false;
149
+ this.forceRestore();
150
+ }, wait);
151
+ return;
152
+ }
153
+ this._restoreScheduled = true;
154
+ queueMicrotask(() => {
155
+ this._restoreScheduled = false;
156
+ this.forceRestore();
157
+ });
158
+ }
159
+
160
+ private forceRestore() {
161
+ if (!this._contextLost) return;
162
+ this._lastRestoreAttemptAt = Date.now();
163
+
164
+ if (this.loseContextExt) {
165
+ try {
166
+ this.loseContextExt.restoreContext();
167
+ // If the browser honors this, `webglcontextrestored` fires asynchronously
168
+ // and clears _contextLost. If it doesn't fire, the next render() call
169
+ // will hit the _contextLost early-return and schedule another attempt.
170
+ return;
171
+ } catch (e) {
172
+ console.warn("[WebGLRenderer] restoreContext() threw, falling back to setSize", e);
173
+ }
174
+ }
175
+ // Fallback: nudge the canvas size to encourage the driver to rebuild the context.
176
+ // Some Android drivers fire `webglcontextrestored` in response to setSize on a
177
+ // lost context. If neither path triggers a restore, render() reschedules us.
178
+ try {
179
+ this.renderer.setSize(Math.max(1, this.currentWidth), Math.max(1, this.currentHeight));
180
+ } catch (e) {
181
+ console.warn("[WebGLRenderer] setSize fallback threw", e);
182
+ }
183
+ }
184
+
185
+ get contextLost() {
186
+ return this._contextLost;
187
+ }
188
+
189
+ onDirty(cb: () => void): () => void {
190
+ this._dirtyCallbacks.add(cb);
191
+ return () => this._dirtyCallbacks.delete(cb);
52
192
  }
53
193
 
54
194
  private evictLeastRecentlyUsedComposer() {
@@ -124,15 +264,79 @@ class WebGLRendererWrapper {
124
264
  return entry;
125
265
  }
126
266
 
127
- private ensureRendererSize(targetWidth: number, targetHeight: number) {
267
+ private _shrinkTimer?: ReturnType<typeof setTimeout>;
268
+ private _activeRenderSizes = new Map<string, { width: number; height: number }>();
269
+
270
+ private ensureRendererSize(targetWidth: number, targetHeight: number, viewerId?: string) {
271
+ if (viewerId) {
272
+ this._activeRenderSizes.set(viewerId, { width: targetWidth, height: targetHeight });
273
+ }
274
+
128
275
  if (targetWidth > this.currentWidth || targetHeight > this.currentHeight) {
276
+ const prevWidth = this.currentWidth;
277
+ const prevHeight = this.currentHeight;
129
278
  this.currentWidth = Math.max(this.currentWidth, targetWidth);
130
279
  this.currentHeight = Math.max(this.currentHeight, targetHeight);
131
280
  this.renderer.setSize(this.currentWidth, this.currentHeight);
281
+ console.log(
282
+ `[WebGLRenderer] Renderer size grew: ${prevWidth}x${prevHeight} -> ${this.currentWidth}x${this.currentHeight} (requested ${targetWidth}x${targetHeight})`,
283
+ );
132
284
  }
133
285
  }
134
286
 
135
- render(sceneWrapper: SceneWrapper, camera: Camera, context2d: CanvasRenderingContext2D, theme: GameTheme) {
287
+ /** Remove a viewer from the active set and schedule a shrink check. */
288
+ unregisterViewerSize(viewerId: string) {
289
+ this._activeRenderSizes.delete(viewerId);
290
+ this.scheduleShrink();
291
+ }
292
+
293
+ private scheduleShrink() {
294
+ if (this._shrinkTimer) return;
295
+ this._shrinkTimer = setTimeout(() => {
296
+ this._shrinkTimer = undefined;
297
+ this.shrinkToFit();
298
+ }, 2000);
299
+ }
300
+
301
+ private shrinkToFit() {
302
+ let maxW = 0;
303
+ let maxH = 0;
304
+ for (const size of this._activeRenderSizes.values()) {
305
+ maxW = Math.max(maxW, size.width);
306
+ maxH = Math.max(maxH, size.height);
307
+ }
308
+
309
+ // Only shrink if we can save at least 25% in one dimension
310
+ if (maxW > 0 && maxH > 0 && (maxW < this.currentWidth * 0.75 || maxH < this.currentHeight * 0.75)) {
311
+ const prevWidth = this.currentWidth;
312
+ const prevHeight = this.currentHeight;
313
+ this.currentWidth = maxW;
314
+ this.currentHeight = maxH;
315
+ this.renderer.setSize(this.currentWidth, this.currentHeight);
316
+ console.log(
317
+ `[WebGLRenderer] Renderer size shrunk: ${prevWidth}x${prevHeight} -> ${this.currentWidth}x${this.currentHeight}`,
318
+ );
319
+ }
320
+ }
321
+
322
+ render(sceneWrapper: SceneWrapper, camera: Camera, context2d: CanvasRenderingContext2D, theme: GameTheme, viewerId?: string): boolean {
323
+ if (this._contextLost) {
324
+ // Still lost — keep trying to restore. The previous attempt may have used
325
+ // the setSize fallback that doesn't always trigger `webglcontextrestored`.
326
+ this.maybeScheduleRestore();
327
+ return false;
328
+ }
329
+
330
+ // Detect silent context loss — on some Android WebViews the `webglcontextlost`
331
+ // event isn't fired reliably for GPU process kills. Without this check we'd
332
+ // happily call composer.render() on a dead context, produce no pixels, and
333
+ // strip the snapshot overlay → blank canvas until the user switches panels.
334
+ const gl = this.renderer.getContext();
335
+ if (gl && gl.isContextLost()) {
336
+ this.handleContextLost("silent");
337
+ return false;
338
+ }
339
+
136
340
  const canvas = context2d.canvas;
137
341
  const width = Math.floor(canvas.width / this.pixelRatio);
138
342
  const height = Math.floor(canvas.height / this.pixelRatio);
@@ -140,7 +344,7 @@ class WebGLRendererWrapper {
140
344
  const targetHeight = Math.ceil(height * this.pixelRatio);
141
345
 
142
346
  // Ensure renderer can accommodate this size
143
- this.ensureRendererSize(width, height);
347
+ this.ensureRendererSize(width, height, viewerId);
144
348
 
145
349
  // Get or create appropriate composer
146
350
  const transparent = true; // Always use transparent for composition
@@ -153,13 +357,23 @@ class WebGLRendererWrapper {
153
357
  this.renderer.setScissor(0, 0, targetWidth, targetHeight);
154
358
  this.renderer.setViewport(0, 0, width, height);
155
359
 
360
+ // Clear *depth only* in this panel's scissor region before composer.render().
361
+ // All viewers share the same WebGL backbuffer (and thus its depth buffer).
362
+ // Each composer's OutputPass renders a fullscreen quad at the same NDC z,
363
+ // and the default depth func is LESS — so the second panel's quad fails
364
+ // depth-test against the first panel's quad and the fragment is discarded.
365
+ // The panel then "didn't render": the backbuffer keeps the previous panel's
366
+ // pixels in its region, and drawImage copies those into the wrong panel's
367
+ // 2D canvas. Clearing depth (but not color) lets the OutputPass actually
368
+ // write its real output without stomping on whatever fallback content might
369
+ // already be visible from a prior frame.
370
+ this.renderer.clear(false, true, false);
371
+
156
372
  // Render using the composer
157
373
  entry.composer.render(sceneWrapper, camera);
158
374
 
159
375
  // Copy the rendered result to the 2D canvas
160
376
  const webglCanvas = this.renderer.domElement;
161
- // context2d.save();
162
- // context2d.scale(1 / this.pixelRatio, 1 / this.pixelRatio);
163
377
  context2d.drawImage(
164
378
  webglCanvas,
165
379
  0,
@@ -171,7 +385,7 @@ class WebGLRendererWrapper {
171
385
  targetWidth,
172
386
  targetHeight, // Dest width, height
173
387
  );
174
- // context2d.restore();
388
+ return true;
175
389
  } finally {
176
390
  entry.referenceCount--;
177
391
  }
@@ -225,3 +439,7 @@ export function useWebGlRenderer(): WebGLRendererWrapper {
225
439
  }
226
440
  return _wrapper;
227
441
  }
442
+
443
+ export function getWebGlRendererInstance(): WebGLRendererWrapper | undefined {
444
+ return _wrapper;
445
+ }
@@ -10,7 +10,7 @@ export { Chit } from "./game/Chit";
10
10
  /** @group Core Game Elements */
11
11
  export { Turn } from "./game/Turn";
12
12
  /** @group Core Game Elements */
13
- export { Pick, ButtonPick, ChitPick } from "./game/Pick";
13
+ export { Pick, ButtonPick, ChitPick, DragTarget, DragPick } from "./game/Pick";
14
14
  /** @group Core Game Elements */
15
15
  export { GameTheme } from "./game/GameTheme";
16
16
  /** @group Chits */
@@ -37,7 +37,7 @@ export class ChitGalleryItemInstance implements GalleryItem {
37
37
  };
38
38
 
39
39
  // handle refreshes.
40
- this.unsubscribe = chit.onChange("deserialized parent onClick", () => {
40
+ this.unsubscribe = chit.onChange("deserialized parent onClick renderInstance", () => {
41
41
  if (chit.renderInstance) {
42
42
  chit.renderInstance.createGalleryItem(this);
43
43
  }
@@ -18,7 +18,6 @@ import { Easing, Tween, Group as TweenGroup } from "@tweenjs/tween.js";
18
18
  import { RootChitRenderInstance } from "./RootChitRenderInstance";
19
19
  import { fixBbox } from "../utilities/BboxUtils";
20
20
  import { ChitGalleryItemInstance } from "./ChitGalleryItemInstance";
21
- import Color from "color";
22
21
 
23
22
  const LINE_COLOR = new MeshBasicMaterial({ color: 0xff0000, wireframe: true, wireframeLinewidth: 2 });
24
23
  const CLICK_LINE_COLOR = new MeshBasicMaterial({ color: 0xffff00, wireframe: true, wireframeLinewidth: 2 });
@@ -128,8 +127,10 @@ export class ChitRenderInstance {
128
127
  let intersection = this.attemptToFindPlaneZ0(this.rootRenderInstance, positionEntranceChit);
129
128
 
130
129
  if (intersection && oldParent) {
131
- // Ensure entrance coordinates are outside visible region if they overlap
132
- intersection = this.ensureCoordinatesOutsideVisibleRegion(intersection);
130
+ if (positionEntranceChit && positionEntranceChit !== chit.parentFallback) {
131
+ // Ensure entrance coordinates are outside visible region if they overlap
132
+ intersection = this.ensureCoordinatesOutsideVisibleRegion(intersection);
133
+ }
133
134
 
134
135
  this.group.removeFromParent();
135
136
  this.group.position.set(intersection.x, intersection.y, intersection.z);
@@ -139,6 +140,7 @@ export class ChitRenderInstance {
139
140
 
140
141
  this.bboxGroup.add(this.bbox);
141
142
  this.bboxGroup.add(this.clickbox);
143
+ this.chit.notifyChange("renderInstance");
142
144
  }
143
145
 
144
146
  public get effectiveParent() {
@@ -370,7 +372,7 @@ export class ChitRenderInstance {
370
372
 
371
373
  protected updateGroupPosition(key: OwnerOriginPosition | string, group: Group) {
372
374
  const vector = this.targetAnchorPoint(key);
373
- group.position.set(vector.x, vector.y, vector.z + this.sizeZ / 2 + (this.renderSpec?.childrenOffsetZ ?? 0));
375
+ group.position.set(vector.x, vector.y, vector.z + this.sizeZ / 2 + this.centerZ + (this.renderSpec?.childrenOffsetZ ?? 0));
374
376
  }
375
377
 
376
378
  protected setOutletPosition(positionKey: string, position: Vector3) {
@@ -662,8 +664,7 @@ export class ChitRenderInstance {
662
664
 
663
665
  if (outlineContext && this.renderSpec.object && outlineContext.renderSpec?.object && c) {
664
666
  const id = outlineContext.renderSpec.object.id % 60000;
665
- const color = Color(c);
666
- const threeColor = new ThreeColor(color.red() / 256, color.green() / 256, color.blue() / 256);
667
+ const threeColor = new ThreeColor(c);
667
668
  this.renderSpec.object.traverseVisible((o) => {
668
669
  o.userData.outlineId = id;
669
670
  o.userData.outlineColor = threeColor;
@@ -884,7 +885,7 @@ export class ChitRenderInstance {
884
885
  const targetOffset = {
885
886
  x: this.renderSpec.offsetX,
886
887
  y: this.renderSpec.offsetY,
887
- z: this.renderSpec.offsetZ + this.sizeZ / 2,
888
+ z: this.renderSpec.offsetZ + this.sizeZ / 2 - this.centerZ,
888
889
  };
889
890
  this.handleOffsetForSplay(targetOffset);
890
891
 
@@ -1053,7 +1054,7 @@ export class ChitRenderInstance {
1053
1054
  const targetOffset = {
1054
1055
  x: this.renderSpec.offsetX,
1055
1056
  y: this.renderSpec.offsetY,
1056
- z: this.renderSpec.offsetZ + this.sizeZ / 2,
1057
+ z: this.renderSpec.offsetZ + this.sizeZ / 2 - this.centerZ,
1057
1058
  };
1058
1059
  const targetRotation = { x: this.renderSpec.rotateX, y: this.renderSpec.rotateY, z: this.renderSpec.rotateZ };
1059
1060
 
@@ -1143,7 +1144,29 @@ export class ChitRenderInstance {
1143
1144
 
1144
1145
  if (rotationEasing) {
1145
1146
  rotation.order = "ZYX";
1146
- this.rotationTween = this.createTween({ x: rotation.x, y: rotation.y, z: rotation.z }, (tween) =>
1147
+
1148
+ // Adjust current angles so each axis takes the shortest path to the target.
1149
+ // e.g. 355° → 5° becomes -5° → 5° (10° rotation) instead of 355° → 5° (350° rotation).
1150
+ // Adding/subtracting full turns doesn't change the visual orientation.
1151
+ const adjustForShortestPath = (current: number, target: number) => {
1152
+ let diff = target - current;
1153
+ while (diff > Math.PI) diff -= 2 * Math.PI;
1154
+ while (diff < -Math.PI) diff += 2 * Math.PI;
1155
+ return target - diff;
1156
+ };
1157
+
1158
+ const adjustedStart = {
1159
+ x: adjustForShortestPath(rotation.x, targetRotation.x),
1160
+ y: adjustForShortestPath(rotation.y, targetRotation.y),
1161
+ z: adjustForShortestPath(rotation.z, targetRotation.z),
1162
+ };
1163
+
1164
+ // Snap the group rotation to the adjusted values (visually identical)
1165
+ rotation.x = adjustedStart.x;
1166
+ rotation.y = adjustedStart.y;
1167
+ rotation.z = adjustedStart.z;
1168
+
1169
+ this.rotationTween = this.createTween({ x: adjustedStart.x, y: adjustedStart.y, z: adjustedStart.z }, (tween) =>
1147
1170
  tween
1148
1171
  .to(targetRotation, duration * this.animationSpeedMultiplier)
1149
1172
  .onUpdate((obj) => {
@@ -210,7 +210,7 @@ export class ChitRenderSpec {
210
210
  }
211
211
 
212
212
  const p = this.outletPositions[ordered.outletName] ?? new Vector3(0, 0, 0);
213
- mesh.position.set(p.x + offsetX, p.y + offsetY, box3.max.z - box3.min.z + p.z + 0.001);
213
+ mesh.position.set(p.x + offsetX, p.y + offsetY, box3.max.z + p.z + 0.001);
214
214
  this.ornaments.push(mesh);
215
215
  }
216
216
  }
@@ -429,22 +429,26 @@ export class IDBasedOutlinePass extends Pass {
429
429
  (this.copyUniforms["tDiffuse"].value as any) = this.renderTargetTempBuffer.texture;
430
430
  this.fsQuad.render(renderer);
431
431
 
432
- // Second: Add edges using additive blending
432
+ // Second: Composite edges using premultiplied alpha blending
433
+ // Edge texture stores premultiplied alpha: (rgb * a, a)
433
434
  renderer.autoClear = false;
434
435
 
435
436
  const originalBlending = this.materialCopy.blending;
436
437
  const originalTransparent = this.materialCopy.transparent;
438
+ const originalPremultipliedAlpha = this.materialCopy.premultipliedAlpha;
437
439
 
438
440
  this.materialCopy.blending = NormalBlending;
439
441
  this.materialCopy.transparent = true;
442
+ this.materialCopy.premultipliedAlpha = true;
440
443
  this.materialCopy.needsUpdate = true;
441
444
 
442
445
  (this.copyUniforms["tDiffuse"].value as any) = edgeTexture;
443
446
  this.fsQuad.render(renderer);
444
447
 
445
- // // Restore material blending settings
448
+ // Restore material blending settings
446
449
  this.materialCopy.blending = originalBlending;
447
450
  this.materialCopy.transparent = originalTransparent;
451
+ this.materialCopy.premultipliedAlpha = originalPremultipliedAlpha;
448
452
  this.materialCopy.needsUpdate = true;
449
453
 
450
454
  this.restoreRenderState(renderer);
@@ -221,12 +221,16 @@ export class InterMeshEdgeDetectionPass extends Pass {
221
221
 
222
222
  // Only draw if we're near an edge (inside the mesh)
223
223
  if (edgeDistance < 1000.0) {
224
- // Create thick outline with smooth falloff
224
+ // Create thick outline with solid core and soft outer edge
225
225
  float lineThickness = thickness + 0.5;
226
- float alpha = 1.0 - smoothstep(0.5, lineThickness, edgeDistance);
226
+ float feather = min(1.5, lineThickness * 0.5);
227
+ float solidEnd = lineThickness - feather;
228
+ float alpha = 1.0 - smoothstep(solidEnd, lineThickness, edgeDistance);
227
229
 
228
230
  if (alpha > 0.01) {
229
- gl_FragColor = vec4(centerOutlineColor.rgb, alpha * strength);
231
+ // Output premultiplied alpha for correct blending with LinearFilter
232
+ float finalAlpha = alpha * strength;
233
+ gl_FragColor = vec4(centerOutlineColor.rgb * finalAlpha, finalAlpha);
230
234
  } else {
231
235
  gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);
232
236
  }
@@ -455,9 +455,14 @@ export class ImageCanvasOperation extends CanvasOperation {
455
455
  if (maxH && syi + shi > maxH) {
456
456
  shi = Math.max(0, maxH - syi);
457
457
  }
458
- // If sw/sh rounded to zero, skip drawing.
459
- if (swi > 0 && shi > 0) {
460
- context.drawImage(source as any, sxi, syi, swi, shi, x, y, w, h);
458
+ // Inset by half a texel and disable smoothing so bilinear filtering
459
+ // never samples neighboring sprites in the spritesheet.
460
+ const inset = 0.5;
461
+ if (swi > inset * 2 && shi > inset * 2) {
462
+ const prevSmoothing = context.imageSmoothingEnabled;
463
+ context.imageSmoothingEnabled = false;
464
+ context.drawImage(source as any, sxi + inset, syi + inset, swi - inset * 2, shi - inset * 2, x, y, w, h);
465
+ context.imageSmoothingEnabled = prevSmoothing;
461
466
  }
462
467
  }
463
468
  }
@@ -517,24 +522,50 @@ export class ImageCanvasOperation extends CanvasOperation {
517
522
  let syiF = Math.floor(sy);
518
523
  let swiF = Math.ceil(sw);
519
524
  let shiF = Math.ceil(sh);
520
- const maxWF = (source as any).width ?? (source as any).naturalWidth ?? 0;
521
- const maxHF = (source as any).height ?? (source as any).naturalHeight ?? 0;
522
- if (sxiF < 0) {
523
- swiF += sxiF;
524
- sxiF = 0;
525
+ // Clamp to sprite bounds so rounding never bleeds into neighboring sprites.
526
+ const sbRight = sourceBounds.x + sourceBounds.width;
527
+ const sbBottom = sourceBounds.y + sourceBounds.height;
528
+ if (sxiF < sourceBounds.x) {
529
+ swiF -= sourceBounds.x - sxiF;
530
+ sxiF = sourceBounds.x;
531
+ }
532
+ if (syiF < sourceBounds.y) {
533
+ shiF -= sourceBounds.y - syiF;
534
+ syiF = sourceBounds.y;
525
535
  }
526
- if (syiF < 0) {
527
- shiF += syiF;
528
- syiF = 0;
536
+ if (sxiF + swiF > sbRight) {
537
+ swiF = sbRight - sxiF;
529
538
  }
539
+ if (syiF + shiF > sbBottom) {
540
+ shiF = sbBottom - syiF;
541
+ }
542
+ // Also clamp to overall image dimensions.
543
+ const maxWF = (source as any).width ?? (source as any).naturalWidth ?? 0;
544
+ const maxHF = (source as any).height ?? (source as any).naturalHeight ?? 0;
530
545
  if (maxWF && sxiF + swiF > maxWF) {
531
546
  swiF = Math.max(0, maxWF - sxiF);
532
547
  }
533
548
  if (maxHF && syiF + shiF > maxHF) {
534
549
  shiF = Math.max(0, maxHF - syiF);
535
550
  }
536
- if (swiF > 0 && shiF > 0) {
537
- context.drawImage(source as any, sxiF, syiF, swiF, shiF, x, y, w, h);
551
+ // Inset by half a texel and disable smoothing so bilinear filtering
552
+ // never samples neighboring sprites in the spritesheet.
553
+ const inset = 0.5;
554
+ if (swiF > inset * 2 && shiF > inset * 2) {
555
+ const prevSmoothing = context.imageSmoothingEnabled;
556
+ 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
+ );
568
+ context.imageSmoothingEnabled = prevSmoothing;
538
569
  }
539
570
  }
540
571
  }
@@ -3,6 +3,7 @@ import {
3
3
  UVMapping,
4
4
  ClampToEdgeWrapping,
5
5
  LinearFilter,
6
+ LinearMipmapLinearFilter,
6
7
  MeshPhongMaterial,
7
8
  Material,
8
9
  SRGBColorSpace,
@@ -12,6 +13,7 @@ import { IUpdatingCanvas } from "../IUpdatingCanvas";
12
13
  import { CanvasOperation } from "./CanvasOperations";
13
14
  import { ImageResult, ImageCache } from "./ImageCache";
14
15
  import { ThreeDisposer } from "../ThreeDisposer";
16
+ import { getWebGlRendererInstance } from "../../hooks/useWebGlRenderer";
15
17
 
16
18
  export type RenderBounds = {
17
19
  x: number;
@@ -96,6 +98,7 @@ export class CanvasStack implements IUpdatingCanvas {
96
98
  this.canvas!.title = `Disposed, mat ${this._material?.uuid} texture ${this._texture?.uuid}`;
97
99
  this.canvas = undefined;
98
100
  this.context = undefined;
101
+ CanvasStack._liveStacks.delete(this);
99
102
 
100
103
  if (this._material) {
101
104
  this._material.dispose();
@@ -122,9 +125,35 @@ export class CanvasStack implements IUpdatingCanvas {
122
125
  }
123
126
  this.context = context;
124
127
 
128
+ CanvasStack._liveStacks.add(this);
129
+ CanvasStack.ensureContextRestoreSubscription();
130
+
125
131
  this.render();
126
132
  }
127
133
 
134
+ private static _liveStacks: Set<CanvasStack> = new Set();
135
+ private static _restoreSubscribed = false;
136
+
137
+ /**
138
+ * After a WebGL context restore, GPU-side textures are gone. The 2D canvas
139
+ * backing data is still valid, but three.js needs to be told to re-upload it.
140
+ * Subscribe once to the renderer's restore notification and re-flag every
141
+ * live instance's texture.
142
+ */
143
+ private static ensureContextRestoreSubscription() {
144
+ if (CanvasStack._restoreSubscribed) return;
145
+ const wrapper = getWebGlRendererInstance();
146
+ if (!wrapper) return;
147
+ CanvasStack._restoreSubscribed = true;
148
+ wrapper.onDirty(() => {
149
+ for (const stack of CanvasStack._liveStacks) {
150
+ if (stack._texture) {
151
+ stack._texture.needsUpdate = true;
152
+ }
153
+ }
154
+ });
155
+ }
156
+
128
157
  get outlets() {
129
158
  return this._outlets;
130
159
  }
@@ -146,14 +175,18 @@ export class CanvasStack implements IUpdatingCanvas {
146
175
  }
147
176
 
148
177
  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;
149
181
  this._texture = new Texture(
150
182
  this.canvas,
151
183
  UVMapping,
152
184
  ClampToEdgeWrapping,
153
185
  ClampToEdgeWrapping,
154
186
  LinearFilter,
155
- LinearFilter,
187
+ useMipmaps ? LinearMipmapLinearFilter : LinearFilter,
156
188
  );
189
+ this._texture.generateMipmaps = useMipmaps;
157
190
  this._texture.needsUpdate = true;
158
191
  this._texture.colorSpace = SRGBColorSpace;
159
192
 
@@ -179,6 +212,10 @@ export class CanvasStack implements IUpdatingCanvas {
179
212
  canvasStack._texture.source.data = _NOTHING_CANVAS; // prevent memory leaks! somehow it holding this reference stops the GC from cleaning anything up
180
213
  canvasStack._texture = undefined;
181
214
  }
215
+ // Drop the strong reference so the instance can be GC'd. Both this
216
+ // path and the explicit dispose() can run for the same stack — Set.delete
217
+ // is idempotent, so the duplicate is harmless.
218
+ CanvasStack._liveStacks.delete(canvasStack);
182
219
  });
183
220
 
184
221
  public static materialDisposer = new ThreeDisposer<Material>((material) => {