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