Open History to see the last commit
1import { W } from "../../../shared/edge-math"
2import { DOT_SPACING } from "../../lib/config"
3import type { ViewState } from "../../hooks/useViewState"
4import type { BoxBitmap } from "../../lib/box-bitmap"
5
6/**
7 * MinimapRenderer handles rendering the minimap using a shared BoxBitmap.
8 * The BoxBitmap provides the 1px-per-box game state, which we scale down
9 * to fit the minimap canvas.
10 */
11export class MinimapRenderer {
12 private canvas: HTMLCanvasElement
13 private ctx: CanvasRenderingContext2D
14 private size = 0
15
16 constructor(canvas: HTMLCanvasElement) {
17 this.canvas = canvas
18
19 const ctx = canvas.getContext(`2d`)
20 if (!ctx) {
21 throw new Error(`Failed to get 2D context`)
22 }
23 this.ctx = ctx
24 }
25
26 /**
27 * Render the minimap using the shared BoxBitmap.
28 * The bitmap is scaled down to fit the minimap size with smooth interpolation.
29 */
30 render(boxBitmap: BoxBitmap): void {
31 // CSS changes the map size at responsive breakpoints. Match that size at
32 // device density, keeping drawing coordinates and line widths in CSS pixels.
33 this.size = this.canvas.getBoundingClientRect().width
34 if (this.size <= 0) return
35 const pixels = Math.round(this.size * (window.devicePixelRatio || 1))
36 if (this.canvas.width !== pixels || this.canvas.height !== pixels) {
37 this.canvas.width = pixels
38 this.canvas.height = pixels
39 }
40 const density = pixels / this.size
41 this.ctx.setTransform(density, 0, 0, density, 0, 0)
42 this.ctx.imageSmoothingEnabled = true
43 this.ctx.imageSmoothingQuality = "high"
44
45 // Clear and draw the bitmap scaled to minimap size
46 this.ctx.clearRect(0, 0, this.size, this.size)
47 boxBitmap.drawScaled(this.ctx, 0, 0, this.size, this.size, true)
48 }
49
50 /**
51 * Draw the viewport rectangle showing the current view.
52 */
53 drawViewport(view: ViewState, canvasWidth: number, canvasHeight: number): void {
54 // Calculate visible world bounds using scale (pixels per grid cell)
55 const viewScale = view.zoom * DOT_SPACING
56 const halfW = canvasWidth / viewScale / 2
57 const halfH = canvasHeight / viewScale / 2
58
59 const worldMinX = view.centerX - halfW
60 const worldMinY = view.centerY - halfH
61 const worldMaxX = view.centerX + halfW
62 const worldMaxY = view.centerY + halfH
63
64 // Convert to minimap coordinates
65 const minimapScale = this.size / W
66 const rectX = worldMinX * minimapScale
67 const rectY = worldMinY * minimapScale
68 const rectW = (worldMaxX - worldMinX) * minimapScale
69 const rectH = (worldMaxY - worldMinY) * minimapScale
70
71 // Draw viewport rectangle
72 this.ctx.strokeStyle = `rgba(0, 0, 0, 0.8)`
73 this.ctx.lineWidth = 2
74 this.ctx.strokeRect(rectX, rectY, rectW, rectH)
75
76 // Draw inner white line for contrast
77 this.ctx.strokeStyle = `rgba(255, 255, 255, 0.8)`
78 this.ctx.lineWidth = 1
79 this.ctx.strokeRect(rectX + 1, rectY + 1, rectW - 2, rectH - 2)
80 }
81}