@pretty-chitty/core 1.2.16 → 1.2.18

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 (73) hide show
  1. package/dist/components/Gallery/GalleryViewer.d.ts.map +1 -1
  2. package/dist/components/Gallery/GalleryViewer.js +7 -2
  3. package/dist/components/Gallery/GalleryViewer.js.map +1 -1
  4. package/dist/components/PanelSpark.js +1 -1
  5. package/dist/components/PlayerImage.d.ts.map +1 -1
  6. package/dist/components/PlayerImage.js +21 -1
  7. package/dist/components/PlayerImage.js.map +1 -1
  8. package/dist/components/SparkLineChart.d.ts.map +1 -1
  9. package/dist/components/SparkLineChart.js +37 -64
  10. package/dist/components/SparkLineChart.js.map +1 -1
  11. package/dist/components/Viewer.d.ts.map +1 -1
  12. package/dist/components/Viewer.js +12 -2
  13. package/dist/components/Viewer.js.map +1 -1
  14. package/dist/game/Chit.js +1 -1
  15. package/dist/game/Chit.js.map +1 -1
  16. package/dist/game/PlayerChit.d.ts +1 -0
  17. package/dist/game/PlayerChit.d.ts.map +1 -1
  18. package/dist/game/PlayerChit.js +5 -2
  19. package/dist/game/PlayerChit.js.map +1 -1
  20. package/dist/game/Turn.d.ts +6 -2
  21. package/dist/game/Turn.d.ts.map +1 -1
  22. package/dist/game/Turn.js +100 -61
  23. package/dist/game/Turn.js.map +1 -1
  24. package/dist/hooks/useWebGlRenderer.d.ts +1 -0
  25. package/dist/hooks/useWebGlRenderer.d.ts.map +1 -1
  26. package/dist/hooks/useWebGlRenderer.js +44 -22
  27. package/dist/hooks/useWebGlRenderer.js.map +1 -1
  28. package/dist/rendering/CameraWrapperPerspective.d.ts.map +1 -1
  29. package/dist/rendering/CameraWrapperPerspective.js +10 -5
  30. package/dist/rendering/CameraWrapperPerspective.js.map +1 -1
  31. package/dist/rendering/LightWrapper.d.ts.map +1 -1
  32. package/dist/rendering/LightWrapper.js +14 -1
  33. package/dist/rendering/LightWrapper.js.map +1 -1
  34. package/dist/rendering/outline/EffectComposer.js +9 -5
  35. package/dist/rendering/outline/EffectComposer.js.map +1 -1
  36. package/dist/utilities/CanvasStack/CanvasOperations.d.ts +15 -1
  37. package/dist/utilities/CanvasStack/CanvasOperations.d.ts.map +1 -1
  38. package/dist/utilities/CanvasStack/CanvasOperations.js +65 -6
  39. package/dist/utilities/CanvasStack/CanvasOperations.js.map +1 -1
  40. package/dist/utilities/CanvasStack/CanvasStack.d.ts +7 -1
  41. package/dist/utilities/CanvasStack/CanvasStack.d.ts.map +1 -1
  42. package/dist/utilities/CanvasStack/CanvasStack.js +72 -6
  43. package/dist/utilities/CanvasStack/CanvasStack.js.map +1 -1
  44. package/dist/utilities/CanvasStack/PlayerCanvas.d.ts +2 -1
  45. package/dist/utilities/CanvasStack/PlayerCanvas.d.ts.map +1 -1
  46. package/dist/utilities/CanvasStack/PlayerCanvas.js +3 -2
  47. package/dist/utilities/CanvasStack/PlayerCanvas.js.map +1 -1
  48. package/dist/utilities/CanvasStack/ReactCanvas.d.ts +2 -1
  49. package/dist/utilities/CanvasStack/ReactCanvas.d.ts.map +1 -1
  50. package/dist/utilities/CanvasStack/ReactCanvas.js +2 -2
  51. package/dist/utilities/CanvasStack/ReactCanvas.js.map +1 -1
  52. package/dist/utilities/ParameterizedCanvas.d.ts +1 -0
  53. package/dist/utilities/ParameterizedCanvas.d.ts.map +1 -1
  54. package/dist/utilities/ParameterizedCanvas.js +4 -1
  55. package/dist/utilities/ParameterizedCanvas.js.map +1 -1
  56. package/package.json +1 -1
  57. package/src/library/components/Gallery/GalleryViewer.tsx +7 -2
  58. package/src/library/components/PanelSpark.tsx +1 -1
  59. package/src/library/components/PlayerImage.tsx +26 -2
  60. package/src/library/components/SparkLineChart.tsx +65 -104
  61. package/src/library/components/Viewer.tsx +11 -2
  62. package/src/library/game/Chit.ts +1 -1
  63. package/src/library/game/PlayerChit.ts +6 -2
  64. package/src/library/game/Turn.ts +112 -69
  65. package/src/library/hooks/useWebGlRenderer.tsx +56 -25
  66. package/src/library/rendering/CameraWrapperPerspective.ts +10 -5
  67. package/src/library/rendering/LightWrapper.ts +20 -1
  68. package/src/library/rendering/outline/EffectComposer.ts +4 -4
  69. package/src/library/utilities/CanvasStack/CanvasOperations.tsx +87 -17
  70. package/src/library/utilities/CanvasStack/CanvasStack.ts +86 -12
  71. package/src/library/utilities/CanvasStack/PlayerCanvas.tsx +5 -2
  72. package/src/library/utilities/CanvasStack/ReactCanvas.tsx +2 -2
  73. package/src/library/utilities/ParameterizedCanvas.ts +5 -1
