blob: bbf52056ab5d5e573bb1f5a98d0616ee43855add [file] [log] [blame]
James Kuszmaula8f2c452020-07-05 21:17:56 -07001// Multiplies all the values in the provided array by scale.
2function scaleVec(vec: number[], scale: number): number[] {
3 const scaled: number[] = [];
4 for (let num of vec) {
5 scaled.push(num * scale);
6 }
7 return scaled;
8}
9
10// Runs the operation op() over every pair of numbers in a, b and returns
11// the result.
12function cwiseOp(
13 a: number[], b: number[], op: (a: number, b: number) => number): number[] {
14 if (a.length !== b.length) {
15 throw new Error("a and b must be of equal length.");
16 }
17 const min: number[] = [];
18 for (let ii = 0; ii < a.length; ++ii) {
19 min.push(op(a[ii], b[ii]));
20 }
21 return min;
22}
23
24// Adds vectors a and b.
25function addVec(a: number[], b: number[]): number[] {
26 return cwiseOp(a, b, (p, q) => {
27 return p + q;
28 });
29}
30
31// Represents a single line within a plot. Handles rendering the line with
32// all of its points and the appropriate color/markers/lines.
33export class Line {
34 private points: Float32Array = new Float32Array([]);
35 private _drawLine: boolean = true;
36 private _pointSize: number = 3.0;
37 private _hasUpdate: boolean = false;
James Kuszmaul71a81932020-12-15 21:08:01 -080038 private _minValues: number[] = [Infinity, Infinity];
39 private _maxValues: number[] = [-Infinity, -Infinity];
James Kuszmaula8f2c452020-07-05 21:17:56 -070040 private _color: number[] = [1.0, 0.0, 0.0];
41 private pointAttribLocation: number;
Philipp Schradere625ba22020-11-16 20:11:37 -080042 private colorLocation: WebGLUniformLocation | null;
43 private pointSizeLocation: WebGLUniformLocation | null;
44 private _label: string = "";
James Kuszmaula8f2c452020-07-05 21:17:56 -070045 constructor(
46 private readonly ctx: WebGLRenderingContext,
47 private readonly program: WebGLProgram,
48 private readonly buffer: WebGLBuffer) {
49 this.pointAttribLocation = this.ctx.getAttribLocation(this.program, 'apos');
50 this.colorLocation = this.ctx.getUniformLocation(this.program, 'color');
51 this.pointSizeLocation =
52 this.ctx.getUniformLocation(this.program, 'point_size');
53 }
54
55 // Return the largest x and y values present in the list of points.
56 maxValues(): number[] {
57 return this._maxValues;
58 }
59
60 // Return the smallest x and y values present in the list of points.
61 minValues(): number[] {
62 return this._minValues;
63 }
64
65 // Whether any parameters have changed that would require re-rending the line.
66 hasUpdate(): boolean {
67 return this._hasUpdate;
68 }
69
70 // Get/set the color of the line, returned as an RGB tuple.
71 color(): number[] {
72 return this._color;
73 }
74
75 setColor(newColor: number[]) {
76 this._color = newColor;
77 this._hasUpdate = true;
78 }
79
80 // Get/set the size of the markers to draw, in pixels (zero means no markers).
81 pointSize(): number {
82 return this._pointSize;
83 }
84
85 setPointSize(size: number) {
86 this._pointSize = size;
87 this._hasUpdate = true;
88 }
89
90 // Get/set whether we draw a line between the points (i.e., setting this to
91 // false would effectively create a scatter-plot). If drawLine is false and
92 // pointSize is zero, then no data is rendered.
93 drawLine(): boolean {
94 return this._drawLine;
95 }
96
97 setDrawLine(newDrawLine: boolean) {
98 this._drawLine = newDrawLine;
99 this._hasUpdate = true;
100 }
101
102 // Set the points to render. The points in the line are ordered and should
103 // be of the format:
104 // [x1, y1, x2, y2, x3, y3, ...., xN, yN]
105 setPoints(points: Float32Array) {
106 if (points.length % 2 !== 0) {
107 throw new Error("Must have even number of elements in points array.");
108 }
109 if (points.BYTES_PER_ELEMENT != 4) {
110 throw new Error(
111 'Must pass in a Float32Array--actual size was ' +
112 points.BYTES_PER_ELEMENT + '.');
113 }
114 this.points = points;
115 this._hasUpdate = true;
116 this._minValues[0] = Infinity;
117 this._minValues[1] = Infinity;
118 this._maxValues[0] = -Infinity;
119 this._maxValues[1] = -Infinity;
120 for (let ii = 0; ii < this.points.length; ii += 2) {
121 const x = this.points[ii];
122 const y = this.points[ii + 1];
123
James Kuszmaul71a81932020-12-15 21:08:01 -0800124 if (isNaN(x) || isNaN(y)) {
125 continue;
126 }
127
James Kuszmaula8f2c452020-07-05 21:17:56 -0700128 this._minValues = cwiseOp(this._minValues, [x, y], Math.min);
129 this._maxValues = cwiseOp(this._maxValues, [x, y], Math.max);
130 }
131 }
132
James Kuszmaul5f5e1232020-12-22 20:58:00 -0800133 getPoints(): Float32Array {
134 return this.points;
135 }
136
James Kuszmaula8f2c452020-07-05 21:17:56 -0700137 // Get/set the label to use for the line when drawing the legend.
138 setLabel(label: string) {
139 this._label = label;
140 }
141
142 label(): string {
143 return this._label;
144 }
145
146 // Render the line on the canvas.
147 draw() {
148 this._hasUpdate = false;
149 if (this.points.length === 0) {
150 return;
151 }
152
153 this.ctx.bindBuffer(this.ctx.ARRAY_BUFFER, this.buffer);
154 // Note: if this is generating errors associated with the buffer size,
155 // confirm that this.points really is a Float32Array.
156 this.ctx.bufferData(
157 this.ctx.ARRAY_BUFFER,
158 this.points,
159 this.ctx.STATIC_DRAW);
160 {
161 const numComponents = 2; // pull out 2 values per iteration
162 const numType = this.ctx.FLOAT; // the data in the buffer is 32bit floats
163 const normalize = false; // don't normalize
164 const stride = 0; // how many bytes to get from one set of values to the
165 // next 0 = use type and numComponents above
166 const offset = 0; // how many bytes inside the buffer to start from
167 this.ctx.vertexAttribPointer(
168 this.pointAttribLocation, numComponents, numType,
169 normalize, stride, offset);
170 this.ctx.enableVertexAttribArray(this.pointAttribLocation);
171 }
172
173 this.ctx.uniform1f(this.pointSizeLocation, this._pointSize);
174 this.ctx.uniform4f(
175 this.colorLocation, this._color[0], this._color[1], this._color[2],
176 1.0);
177
178 if (this._drawLine) {
179 this.ctx.drawArrays(this.ctx.LINE_STRIP, 0, this.points.length / 2);
180 }
181 if (this._pointSize > 0.0) {
182 this.ctx.drawArrays(this.ctx.POINTS, 0, this.points.length / 2);
183 }
184 }
185}
186
187// Parameters used when scaling the lines to the canvas.
188// If a point in a line is at pos then its position in the canvas space will be
189// scale * pos + offset.
190class ZoomParameters {
191 public scale: number[] = [1.0, 1.0];
192 public offset: number[] = [0.0, 0.0];
193}
194
195enum MouseButton {
196 Right,
197 Middle,
198 Left
199}
200
201// The button to use for panning the plot.
202const PAN_BUTTON = MouseButton.Left;
203
204// Returns the mouse button that generated a given event.
205function transitionButton(event: MouseEvent): MouseButton {
206 switch (event.button) {
207 case 0:
208 return MouseButton.Left;
209 case 1:
James Kuszmaula8f2c452020-07-05 21:17:56 -0700210 return MouseButton.Middle;
James Kuszmaulbce45332020-12-15 19:50:01 -0800211 case 2:
212 return MouseButton.Right;
James Kuszmaula8f2c452020-07-05 21:17:56 -0700213 }
214}
215
216// Returns whether the given button is pressed on the mouse.
217function buttonPressed(event: MouseEvent, button: MouseButton): boolean {
218 switch (button) {
219 // For some reason, the middle/right buttons are swapped relative to where
220 // we would expect them to be given the .button field.
221 case MouseButton.Left:
222 return 0 !== (event.buttons & 0x1);
James Kuszmaula8f2c452020-07-05 21:17:56 -0700223 case MouseButton.Right:
James Kuszmaulbce45332020-12-15 19:50:01 -0800224 return 0 !== (event.buttons & 0x2);
225 case MouseButton.Middle:
James Kuszmaula8f2c452020-07-05 21:17:56 -0700226 return 0 !== (event.buttons & 0x4);
227 }
228}
229
230// Handles rendering a Legend for a list of lines.
231// This takes a 2d canvas, which is what we use for rendering all the text of
232// the plot and is separate, but overlayed on top of, the WebGL canvas that the
233// lines are drawn on.
234export class Legend {
235 // Location, in pixels, of the legend in the text canvas.
236 private location: number[] = [0, 0];
237 constructor(private ctx: CanvasRenderingContext2D, private lines: Line[]) {
James Kuszmaul5f5e1232020-12-22 20:58:00 -0800238 this.location = [80, 30];
James Kuszmaula8f2c452020-07-05 21:17:56 -0700239 }
240
241 setPosition(location: number[]): void {
242 this.location = location;
243 }
244
245 draw(): void {
246 this.ctx.save();
247
248 this.ctx.translate(this.location[0], this.location[1]);
249
250 // Space between rows of the legend.
251 const step = 20;
252
253 // Total height of the body of the legend.
254 const height = step * this.lines.length;
255
256 let maxWidth = 0;
257
258 // In the legend, we render both a small line of the appropriate color as
259 // well as the text label--start/endPoint are the relative locations of the
260 // endpoints of the miniature line within the row, and textStart is where
261 // we begin rendering the text within the row.
262 const startPoint = [0, 0];
263 const endPoint = [10, -10];
264 const textStart = endPoint[0] + 5;
265
266 // Calculate how wide the legend needs to be to fit all the text.
267 this.ctx.textAlign = 'left';
268 for (let line of this.lines) {
269 const width =
270 textStart + this.ctx.measureText(line.label()).actualBoundingBoxRight;
271 maxWidth = Math.max(width, maxWidth);
272 }
273
274 // Set the legend background to be white and opaque.
275 this.ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
276 const backgroundBuffer = 5;
277 this.ctx.fillRect(
278 -backgroundBuffer, 0, maxWidth + 2.0 * backgroundBuffer,
279 height + backgroundBuffer);
280
281 // Go through each line and render the little lines and text for each Line.
282 for (let line of this.lines) {
283 this.ctx.translate(0, step);
284 const color = line.color();
285 this.ctx.strokeStyle = `rgb(${255.0 * color[0]}, ${255.0 * color[1]}, ${255.0 * color[2]})`;
286 this.ctx.fillStyle = this.ctx.strokeStyle;
287 if (line.drawLine()) {
288 this.ctx.beginPath();
289 this.ctx.moveTo(startPoint[0], startPoint[1]);
290 this.ctx.lineTo(endPoint[0], endPoint[1]);
291 this.ctx.closePath();
292 this.ctx.stroke();
293 }
294 const pointSize = line.pointSize();
295 if (pointSize > 0) {
296 this.ctx.fillRect(
297 startPoint[0] - pointSize / 2.0, startPoint[1] - pointSize / 2.0,
298 pointSize, pointSize);
299 this.ctx.fillRect(
300 endPoint[0] - pointSize / 2.0, endPoint[1] - pointSize / 2.0,
301 pointSize, pointSize);
302 }
303
304 this.ctx.fillStyle = 'black';
305 this.ctx.textAlign = 'left';
306 this.ctx.fillText(line.label(), textStart, 0);
307 }
308
309 this.ctx.restore();
310 }
311}
312
313// This class manages all the WebGL rendering--namely, drawing the reference
314// grid for the user and then rendering all the actual lines of the plot.
315export class LineDrawer {
316 private program: WebGLProgram|null = null;
317 private scaleLocation: WebGLUniformLocation;
318 private offsetLocation: WebGLUniformLocation;
319 private vertexBuffer: WebGLBuffer;
320 private lines: Line[] = [];
321 private zoom: ZoomParameters = new ZoomParameters();
322 private zoomUpdated: boolean = true;
323 // Maximum grid lines to render at once--this is used provide an upper limit
324 // on the number of Line objects we need to create in order to render the
325 // grid.
326 public readonly MAX_GRID_LINES: number = 5;
327 // Arrays of the points at which we will draw grid lines for the x/y axes.
328 private xTicks: number[] = [];
329 private yTicks: number[] = [];
330 private xGridLines: Line[] = [];
331 private yGridLines: Line[] = [];
332
333 constructor(public readonly ctx: WebGLRenderingContext) {
334 this.program = this.compileShaders();
335 this.scaleLocation = this.ctx.getUniformLocation(this.program, 'scale');
336 this.offsetLocation = this.ctx.getUniformLocation(this.program, 'offset');
337 this.vertexBuffer = this.ctx.createBuffer();
338
339 for (let ii = 0; ii < this.MAX_GRID_LINES; ++ii) {
340 this.xGridLines.push(new Line(this.ctx, this.program, this.vertexBuffer));
341 this.yGridLines.push(new Line(this.ctx, this.program, this.vertexBuffer));
342 }
343 }
344
345 setXGrid(lines: Line[]) {
346 this.xGridLines = lines;
347 }
348
349 getZoom(): ZoomParameters {
350 return this.zoom;
351 }
352
353 plotToCanvasCoordinates(plotPos: number[]): number[] {
354 return addVec(cwiseOp(plotPos, this.zoom.scale, (a, b) => {
355 return a * b;
356 }), this.zoom.offset);
357 }
358
359
360 canvasToPlotCoordinates(canvasPos: number[]): number[] {
361 return cwiseOp(cwiseOp(canvasPos, this.zoom.offset, (a, b) => {
362 return a - b;
363 }), this.zoom.scale, (a, b) => {
364 return a / b;
365 });
366 }
367
368 // Tehse return the max/min rendered points, in plot-space (this is helpful
369 // for drawing axis labels).
370 maxVisiblePoint(): number[] {
371 return this.canvasToPlotCoordinates([1.0, 1.0]);
372 }
373
374 minVisiblePoint(): number[] {
375 return this.canvasToPlotCoordinates([-1.0, -1.0]);
376 }
377
378 getLines(): Line[] {
379 return this.lines;
380 }
381
382 setZoom(zoom: ZoomParameters) {
383 this.zoomUpdated = true;
384 this.zoom = zoom;
385 }
386
387 setXTicks(ticks: number[]): void {
388 this.xTicks = ticks;
389 }
390
391 setYTicks(ticks: number[]): void {
392 this.yTicks = ticks;
393 }
394
395 // Update the grid lines.
396 updateTicks() {
397 for (let ii = 0; ii < this.MAX_GRID_LINES; ++ii) {
398 this.xGridLines[ii].setPoints(new Float32Array([]));
399 this.yGridLines[ii].setPoints(new Float32Array([]));
400 }
401
402 const minValues = this.minVisiblePoint();
403 const maxValues = this.maxVisiblePoint();
404
405 for (let ii = 0; ii < this.xTicks.length; ++ii) {
406 this.xGridLines[ii].setColor([0.0, 0.0, 0.0]);
407 const points = new Float32Array(
408 [this.xTicks[ii], minValues[1], this.xTicks[ii], maxValues[1]]);
409 this.xGridLines[ii].setPointSize(0);
410 this.xGridLines[ii].setPoints(points);
411 this.xGridLines[ii].draw();
412 }
413
414 for (let ii = 0; ii < this.yTicks.length; ++ii) {
415 this.yGridLines[ii].setColor([0.0, 0.0, 0.0]);
416 const points = new Float32Array(
417 [minValues[0], this.yTicks[ii], maxValues[0], this.yTicks[ii]]);
418 this.yGridLines[ii].setPointSize(0);
419 this.yGridLines[ii].setPoints(points);
420 this.yGridLines[ii].draw();
421 }
422 }
423
424 // Handles redrawing any of the WebGL objects, if necessary.
425 draw(): void {
426 let needsUpdate = this.zoomUpdated;
427 this.zoomUpdated = false;
428 for (let line of this.lines) {
429 if (line.hasUpdate()) {
430 needsUpdate = true;
431 break;
432 }
433 }
434 if (!needsUpdate) {
435 return;
436 }
437
438 this.reset();
439
440 this.updateTicks();
441
442 for (let line of this.lines) {
443 line.draw();
444 }
445
446 return;
447 }
448
449 loadShader(shaderType: number, source: string): WebGLShader {
450 const shader = this.ctx.createShader(shaderType);
451 this.ctx.shaderSource(shader, source);
452 this.ctx.compileShader(shader);
453 if (!this.ctx.getShaderParameter(shader, this.ctx.COMPILE_STATUS)) {
454 alert(
455 'Got an error compiling a shader: ' +
456 this.ctx.getShaderInfoLog(shader));
457 this.ctx.deleteShader(shader);
458 return null;
459 }
460
461 return shader;
462 }
463
464 compileShaders(): WebGLProgram {
465 const vertexShader = 'attribute vec2 apos;' +
466 'uniform vec2 scale;' +
467 'uniform vec2 offset;' +
468 'uniform float point_size;' +
469 'void main() {' +
470 ' gl_Position.xy = apos.xy * scale.xy + offset.xy;' +
471 ' gl_Position.z = 0.0;' +
472 ' gl_Position.w = 1.0;' +
473 ' gl_PointSize = point_size;' +
474 '}';
475
476 const fragmentShader = 'precision highp float;' +
477 'uniform vec4 color;' +
478 'void main() {' +
479 ' gl_FragColor = color;' +
480 '}';
481
482 const compiledVertex =
483 this.loadShader(this.ctx.VERTEX_SHADER, vertexShader);
484 const compiledFragment =
485 this.loadShader(this.ctx.FRAGMENT_SHADER, fragmentShader);
486 const program = this.ctx.createProgram();
487 this.ctx.attachShader(program, compiledVertex);
488 this.ctx.attachShader(program, compiledFragment);
489 this.ctx.linkProgram(program);
490 if (!this.ctx.getProgramParameter(program, this.ctx.LINK_STATUS)) {
491 alert(
492 'Unable to link the shaders: ' + this.ctx.getProgramInfoLog(program));
493 return null;
494 }
495 return program;
496 }
497
498 addLine(): Line {
499 this.lines.push(new Line(this.ctx, this.program, this.vertexBuffer));
500 return this.lines[this.lines.length - 1];
501 }
502
503 minValues(): number[] {
504 let minValues = [Infinity, Infinity];
505 for (let line of this.lines) {
506 minValues = cwiseOp(minValues, line.minValues(), Math.min);
507 }
508 return minValues;
509 }
510
511 maxValues(): number[] {
512 let maxValues = [-Infinity, -Infinity];
513 for (let line of this.lines) {
514 maxValues = cwiseOp(maxValues, line.maxValues(), Math.max);
515 }
516 return maxValues;
517 }
518
519 reset(): void {
520 // Set the background color
521 this.ctx.clearColor(0.5, 0.5, 0.5, 1.0);
522 this.ctx.clearDepth(1.0);
523 this.ctx.enable(this.ctx.DEPTH_TEST);
524 this.ctx.depthFunc(this.ctx.LEQUAL);
525 this.ctx.clear(this.ctx.COLOR_BUFFER_BIT | this.ctx.DEPTH_BUFFER_BIT);
526
527 this.ctx.useProgram(this.program);
528
529 this.ctx.uniform2f(
530 this.scaleLocation, this.zoom.scale[0], this.zoom.scale[1]);
531 this.ctx.uniform2f(
532 this.offsetLocation, this.zoom.offset[0], this.zoom.offset[1]);
533 }
534}
535
536// Class to store how much whitespace we put between the edges of the WebGL
537// canvas (where we draw all the lines) and the edge of the plot. This gives
538// us space to, e.g., draw axis labels, the plot title, etc.
539class WhitespaceBuffers {
540 constructor(
541 public left: number, public right: number, public top: number,
542 public bottom: number) {}
543}
544
545// Class to manage all the annotations associated with the plot--the axis/tick
546// labels and the plot title.
547class AxisLabels {
548 private readonly INCREMENTS: number[] = [2, 4, 5, 10];
549 // Space to leave to create some visual space around the text.
550 private readonly TEXT_BUFFER: number = 5;
551 private title: string = "";
552 private xlabel: string = "";
553 private ylabel: string = "";
554 constructor(
555 private ctx: CanvasRenderingContext2D, private drawer: LineDrawer,
556 private graphBuffers: WhitespaceBuffers) {}
557
558 numberToLabel(num: number): string {
559 return num.toPrecision(5);
560 }
561
562 textWidth(str: string): number {
563 return this.ctx.measureText(str).actualBoundingBoxRight;
564 }
565
566 textHeight(str: string): number {
567 return this.ctx.measureText(str).actualBoundingBoxAscent;
568 }
569
570 textDepth(str: string): number {
571 return this.ctx.measureText(str).actualBoundingBoxDescent;
572 }
573
574 setTitle(title: string) {
575 this.title = title;
576 }
577
578 setXLabel(xlabel: string) {
579 this.xlabel = xlabel;
580 }
581
582 setYLabel(ylabel: string) {
583 this.ylabel = ylabel;
584 }
585
586 getIncrement(range: number[]): number {
587 const diff = Math.abs(range[1] - range[0]);
588 const minDiff = diff / this.drawer.MAX_GRID_LINES;
589 const incrementsRatio = this.INCREMENTS[this.INCREMENTS.length - 1];
590 const order = Math.pow(
591 incrementsRatio,
592 Math.floor(Math.log(minDiff) / Math.log(incrementsRatio)));
593 const normalizedDiff = minDiff / order;
594 for (let increment of this.INCREMENTS) {
595 if (increment > normalizedDiff) {
596 return increment * order;
597 }
598 }
599 return 1.0;
600 }
601
602 getTicks(range: number[]): number[] {
603 const increment = this.getIncrement(range);
604 const start = Math.ceil(range[0] / increment) * increment;
605 const values = [start];
606 for (let ii = 0; ii < this.drawer.MAX_GRID_LINES - 1; ++ii) {
607 const nextValue = values[ii] + increment;
608 if (nextValue > range[1]) {
609 break;
610 }
611 values.push(nextValue);
612 }
613 return values;
614 }
615
616 plotToCanvasCoordinates(plotPos: number[]): number[] {
617 const webglCoord = this.drawer.plotToCanvasCoordinates(plotPos);
618 const webglX = (webglCoord[0] + 1.0) / 2.0 * this.drawer.ctx.canvas.width;
619 const webglY = (1.0 - webglCoord[1]) / 2.0 * this.drawer.ctx.canvas.height;
620 return [webglX + this.graphBuffers.left, webglY + this.graphBuffers.top];
621 }
622
623 drawXTick(x: number) {
624 const text = this.numberToLabel(x);
625 const height = this.textHeight(text);
626 const xpos = this.plotToCanvasCoordinates([x, 0])[0];
627 this.ctx.textAlign = "center";
628 this.ctx.fillText(
629 text, xpos,
630 this.ctx.canvas.height - this.graphBuffers.bottom + height +
631 this.TEXT_BUFFER);
632 }
633
634 drawYTick(y: number) {
635 const text = this.numberToLabel(y);
636 const height = this.textHeight(text);
637 const ypos = this.plotToCanvasCoordinates([0, y])[1];
638 this.ctx.textAlign = "right";
639 this.ctx.fillText(
640 text, this.graphBuffers.left - this.TEXT_BUFFER,
641 ypos + height / 2.0);
642 }
643
644 drawTitle() {
645 if (this.title) {
646 this.ctx.textAlign = 'center';
647 this.ctx.fillText(
648 this.title, this.ctx.canvas.width / 2.0,
649 this.graphBuffers.top - this.TEXT_BUFFER);
650 }
651 }
652
653 drawXLabel() {
654 if (this.xlabel) {
655 this.ctx.textAlign = 'center';
656 this.ctx.fillText(
657 this.xlabel, this.ctx.canvas.width / 2.0,
658 this.ctx.canvas.height - this.TEXT_BUFFER);
659 }
660 }
661
662 drawYLabel() {
663 this.ctx.save();
664 if (this.ylabel) {
665 this.ctx.textAlign = 'center';
666 const height = this.textHeight(this.ylabel);
667 this.ctx.translate(
668 height + this.TEXT_BUFFER, this.ctx.canvas.height / 2.0);
669 this.ctx.rotate(-Math.PI / 2.0);
670 this.ctx.fillText(this.ylabel, 0, 0);
671 }
672 this.ctx.restore();
673 }
674
675 draw() {
676 this.ctx.fillStyle = 'black';
677 const minValues = this.drawer.minVisiblePoint();
678 const maxValues = this.drawer.maxVisiblePoint();
679 let text = this.numberToLabel(maxValues[1]);
680 this.drawYTick(maxValues[1]);
681 this.drawYTick(minValues[1]);
682 this.drawXTick(minValues[0]);
683 this.drawXTick(maxValues[0]);
684 this.ctx.strokeStyle = 'black';
685 this.ctx.strokeRect(
686 this.graphBuffers.left, this.graphBuffers.top,
687 this.drawer.ctx.canvas.width, this.drawer.ctx.canvas.height);
688 this.ctx.strokeRect(
689 0, 0,
690 this.ctx.canvas.width, this.ctx.canvas.height);
691 const xTicks = this.getTicks([minValues[0], maxValues[0]]);
692 this.drawer.setXTicks(xTicks);
693 const yTicks = this.getTicks([minValues[1], maxValues[1]]);
694 this.drawer.setYTicks(yTicks);
695
696 for (let x of xTicks) {
697 this.drawXTick(x);
698 }
699
700 for (let y of yTicks) {
701 this.drawYTick(y);
702 }
703
704 this.drawTitle();
705 this.drawXLabel();
706 this.drawYLabel();
707 }
708
709 // Draws the current mouse position in the bottom-right of the plot.
710 drawMousePosition(mousePos: number[]) {
711 const plotPos = this.drawer.canvasToPlotCoordinates(mousePos);
712
713 const text =
714 `(${plotPos[0].toPrecision(10)}, ${plotPos[1].toPrecision(10)})`;
715 const textDepth = this.textDepth(text);
716 this.ctx.textAlign = 'right';
717 this.ctx.fillText(
718 text, this.ctx.canvas.width - this.graphBuffers.right,
719 this.ctx.canvas.height - this.graphBuffers.bottom - textDepth);
720 }
721}
722
723// This class manages the entirety of a single plot. Most of the logic in
724// this class is around handling mouse/keyboard events for interacting with
725// the plot.
726export class Plot {
727 private canvas = document.createElement('canvas');
728 private textCanvas = document.createElement('canvas');
729 private drawer: LineDrawer;
730 private static keysPressed: object = {'x': false, 'y': false};
731 // In canvas coordinates (the +/-1 square).
732 private lastMousePanPosition: number[] = null;
733 private axisLabelBuffer: WhitespaceBuffers =
734 new WhitespaceBuffers(50, 20, 20, 30);
735 private axisLabels: AxisLabels;
736 private legend: Legend;
737 private lastMousePosition: number[] = [0.0, 0.0];
738 private autoFollow: boolean = true;
739 private linkedXAxes: Plot[] = [];
James Kuszmaul71a81932020-12-15 21:08:01 -0800740 private lastTimeMs: number = 0;
James Kuszmaul5f5e1232020-12-22 20:58:00 -0800741 private defaultYRange: number[]|null = null;
James Kuszmaula8f2c452020-07-05 21:17:56 -0700742
743 constructor(wrapperDiv: HTMLDivElement, width: number, height: number) {
744 wrapperDiv.appendChild(this.canvas);
745 wrapperDiv.appendChild(this.textCanvas);
James Kuszmaul71a81932020-12-15 21:08:01 -0800746 this.lastTimeMs = (new Date()).getTime();
James Kuszmaula8f2c452020-07-05 21:17:56 -0700747
748 this.canvas.width =
749 width - this.axisLabelBuffer.left - this.axisLabelBuffer.right;
750 this.canvas.height =
751 height - this.axisLabelBuffer.top - this.axisLabelBuffer.bottom;
752 this.canvas.style.left = this.axisLabelBuffer.left.toString();
753 this.canvas.style.top = this.axisLabelBuffer.top.toString();
754 this.canvas.style.position = 'absolute';
755 this.drawer = new LineDrawer(this.canvas.getContext('webgl'));
756
757 this.textCanvas.width = width;
758 this.textCanvas.height = height;
759 this.textCanvas.style.left = '0';
760 this.textCanvas.style.top = '0';
761 this.textCanvas.style.position = 'absolute';
762 this.textCanvas.style.pointerEvents = 'none';
763
764 this.canvas.addEventListener('dblclick', (e) => {
765 this.handleDoubleClick(e);
766 });
767 this.canvas.onwheel = (e) => {
768 this.handleWheel(e);
769 e.preventDefault();
770 };
771 this.canvas.onmousedown = (e) => {
772 this.handleMouseDown(e);
773 };
774 this.canvas.onmouseup = (e) => {
775 this.handleMouseUp(e);
776 };
777 this.canvas.onmousemove = (e) => {
778 this.handleMouseMove(e);
779 };
780 // TODO(james): Deconflict the global state....
781 document.onkeydown = (e) => {
782 this.handleKeyDown(e);
783 };
784 document.onkeyup = (e) => {
785 this.handleKeyUp(e);
786 };
787
788 const textCtx = this.textCanvas.getContext("2d");
789 this.axisLabels =
790 new AxisLabels(textCtx, this.drawer, this.axisLabelBuffer);
791 this.legend = new Legend(textCtx, this.drawer.getLines());
792
793 this.draw();
794 }
795
796 handleDoubleClick(event: MouseEvent) {
797 this.resetZoom();
798 }
799
800 mouseCanvasLocation(event: MouseEvent): number[] {
801 return [
802 event.offsetX * 2.0 / this.canvas.width - 1.0,
803 -event.offsetY * 2.0 / this.canvas.height + 1.0
804 ];
805 }
806
807 handleWheel(event: WheelEvent) {
808 if (event.deltaMode !== event.DOM_DELTA_PIXEL) {
809 return;
810 }
811 const mousePosition = this.mouseCanvasLocation(event);
812 const kWheelTuningScalar = 1.5;
813 const zoom = -kWheelTuningScalar * event.deltaY / this.canvas.height;
814 let zoomScalar = 1.0 + Math.abs(zoom);
815 if (zoom < 0.0) {
816 zoomScalar = 1.0 / zoomScalar;
817 }
818 const scale = scaleVec(this.drawer.getZoom().scale, zoomScalar);
819 const offset = addVec(
820 scaleVec(mousePosition, 1.0 - zoomScalar),
821 scaleVec(this.drawer.getZoom().offset, zoomScalar));
822 this.setZoom(scale, offset);
823 }
824
825 handleMouseDown(event: MouseEvent) {
826 if (transitionButton(event) === PAN_BUTTON) {
827 this.lastMousePanPosition = this.mouseCanvasLocation(event);
828 }
829 }
830
831 handleMouseUp(event: MouseEvent) {
832 if (transitionButton(event) === PAN_BUTTON) {
833 this.lastMousePanPosition = null;
834 }
835 }
836
837 handleMouseMove(event: MouseEvent) {
838 const mouseLocation = this.mouseCanvasLocation(event);
839 if (buttonPressed(event, PAN_BUTTON) &&
840 (this.lastMousePanPosition !== null)) {
841 const mouseDiff =
842 addVec(mouseLocation, scaleVec(this.lastMousePanPosition, -1));
843 this.setZoom(
844 this.drawer.getZoom().scale,
845 addVec(this.drawer.getZoom().offset, mouseDiff));
846 this.lastMousePanPosition = mouseLocation;
847 }
848 this.lastMousePosition = mouseLocation;
849 }
850
851 setZoom(scale: number[], offset: number[]) {
James Kuszmaul71a81932020-12-15 21:08:01 -0800852 if (!isFinite(scale[0]) || !isFinite(scale[1])) {
853 throw new Error("Doesn't support non-finite scales due to singularities.");
854 }
James Kuszmaula8f2c452020-07-05 21:17:56 -0700855 const x_pressed = Plot.keysPressed["x"];
856 const y_pressed = Plot.keysPressed["y"];
857 const zoom = this.drawer.getZoom();
858 if (x_pressed && !y_pressed) {
859 zoom.scale[0] = scale[0];
860 zoom.offset[0] = offset[0];
861 } else if (y_pressed && !x_pressed) {
862 zoom.scale[1] = scale[1];
863 zoom.offset[1] = offset[1];
864 } else {
865 zoom.scale = scale;
866 zoom.offset = offset;
867 }
868
869 for (let plot of this.linkedXAxes) {
870 const otherZoom = plot.drawer.getZoom();
871 otherZoom.scale[0] = zoom.scale[0];
872 otherZoom.offset[0] = zoom.offset[0];
873 plot.drawer.setZoom(otherZoom);
874 plot.autoFollow = false;
875 }
876 this.drawer.setZoom(zoom);
877 this.autoFollow = false;
878 }
879
880
881 setZoomCorners(c1: number[], c2: number[]) {
882 const scale = cwiseOp(c1, c2, (a, b) => {
883 return 2.0 / Math.abs(a - b);
884 });
885 const offset = cwiseOp(scale, cwiseOp(c1, c2, Math.max), (a, b) => {
886 return 1.0 - a * b;
887 });
888 this.setZoom(scale, offset);
889 }
890
James Kuszmaul5f5e1232020-12-22 20:58:00 -0800891 setDefaultYRange(range: number[]|null) {
892 if (range == null) {
893 this.defaultYRange = null;
894 return;
895 }
896 if (range.length != 2) {
897 throw new Error('Range should contain exactly two values.');
898 }
899 this.defaultYRange = range;
900 }
901
James Kuszmaula8f2c452020-07-05 21:17:56 -0700902 resetZoom() {
James Kuszmaul71a81932020-12-15 21:08:01 -0800903 const minValues = this.drawer.minValues();
904 const maxValues = this.drawer.maxValues();
James Kuszmaul5f5e1232020-12-22 20:58:00 -0800905 for (const plot of this.linkedXAxes) {
906 const otherMin = plot.drawer.minValues();
907 const otherMax = plot.drawer.maxValues();
908 // For linked x-axes, only adjust the x limits.
909 minValues[0] = Math.min(minValues[0], otherMin[0]);
910 maxValues[0] = Math.max(maxValues[0], otherMax[0]);
911 }
912 if (!isFinite(minValues[0]) || !isFinite(maxValues[0])) {
913 minValues[0] = 0;
914 maxValues[0] = 0;
915 }
916 if (!isFinite(minValues[1]) || !isFinite(maxValues[1])) {
917 minValues[1] = 0;
918 maxValues[1] = 0;
919 }
James Kuszmaul71a81932020-12-15 21:08:01 -0800920 if (minValues[0] == maxValues[0]) {
921 minValues[0] -= 1;
922 maxValues[0] += 1;
923 }
924 if (minValues[1] == maxValues[1]) {
925 minValues[1] -= 1;
926 maxValues[1] += 1;
927 }
James Kuszmaul5f5e1232020-12-22 20:58:00 -0800928 if (this.defaultYRange != null) {
929 minValues[1] = this.defaultYRange[0];
930 maxValues[1] = this.defaultYRange[1];
931 }
James Kuszmaul71a81932020-12-15 21:08:01 -0800932 this.setZoomCorners(minValues, maxValues);
James Kuszmaula8f2c452020-07-05 21:17:56 -0700933 this.autoFollow = true;
934 for (let plot of this.linkedXAxes) {
935 plot.autoFollow = true;
936 }
937 }
938
939 handleKeyUp(event: KeyboardEvent) {
940 Plot.keysPressed[event.key] = false;
941 }
942
943 handleKeyDown(event: KeyboardEvent) {
944 Plot.keysPressed[event.key] = true;
945 }
946
947 draw() {
948 window.requestAnimationFrame(() => this.draw());
James Kuszmaul71a81932020-12-15 21:08:01 -0800949 const curTime = (new Date()).getTime();
950 const frameRate = 1000.0 / (curTime - this.lastTimeMs);
951 this.lastTimeMs = curTime;
James Kuszmaula8f2c452020-07-05 21:17:56 -0700952
953 // Clear the overlay.
954 const textCtx = this.textCanvas.getContext("2d");
955 textCtx.clearRect(0, 0, this.textCanvas.width, this.textCanvas.height);
956
957 this.axisLabels.draw();
958 this.axisLabels.drawMousePosition(this.lastMousePosition);
959 this.legend.draw();
960
961 this.drawer.draw();
962
963 if (this.autoFollow) {
964 this.resetZoom();
965 }
966 }
967
968 getDrawer(): LineDrawer {
969 return this.drawer;
970 }
971
972 getLegend(): Legend {
973 return this.legend;
974 }
975
976 getAxisLabels(): AxisLabels {
977 return this.axisLabels;
978 }
979
980 // Links this plot's x-axis with that of another Plot (e.g., to share time
981 // axes).
982 linkXAxis(other: Plot) {
983 this.linkedXAxes.push(other);
984 other.linkedXAxes.push(this);
985 }
986}