Skip to content
Source
Sign inSign up
samwillis/one-million-boxes
Open History to see the last commit

DotPatternCache.ts

222 lines6.9 KB

1/**
2 * Cache for the tiled dot pattern.
3 * Pre-renders dots at grid intersections and uses ctx.createPattern() for efficient tiling.
4 *
5 * Using a larger tile (4x4 cells = 5x5 dots) provides variation before repeating.
6 * Dots are offset by half a cell so tile seams fall at cell centers.
7 */
8​
9import { GRID_HEIGHT, GRID_WIDTH } from "../../../shared/game-config"
10import { drawWobblyDot } from "../../lib/hand-drawn"
11​
12const DOT_COLOR = `#494B50`
13​
14// Tile covers multiple grid cells for variation (5x5 = 25 dots per tile)
15const TILE_CELLS = 4
16​
17// Cache tiles at different cell sizes for crisp rendering at different zoom levels
18interface CacheEntry {
19 canvas: OffscreenCanvas
20 lastUsed: number
22const tileCache = new Map<string, CacheEntry>()
23​
24// Available cell sizes to cache (dots only render when scale >= 15)
25const CACHED_CELL_SIZES = [16, 32, 64, 128, 256]
26​
27// Dispose tiles not used within this time (in ms)
28const CACHE_TTL = 5_000 // 5 seconds
29​
30// Cleanup interval
31let cleanupTimer: ReturnType<typeof setInterval> | null = null
32​
33// Track the currently active tile size (never evict this one)
34let currentTileKey: string | null = null
35​
36function startCleanupTimer(): void {
37 if (cleanupTimer) return
38 cleanupTimer = setInterval(() => {
39 const now = Date.now()
40 for (const [key, entry] of tileCache) {
41 // Never evict the currently active tile
42 if (key === currentTileKey) continue
43 if (now - entry.lastUsed > CACHE_TTL) {
44 tileCache.delete(key)
45 }
46 }
47 // Stop timer if cache is empty
48 if (tileCache.size === 0 && cleanupTimer) {
49 clearInterval(cleanupTimer)
50 cleanupTimer = null
51 }
52 }, 10_000) // Check every 10 seconds
54​
55/**
56 * Get the best cached cell size for the given target size.
57 * Returns the smallest cached size that's >= target (to scale down, not up).
58 */
59function getBestCellSize(targetSize: number): number {
60 for (const size of CACHED_CELL_SIZES) {
61 if (size >= targetSize) return size
62 }
63 return CACHED_CELL_SIZES[CACHED_CELL_SIZES.length - 1]
65​
66/**
67 * Create a dot tile canvas at the specified cell size.
68 *
69 * Dots are placed at grid intersections. The tile is offset by half a cell
70 * so dots are fully inside the tile and seams fall at cell centers.
71 */
72function createTile(cellSize: number, pixelRatio: number): OffscreenCanvas | null {
73 const tileSize = TILE_CELLS * cellSize
74 // Render logical tile geometry into a Retina-sized texture. Use the actual
75 // rounded density so fractional display ratios cannot introduce tile seams.
76 const pixelSize = Math.ceil(tileSize * pixelRatio)
77 const canvas = new OffscreenCanvas(pixelSize, pixelSize)
78 const ctx = canvas.getContext(`2d`)
79 if (!ctx) return null
80 ctx.scale(pixelSize / tileSize, pixelSize / tileSize)
81​
82 const dotRadius = Math.max(2, cellSize * 0.15)
83 ctx.fillStyle = DOT_COLOR
84​
85 // Offset: tile origin is at grid position (-0.5, -0.5)
86 // So grid intersection (0,0) is at tile position (cellSize/2, cellSize/2)
87 const offset = cellSize / 2
88​
89 let seed = 1000 // Different seed range from edges
90​
91 // Draw dots at grid intersections
92 // For a TILE_CELLS x TILE_CELLS tile, we have (TILE_CELLS) x (TILE_CELLS) dots
93 // (the +1 dots at the far edges will come from adjacent tiles)
94 for (let row = 0; row < TILE_CELLS; row++) {
95 for (let col = 0; col < TILE_CELLS; col++) {
96 const x = offset + col * cellSize
97 const y = offset + row * cellSize
98 drawWobblyDot(ctx, x, y, dotRadius, seed++)
99 }
100 }
101​
102 return canvas
104​
105/**
106 * Get or create a cached tile at the appropriate size.
107 */
108function getTile(
109 targetCellSize: number,
110 pixelRatio: number,
111): {
112 canvas: OffscreenCanvas
113 cellSize: number
114 pixelRatio: number
115} | null {
116 const cellSize = getBestCellSize(targetCellSize)
117​
118 // Track current tile size so it's never evicted
119 const key = `${cellSize}:${pixelRatio}`
120 currentTileKey = key
121​
122 let entry = tileCache.get(key)
123 if (entry) {
124 // Update last used time
125 entry.lastUsed = Date.now()
126 } else {
127 const canvas = createTile(cellSize, pixelRatio)
128 if (canvas) {
129 entry = { canvas, lastUsed: Date.now() }
130 tileCache.set(key, entry)
131 startCleanupTimer()
132 }
133 }
134​
135 if (!entry) return null
136 return {
137 canvas: entry.canvas,
138 cellSize,
139 pixelRatio: entry.canvas.width / (TILE_CELLS * cellSize),
140 }
142​
143/**
144 * Render the dot pattern across the visible area.
145 * Uses pattern.setTransform() to scale the pattern to match the current grid size.
146 * Clips to the playable area boundaries to prevent overflow.
147 */
148export function renderDotPattern(
149 ctx: CanvasRenderingContext2D,
150 gridSize: number,
151 viewCenterX: number,
152 viewCenterY: number,
153 canvasWidth: number,
154 canvasHeight: number,
155): void {
156 // Only render dots when zoomed in enough (matches original threshold)
157 if (gridSize < 15) return
158​
159 // The canvas transform carries its backing-store density; gridSize remains
160 // in CSS pixels so dot sizes, dash lengths and the sketch stay unchanged.
161 const matrixScale = ctx.getTransform()
162 const density = Math.hypot(matrixScale.a, matrixScale.b) || 1
163 const tileData = getTile(gridSize, density)
164 if (!tileData) return
165​
166 const { canvas, cellSize, pixelRatio } = tileData
167​
168 const pattern = ctx.createPattern(canvas, `repeat`)
169 if (!pattern) return
170​
171 // Scale factor to match current grid size
172 const scale = gridSize / (cellSize * pixelRatio)
173​
174 // World (0,0) in screen coordinates
175 const worldOriginX = canvasWidth / 2 - viewCenterX * gridSize
176 const worldOriginY = canvasHeight / 2 - viewCenterY * gridSize
177​
178 // Offset for the half-cell shift
179 const tileOffset = (cellSize * pixelRatio) / 2
180​
181 const matrix = new DOMMatrix()
182 .translate(worldOriginX, worldOriginY)
183 .scale(scale, scale)
184 .translate(-tileOffset, -tileOffset)
185​
186 pattern.setTransform(matrix)
187​
188 // Calculate the playable area bounds in screen coordinates
189 // Dots exist at grid intersections from (0,0) to (W,H) in world coordinates
190 // Expand bounds slightly to include full dots at edges (not just half)
191 // Dot radius in screen pixels is approximately 0.15 * gridSize, add margin for wobble
192 const dotMargin = 0.2 * gridSize
193 const boundsMinX = worldOriginX - dotMargin
194 const boundsMinY = worldOriginY - dotMargin
195 const boundsMaxX = worldOriginX + GRID_WIDTH * gridSize + dotMargin
196 const boundsMaxY = worldOriginY + GRID_HEIGHT * gridSize + dotMargin
197​
198 // Clip to visible canvas area
199 const fillX = Math.max(0, boundsMinX)
200 const fillY = Math.max(0, boundsMinY)
201 const fillMaxX = Math.min(canvasWidth, boundsMaxX)
202 const fillMaxY = Math.min(canvasHeight, boundsMaxY)
203 const fillW = fillMaxX - fillX
204 const fillH = fillMaxY - fillY
205​
206 // Only render if there's something visible
207 if (fillW > 0 && fillH > 0) {
208 ctx.fillStyle = pattern
209 ctx.fillRect(fillX, fillY, fillW, fillH)
210 }
212​
213/**
214 * Clear the tile cache.
215 */
216export function clearDotPatternCache(): void {
217 tileCache.clear()
218 if (cleanupTimer) {
219 clearInterval(cleanupTimer)
220 cleanupTimer = null
221 }