blob: 17b713972f66997c9b7702e18928236108f6f15e [file] [log] [blame]
Alex Perry554cec02019-03-23 20:15:12 -07001import {FT_TO_M, FIELD_WIDTH} from './constants';
Alex Perryd2df9652019-03-23 22:53:04 -07002import {drawField, drawTarget} from './field';
Alex Perry554cec02019-03-23 20:15:12 -07003import {drawRobot} from './robot';
4
Alex Perry554cec02019-03-23 20:15:12 -07005function main(): void {
6 const vis = new Visualiser();
7}
8
9class Visualiser {
10 private x = 3;
11 private y = 0;
12 private theta = 0;
13
Alex Perryd2df9652019-03-23 22:53:04 -070014 private drawLocked = false;
Alex Perryb2433462019-03-26 21:45:26 -070015 private targetLocked = false;
16 private targetX = 0;
17 private targetY = 0;
18 private targetTheta = 0;
Alex Perryd2df9652019-03-23 22:53:04 -070019
Alex Perry554cec02019-03-23 20:15:12 -070020 constructor() {
21 const canvas = <HTMLCanvasElement>document.getElementById('field');
22 const ctx = canvas.getContext('2d');
23
24 const server = location.host;
25 const socket = new WebSocket(`ws://${server}/ws`);
26 const reader = new FileReader();
27 reader.addEventListener('loadend', (e) => {
28 const text = e.srcElement.result;
29 const j = JSON.parse(text);
30 this.x = j.robot.x;
31 this.y = j.robot.y;
32 this.theta = j.robot.theta;
Alex Perryd2df9652019-03-23 22:53:04 -070033
34 if(j.target) {
James Kuszmaul94b3c172019-03-24 14:31:48 -070035 this.targetLocked = j.target.frozen && j.target.have_target;
36 this.targetX = j.target.x;
37 this.targetY = j.target.y;
38 this.targetTheta = j.target.theta;
Alex Perryd2df9652019-03-23 22:53:04 -070039 }
Alex Perry554cec02019-03-23 20:15:12 -070040 });
41 socket.addEventListener('message', (event) => {
42 reader.readAsText(event.data);
43 });
44 window.requestAnimationFrame(() => this.draw(ctx));
45 }
46
47 reset(ctx : CanvasRenderingContext2D) : void {
48 ctx.setTransform(1,0,0,1,0,0);
49 const size = Math.min(window.innerHeight, window.innerWidth) * 0.98;
50 ctx.canvas.height = size;
51 ctx.canvas.width = size;
52 ctx.clearRect(0,0,size,size);
53
54 ctx.translate(size/2, size);
55 ctx.rotate(-Math.PI / 2);
56 ctx.scale(1, -1);
57 const M_TO_PX = size / FIELD_WIDTH
58 ctx.scale(M_TO_PX, M_TO_PX);
59 ctx.lineWidth = 1 / M_TO_PX;
Alex Perry554cec02019-03-23 20:15:12 -070060 }
61
62 draw(ctx : CanvasRenderingContext2D) : void {
63 this.reset(ctx);
64
65 drawField(ctx);
66 drawRobot(ctx, this.x, this.y, this.theta);
James Kuszmaul94b3c172019-03-24 14:31:48 -070067 ctx.save();
68 ctx.lineWidth = 2.0 * ctx.lineWidth;
69 if (this.targetLocked) {
70 ctx.strokeStyle = 'blue';
71 } else {
Alex Perryd2df9652019-03-23 22:53:04 -070072 ctx.strokeStyle = 'red';
Alex Perryd2df9652019-03-23 22:53:04 -070073 }
James Kuszmaul94b3c172019-03-24 14:31:48 -070074 drawTarget(ctx, this.targetX, this.targetY, this.targetTheta);
75 ctx.restore();
Alex Perry554cec02019-03-23 20:15:12 -070076 window.requestAnimationFrame(() => this.draw(ctx));
77 }
78}
79
80main();