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

EdgeRenderer.ts

334 lines9.4 KB

1import { H, W, coordsToEdgeId } from "../../../shared/edge-math"
2import { getTeamColor } from "../../../shared/teams"
3import { getScale, getVisibleBounds, worldToScreen } from "../../lib/view-transform"
4import { HOVERED_EDGE_COLOR } from "../../lib/config"
5import { renderGridPattern } from "./GridPatternCache"
6import type { ViewState } from "../../hooks/useViewState"
7import type { GameState } from "../../../shared/game-state"
8​
9const PENDING_COLOR = `rgba(100, 100, 100, 0.6)`
10​
11// Threshold below which we use straight lines with wobbled endpoints (faster)
12// Above this, we use full quadratic curves
13const CURVE_THRESHOLD = 15
14​
15// Threshold below which we disable endpoint wobble entirely (fastest)
16const WOBBLE_THRESHOLD = 8
17​
18/**
19 * Simple seeded random for deterministic wobble
20 */
21function seededRandom(seed: number): number {
22 seed = (seed * 1103515245 + 12345) & 0x7fffffff
23 return (seed / 0x7fffffff) * 2 - 1 // -1 to 1
25​
26/**
27 * Get second seeded random value
28 */
29function seededRandom2(seed: number): number {
30 return seededRandom(seed * 127 + 31)
32​
33/**
34 * Edge data for batched rendering
35 */
36interface EdgeSegment {
37 x1: number
38 y1: number
39 x2: number
40 y2: number
41 edgeId: number
43​
44/**
45 * Batched edges grouped by color
46 */
47interface EdgeBatch {
48 color: string
49 lineWidth: number
50 dashed: boolean
51 edges: Array<EdgeSegment>
53​
54/**
55 * Render all visible edges on the canvas.
56 */
57export function renderEdges(
58 ctx: CanvasRenderingContext2D,
59 gameState: GameState,
60 view: ViewState,
61 canvasWidth: number,
62 canvasHeight: number,
63 pendingEdgeId: number | null = null,
64 hoveredEdgeId: number | null = null,
65 renderGridLines: boolean = true,
66 renderDrawnLines: boolean = true,
67 bounds?: { minX: number; minY: number; maxX: number; maxY: number },
68 drawingEdge?: { edgeId: number; progress: number } | null,
69): void {
70 // Early exit if nothing to render
71 if (!renderGridLines && !renderDrawnLines) return
72​
73 const gridSize = getScale(view) // pixels per grid cell
74​
75 // Only render if zoomed in enough to see edges
76 if (gridSize < 2) return
77​
78 // Render grid lines using cached tiled pattern (much faster than individual lines)
79 if (renderGridLines) {
80 renderGridPattern(ctx, gridSize, view.centerX, view.centerY, canvasWidth, canvasHeight)
81 }
82​
83 // Only iterate edges if we need to render taken/pending/hovered edges
84 if (!renderDrawnLines && pendingEdgeId === null && hoveredEdgeId === null) {
85 return
86 }
87​
88 const visibleBounds = bounds ?? getVisibleBounds(view, canvasWidth, canvasHeight)
89 // Line width scales with grid size, with a minimum of 0.5px for very small sizes
90 const lineWidth = Math.max(0.5, gridSize * 0.1)
91​
92 // Batches for color grouping: Map<colorKey, EdgeBatch>
93 // colorKey format: "color|lineWidthMultiplier|dashed"
94 const batches = new Map<string, EdgeBatch>()
95 let drawingBatch: EdgeBatch | null = null
96​
97 // Helper to add edge to batch
98 const addToBatch = (
99 color: string,
100 lineWidthMult: number,
101 dashed: boolean,
102 segment: EdgeSegment,
103 ) => {
104 // Keep the animated edge out of the full-length batches, even if Realtime
105 // has already confirmed its owner before the pencil finishes the stroke.
106 if (segment.edgeId === drawingEdge?.edgeId) {
107 drawingBatch = { color, lineWidth: lineWidth * lineWidthMult, dashed, edges: [segment] }
108 return
109 }
110 const key = `${color}|${lineWidthMult}|${dashed}`
111 let batch = batches.get(key)
112 if (!batch) {
113 batch = {
114 color,
115 lineWidth: lineWidth * lineWidthMult,
116 dashed,
117 edges: [],
118 }
119 batches.set(key, batch)
120 }
121 batch.edges.push(segment)
122 }
123​
124 // Collect horizontal edges in visible range
125 for (let y = Math.max(0, visibleBounds.minY); y <= Math.min(H, visibleBounds.maxY + 1); y++) {
126 for (let x = Math.max(0, visibleBounds.minX); x < Math.min(W, visibleBounds.maxX + 1); x++) {
127 const edgeId = coordsToEdgeId(x, y, true)
128 collectEdge(
129 edgeId,
130 x,
131 y,
132 true,
133 gameState,
134 view,
135 canvasWidth,
136 canvasHeight,
137 pendingEdgeId,
138 hoveredEdgeId,
139 renderDrawnLines,
140 addToBatch,
141 )
142 }
143 }
144​
145 // Collect vertical edges in visible range
146 for (let y = Math.max(0, visibleBounds.minY); y < Math.min(H, visibleBounds.maxY + 1); y++) {
147 for (let x = Math.max(0, visibleBounds.minX); x <= Math.min(W, visibleBounds.maxX + 1); x++) {
148 const edgeId = coordsToEdgeId(x, y, false)
149 collectEdge(
150 edgeId,
151 x,
152 y,
153 false,
154 gameState,
155 view,
156 canvasWidth,
157 canvasHeight,
158 pendingEdgeId,
159 hoveredEdgeId,
160 renderDrawnLines,
161 addToBatch,
162 )
163 }
164 }
165​
166 // Render all batches
167 ctx.lineCap = `round`
168 const useCurves = gridSize >= CURVE_THRESHOLD
169 const useWobble = gridSize >= WOBBLE_THRESHOLD
170 const wobbleAmount = lineWidth * 0.5
171​
172 for (const batch of batches.values()) {
173 renderBatch(ctx, batch, useCurves, useWobble, wobbleAmount)
174 }
175​
176 // Clip the existing hand-drawn path rather than shortening its geometry,
177 // so the curve and wobble stay identical throughout the reveal.
178 const animatedBatch = drawingBatch as EdgeBatch | null
179 if (animatedBatch && drawingEdge && drawingEdge.progress > 0) {
180 ctx.save()
181 if (drawingEdge.progress < 1) {
182 const edge = animatedBatch.edges[0]
183 const padding = lineWidth * 3 + 2
184 ctx.beginPath()
185 if (edge.x1 !== edge.x2) {
186 ctx.rect(
187 edge.x1 - padding,
188 edge.y1 - padding,
189 (edge.x2 - edge.x1) * drawingEdge.progress + padding,
190 padding * 2,
191 )
192 } else {
193 ctx.rect(
194 edge.x1 - padding,
195 edge.y1 - padding,
196 padding * 2,
197 (edge.y2 - edge.y1) * drawingEdge.progress + padding,
198 )
199 }
200 ctx.clip()
201 }
202 renderBatch(ctx, animatedBatch, useCurves, useWobble, wobbleAmount)
203 ctx.restore()
204 }
206​
207/**
208 * Collect edge into appropriate batch if it's a special edge (taken, pending, or hovered).
209 * Grid lines are handled by the tiled pattern.
210 */
211function collectEdge(
212 edgeId: number,
213 x: number,
214 y: number,
215 horizontal: boolean,
216 gameState: GameState,
217 view: ViewState,
218 canvasWidth: number,
219 canvasHeight: number,
220 pendingEdgeId: number | null,
221 hoveredEdgeId: number | null,
222 renderDrawnLines: boolean,
223 addToBatch: (color: string, lineWidthMult: number, dashed: boolean, segment: EdgeSegment) => void,
224): void {
225 const isTaken = gameState.isEdgeTaken(edgeId)
226 const isPending = edgeId === pendingEdgeId
227 const isHovered = edgeId === hoveredEdgeId
228​
229 // Skip unplaced edges (handled by tiled pattern)
230 if (!isTaken && !isPending && !isHovered) return
231​
232 // Skip taken edges if debug flag is off
233 if (isTaken && !renderDrawnLines) return
234​
235 let x1: number, y1: number, x2: number, y2: number
236​
237 if (horizontal) {
238 // Horizontal edge from (x, y) to (x+1, y)
239 const start = worldToScreen(x, y, view, canvasWidth, canvasHeight)
240 const end = worldToScreen(x + 1, y, view, canvasWidth, canvasHeight)
241 x1 = start.x
242 y1 = start.y
243 x2 = end.x
244 y2 = end.y
245 } else {
246 // Vertical edge from (x, y) to (x, y+1)
247 const start = worldToScreen(x, y, view, canvasWidth, canvasHeight)
248 const end = worldToScreen(x, y + 1, view, canvasWidth, canvasHeight)
249 x1 = start.x
250 y1 = start.y
251 x2 = end.x
252 y2 = end.y
253 }
254​
255 const segment: EdgeSegment = { x1, y1, x2, y2, edgeId }
256​
257 if (isTaken) {
258 const teamId = gameState.getEdgeOwner(edgeId) ?? 0
259 const color = getTeamColor(teamId).primary
260 addToBatch(color, 1.2, false, segment)
261 } else if (isPending) {
262 addToBatch(PENDING_COLOR, 1.5, true, segment)
263 } else if (isHovered) {
264 addToBatch(HOVERED_EDGE_COLOR, 1.3, false, segment)
265 }
267​
268/**
269 * Render a batch of edges with the same style.
270 * Uses a single Path2D and stroke() call for all edges in the batch.
271 */
272function renderBatch(
273 ctx: CanvasRenderingContext2D,
274 batch: EdgeBatch,
275 useCurves: boolean,
276 useWobble: boolean,
277 wobbleAmount: number,
278): void {
279 if (batch.edges.length === 0) return
280​
281 ctx.strokeStyle = batch.color
282 ctx.lineWidth = batch.lineWidth
283 ctx.setLineDash(batch.dashed ? [4, 4] : [])
284​
285 const path = new Path2D()
286​
287 for (const edge of batch.edges) {
288 const { x1, y1, x2, y2, edgeId } = edge
289​
290 if (useWobble) {
291 // Deterministic wobble based on edge ID
292 const r1 = seededRandom(edgeId)
293 const r2 = seededRandom2(edgeId)
294 const r3 = seededRandom(edgeId + 1000)
295 const r4 = seededRandom2(edgeId + 1000)
296​
297 // Wobbled start and end points
298 const startX = x1 + r1 * 0.5
299 const startY = y1 + r2 * 0.5
300 const endX = x2 + r3 * 0.5
301 const endY = y2 + r4 * 0.5
302​
303 path.moveTo(startX, startY)
304​
305 if (useCurves) {
306 // Full quadratic curve for zoomed in view
307 const dx = x2 - x1
308 const dy = y2 - y1
309 const length = Math.sqrt(dx * dx + dy * dy)
310​
311 if (length > 0.001) {
312 // Perpendicular direction for midpoint wobble
313 const px = -dy / length
314 const py = dx / length
315 const midX = (x1 + x2) / 2 + px * wobbleAmount * r1
316 const midY = (y1 + y2) / 2 + py * wobbleAmount * r2
317​
318 path.quadraticCurveTo(midX, midY, endX, endY)
319 } else {
320 path.lineTo(endX, endY)
321 }
322 } else {
323 // Straight line with wobbled endpoints
324 path.lineTo(endX, endY)
325 }
326 } else {
327 // No wobble - pure straight lines (fastest)
328 path.moveTo(x1, y1)
329 path.lineTo(x2, y2)
330 }
331 }
332​
333 ctx.stroke(path)