blob: bda682803225e9c11fd3eed6576acf0a45723f2d [file] [log] [blame]
James Kuszmauldac091f2022-03-22 09:35:06 -07001import {ByteBuffer} from 'flatbuffers';
James Kuszmaulf3ef9e12022-03-05 17:13:00 -08002import {Connection} from 'org_frc971/aos/network/www/proxy';
James Kuszmauldac091f2022-03-22 09:35:06 -07003import {IntakeState, Status as SuperstructureStatus, SuperstructureState} from 'org_frc971/y2022/control_loops/superstructure/superstructure_status_generated'
4import {LocalizerOutput} from 'org_frc971/y2022/localizer/localizer_output_generated';
5import {RejectionReason} from 'org_frc971/y2022/localizer/localizer_status_generated';
6import {LocalizerVisualization, TargetEstimateDebug} from 'org_frc971/y2022/localizer/localizer_visualization_generated';
James Kuszmaulf3ef9e12022-03-05 17:13:00 -08007
8import {FIELD_LENGTH, FIELD_WIDTH, FT_TO_M, IN_TO_M} from './constants';
9
10// (0,0) is field center, +X is toward red DS
11const FIELD_SIDE_Y = FIELD_WIDTH / 2;
12const FIELD_EDGE_X = FIELD_LENGTH / 2;
13
14const ROBOT_WIDTH = 34 * IN_TO_M;
15const ROBOT_LENGTH = 36 * IN_TO_M;
16
17const PI_COLORS = ['#ff00ff', '#ffff00', '#00ffff', '#ffa500'];
18
19export class FieldHandler {
20 private canvas = document.createElement('canvas');
21 private localizerOutput: LocalizerOutput|null = null;
22 private superstructureStatus: SuperstructureStatus|null = null;
23
24 // Image information indexed by timestamp (seconds since the epoch), so that
25 // we can stop displaying images after a certain amount of time.
26 private localizerImageMatches = new Map<number, LocalizerVisualization>();
27 private outerTarget: HTMLElement =
28 (document.getElementById('outer_target') as HTMLElement);
29 private innerTarget: HTMLElement =
30 (document.getElementById('inner_target') as HTMLElement);
31 private x: HTMLElement = (document.getElementById('x') as HTMLElement);
32 private y: HTMLElement = (document.getElementById('y') as HTMLElement);
33 private theta: HTMLElement =
34 (document.getElementById('theta') as HTMLElement);
35 private shotDistance: HTMLElement =
36 (document.getElementById('shot_distance') as HTMLElement);
37 private turret: HTMLElement =
38 (document.getElementById('turret') as HTMLElement);
James Kuszmaula0871872022-03-05 22:12:39 -080039 private fire: HTMLElement =
40 (document.getElementById('fire') as HTMLElement);
41 private mpcSolveTime: HTMLElement =
42 (document.getElementById('mpc_solve_time') as HTMLElement);
Austin Schuh41472552022-03-13 18:09:41 -070043 private mpcHorizon: HTMLElement =
44 (document.getElementById('mpc_horizon') as HTMLElement);
James Kuszmaula0871872022-03-05 22:12:39 -080045 private shotCount: HTMLElement =
46 (document.getElementById('shot_count') as HTMLElement);
47 private catapult: HTMLElement =
48 (document.getElementById('catapult') as HTMLElement);
49 private superstructureState: HTMLElement =
50 (document.getElementById('superstructure_state') as HTMLElement);
51 private intakeState: HTMLElement =
52 (document.getElementById('intake_state') as HTMLElement);
53 private reseatingInCatapult: HTMLElement =
54 (document.getElementById('reseating_in_catapult') as HTMLElement);
55 private flippersOpen: HTMLElement =
56 (document.getElementById('flippers_open') as HTMLElement);
57 private climber: HTMLElement =
58 (document.getElementById('climber') as HTMLElement);
James Kuszmaulf3ef9e12022-03-05 17:13:00 -080059 private frontIntake: HTMLElement =
60 (document.getElementById('front_intake') as HTMLElement);
61 private backIntake: HTMLElement =
62 (document.getElementById('back_intake') as HTMLElement);
63 private imagesAcceptedCounter: HTMLElement =
64 (document.getElementById('images_accepted') as HTMLElement);
65 private imagesRejectedCounter: HTMLElement =
66 (document.getElementById('images_rejected') as HTMLElement);
67 private rejectionReasonCells: HTMLElement[] = [];
68 private fieldImage: HTMLImageElement = new Image();
69
70 constructor(private readonly connection: Connection) {
71 (document.getElementById('field') as HTMLElement).appendChild(this.canvas);
72
73 this.fieldImage.src = "2022.png";
74
75 for (const value in RejectionReason) {
76 // Typescript generates an iterator that produces both numbers and
77 // strings... don't do anything on the string iterations.
78 if (isNaN(Number(value))) {
79 continue;
80 }
81 const row = document.createElement('div');
82 const nameCell = document.createElement('div');
83 nameCell.innerHTML = RejectionReason[value];
84 row.appendChild(nameCell);
85 const valueCell = document.createElement('div');
86 valueCell.innerHTML = 'NA';
87 this.rejectionReasonCells.push(valueCell);
88 row.appendChild(valueCell);
89 document.getElementById('vision_readouts').appendChild(row);
90 }
91
92 for (let ii = 0; ii < PI_COLORS.length; ++ii) {
93 const legendEntry = document.createElement('div');
94 legendEntry.style.color = PI_COLORS[ii];
95 legendEntry.innerHTML = 'PI' + (ii + 1).toString()
96 document.getElementById('legend').appendChild(legendEntry);
97 }
98
99 this.connection.addConfigHandler(() => {
100 this.connection.addHandler(
101 '/localizer', LocalizerVisualization.getFullyQualifiedName(),
102 (data) => {
103 this.handleLocalizerDebug(data);
104 });
105 this.connection.addHandler(
106 '/localizer', LocalizerOutput.getFullyQualifiedName(), (data) => {
107 this.handleLocalizerOutput(data);
108 });
109 this.connection.addHandler(
110 '/superstructure', SuperstructureStatus.getFullyQualifiedName(),
111 (data) => {
112 this.handleSuperstructureStatus(data);
113 });
114 });
115 }
116
117 private handleLocalizerDebug(data: Uint8Array): void {
118 const now = Date.now() / 1000.0;
119
120 const fbBuffer = new ByteBuffer(data);
121 this.localizerImageMatches.set(
James Kuszmauldac091f2022-03-22 09:35:06 -0700122 now, LocalizerVisualization.getRootAsLocalizerVisualization(fbBuffer));
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800123
124 const debug = this.localizerImageMatches.get(now);
125
126 if (debug.statistics()) {
127 this.imagesAcceptedCounter.innerHTML =
128 debug.statistics().totalAccepted().toString();
129 this.imagesRejectedCounter.innerHTML =
130 (debug.statistics().totalCandidates() -
131 debug.statistics().totalAccepted())
132 .toString();
133 if (debug.statistics().rejectionReasonCountLength() ==
134 this.rejectionReasonCells.length) {
135 for (let ii = 0; ii < debug.statistics().rejectionReasonCountLength();
136 ++ii) {
137 this.rejectionReasonCells[ii].innerHTML =
138 debug.statistics().rejectionReasonCount(ii).toString();
139 }
140 } else {
141 console.error('Unexpected number of rejection reasons in counter.');
142 }
143 this.imagesRejectedCounter.innerHTML =
144 (debug.statistics().totalCandidates() -
145 debug.statistics().totalAccepted())
146 .toString();
147 }
148 }
149
150 private handleLocalizerOutput(data: Uint8Array): void {
151 const fbBuffer = new ByteBuffer(data);
James Kuszmauldac091f2022-03-22 09:35:06 -0700152 this.localizerOutput = LocalizerOutput.getRootAsLocalizerOutput(fbBuffer);
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800153 }
154
155 private handleSuperstructureStatus(data: Uint8Array): void {
156 const fbBuffer = new ByteBuffer(data);
James Kuszmauldac091f2022-03-22 09:35:06 -0700157 this.superstructureStatus = SuperstructureStatus.getRootAsStatus(fbBuffer);
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800158 }
159
160 drawField(): void {
161 const ctx = this.canvas.getContext('2d');
162 ctx.drawImage(
163 this.fieldImage, 0, 0, this.fieldImage.width, this.fieldImage.height,
164 -FIELD_EDGE_X, -FIELD_SIDE_Y, FIELD_LENGTH, FIELD_WIDTH);
165 }
166
167 drawCamera(
168 x: number, y: number, theta: number, color: string = 'blue',
169 extendLines: boolean = true): void {
170 const ctx = this.canvas.getContext('2d');
171 ctx.save();
172 ctx.translate(x, y);
173 ctx.rotate(theta);
174 ctx.strokeStyle = color;
175 ctx.beginPath();
176 ctx.moveTo(0.5, 0.5);
177 ctx.lineTo(0, 0);
178 if (extendLines) {
179 ctx.lineTo(100.0, 0);
180 ctx.lineTo(0, 0);
181 }
182 ctx.lineTo(0.5, -0.5);
183 ctx.stroke();
184 ctx.beginPath();
185 ctx.arc(0, 0, 0.25, -Math.PI / 4, Math.PI / 4);
186 ctx.stroke();
187 ctx.restore();
188 }
189
190 drawRobot(
191 x: number, y: number, theta: number, turret: number|null,
192 color: string = 'blue', dashed: boolean = false,
193 extendLines: boolean = true): void {
194 const ctx = this.canvas.getContext('2d');
195 ctx.save();
196 ctx.translate(x, y);
197 ctx.rotate(theta);
198 ctx.strokeStyle = color;
199 ctx.lineWidth = ROBOT_WIDTH / 10.0;
200 if (dashed) {
201 ctx.setLineDash([0.05, 0.05]);
202 } else {
203 // Empty array = solid line.
204 ctx.setLineDash([]);
205 }
206 ctx.rect(-ROBOT_LENGTH / 2, -ROBOT_WIDTH / 2, ROBOT_LENGTH, ROBOT_WIDTH);
207 ctx.stroke();
208
209 // Draw line indicating which direction is forwards on the robot.
210 ctx.beginPath();
211 ctx.moveTo(0, 0);
212 if (extendLines) {
213 ctx.lineTo(1000.0, 0);
214 } else {
215 ctx.lineTo(ROBOT_LENGTH / 2.0, 0);
216 }
217 ctx.stroke();
218
219 if (turret !== null) {
220 ctx.save();
221 ctx.rotate(turret);
222 const turretRadius = ROBOT_WIDTH / 3.0;
223 ctx.strokeStyle = 'red';
224 // Draw circle for turret.
225 ctx.beginPath();
226 ctx.arc(0, 0, turretRadius, 0, 2.0 * Math.PI);
227 ctx.stroke();
228 // Draw line in circle to show forwards.
229 ctx.beginPath();
230 ctx.moveTo(0, 0);
231 if (extendLines) {
232 ctx.lineTo(1000.0, 0);
233 } else {
234 ctx.lineTo(turretRadius, 0);
235 }
236 ctx.stroke();
237 ctx.restore();
238 }
239 ctx.restore();
240 }
241
242 setZeroing(div: HTMLElement): void {
243 div.innerHTML = 'zeroing';
244 div.classList.remove('faulted');
245 div.classList.add('zeroing');
246 div.classList.remove('near');
247 }
248
249 setEstopped(div: HTMLElement): void {
250 div.innerHTML = 'estopped';
251 div.classList.add('faulted');
252 div.classList.remove('zeroing');
253 div.classList.remove('near');
254 }
255
256 setTargetValue(
257 div: HTMLElement, target: number, val: number, tolerance: number): void {
258 div.innerHTML = val.toFixed(4);
259 div.classList.remove('faulted');
260 div.classList.remove('zeroing');
261 if (Math.abs(target - val) < tolerance) {
262 div.classList.add('near');
263 } else {
264 div.classList.remove('near');
265 }
266 }
267
268 setValue(div: HTMLElement, val: number): void {
269 div.innerHTML = val.toFixed(4);
270 div.classList.remove('faulted');
271 div.classList.remove('zeroing');
272 div.classList.remove('near');
273 }
274
275 draw(): void {
276 this.reset();
277 this.drawField();
278
279 // Draw the matches with debugging information from the localizer.
280 const now = Date.now() / 1000.0;
281 for (const [time, value] of this.localizerImageMatches) {
282 const age = now - time;
283 const kRemovalAge = 2.0;
284 if (age > kRemovalAge) {
285 this.localizerImageMatches.delete(time);
286 continue;
287 }
288 const ageAlpha = (kRemovalAge - age) / kRemovalAge
289 for (let i = 0; i < value.targetsLength(); i++) {
290 const imageDebug = value.targets(i);
291 const x = imageDebug.impliedRobotX();
292 const y = imageDebug.impliedRobotY();
293 const theta = imageDebug.impliedRobotTheta();
294 const cameraX = imageDebug.cameraX();
295 const cameraY = imageDebug.cameraY();
296 const cameraTheta = imageDebug.cameraTheta();
297 const accepted = imageDebug.accepted();
298 // Make camera readings fade over time.
299 const alpha = Math.round(255 * ageAlpha).toString(16).padStart(2, '0');
300 const dashed = false;
301 const acceptedRgb = accepted ? '#00FF00' : '#FF0000';
302 const acceptedRgba = acceptedRgb + alpha;
303 const cameraRgb = PI_COLORS[imageDebug.camera()];
304 const cameraRgba = cameraRgb + alpha;
305 this.drawRobot(x, y, theta, null, acceptedRgba, dashed, false);
306 this.drawCamera(cameraX, cameraY, cameraTheta, cameraRgba, false);
307 }
308 }
James Kuszmaula0871872022-03-05 22:12:39 -0800309 if (this.superstructureStatus) {
310 this.shotDistance.innerHTML = this.superstructureStatus.aimer() ?
Austin Schuh0a732cd2022-03-29 21:19:59 -0700311 (this.superstructureStatus.aimer().shotDistance() /
312 0.0254).toFixed(2) +
313 'in, ' +
314 this.superstructureStatus.aimer().shotDistance().toFixed(2) +
315 'm' :
James Kuszmaula0871872022-03-05 22:12:39 -0800316 'NA';
317
318 this.fire.innerHTML = this.superstructureStatus.fire() ? 'true' : 'false';
319
Austin Schuh41472552022-03-13 18:09:41 -0700320 this.mpcHorizon.innerHTML =
321 this.superstructureStatus.mpcHorizon().toFixed(2);
James Kuszmaula0871872022-03-05 22:12:39 -0800322
323 this.setValue(this.mpcSolveTime, this.superstructureStatus.solveTime());
324
325 this.shotCount.innerHTML =
326 this.superstructureStatus.shotCount().toFixed(0);
327
328 this.superstructureState.innerHTML =
329 SuperstructureState[this.superstructureStatus.state()];
330
331 this.intakeState.innerHTML =
332 IntakeState[this.superstructureStatus.intakeState()];
333
334 this.reseatingInCatapult.innerHTML =
335 this.superstructureStatus.reseatingInCatapult() ? 'true' : 'false';
336
337 this.flippersOpen.innerHTML =
338 this.superstructureStatus.flippersOpen() ? 'true' : 'false';
339
340 if (!this.superstructureStatus.catapult() ||
341 !this.superstructureStatus.catapult().zeroed()) {
342 this.setZeroing(this.catapult);
343 } else if (this.superstructureStatus.catapult().estopped()) {
344 this.setEstopped(this.catapult);
345 } else {
346 this.setTargetValue(
347 this.catapult,
348 this.superstructureStatus.catapult().unprofiledGoalPosition(),
349 this.superstructureStatus.catapult().estimatorState().position(),
350 1e-3);
351 }
352
353 if (!this.superstructureStatus.climber() ||
354 !this.superstructureStatus.climber().zeroed()) {
355 this.setZeroing(this.climber);
356 } else if (this.superstructureStatus.climber().estopped()) {
357 this.setEstopped(this.climber);
358 } else {
359 this.setTargetValue(
360 this.climber,
361 this.superstructureStatus.climber().unprofiledGoalPosition(),
362 this.superstructureStatus.climber().estimatorState().position(),
363 1e-3);
364 }
365
366
367
368 if (!this.superstructureStatus.turret() ||
369 !this.superstructureStatus.turret().zeroed()) {
370 this.setZeroing(this.turret);
371 } else if (this.superstructureStatus.turret().estopped()) {
372 this.setEstopped(this.turret);
373 } else {
374 this.setTargetValue(
375 this.turret,
376 this.superstructureStatus.turret().unprofiledGoalPosition(),
377 this.superstructureStatus.turret().estimatorState().position(),
378 1e-3);
379 }
380
381 if (!this.superstructureStatus.intakeBack() ||
382 !this.superstructureStatus.intakeBack().zeroed()) {
383 this.setZeroing(this.backIntake);
384 } else if (this.superstructureStatus.intakeBack().estopped()) {
385 this.setEstopped(this.backIntake);
386 } else {
387 this.setValue(
388 this.backIntake,
389 this.superstructureStatus.intakeBack().estimatorState().position());
390 }
391
392 if (!this.superstructureStatus.intakeFront() ||
393 !this.superstructureStatus.intakeFront().zeroed()) {
394 this.setZeroing(this.frontIntake);
395 } else if (this.superstructureStatus.intakeFront().estopped()) {
396 this.setEstopped(this.frontIntake);
397 } else {
398 this.setValue(
399 this.frontIntake,
400 this.superstructureStatus.intakeFront()
401 .estimatorState()
402 .position());
403 }
404 }
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800405
406 if (this.localizerOutput) {
407 if (!this.localizerOutput.zeroed()) {
408 this.setZeroing(this.x);
409 this.setZeroing(this.y);
410 this.setZeroing(this.theta);
411 } else {
412 this.setValue(this.x, this.localizerOutput.x());
413 this.setValue(this.y, this.localizerOutput.y());
414 this.setValue(this.theta, this.localizerOutput.theta());
415 }
416
James Kuszmaulf3ef9e12022-03-05 17:13:00 -0800417 this.drawRobot(
418 this.localizerOutput.x(), this.localizerOutput.y(),
419 this.localizerOutput.theta(),
420 this.superstructureStatus ?
421 this.superstructureStatus.turret().position() :
422 null);
423 }
424
425 window.requestAnimationFrame(() => this.draw());
426 }
427
428 reset(): void {
429 const ctx = this.canvas.getContext('2d');
430 ctx.setTransform(1, 0, 0, 1, 0, 0);
431 const size = window.innerHeight * 0.9;
432 ctx.canvas.height = size;
433 const width = size / 2 + 20;
434 ctx.canvas.width = width;
435 ctx.clearRect(0, 0, size, width);
436
437 // Translate to center of display.
438 ctx.translate(width / 2, size / 2);
439 // Coordinate system is:
440 // x -> forward.
441 // y -> to the left.
442 ctx.rotate(-Math.PI / 2);
443 ctx.scale(1, -1);
444
445 const M_TO_PX = (size - 10) / FIELD_LENGTH;
446 ctx.scale(M_TO_PX, M_TO_PX);
447 ctx.lineWidth = 1 / M_TO_PX;
448 }
449}