-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathTrackCanvas.tsx
More file actions
591 lines (534 loc) · 17.3 KB
/
Copy pathTrackCanvas.tsx
File metadata and controls
591 lines (534 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { Driver } from '@irdashies/types';
import tracks from './tracks/tracks.json';
import { getColor, getTailwindStyle } from '@irdashies/utils/colors';
import { shouldShowTrack } from './tracks/brokenTracks';
import { TrackDebug } from './TrackDebug';
import { useStartFinishLine } from './hooks/useStartFinishLine';
import {
setupCanvasContext,
drawTrack,
drawStartFinishLine,
drawTurnNames,
drawDrivers,
drawSectorColors,
drawSectorDividers,
} from './trackDrawingUtils';
const EMPTY_PIT_STATE: readonly boolean[] = [];
import type { SectorColor } from '@irdashies/context';
import type { Sector } from '@irdashies/types';
import { useTrackStateSnapshot, useCarIdxOffTrack } from '@irdashies/context';
export interface DriverIdentity {
driver: Driver;
isPlayer: boolean;
classPosition?: number;
}
export interface TrackProps {
trackId: number;
drivers: TrackDriver[];
driverIdentities?: DriverIdentity[];
turnLabels?: {
enabled: boolean;
labelType: 'names' | 'numbers' | 'both';
highContrast: boolean;
labelFontSize: number;
};
showCarNumbers?: boolean;
displayMode?: 'carNumber' | 'sessionPosition' | 'livePosition';
invertTrackColors?: boolean;
driverCircleSize?: number;
playerCircleSize?: number;
trackmapFontSize?: number;
trackLineWidth?: number;
trackOutlineWidth?: number;
highlightColor?: number;
invertLeaderColor?: boolean;
debug?: boolean;
isMinimalTrack?: boolean;
isMinimalCar?: boolean;
sectors?: Sector[];
sectorColors?: SectorColor[];
currentSectorIdx?: number;
playerIconDataUrl?: string | null;
driverLivePositions?: Record<number, number>;
}
export interface TrackDriver {
driver: Driver;
progress: number;
isPlayer: boolean;
classPosition?: number;
}
export interface TrackDrawing {
active: {
inside: string;
outside: string;
trackPathPoints?: { x: number; y: number }[];
totalLength?: number;
};
startFinish: {
line?: string;
arrow?: string;
point?: { x?: number; y?: number; length?: number } | null;
direction?: 'clockwise' | 'anticlockwise' | null;
};
turns?: {
x?: number;
y?: number;
content?: string;
}[];
}
export interface TurnLabels {
enabled: boolean;
labelType: 'names' | 'numbers' | 'both';
highContrast: boolean;
labelFontSize: number;
}
const TRACK_DRAWING_WIDTH = 1920;
const TRACK_DRAWING_HEIGHT = 1080;
export const TrackCanvas = ({
trackId,
drivers,
driverIdentities,
turnLabels = {
enabled: false,
labelType: 'both',
highContrast: true,
labelFontSize: 100,
},
showCarNumbers = true,
displayMode = 'carNumber',
invertTrackColors = false,
driverCircleSize = 40,
playerCircleSize = 40,
trackmapFontSize = 100,
trackLineWidth = 20,
trackOutlineWidth = 40,
highlightColor,
invertLeaderColor = false,
debug,
isMinimalTrack = false,
isMinimalCar = false,
sectors,
sectorColors,
currentSectorIdx,
playerIconDataUrl = null,
driverLivePositions = {},
}: TrackProps) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const cacheCanvasRef = useRef<HTMLCanvasElement | null>(null);
const debounceResizeRef = useRef<ReturnType<typeof setTimeout> | undefined>(
undefined
);
const [canvasSize, setCanvasSize] = useState({ width: 0, height: 0 });
const playerIconElRef = useRef<HTMLImageElement>(null);
const playerPitBadgeRef = useRef<HTMLDivElement>(null);
const trackDrawing = (tracks as unknown as TrackDrawing[])[trackId];
const shouldShow = shouldShowTrack(trackId, trackDrawing);
const driversOffTrack = useCarIdxOffTrack();
const carIdxIsOnPitRoad =
useTrackStateSnapshot()?.carIdxOnPitRoad ?? EMPTY_PIT_STATE;
// Memoize Path2D objects to avoid re-creating them on every render
const insidePath = trackDrawing?.active?.inside;
const startFinishLinePath = trackDrawing?.startFinish?.line;
// Stable refs for sector color drawing (only change when track changes)
const trackPathPoints = trackDrawing?.active?.trackPathPoints;
const totalLength = trackDrawing?.active?.totalLength;
const sfDirection = trackDrawing?.startFinish?.direction;
const sfIntersectionLength = trackDrawing?.startFinish?.point?.length;
const path2DObjects = useMemo(() => {
if (!insidePath || !startFinishLinePath) return null;
return {
inside: new Path2D(insidePath),
startFinish: new Path2D(startFinishLinePath),
};
}, [insidePath, startFinishLinePath]);
// Fall back to deriving identities from drivers when not provided (e.g. stories)
const resolvedIdentities = driverIdentities ?? drivers;
// Calculate if this is a multi-class race — depends on stable identities
const isMultiClass = useMemo(() => {
if (!resolvedIdentities || resolvedIdentities.length === 0) return false;
const uniqueClassIds = new Set(
resolvedIdentities.map(({ driver }) => driver.CarClassID)
);
return uniqueClassIds.size > 1;
}, [resolvedIdentities]);
// Memoize color calculations — depends on stable identities, so this
// only recomputes when the driver roster actually changes.
const driverColors = useMemo(() => {
const colors: Record<number, { fill: string; text: string }> = {};
resolvedIdentities?.forEach(({ driver, isPlayer }) => {
if (isPlayer) {
if (highlightColor) {
const highlightColorHex = `#${highlightColor.toString(16).padStart(6, '0')}`;
colors[driver.CarIdx] = { fill: highlightColorHex, text: 'white' };
} else {
colors[driver.CarIdx] = { fill: getColor('amber'), text: 'white' };
}
} else {
const style = getTailwindStyle(
driver.CarClassColor,
undefined,
isMultiClass
);
colors[driver.CarIdx] = { fill: style.canvasFill, text: 'white' };
}
});
return colors;
}, [resolvedIdentities, isMultiClass, highlightColor]);
// Get start/finish line calculations
const startFinishLine = useStartFinishLine({
startFinishPoint: trackDrawing?.startFinish?.point,
trackPathPoints: trackDrawing?.active?.trackPathPoints,
});
// Position calculation based on the percentage of the track completed
// with linear interpolation between track points for sub-pixel smoothness
const calculatePositions = useMemo(() => {
if (
!trackDrawing?.active?.trackPathPoints ||
!trackDrawing?.startFinish?.point?.length ||
!trackDrawing?.active?.totalLength
) {
return {};
}
const trackPathPoints = trackDrawing.active.trackPathPoints;
const direction = trackDrawing.startFinish.direction;
const intersectionLength = trackDrawing.startFinish.point.length;
const totalLength = trackDrawing.active.totalLength;
const result: Record<
number,
TrackDriver & {
position: { x: number; y: number };
sessionPosition?: number;
}
> = {};
for (const {
driver,
progress,
isPlayer,
classPosition: sessionPosition,
} of drivers) {
// Calculate position based on progress
const adjustedLength = (totalLength * progress) % totalLength;
const length =
direction === 'anticlockwise'
? (intersectionLength + adjustedLength) % totalLength
: (intersectionLength - adjustedLength + totalLength) % totalLength;
// --- Linear Interpolation between points ---
const floatIndex = (length / totalLength) * (trackPathPoints.length - 1);
const index1 = Math.floor(floatIndex);
const index2 = Math.min(index1 + 1, trackPathPoints.length - 1);
const t = floatIndex - index1;
const p1 = trackPathPoints[index1];
const p2 = trackPathPoints[index2];
result[driver.CarIdx] = {
position: {
x: p1.x + (p2.x - p1.x) * t,
y: p1.y + (p2.y - p1.y) * t,
},
driver,
isPlayer,
progress,
sessionPosition,
};
}
return result;
}, [
drivers,
trackDrawing?.active?.trackPathPoints,
trackDrawing?.startFinish?.point?.length,
trackDrawing?.startFinish?.direction,
trackDrawing?.active?.totalLength,
]);
// Canvas setup and resize handling
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const resize = () => {
if (!canvas) return;
// Get device pixel ratio for high-DPI displays
const dpr = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
// Set the actual canvas size in memory (scaled up for high-DPI)
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
// Apply device pixel ratio scaling to the context
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.setTransform(1, 0, 0, 1, 0, 0); // Reset transform
ctx.scale(dpr, dpr); // Apply DPR scaling
}
// Update state to trigger redraw
setCanvasSize({ width: rect.width, height: rect.height });
};
// Initial resize
resize();
// Use ResizeObserver to watch the canvas container
const resizeObserver = new ResizeObserver(() => {
// Clear existing timeout
if (debounceResizeRef.current) {
clearTimeout(debounceResizeRef.current);
}
// Set new timeout
debounceResizeRef.current = setTimeout(() => {
resize();
}, 50);
});
// Observe the canvas element itself
resizeObserver.observe(canvas);
// Add window resize listener as fallback
const handleWindowResize = () => {
if (debounceResizeRef.current) {
clearTimeout(debounceResizeRef.current);
}
debounceResizeRef.current = setTimeout(() => {
resize();
}, 50);
};
window.addEventListener('resize', handleWindowResize);
return () => {
resizeObserver.disconnect();
window.removeEventListener('resize', handleWindowResize);
if (debounceResizeRef.current) {
clearTimeout(debounceResizeRef.current);
}
cacheCanvasRef.current = null;
};
}, [trackId]);
// Static layer — redraws only when track settings, size, or appearance change
useLayoutEffect(() => {
const canvas = canvasRef.current;
if (!canvas || !path2DObjects) return;
if (canvasSize.width === 0 || canvasSize.height === 0) return;
if (!cacheCanvasRef.current) {
cacheCanvasRef.current = document.createElement('canvas');
}
const cacheCanvas = cacheCanvasRef.current;
const cacheCtx = cacheCanvas.getContext('2d');
if (!cacheCtx) return;
cacheCanvas.width = canvas.width;
cacheCanvas.height = canvas.height;
const maxCircleSize = Math.max(driverCircleSize, playerCircleSize);
const scaleX = canvasSize.width / (TRACK_DRAWING_WIDTH + 2 * maxCircleSize);
const scaleY =
canvasSize.height / (TRACK_DRAWING_HEIGHT + 2 * maxCircleSize);
const scale = Math.min(scaleX, scaleY);
const offsetX = (canvasSize.width - TRACK_DRAWING_WIDTH * scale) / 2;
const offsetY = (canvasSize.height - TRACK_DRAWING_HEIGHT * scale) / 2;
const dpr = window.devicePixelRatio || 1;
cacheCtx.setTransform(1, 0, 0, 1, 0, 0);
cacheCtx.scale(dpr, dpr);
setupCanvasContext(cacheCtx, scale, offsetX, offsetY, isMinimalTrack);
drawTrack(
cacheCtx,
path2DObjects,
invertTrackColors,
trackLineWidth,
trackOutlineWidth,
isMinimalTrack
);
if (
sectors &&
trackPathPoints &&
totalLength &&
sfIntersectionLength !== undefined &&
sfDirection
) {
if (sectorColors) {
drawSectorColors(
cacheCtx,
trackPathPoints,
totalLength,
sfIntersectionLength,
sfDirection,
sectors,
sectorColors,
trackLineWidth,
currentSectorIdx
);
}
drawSectorDividers(
cacheCtx,
trackPathPoints,
totalLength,
sfIntersectionLength,
sfDirection,
sectors,
trackLineWidth
);
}
drawStartFinishLine(cacheCtx, startFinishLine);
drawTurnNames(cacheCtx, trackDrawing.turns, turnLabels);
cacheCtx.restore();
// Blit to main canvas so static-only changes are visible immediately
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(cacheCanvas, 0, 0);
ctx.restore();
}
}, [
path2DObjects,
trackDrawing?.turns,
turnLabels,
canvasSize,
invertTrackColors,
trackLineWidth,
trackOutlineWidth,
trackmapFontSize,
startFinishLine,
driverCircleSize,
playerCircleSize,
isMinimalTrack,
sectors,
sectorColors,
currentSectorIdx,
trackPathPoints,
totalLength,
sfDirection,
sfIntersectionLength,
]);
// Dynamic layer — runs on every position tick, blits static cache then draws drivers
useLayoutEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas?.getContext('2d');
if (!canvas || !ctx || !cacheCanvasRef.current) return;
if (canvasSize.width === 0 || canvasSize.height === 0) return;
// Blit static cache (identity transform to avoid double DPR scaling)
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(cacheCanvasRef.current, 0, 0);
ctx.restore();
// Draw drivers
const maxCircleSize = Math.max(driverCircleSize, playerCircleSize);
const scaleX = canvasSize.width / (TRACK_DRAWING_WIDTH + 2 * maxCircleSize);
const scaleY =
canvasSize.height / (TRACK_DRAWING_HEIGHT + 2 * maxCircleSize);
const scale = Math.min(scaleX, scaleY);
const offsetX = (canvasSize.width - TRACK_DRAWING_WIDTH * scale) / 2;
const offsetY = (canvasSize.height - TRACK_DRAWING_HEIGHT * scale) / 2;
setupCanvasContext(ctx, scale, offsetX, offsetY, isMinimalCar);
const hasIconOverlay = !!playerIconDataUrl;
drawDrivers(
ctx,
calculatePositions,
driverColors,
invertLeaderColor,
driversOffTrack,
driverCircleSize,
playerCircleSize,
trackmapFontSize,
showCarNumbers,
displayMode,
driverLivePositions,
carIdxIsOnPitRoad,
hasIconOverlay
);
ctx.restore();
// Position the icon overlay imperatively — mutating transform/dimensions
// directly avoids a React render on every position tick.
const iconEl = playerIconElRef.current;
const pitEl = playerPitBadgeRef.current;
if (!hasIconOverlay) {
if (iconEl) iconEl.style.display = 'none';
if (pitEl) pitEl.style.display = 'none';
return;
}
const playerEntry = Object.values(calculatePositions).find(
(e) => e.isPlayer
);
if (!playerEntry) {
if (iconEl) iconEl.style.display = 'none';
if (pitEl) pitEl.style.display = 'none';
return;
}
const radius = playerCircleSize * scale;
const screenX = playerEntry.position.x * scale + offsetX - radius;
const screenY = playerEntry.position.y * scale + offsetY - radius;
const size = radius * 2;
if (iconEl) {
iconEl.style.transform = `translate(${screenX}px, ${screenY}px)`;
iconEl.style.width = `${size}px`;
iconEl.style.height = `${size}px`;
iconEl.style.display = '';
}
const onPitRoad = !!carIdxIsOnPitRoad?.[playerEntry.driver.CarIdx];
if (pitEl) {
if (onPitRoad) {
pitEl.style.transform = `translate(${screenX}px, ${screenY}px)`;
pitEl.style.width = `${size}px`;
pitEl.style.height = `${size}px`;
pitEl.style.fontSize = `${size * 0.6}px`;
pitEl.style.display = '';
} else {
pitEl.style.display = 'none';
}
}
}, [
calculatePositions,
canvasSize,
showCarNumbers,
displayMode,
driversOffTrack,
driverLivePositions,
carIdxIsOnPitRoad,
driverCircleSize,
playerCircleSize,
trackmapFontSize,
turnLabels,
driverColors,
invertLeaderColor,
isMinimalCar,
isMinimalTrack,
playerIconDataUrl,
]);
const renderIconOverlay = () =>
playerIconDataUrl ? (
<>
<img
ref={playerIconElRef}
src={playerIconDataUrl}
alt=""
className="absolute top-0 left-0 pointer-events-none origin-top-left will-change-transform"
style={{ display: 'none' }}
/>
<div
ref={playerPitBadgeRef}
className="absolute top-0 left-0 pointer-events-none flex items-center justify-center font-bold text-white origin-top-left will-change-transform"
style={{
display: 'none',
background: 'rgba(0, 0, 0, 0.6)',
borderRadius: '50%',
}}
>
P
</div>
</>
) : null;
// Development/Storybook mode - show debug info and canvas
if (debug) {
return (
<div className="overflow-hidden w-full h-full relative">
<TrackDebug trackId={trackId} trackDrawing={trackDrawing} />
<canvas
className="will-change-transform w-full h-full"
ref={canvasRef}
></canvas>
{renderIconOverlay()}
</div>
);
}
// Hide broken tracks in production
if (!shouldShow) return null;
return (
<div className="overflow-hidden w-full h-full relative">
<canvas
className="will-change-transform w-full h-full"
ref={canvasRef}
></canvas>
{renderIconOverlay()}
</div>
);
};