@@ -51,11 +51,8 @@ class WebGLRendererWrapper {
51
51
  const gl = this.renderer.getContext();
52
52
  this.memoryExtension = gl.getExtension("WEBGL_debug_renderer_info");
53
53
  this.loseContextExt = gl.getExtension("WEBGL_lose_context");
54
- this.isWebGL2 =
55
- typeof WebGL2RenderingContext !== "undefined" &&
56
- gl instanceof WebGL2RenderingContext;
54
+ this.isWebGL2 = typeof WebGL2RenderingContext !== "undefined" && gl instanceof WebGL2RenderingContext;
57
55
 
58
- this.renderer.setPixelRatio(this.pixelRatio);
59
56
  this.renderer.shadowMap.enabled = true;
60
57
  this.renderer.setClearColor(0xffffff, 1.0);
61
58
 
@@ -115,7 +112,6 @@ class WebGLRendererWrapper {
115
112
  this._restoreScheduled = false;
116
113
 
117
114
  // Re-apply renderer state
118
- this.renderer.setPixelRatio(this.pixelRatio);
119
115
  this.renderer.shadowMap.enabled = true;
120
116
  this.renderer.setClearColor(0xffffff, 1.0);
121
117
  this.renderer.setScissorTest(true);
@@ -186,6 +182,10 @@ class WebGLRendererWrapper {
186
182
  return this._contextLost;
187
183
  }
188
184
 
185
+ get maxAnisotropy(): number {
186
+ return this.renderer.capabilities.getMaxAnisotropy();
187
+ }
188
+
189
189
  onDirty(cb: () => void): () => void {
190
190
  this._dirtyCallbacks.add(cb);
191
191
  return () => this._dirtyCallbacks.delete(cb);
@@ -222,7 +222,9 @@ class WebGLRendererWrapper {
222
222
 
223
223
  const composer = new EffectComposer(this.renderer, width, height);
224
224
  const renderPass = new RenderPass();
225
- const outlinePass = new IDBasedOutlinePass(new Vector2(width, height), this.pixelRatio);
225
+ // width/height are already physical pixels; pixelRatio=1 so the pass
226
+ // doesn't scale them again when creating its internal render targets.
227
+ const outlinePass = new IDBasedOutlinePass(new Vector2(width, height), 1);
226
228
  const outputPass = new OutputPass();
227
229
 
228
230
  // Configure transparency
@@ -319,12 +321,27 @@ class WebGLRendererWrapper {
319
321
  }
320
322
  }
321
323
 
322
- render(sceneWrapper: SceneWrapper, camera: Camera, context2d: CanvasRenderingContext2D, theme: GameTheme, viewerId?: string): boolean {
324
+ render(
325
+ sceneWrapper: SceneWrapper,
326
+ camera: Camera,
327
+ context2d: CanvasRenderingContext2D,
328
+ theme: GameTheme,
329
+ viewerId?: string,
330
+ ): boolean {
323
331
  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;
332
+ // On some mobile browsers (Android Chrome, iOS Safari) the context may be
333
+ // silently restored after a screen lock without firing `webglcontextrestored`.
334
+ // Detect this by checking the actual GL state instead of relying on the event.
335
+ const glCheck = this.renderer.getContext();
336
+ if (glCheck && !glCheck.isContextLost()) {
337
+ this.handleContextRestored();
338
+ // fall through to render
339
+ } else {
340
+ // Still lost — keep trying to restore. The previous attempt may have used
341
+ // the setSize fallback that doesn't always trigger `webglcontextrestored`.
342
+ this.maybeScheduleRestore();
343
+ return false;
344
+ }
328
345
  }
329
346
 
330
347
  // Detect silent context loss — on some Android WebViews the `webglcontextlost`
@@ -332,16 +349,16 @@ class WebGLRendererWrapper {
332
349
  // happily call composer.render() on a dead context, produce no pixels, and
333
350
  // strip the snapshot overlay → blank canvas until the user switches panels.
334
351
  const gl = this.renderer.getContext();
335
- if (gl && gl.isContextLost()) {
352
+ if (!gl || gl.isContextLost()) {
336
353
  this.handleContextLost("silent");
337
354
  return false;
338
355
  }
339
356
 
357
+ // Use physical pixel dimensions directly — Viewer.tsx is responsible for
358
+ // passing a canvas sized at the correct physical resolution.
340
359
  const canvas = context2d.canvas;
341
- const width = Math.floor(canvas.width / this.pixelRatio);
342
- const height = Math.floor(canvas.height / this.pixelRatio);
343
- const targetWidth = Math.ceil(width * this.pixelRatio);
344
- const targetHeight = Math.ceil(height * this.pixelRatio);
360
+ const width = canvas.width;
361
+ const height = canvas.height;
345
362
 
346
363
  // Ensure renderer can accommodate this size
347
364
  this.ensureRendererSize(width, height, viewerId);
@@ -353,8 +370,8 @@ class WebGLRendererWrapper {
353
370
  entry.referenceCount++;
354
371
 
355
372
  try {
356
- // Set scissor to render only to target region
357
- this.renderer.setScissor(0, 0, targetWidth, targetHeight);
373
+ // Set scissor and viewport in physical pixels (pixelRatio=1 on the renderer).
374
+ this.renderer.setScissor(0, 0, width, height);
358
375
  this.renderer.setViewport(0, 0, width, height);
359
376
 
360
377
  // Clear *depth only* in this panel's scissor region before composer.render().
@@ -372,18 +389,32 @@ class WebGLRendererWrapper {
372
389
  // Render using the composer
373
390
  entry.composer.render(sceneWrapper, camera);
374
391
 
375
- // Copy the rendered result to the 2D canvas
392
+ // Re-check for context loss after the render. The webglcontextlost event
393
+ // is dispatched asynchronously, so a loss that happened during composer.render
394
+ // wouldn't have been caught by the pre-render check above. If we proceeded to
395
+ // drawImage anyway, we'd copy stale pixels from the WebGL backbuffer (which
396
+ // is preserved across frames) and report success.
397
+ const glAfter = this.renderer.getContext();
398
+ if (!glAfter || glAfter.isContextLost()) {
399
+ this.handleContextLost("silent");
400
+ return false;
401
+ }
402
+
403
+ // Copy the rendered result to the 2D canvas.
404
+ // WebGL origin is bottom-left; canvas/DOM is top-left. When the renderer
405
+ // is larger than this viewer (multi-viewer sharing), the rendered region
406
+ // sits at the bottom of the WebGL canvas, so offset by the difference.
376
407
  const webglCanvas = this.renderer.domElement;
377
408
  context2d.drawImage(
378
409
  webglCanvas,
379
410
  0,
380
- webglCanvas.height - targetHeight, // Invert Y axis
381
- targetWidth,
382
- targetHeight, // Source width, height
411
+ webglCanvas.height - height, // Y-flip for bottom-left WebGL origin
412
+ width,
413
+ height,
414
+ 0,
383
415
  0,
384
- 0, // Dest x, y
385
- targetWidth,
386
- targetHeight, // Dest width, height
416
+ width,
417
+ height,
387
418
  );
388
419
  return true;
389
420
  } finally {
@@ -566,7 +566,13 @@ export class CameraWrapperPerspective {
566
566
  tween
567
567
  .to(newPosition, duration)
568
568
  .easing(Easing.Quadratic.InOut)
569
- .onUpdate((obj) => this.camera.position.set(obj.x, obj.y, obj.z)),
569
+ .onUpdate((obj) => {
570
+ this.camera.position.set(obj.x, obj.y, obj.z);
571
+ const planes = this.calculateOptimalNearFar(this.bbox, this.camera.position);
572
+ this.camera.near = planes.near;
573
+ this.camera.far = planes.far;
574
+ this.camera.updateProjectionMatrix();
575
+ }),
570
576
  );
571
577
  }
572
578
 
@@ -581,8 +587,8 @@ export class CameraWrapperPerspective {
581
587
  );
582
588
  }
583
589
 
584
- // Always tween near/far if they differ, even slightly
585
- if (nearFarDistance > 0.001) {
590
+ // Only tween near/far independently when camera position isn't changing
591
+ if (positionDistance === 0 && nearFarDistance > 0.001) {
586
592
  this.nearFarTween = this.chit.createTween({ near: currentNear, far: currentFar }, (tween) =>
587
593
  tween
588
594
  .to({ near: optimalPlanes.near, far: optimalPlanes.far }, duration)
@@ -593,8 +599,7 @@ export class CameraWrapperPerspective {
593
599
  this.camera.updateProjectionMatrix();
594
600
  }),
595
601
  );
596
- } else if (nearFarDistance > 0) {
597
- // If difference is tiny, just set immediately
602
+ } else if (positionDistance === 0 && nearFarDistance > 0) {
598
603
  this.camera.near = optimalPlanes.near;
599
604
  this.camera.far = optimalPlanes.far;
600
605
  this.camera.updateProjectionMatrix();
@@ -74,7 +74,6 @@ export class LightWrapper {
74
74
  l.shadow.camera.right = 0.1;
75
75
  l.shadow.camera.top = 0.1;
76
76
  l.shadow.camera.bottom = -0.1;
77
- l.shadow.camera.near = 0.000001;
78
77
  this.group.add(l);
79
78
  }
80
79
 
@@ -147,6 +146,26 @@ export class LightWrapper {
147
146
  camera.right = Math.max(right, b.max.x);
148
147
  camera.bottom = Math.min(bottom, b.min.y);
149
148
  camera.top = Math.max(top, b.max.y);
149
+
150
+ const lDist = light.position.length();
151
+ if (lDist > 0) {
152
+ const lightDir = light.position.clone().normalize();
153
+ let minDepth = Infinity;
154
+ let maxDepth = -Infinity;
155
+ [this.bbox.min.x, this.bbox.max.x].forEach((x) =>
156
+ [this.bbox.min.y, this.bbox.max.y].forEach((y) =>
157
+ [this.bbox.min.z, this.bbox.max.z].forEach((z) => {
158
+ const depth = lDist - (x * lightDir.x + y * lightDir.y + z * lightDir.z);
159
+ minDepth = Math.min(minDepth, depth);
160
+ maxDepth = Math.max(maxDepth, depth);
161
+ }),
162
+ ),
163
+ );
164
+ const margin = Math.max(1, (maxDepth - minDepth) * 0.1);
165
+ camera.near = Math.max(0.1, minDepth - margin);
166
+ camera.far = maxDepth + margin;
167
+ }
168
+
150
169
  camera.updateProjectionMatrix();
151
170
  }
152
171
  }
@@ -69,7 +69,7 @@ export class EffectComposer {
69
69
  Math.max(1, Math.floor(this._width * this._pixelRatio)),
70
70
  Math.max(1, Math.floor(this._height * this._pixelRatio)),
71
71
  );
72
- // renderTarget.depthTexture.type = FloatType;
72
+ if (renderer.capabilities.isWebGL2) renderTarget.depthTexture.type = FloatType;
73
73
 
74
74
  this.renderTarget = renderTarget;
75
75
 
@@ -83,7 +83,7 @@ export class EffectComposer {
83
83
  Math.max(1, Math.floor(this._width * this._pixelRatio)),
84
84
  Math.max(1, Math.floor(this._height * this._pixelRatio)),
85
85
  );
86
- // this.renderTarget2.depthTexture.type = FloatType;
86
+ if (renderer.capabilities.isWebGL2) this.renderTarget2.depthTexture.type = FloatType;
87
87
 
88
88
  this.copyPass = new ShaderPass(CopyShader, this.textureId);
89
89
  }
@@ -166,13 +166,13 @@ export class EffectComposer {
166
166
  if (this.renderTarget.depthTexture) {
167
167
  this.renderTarget.depthTexture.dispose();
168
168
  this.renderTarget.depthTexture = new DepthTexture(effectiveWidth, effectiveHeight);
169
- // this.renderTarget.depthTexture.type = FloatType;
169
+ if (this.renderer.capabilities.isWebGL2) this.renderTarget.depthTexture.type = FloatType;
170
170
  }
171
171
 
172
172
  if (this.renderTarget2.depthTexture) {
173
173
  this.renderTarget2.depthTexture.dispose();
174
174
  this.renderTarget2.depthTexture = new DepthTexture(effectiveWidth, effectiveHeight);
175
- // this.renderTarget2.depthTexture.type = FloatType;
175
+ if (this.renderer.capabilities.isWebGL2) this.renderTarget2.depthTexture.type = FloatType;
176
176
  }
177
177
 
178
178
  for (let i = 0; i < this.passes.length; i++) {
@@ -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,6 +102,8 @@ 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);
102
108
 
103
109
  if (this._material) {
@@ -114,6 +120,7 @@ export class CanvasStack implements IUpdatingCanvas {
114
120
  public width: number,
115
121
  public height: number,
116
122
  public operation: CanvasOperation,
123
+ private _mipLevelsOverride?: number,
117
124
  ) {
118
125
  this.canvas = document.createElement("canvas");
119
126
  this.canvas.width = width;
@@ -129,6 +136,56 @@ export class CanvasStack implements IUpdatingCanvas {
129
136
  CanvasStack.ensureContextRestoreSubscription();
130
137
 
131
138
  this.render();
139
+ this._initMipCanvases();
140
+ }
141
+
142
+ get mipMaps(): number {
143
+ if (this._mipLevelsOverride !== undefined) return this._mipLevelsOverride;
144
+ return this.operation.benefitsFromMipMap() ? 2 : 0;
145
+ }
146
+
147
+ private _initMipCanvases() {
148
+ this._mipCanvases = [];
149
+ this._mipContexts = [];
150
+ // Build the full mipmap chain down to 1×1. WebGL requires a complete chain
151
+ // when using a mipmap filter — a partial chain makes the texture incomplete
152
+ // and WebGL renders it as transparent.
153
+ let w = this.width;
154
+ let h = this.height;
155
+ while (w > 1 || h > 1) {
156
+ w = Math.max(1, Math.floor(w / 2));
157
+ h = Math.max(1, Math.floor(h / 2));
158
+ const c = document.createElement("canvas");
159
+ c.width = w;
160
+ c.height = h;
161
+ this._mipCanvases.push(c);
162
+ this._mipContexts.push(c.getContext("2d")!);
163
+ }
164
+ this._renderMipCanvases();
165
+ }
166
+
167
+ private _renderMipCanvases() {
168
+ const noop = () => {};
169
+ const numCustomLevels = this.mipMaps;
170
+ for (let i = 0; i < this._mipCanvases.length; i++) {
171
+ const ctx = this._mipContexts[i];
172
+ const c = this._mipCanvases[i];
173
+ if (i < numCustomLevels) {
174
+ // Custom render: canvas scale so text is rasterized natively at the
175
+ // smaller effective size rather than downsampled from the base canvas.
176
+ const scale = c.width / this.width;
177
+ ctx.save();
178
+ ctx.scale(scale, scale);
179
+ ctx.clearRect(0, 0, this.width, this.height);
180
+ this.operation.render(ctx, { x: 0, y: 0, w: this.width, h: this.height }, this.loadUrl.bind(this), noop);
181
+ ctx.restore();
182
+ } else {
183
+ // Complete the chain by box-filtering down from the previous level.
184
+ const prev = i === 0 ? this.canvas! : this._mipCanvases[i - 1];
185
+ ctx.clearRect(0, 0, c.width, c.height);
186
+ ctx.drawImage(prev, 0, 0, c.width, c.height);
187
+ }
188
+ }
132
189
  }
133
190
 
134
191
  private static _liveStacks: Set<CanvasStack> = new Set();
@@ -175,18 +232,35 @@ export class CanvasStack implements IUpdatingCanvas {
175
232
  }
176
233
 
177
234
  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;
181
- this._texture = new Texture(
182
- this.canvas,
183
- UVMapping,
184
- ClampToEdgeWrapping,
185
- ClampToEdgeWrapping,
186
- LinearFilter,
187
- useMipmaps ? LinearMipmapLinearFilter : LinearFilter,
188
- );
189
- this._texture.generateMipmaps = useMipmaps;
235
+ const wrapper = getWebGlRendererInstance();
236
+ if (this.mipMaps > 0) {
237
+ this._texture = new Texture(
238
+ this.canvas,
239
+ UVMapping,
240
+ ClampToEdgeWrapping,
241
+ ClampToEdgeWrapping,
242
+ LinearFilter,
243
+ LinearMipmapLinearFilter,
244
+ );
245
+ this._texture.generateMipmaps = false;
246
+ // mipmaps[i] is uploaded as WebGL level i. Level 0 must be the base
247
+ // canvas; levels 1..N are the custom-rendered smaller canvases.
248
+ // Rendering text natively at each mip size is sharper than GPU box-filtering.
249
+ this._texture.mipmaps = [this.canvas, ...this._mipCanvases];
250
+ } else {
251
+ // WebGL1 only supports mipmaps on power-of-two textures, and these
252
+ // canvases are arbitrarily sized. Skip mipmap generation outside WebGL2.
253
+ this._texture = new Texture(
254
+ this.canvas,
255
+ UVMapping,
256
+ ClampToEdgeWrapping,
257
+ ClampToEdgeWrapping,
258
+ LinearFilter,
259
+ LinearMipmapLinearFilter,
260
+ );
261
+ this._texture.generateMipmaps = true;
262
+ }
263
+ this._texture.anisotropy = wrapper?.maxAnisotropy ?? 1;
190
264
  this._texture.needsUpdate = true;
191
265
  this._texture.colorSpace = SRGBColorSpace;
192
266
 
@@ -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([]));