A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
canvas engine
sora4a6440ec40f5
diff --git a/src/App.tsx b/src/App.tsxindex 91216c4..4418863 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -690,19 +690,25 @@ export function App() {async () => {const cur = recoveryStateRef.current;const doc = cur.documents.find((d) => d.id === activeDocumentId);- const firstCanvas =- layerCanvasesRef.current.get(doc?.activeLayerId || cur.activeLayerId) ||- layerCanvasesRef.current.values().next().value;- if (!firstCanvas) return null;- return new Promise((resolve) => {- firstCanvas.toBlob((blob: Blob | null) => {- if (!blob) return resolve(null);- blob- .arrayBuffer()- .then((buf: ArrayBuffer) => resolve(new Uint8Array(buf)))- .catch(() => resolve(null));- }, 'image/png');- });+ const targetLayerId = doc?.activeLayerId || cur.activeLayerId;+ const dims = doc?.dimensions || cur.dimensions;+ if (!targetLayerId || dims.width <= 0 || dims.height <= 0) return null;+ try {+ const thumbW = 120;+ const thumbH = Math.max(68, Math.round((dims.height / Math.max(1, dims.width)) * thumbW));+ const dataUrl = globalTileGrid.generateThumbnail(targetLayerId, thumbW, thumbH, dims);+ const commaIdx = dataUrl.indexOf(',');+ if (commaIdx < 0) return null;+ const b64 = dataUrl.slice(commaIdx + 1);+ const binStr = atob(b64);+ const bytes = new Uint8Array(binStr.length);+ for (let i = 0; i < binStr.length; i++) {+ bytes[i] = binStr.charCodeAt(i);+ }+ return bytes;+ } catch {+ return null;+ }});}, [activeDocumentId, layerCanvasesRef]);diff --git a/src/hooks/useCanvasDrawing.ts b/src/hooks/useCanvasDrawing.tsindex 60b9df9..d974e36 100644--- a/src/hooks/useCanvasDrawing.ts+++ b/src/hooks/useCanvasDrawing.ts@@ -230,6 +230,7 @@ export function useCanvasDrawing({const latestPredictedRef = useRef<{ predEvents: PointerEvent[]; vRect: DOMRect } | null>(null);const clearPredictedCanvas = useCallback(() => {+ if (!isPredictedCanvasDirtyRef.current) return;const pCanvas = getPredictedCanvas();if (pCanvas) {const pCtx = get2DContext(pCanvas);@@ -360,6 +361,8 @@ export function useCanvasDrawing({const liveOrigCanvasTilesRef = useRef<Map<number, ImageData>>(new Map());const liveBeforeTileSnapshotRef = useRef<Map<string, { format: TileFormat; data: Uint8Array | null }>>(new Map());const liveNeedsNotifyRef = useRef<boolean>(false);+ const isBatchFlushingRef = useRef<boolean>(false);+ const pendingBatchSyncRectRef = useRef<{ minX: number; minY: number; maxX: number; maxY: number } | null>(null);const lastStrokeEndRef = useRef<{ x: number; y: number; pressure: number; width: number; layerId: string } | null>(null);const isShiftLineStrokeRef = useRef<boolean>(false);const historyQueueRef = useRef<Promise<void>>(Promise.resolve());@@ -612,10 +615,15 @@ export function useCanvasDrawing({if (canvas) {const isLarge = canvas.width * canvas.height > 1024 * 1024 && globalTileGrid.isLayerIngested(targetLayerId);- const targetH = Math.max(38, Math.round((canvas.height / Math.max(1, canvas.width)) * 60));- item.thumbnailUrl = isLarge- ? globalTileGrid.generateThumbnail(targetLayerId, 60, targetH, { width: canvas.width, height: canvas.height })- : createCanvasThumbnail(canvas, !isBackgroundLayerId(targetLayerId));+ if (isLarge && hasDeltas) {+ const existingLayerThumb = layersRef.current?.find((l) => l.id === targetLayerId)?.thumbnailUrl || '';+ item.thumbnailUrl = existingLayerThumb;+ } else {+ const targetH = Math.max(38, Math.round((canvas.height / Math.max(1, canvas.width)) * 60));+ item.thumbnailUrl = isLarge+ ? globalTileGrid.generateThumbnail(targetLayerId, 60, targetH, { width: canvas.width, height: canvas.height })+ : createCanvasThumbnail(canvas, !isBackgroundLayerId(targetLayerId));+ }}syncHistoryState();@@ -663,9 +671,9 @@ export function useCanvasDrawing({if (idleCallbackIdRef.current === null) {const scheduleRun = () => {if (typeof window !== 'undefined' && 'requestIdleCallback' in window) {- idleCallbackIdRef.current = (window as any).requestIdleCallback(runTasks, { timeout: 250 });+ idleCallbackIdRef.current = (window as any).requestIdleCallback(runTasks, { timeout: 1200 });} else {- idleCallbackIdRef.current = setTimeout(runTasks, 32);+ idleCallbackIdRef.current = setTimeout(runTasks, 64);}};const runTasks = () => {@@ -766,7 +774,18 @@ export function useCanvasDrawing({const tw = Math.min(TILE_SIZE, canvas.width - ox);const th = Math.min(TILE_SIZE, canvas.height - oy);if (tw <= 0 || th <= 0) continue;- const origImg = canvasCtx.getImageData(ox, oy, tw, th);+ if (liveStrokeIsolationRef.current && liveAccumCanvasRef.current) {+ const accCtx = get2DContext(liveAccumCanvasRef.current);+ accCtx?.clearRect(ox, oy, tw, th);+ }+ let origImg: ImageData;+ if (globalTileGrid.isLayerIngested(layerId) && typeof ImageData !== 'undefined') {+ const rawTile = globalTileGrid.readImageData(layerId, ox, oy, tw, th);+ origImg = new ImageData(new Uint8ClampedArray(rawTile.data), tw, th);+ canvasCtx.putImageData(origImg, ox, oy);+ } else {+ origImg = canvasCtx.getImageData(ox, oy, tw, th);+ }liveOrigCanvasTilesRef.current.set(numKey, origImg);if (!globalTileGrid.isLayerIngested(layerId) && !globalTileGrid.getTile(layerId, tx, ty, 0)) {const activeLayer = layersRef.current?.find((l) => l.id === layerId);@@ -1748,20 +1767,36 @@ export function useCanvasDrawing({stampRemainderDistRef.current = renderSegmentToContext(canvasCtx, segStart, c1, c2, segEnd, false);canvasCtx.restore();}- syncLiveRegionToTiles(- canvas,- canvasCtx,- currentLayerId,- segMinX,- segMinY,- segMaxX,- segMaxY,- isMonochrome,- activeLayer,- bs,- isEraser,- isBgEraser- );+ if (isBatchFlushingRef.current) {+ if (!pendingBatchSyncRectRef.current) {+ pendingBatchSyncRectRef.current = {+ minX: segMinX,+ minY: segMinY,+ maxX: segMaxX,+ maxY: segMaxY,+ };+ } else {+ pendingBatchSyncRectRef.current.minX = Math.min(pendingBatchSyncRectRef.current.minX, segMinX);+ pendingBatchSyncRectRef.current.minY = Math.min(pendingBatchSyncRectRef.current.minY, segMinY);+ pendingBatchSyncRectRef.current.maxX = Math.max(pendingBatchSyncRectRef.current.maxX, segMaxX);+ pendingBatchSyncRectRef.current.maxY = Math.max(pendingBatchSyncRectRef.current.maxY, segMaxY);+ }+ } else {+ syncLiveRegionToTiles(+ canvas,+ canvasCtx,+ currentLayerId,+ segMinX,+ segMinY,+ segMaxX,+ segMaxY,+ isMonochrome,+ activeLayer,+ bs,+ isEraser,+ isBgEraser+ );+ }return;}}@@ -2078,6 +2113,7 @@ export function useCanvasDrawing({}pCtx.restore();+ isPredictedCanvasDirtyRef.current = true;},[clearPredictedCanvas, getPredictedCanvas]);@@ -2093,9 +2129,8 @@ export function useCanvasDrawing({const predData = latestPredictedRef.current;latestPredictedRef.current = null;const vRect = getViewportRect();- if (vRect && allStrokePointsRef.current.length > 0) {+ if (vRect && allStrokePointsRef.current.length > 0 && !drewDirectlyOnLayerCanvasRef.current) {renderPredictedStroke(predData ? predData.predEvents : [], vRect);- isPredictedCanvasDirtyRef.current = true;} else if (isPredictedCanvasDirtyRef.current) {clearPredictedCanvas();}@@ -2115,6 +2150,9 @@ export function useCanvasDrawing({let batchMaxY = -Infinity;let maxStrokeWidth = 0;+ isBatchFlushingRef.current = true;+ pendingBatchSyncRectRef.current = null;+for (let i = 0; i < queueLen; i++) {const item = queue[i];applyStabilizedPointAndRender(@@ -2139,7 +2177,35 @@ export function useCanvasDrawing({}}queue.length = 0;+ isBatchFlushingRef.current = false;+ const pendingSync = pendingBatchSyncRectRef.current as { minX: number; minY: number; maxX: number; maxY: number } | null;+ pendingBatchSyncRectRef.current = null;+ if (pendingSync && drewDirectlyOnLayerCanvasRef.current) {+ const canvas = getActiveCanvas();+ const canvasCtx = canvas ? get2DContext(canvas) : null;+ if (canvas && canvasCtx) {+ const currentLayerId = activeLayerIdRef.current;+ const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);+ const isMonochrome = colorModeRef.current === 'monochrome' || activeLayer?.expressionColor === 'monochrome';+ const isEraser = toolRef.current === 'eraser';+ const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);+ syncLiveRegionToTiles(+ canvas,+ canvasCtx,+ currentLayerId,+ pendingSync.minX,+ pendingSync.minY,+ pendingSync.maxX,+ pendingSync.maxY,+ isMonochrome,+ activeLayer,+ brushSettingsRef.current,+ isEraser,+ isBgEraser+ );+ }+ }if (batchMinX <= batchMaxX) {const dims = dimensionsRef.current;@@ -2170,9 +2236,8 @@ export function useCanvasDrawing({const predData = latestPredictedRef.current;latestPredictedRef.current = null;const vRect = getViewportRect();- if (vRect && allStrokePointsRef.current.length > 0) {+ if (vRect && allStrokePointsRef.current.length > 0 && !drewDirectlyOnLayerCanvasRef.current) {renderPredictedStroke(predData ? predData.predEvents : [], vRect);- isPredictedCanvasDirtyRef.current = true;} else if (isPredictedCanvasDirtyRef.current) {clearPredictedCanvas();}@@ -2183,6 +2248,7 @@ export function useCanvasDrawing({getActiveCanvas,getViewportRect,renderPredictedStroke,+ syncLiveRegionToTiles,]);@@ -2472,9 +2538,6 @@ export function useCanvasDrawing({liveAccumCanvasRef.current = document.createElement('canvas');liveAccumCanvasRef.current.width = canvas.width;liveAccumCanvasRef.current.height = canvas.height;- } else {- const accCtx = get2DContext(liveAccumCanvasRef.current);- accCtx?.clearRect(0, 0, canvas.width, canvas.height);}}@@ -3202,7 +3265,7 @@ export function useCanvasDrawing({const beforeSnapshot = new Map<string, { format: TileFormat; data: Uint8Array | null }>(liveBeforeTileSnapshotRef.current);- const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);+ const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);enqueueHistoryTask(() => {pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);});diff --git a/src/hooks/useLayerManager.ts b/src/hooks/useLayerManager.tsindex 14a70b3..5250449 100644--- a/src/hooks/useLayerManager.ts+++ b/src/hooks/useLayerManager.ts@@ -371,8 +371,9 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Usconst layersRef = useRef(layers);layersRef.current = layers;- // Track layer mutations and log to recovery service WAL+ // Track structural layer mutations and log to recovery service WAL (ignore pure thumbnailUrl refreshes)const isInitialLayerMount = useRef(true);+ const lastLoggedLayersSigRef = useRef<string>('');useEffect(() => {if (isInitialLayerMount.current) {isInitialLayerMount.current = false;@@ -380,6 +381,11 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us}const sId = activeSessionId || recoveryService.getCurrentSessionId();if (sId && layers.length > 0) {+ const sig = `${activeLayerId}|` + layers+ .map((l) => `${l.id}:${l.name}:${l.visible ? 1 : 0}:${l.opacity}:${l.blendMode}:${l.locked ? 1 : 0}:${l.clipped ? 1 : 0}:${l.alphaLocked ? 1 : 0}:${l.parentId || ''}:${l.expressionColor || ''}:${l.toneEnabled ? 1 : 0}`)+ .join(';');+ if (sig === lastLoggedLayersSigRef.current) return;+ lastLoggedLayersSigRef.current = sig;recoveryService.logLayerMutation(sId, 'update', layers, activeLayerId);}}, [layers, activeSessionId, activeLayerId]);@@ -558,10 +564,12 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: UsthumbDebounceTimersRef.current.delete(id);run();} else {+ const isLargeDoc = _dimensions.width * _dimensions.height > 1024 * 1024;+ const delayMs = isLargeDoc ? 900 : 350;const timer = setTimeout(() => {thumbDebounceTimersRef.current.delete(id);run();- }, 350);+ }, delayMs);thumbDebounceTimersRef.current.set(id, timer);}}, [_dimensions]);diff --git a/src/services/recoveryService.ts b/src/services/recoveryService.tsindex a31d5e6..263f68c 100644--- a/src/services/recoveryService.ts+++ b/src/services/recoveryService.ts@@ -294,16 +294,9 @@ class RecoveryService {}}- // Increment checkpoint stroke counter+ // Increment checkpoint stroke counter and defer full grid snapshot to idle timer so active drawing never freezesthis.strokesSinceCheckpoint++;-- // Check Checkpoint Policy: 25-30 completed strokes- if (this.strokesSinceCheckpoint >= CHECKPOINT_STROKE_THRESHOLD) {- void this.triggerCheckpoint(activeId);- } else {- // Schedule 30-second idle timer- this.resetIdleCheckpointTimer(activeId);- }+ this.resetIdleCheckpointTimer(activeId);}/**diff --git a/src/utils/__tests__/strokeHandshake.test.ts b/src/utils/__tests__/strokeHandshake.test.tsindex 60aaace..7785ffe 100644--- a/src/utils/__tests__/strokeHandshake.test.ts+++ b/src/utils/__tests__/strokeHandshake.test.ts@@ -316,4 +316,55 @@ describe('Zero-Flicker Stroke Handshake & WYSIWYG Monochrome Pipeline', () => {expect(sampled.g).toBe(200);expect(sampled.a).toBeCloseTo(1.0, 2);});++ it('Ctrl+Z undo never deletes untouched pre-existing tiles inside a stroke bounding box dirtyRect', () => {+ const layerId = 'layer-carbon';+ const existingInk = new Uint8ClampedArray(20 * 20 * 4);+ for (let i = 0; i < 20 * 20; i++) {+ existingInk[i * 4 + 3] = 255;+ }++ // 1. Pre-existing strokes ('CARBON') in all 4 tiles: (0,0), (1,0), (0,1), (1,1)+ grid.writeImageData(layerId, { data: existingInk, width: 20, height: 20 }, 10, 10, 'color-32bit');+ grid.writeImageData(layerId, { data: existingInk, width: 20, height: 20 }, 300, 10, 'color-32bit');+ grid.writeImageData(layerId, { data: existingInk, width: 20, height: 20 }, 10, 300, 'color-32bit');+ grid.writeImageData(layerId, { data: existingInk, width: 20, height: 20 }, 300, 300, 'color-32bit');++ // 2. New diagonal stroke only touches tiles (0,0) and (1,1), so ensureLiveTileSnapshots only snapshots (0,0) and (1,1)+ const liveBeforeSnapshot = new Map();+ for (const [k, v] of grid.snapshotTilesInRect(layerId, { x: 0, y: 0, width: 100, height: 100 })) {+ liveBeforeSnapshot.set(k, v);+ }+ for (const [k, v] of grid.snapshotTilesInRect(layerId, { x: 260, y: 260, width: 100, height: 100 })) {+ liveBeforeSnapshot.set(k, v);+ }++ // Mutate tiles (0,0) and (1,1) with new red stroke+ const newStroke = new Uint8ClampedArray(20 * 20 * 4);+ for (let i = 0; i < 20 * 20; i++) {+ newStroke[i * 4] = 255;+ newStroke[i * 4 + 3] = 255;+ }+ grid.writeImageData(layerId, { data: newStroke, width: 20, height: 20 }, 50, 50, 'color-32bit');+ grid.writeImageData(layerId, { data: newStroke, width: 20, height: 20 }, 340, 340, 'color-32bit');++ // 3. Compute deltas even if full 512x512 bounding box dirtyRect is passed+ const deltas = grid.computeDeltasFromSnapshot(liveBeforeSnapshot, layerId, {+ x: 0,+ y: 0,+ width: 512,+ height: 512,+ });+ expect(deltas.length).toBe(2);++ // 4. Press Ctrl+Z (undo): untouched tiles (1,0) and (0,1) MUST still exist and retain their original pixels!+ grid.applyTileDeltas(deltas, 'undo');+ expect(grid.getTile(layerId, 1, 0)).not.toBeNull();+ expect(grid.getTile(layerId, 0, 1)).not.toBeNull();+ expect(grid.readImageData(layerId, 300, 10, 1, 1).data[3]).toBe(255);+ expect(grid.readImageData(layerId, 10, 300, 1, 1).data[3]).toBe(255);+ // And touched tiles (0,0) and (1,1) must be restored to their pre-stroke CARBON pixels without the red stroke+ expect(grid.readImageData(layerId, 10, 10, 1, 1).data[3]).toBe(255);+ expect(grid.readImageData(layerId, 50, 50, 1, 1).data[3]).toBe(0);+ });});diff --git a/src/utils/canvasUtils.ts b/src/utils/canvasUtils.tsindex 320be2f..136ed93 100644--- a/src/utils/canvasUtils.ts+++ b/src/utils/canvasUtils.ts@@ -19,7 +19,7 @@ import {export const CANVAS_2D_CONTEXT_OPTIONS: CanvasRenderingContext2DSettings = {alpha: true,desynchronized: false,- willReadFrequently: false,+ willReadFrequently: true,};/**diff --git a/src/utils/tileEngine.ts b/src/utils/tileEngine.tsindex 31c503c..990768e 100644--- a/src/utils/tileEngine.ts+++ b/src/utils/tileEngine.ts@@ -383,6 +383,20 @@ const _downsampleRgbaView = new Uint8Array(_downsampleRgbaScratch.buffer);const _downsample8BitScratch = new Uint8Array(BYTES_8BIT);const _downsample1BitScratch = new Uint8Array(BYTES_1BIT);+// Precomputed 256-entry LUT mapping an 8-bit 1-bit-row byte to a 4-bit downsampled nibble (2x1 horizontal OR)+const _lut1BitByteToNibble = (() => {+ const lut = new Uint8Array(256);+ for (let b = 0; b < 256; b++) {+ let nib = 0;+ if (b & 0xc0) nib |= 0x08;+ if (b & 0x30) nib |= 0x04;+ if (b & 0x0c) nib |= 0x02;+ if (b & 0x03) nib |= 0x01;+ lut[b] = nib;+ }+ return lut;+})();+/*** Downsample 4 child tiles (2x2 cluster) at LOD k-1 into a single destination tile at LOD k.* Reuses pre-allocated scratch buffers for zero 256KB heap allocations during zoom-out LOD builds.@@ -450,6 +464,11 @@ export function downsample2x2ToParentTile(dst[outIdx + 1] = 0;dst[outIdx + 2] = 0;dst[outIdx + 3] = 0;+ } else if (sumA === 1020) {+ dst[outIdx] = (childData[p00] + childData[p10] + childData[p01] + childData[p11] + 2) >> 2;+ dst[outIdx + 1] = (childData[p00 + 1] + childData[p10 + 1] + childData[p01 + 1] + childData[p11 + 1] + 2) >> 2;+ dst[outIdx + 2] = (childData[p00 + 2] + childData[p10 + 2] + childData[p01 + 2] + childData[p11 + 2] + 2) >> 2;+ dst[outIdx + 3] = 255;} else {dst[outIdx + 3] = sumA >> 2;dst[outIdx] = Math.round(@@ -503,22 +522,18 @@ export function downsample2x2ToParentTile(packRGBATo1Bit(_downsampleRgbaScratch, _downsample1BitScratch);childData = _downsample1BitScratch;}+ const dstByteBaseX = xBase >> 3;for (let ly = 0; ly < 128; ly++) {const sy0 = ly << 1;- const sy1 = sy0 + 1;- const dy = yBase + ly;-- for (let lx = 0; lx < 128; lx++) {- const sx0 = lx << 1;- const sx1 = sx0 + 1;- const dx = xBase + lx;-- const b0 = getPixel1Bit(childData, sx0, sy0);- const b1 = getPixel1Bit(childData, sx1, sy0);- const b2 = getPixel1Bit(childData, sx0, sy1);- const b3 = getPixel1Bit(childData, sx1, sy1);-- setPixel1Bit(dst, dx, dy, (b0 | b1 | b2 | b3) !== 0);+ const srcRow0 = sy0 << 5;+ const srcRow1 = (sy0 + 1) << 5;+ const dstRow = ((yBase + ly) << 5) + dstByteBaseX;++ for (let bx = 0; bx < 16; bx++) {+ const sBx = bx << 1;+ const comb0 = childData[srcRow0 + sBx] | childData[srcRow1 + sBx];+ const comb1 = childData[srcRow0 + sBx + 1] | childData[srcRow1 + sBx + 1];+ dst[dstRow + bx] = (_lut1BitByteToNibble[comb0] << 4) | _lut1BitByteToNibble[comb1];}}}@@ -955,9 +970,10 @@ export class SparseTileGrid {private ingestedLayers: Set<string> = new Set();private dirtyLodTiles: Set<string> = new Set();private scratchRGBA: Uint8ClampedArray = new Uint8ClampedArray(BYTES_32BIT);+ private writeScratchRGBA: Uint8ClampedArray = new Uint8ClampedArray(BYTES_32BIT);+ private thumbCanvas: HTMLCanvasElement | null = null;private listeners: Set<(immediate?: boolean) => void> = new Set();private memoryManager: TileMemoryManager | null = null;- private idleCallbackScheduled: boolean = false;constructor(memoryManagerOptions?: TileMemoryManagerOptions) {this.memoryManager = new TileMemoryManager(this, memoryManagerOptions);@@ -1175,7 +1191,7 @@ export class SparseTileGrid {const maxTileX = pixelToTileCoord(destX + w - 1, 0);const maxTileY = pixelToTileCoord(destY + h - 1, 0);- const tileScratch = new Uint8ClampedArray(BYTES_32BIT);+ const tileScratch = this.writeScratchRGBA;const srcData = imgData.data;for (let ty = minTileY; ty <= maxTileY; ty++) {@@ -1349,37 +1365,32 @@ export class SparseTileGrid {maxY = Math.min(targetCanvas.height, Math.ceil(dirtyRect.y + dirtyRect.height));}- ctx.clearRect(minX, minY, maxX - minX, maxY - minY);+ if (maxX <= minX || maxY <= minY) return;const minTileX = pixelToTileCoord(minX, 0);const minTileY = pixelToTileCoord(minY, 0);const maxTileX = pixelToTileCoord(maxX - 1, 0);const maxTileY = pixelToTileCoord(maxY - 1, 0);- let helperCanvas: HTMLCanvasElement | null = null;- let helperCtx: CanvasRenderingContext2D | null = null;-for (let ty = minTileY; ty <= maxTileY; ty++) {const tileDocY = ty * TILE_SIZE;+ const validH = Math.min(TILE_SIZE, targetCanvas.height - tileDocY);+ if (validH <= 0) continue;for (let tx = minTileX; tx <= maxTileX; tx++) {- const tile = this.getTile(layerId, tx, ty, 0);- if (!tile) continue;-const tileDocX = tx * TILE_SIZE;- const rgba = this.getTileAsRGBA(tile);-- if (!helperCanvas && typeof document !== 'undefined') {- helperCanvas = document.createElement('canvas');- helperCanvas.width = TILE_SIZE;- helperCanvas.height = TILE_SIZE;- helperCtx = helperCanvas.getContext('2d');+ const validW = Math.min(TILE_SIZE, targetCanvas.width - tileDocX);+ if (validW <= 0) continue;+ const tile = this.getTile(layerId, tx, ty, 0);+ if (!tile) {+ ctx.clearRect(tileDocX, tileDocY, validW, validH);+ continue;}- if (helperCtx && helperCanvas) {+ const rgba = this.getTileAsRGBA(tile);+ if (typeof ImageData !== 'undefined') {const clamped = new Uint8ClampedArray(rgba.buffer as ArrayBuffer, rgba.byteOffset, BYTES_32BIT);const imgData = new ImageData(clamped, TILE_SIZE, TILE_SIZE);- helperCtx.putImageData(imgData, 0, 0);- ctx.drawImage(helperCanvas, tileDocX, tileDocY);+ ctx.putImageData(imgData, tileDocX, tileDocY, 0, 0, validW, validH);}}}@@ -1396,9 +1407,12 @@ export class SparseTileGrid {docDimensions: { width: number; height: number }): string {if (typeof document === 'undefined') return '';- const canvas = document.createElement('canvas');- canvas.width = thumbWidth;- canvas.height = thumbHeight;+ if (!this.thumbCanvas) {+ this.thumbCanvas = document.createElement('canvas');+ }+ const canvas = this.thumbCanvas;+ if (canvas.width !== thumbWidth) canvas.width = thumbWidth;+ if (canvas.height !== thumbHeight) canvas.height = thumbHeight;const ctx = canvas.getContext('2d');if (!ctx) return '';@@ -1407,15 +1421,12 @@ export class SparseTileGrid {const docW = Math.max(1, docDimensions.width);const docH = Math.max(1, docDimensions.height);- // Prefer LOD 3 (1/8 scale) or LOD 2 if available, else LOD 0- if (this.dirtyLodTiles.size > 0) {- this.flushMipmaps(layerId);- }- let renderLod = 3;- let tiles = this.getLayerTiles(layerId, 3);+ // Sample directly from LOD 0 tiles without flushing full mipmap pyramids+ let renderLod = 0;+ let tiles = this.getLayerTiles(layerId, 0);if (tiles.length === 0) {- renderLod = 0;- tiles = this.getLayerTiles(layerId, 0);+ renderLod = 3;+ tiles = this.getLayerTiles(layerId, 3);}if (tiles.length === 0) {@@ -1497,29 +1508,6 @@ export class SparseTileGrid {existing.dirty = true;}}- this.scheduleIdleDownsampling();- }-- private scheduleIdleDownsampling(): void {- if (this.idleCallbackScheduled || this.dirtyLodTiles.size === 0) return;- this.idleCallbackScheduled = true;-- const run = () => {- this.idleCallbackScheduled = false;- const updated = this.updateDirtyMipmaps(16);- if (updated > 0) {- this.notifyChange();- }- if (this.dirtyLodTiles.size > 0) {- this.scheduleIdleDownsampling();- }- };-- if (typeof window !== 'undefined' && 'requestIdleCallback' in window) {- (window as any).requestIdleCallback(run, { timeout: 100 });- } else {- setTimeout(run, 16);- }}/**@@ -1869,7 +1857,7 @@ export class SparseTileGrid {const deltas: TileDelta[] = [];const keysToCheck = new Set<string>(beforeSnapshot.keys());- if (bounds && bounds.width > 0 && bounds.height > 0) {+ if (beforeSnapshot.size === 0 && bounds && bounds.width > 0 && bounds.height > 0) {const minTileX = pixelToTileCoord(bounds.x, 0);const minTileY = pixelToTileCoord(bounds.y, 0);const maxTileX = pixelToTileCoord(bounds.x + bounds.width - 1, 0);@@ -1882,6 +1870,7 @@ export class SparseTileGrid {}for (const key of keysToCheck) {+ if (beforeSnapshot.size > 0 && !beforeSnapshot.has(key)) continue;const before = beforeSnapshot.get(key);const { tileX, tileY } = parseTileKey(key);const currentTile = this.getTile(layerId, tileX, tileY, 0);