-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
1083 lines (957 loc) · 51.2 KB
/
main.js
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { interpolate, turboColormapData } from "./colormap.js"
import { bowyerWatson, Vertex } from "./delaunay.js"
import { Mat4, Quat, Vector3 } from "./math.js"
import { getNumberOfStations, MoodyReport, SurfacePlate, roundTo, roundToSlow } from "./moody.js"
import WebGLDebugUtils from "./webgl-debug.js"
// Moody's original paper states 48x78 which is a non-standard size. It is most likely a typo. Bruce Allen's corrections paper states:
// Table 1 carries the title “Worksheets for Calibrating a 48 x 78-Inch Surface Plate”. The diagonal length of
// such a plate would be slightly less than 92 inches. However the first and second worksheets indicate diagonal
// stations beginning at 3 inches and ending at 83 inches. That is consistent with a 48 x 72 inch surface plate
// (also a US standard size [13]) which has an 86.5-inch diagonal. The title of the Table 1 should be
// “Worksheets for Calibrating a 48 x 72-Inch Surface Plate”.
const moodySurfacePlateHeightInches = 48
const moodySurfacePlateWidthInches = 72
const moodyReflectorFootSpacingInches = 4
// TODO: Use a unit pair to specify reflector foot spacing and surface plate width/height and remove naming *Inches
const moodyData = [
[6.5, 6.0, 5.0, 5.2, 5.5, 5.6, 5.5, 5.0, 5.5, 4.8, 5.0, 5.2, 5.3, 4.9, 4.6, 4.2, 5.3, 4.9, 4.5, 3.5], // topStartingDiagonal
[6.6, 5.4, 5.4, 5.2, 5.5, 5.7, 5.0, 5.0, 5.4, 4.5, 4.4, 4.5, 4.5, 4.8, 4.2, 4.2, 4.2, 4.8, 4.3, 3.2], // bottomStartingDiagonal
[20.5, 19.7, 20.5, 20.3, 20.2, 19.9, 19.0, 19.5, 18.8, 18.6, 18.7, 18.6, 18.4, 18.5, 19.0, 17.9], // northPerimeter
[3.5, 2.1, 2.5, 2.8, 3.4, 3.2, 3.5, 4.0, 4.2, 3.5], // eastPerimeter
[16.4, 15, 15.6, 15.5, 15.1, 15.3, 15.1, 14.6, 14, 13.5, 13.5, 13.3, 13.3, 13.4, 14, 13.9], // southPerimeter
[6, 4.6, 4.5, 4.7, 5.0, 4.5, 5.9, 6, 6, 4.9], // westPerimeter
[11.7, 12.4, 12.1, 12.5, 12.0, 11.5, 11.5, 11.3, 11.3, 10.3, 10.8, 10.3, 10, 10.7, 10.4, 10.4], // horizontalCenter
[6.6, 6.4, 6.3, 6.5, 6.6, 6.9, 7.5, 7.4, 7.1, 7]] // verticalCenter
const lines = [ "topStartingDiagonal", "bottomStartingDiagonal", "northPerimeter", "eastPerimeter", "southPerimeter",
"westPerimeter", "horizontalCenter", "verticalCenter"]
window.addEventListener('DOMContentLoaded', () => {
// FIXME: This is just for testing - so we don't have to type in the values each time.
document.getElementById("plateHeight").value = moodySurfacePlateHeightInches
document.getElementById("plateWidth").value = moodySurfacePlateWidthInches
document.getElementById("reflectorFootSpacing").value = moodyReflectorFootSpacingInches
zMultiplier = document.querySelector("#zMultiplier").value
document.getElementById('fillTestData').addEventListener("click", () => {
lines.forEach((line, lineIndex) => {
moodyData[lineIndex].forEach((tableEntry, index) => {
document.getElementById(line + "Table" + (index + 1)).value = tableEntry
})
})
// Trigger table refresh.
document.getElementsByClassName("readingInput")[0].dispatchEvent(new Event('input', { bubbles: true }))
})
document.getElementById('fillZeroData').addEventListener("click", () => {
lines.forEach((line, lineIndex) => {
moodyData[lineIndex].forEach((tableEntry, index) => {
document.getElementById(line + "Table" + (index + 1)).value = 0.0
})
})
// Trigger table refresh.
document.getElementsByClassName("readingInput")[0].dispatchEvent(new Event('input', { bubbles: true }))
})
document.getElementById("createTables").addEventListener("click", () => {
createTables()
})
})
// Creates the tables for each line (along with its' own table graphic) and adds to the DOM.
function createTables() {
const surfacePlate = new SurfacePlate(document.getElementById("plateHeight").value,
document.getElementById("plateWidth").value, document.getElementById("reflectorFootSpacing").value)
document.getElementById('plateDiagonal').value = surfacePlate.surfacePlateDiagonalInches
document.getElementById('diagonalInset').value = surfacePlate.suggestedDiagonalInset
document.getElementById('numHorizontalStations').value = surfacePlate.suggestedNumberOfHorizontalStations
document.getElementById('numVerticalStations').value = surfacePlate.suggestedNumberOfVerticalStations
document.getElementById('numDiagonalStations').value = surfacePlate.suggestedNumberOfDiagonalStations
const plateDiagonalFull = Math.sqrt(((surfacePlate.surfacePlateHeightInches * surfacePlate.surfacePlateHeightInches) +
(surfacePlate.surfacePlateWidthInches * surfacePlate.surfacePlateWidthInches)))
const gradeAAFlatnessReq = .04 * (plateDiagonalFull * plateDiagonalFull) + 40
// Convert microinches to micrometers (microns)
const microinchesToMicrons = .0254
document.getElementById('gradeAAInches').value = roundToSlow(gradeAAFlatnessReq, 2)
document.getElementById('gradeAInches').value = roundToSlow(gradeAAFlatnessReq * 2, 2)
document.getElementById('gradeBInches').value = roundToSlow(gradeAAFlatnessReq * 4, 2)
document.getElementById('gradeAAMetric').value = roundToSlow(gradeAAFlatnessReq * microinchesToMicrons, 2)
document.getElementById('gradeAMetric').value = roundToSlow(gradeAAFlatnessReq * 2 * microinchesToMicrons, 2)
document.getElementById('gradeBMetric').value = roundToSlow(gradeAAFlatnessReq * 4 * microinchesToMicrons, 2)
const plateDiagonalFullMicrometers = plateDiagonalFull * 25.4
const micronsToMicroInches = 39.37
const isoGrade0FlatnessReq = 0.003 * (Math.ceil(plateDiagonalFullMicrometers / 100) * 100) + 2.5
document.getElementById('grade0Inches').value = roundToSlow(isoGrade0FlatnessReq * micronsToMicroInches, 2) // Convert from micrometers to microinches
const isoGrade1FlatnessReq = 0.006 * (Math.ceil(plateDiagonalFullMicrometers / 100) * 100) + 5
document.getElementById('grade1Inches').value = roundToSlow(isoGrade1FlatnessReq * micronsToMicroInches, 2) // Convert from micrometers to microinches
const isoGrade2FlatnessReq = 0.012 * (Math.ceil(plateDiagonalFullMicrometers / 100) * 100) + 10
document.getElementById('grade2Inches').value = roundToSlow(isoGrade2FlatnessReq * micronsToMicroInches, 2) // Convert from micrometers to microinches
const isoGrade3FlatnessReq = 0.024 * (Math.ceil(plateDiagonalFullMicrometers / 100) * 100) + 20
document.getElementById('grade3Inches').value = roundToSlow(isoGrade3FlatnessReq * micronsToMicroInches, 2) // Convert from micrometers to microinches
document.getElementById('grade0Metric').value = roundToSlow(isoGrade0FlatnessReq, 2)
document.getElementById('grade1Metric').value = roundToSlow(isoGrade1FlatnessReq, 2)
document.getElementById('grade2Metric').value = roundToSlow(isoGrade2FlatnessReq, 2)
document.getElementById('grade3Metric').value = roundToSlow(isoGrade3FlatnessReq, 2)
const flatnessInputs = [document.getElementById('gradeAAInches'), document.getElementById('gradeAInches'), document.getElementById('gradeBInches'),
document.getElementById('gradeAAMetric'), document.getElementById('gradeAMetric'), document.getElementById('gradeBMetric'),
document.getElementById('grade0Inches'), document.getElementById('grade1Inches'), document.getElementById('grade2Inches'), document.getElementById('grade3Inches'),
document.getElementById('grade0Metric'), document.getElementById('grade1Metric'), document.getElementById('grade2Metric'), document.getElementById('grade3Metric')]
const inchMultiplier = 1 // No multiplier for inches
const metricMultiplier = 25.4 // Convert inches to micrometers (you can adjust the unit if needed)
document.getElementById("overallFlatnessInch").addEventListener("input", event => {
for (const flatnessInput of flatnessInputs) {
const isMetric = flatnessInput.id.endsWith('Metric')
const multiplier = isMetric ? metricMultiplier : inchMultiplier // Use appropriate multiplier
if (Number(event.target.value) <= Number(flatnessInput.value) * multiplier) {
flatnessInput.style.background = '#C6EFCE'
} else {
flatnessInput.style.background = '#FFC7CE'
}
}
})
createTableGraphic(surfacePlate)
lines.forEach(line => {
const linePropertyName = line[0].toUpperCase() + line.slice(1)
document.getElementById(line + "Table").createCaption().textContent =
surfacePlate[linePropertyName].name + " (" + surfacePlate[linePropertyName].displayName() + ")"
// Delete all non-header rows from table.
Array.from(document.getElementById(line + "Table").getElementsByTagName("tbody")[0].getElementsByTagName("tr")).forEach(tr => tr.remove())
// Delete all previously constructed SVG table graphics (for each line).
if (document.getElementById(line + "TableSvg") != null) {
document.getElementById(line + "TableSvg").remove()
}
const numberOfStations = getNumberOfStations(line, surfacePlate)
for (let i = 0; i <= numberOfStations; i++) {
// Create the table rows.
const row = document.getElementById(line + "Table").getElementsByTagName("tbody")[0].insertRow()
row.insertCell().textContent = i + 1
const readingInput = document.createElement("input")
readingInput.inputMode = "decimal"
readingInput.required = true
readingInput.pattern = "[0-9]*[.,]{0,1}[0-9]*"
readingInput.id = line + "Table" + i
readingInput.classList.add("readingInput", line + "ReadingInput")
readingInput.addEventListener("input", () => {
refreshTables(lines, surfacePlate)
})
row.insertCell().appendChild(readingInput)
}
document.getElementById(line + "Table").style.visibility = "visible"
// Create the table graphics for each line (with the others greyed out).
const tableGraphic = document.getElementById("tableGraphic")
const specificLineTableGraphic = tableGraphic.cloneNode(true)
specificLineTableGraphic.id = line + "TableSvg"
specificLineTableGraphic.setAttribute("width", "97%")
lines.filter(l => l !== line).forEach(otherLine => {
specificLineTableGraphic.getElementById(otherLine + "LineGroup").setAttribute("stroke", "#A0A0A0")
specificLineTableGraphic.getElementById(otherLine + "LineGroup").setAttribute("fill", "#A0A0A0")
})
document.getElementById(line + "TableSvgContainer").appendChild(specificLineTableGraphic)
})
// Now that the rows have been created, set the first input for autocollimator readings to 0 and readonly.
lines.forEach(line => {
document.getElementById(line + "Table0").value = "0"
document.getElementById(line + "Table0").readOnly = true
})
}
// Creates the main SVG table graphic (with multi-colored lines) and adds it to the DOM.
function createTableGraphic(surfacePlate) {
const surfacePlateWidthInches = Number(document.getElementById("plateWidth").value)
const surfacePlateHeightInches = Number(document.getElementById("plateHeight").value)
document.getElementById('tableGraphic').style.visibility = "visible"
const surfacePlatePercentHeight = 100 * (surfacePlateHeightInches / (surfacePlateWidthInches + surfacePlateHeightInches))
const surfacePlatePercentWidth = 100 * (surfacePlateWidthInches / (surfacePlateWidthInches + surfacePlateHeightInches))
document.getElementById('tableGraphic').setAttribute("viewBox", "0 0 " + surfacePlatePercentWidth + " " + surfacePlatePercentHeight)
document.getElementById('tableGraphic').setAttribute("width", "30%")
document.getElementById('outsideRect').setAttribute("width", surfacePlatePercentWidth)
document.getElementById('outsideRect').setAttribute("height", surfacePlatePercentHeight)
const plateDiagonalAngle = Math.atan(surfacePlateWidthInches / surfacePlateHeightInches)
const xInset = surfacePlate.suggestedDiagonalInset * Math.sin(plateDiagonalAngle)
const yInset = surfacePlate.suggestedDiagonalInset * Math.cos(plateDiagonalAngle)
document.getElementById('insideRect').setAttribute("x", xInset)
document.getElementById('insideRect').setAttribute("y", yInset)
document.getElementById('insideRect').setAttribute("width", surfacePlatePercentWidth - (2 * xInset))
document.getElementById('insideRect').setAttribute("height", surfacePlatePercentHeight - (2 * yInset))
// Setup each path of the table SVG graphic (move to start position, draw to end position).
document.getElementById('topStartingDiagonalLine').setAttribute("d", `M ${xInset} ${yInset} L ${surfacePlatePercentWidth - xInset} ${surfacePlatePercentHeight - yInset}`)
document.getElementById('bottomStartingDiagonalLine').setAttribute("d", `M ${xInset} ${surfacePlatePercentHeight - yInset} L ${surfacePlatePercentWidth - xInset} ${yInset}`)
document.getElementById('northPerimeterLine').setAttribute("d", `M ${xInset} ${yInset} L ${surfacePlatePercentWidth - xInset} ${yInset}`)
document.getElementById('eastPerimeterLine').setAttribute("d", `M ${surfacePlatePercentWidth - xInset} ${yInset} L ${surfacePlatePercentWidth - xInset} ${surfacePlatePercentHeight - yInset}`)
document.getElementById('southPerimeterLine').setAttribute("d", `M ${surfacePlatePercentWidth - xInset} ${surfacePlatePercentHeight - yInset} L ${xInset} ${surfacePlatePercentHeight - yInset}`)
document.getElementById('westPerimeterLine').setAttribute("d", `M ${xInset} ${surfacePlatePercentHeight - yInset} L ${xInset} ${yInset}`)
document.getElementById('horizontalCenterLine').setAttribute("d", `M ${surfacePlatePercentWidth - xInset} ${surfacePlatePercentHeight / 2} L ${xInset} ${surfacePlatePercentHeight / 2}`)
document.getElementById('verticalCenterLine').setAttribute("d", `M ${surfacePlatePercentWidth / 2} ${yInset} L ${surfacePlatePercentWidth / 2} ${surfacePlatePercentHeight - yInset}`)
}
// Recalculates the values by creating a new MoodyReport and updates the table cell values accordingly.
function refreshTables(lines, surfacePlate) {
// One of the autocollimator readings have changed - so recalculate everything (by making a new MoodyReport).
const readingInputs = document.getElementsByClassName("readingInput")
if (readingInputs.length > 0) {
if (Array.from(readingInputs).filter(readingInput => readingInput.value !== '').length == readingInputs.length) {
// All inputs for autocollimator readings are non-empty, so create new MoodyTable with the readings.
const moodyReport = new MoodyReport(surfacePlate,
Array.from(document.getElementsByClassName("topStartingDiagonalReadingInput")).filter(input => input.readOnly == false).map(input => input.value),
Array.from(document.getElementsByClassName("bottomStartingDiagonalReadingInput")).filter(input => input.readOnly == false).map(input => input.value),
Array.from(document.getElementsByClassName("northPerimeterReadingInput")).filter(input => input.readOnly == false).map(input => input.value),
Array.from(document.getElementsByClassName("eastPerimeterReadingInput")).filter(input => input.readOnly == false).map(input => input.value),
Array.from(document.getElementsByClassName("southPerimeterReadingInput")).filter(input => input.readOnly == false).map(input => input.value),
Array.from(document.getElementsByClassName("westPerimeterReadingInput")).filter(input => input.readOnly == false).map(input => input.value),
Array.from(document.getElementsByClassName("horizontalCenterReadingInput")).filter(input => input.readOnly == false).map(input => input.value),
Array.from(document.getElementsByClassName("verticalCenterReadingInput")).filter(input => input.readOnly == false).map(input => input.value))
const allZPositions = moodyReport.vertices().map(point => point[2])
const overallFlatness = (Math.max(...allZPositions) - Math.min(...allZPositions)) * 1000000 // Convert inches to microinches.
document.getElementById("overallFlatnessInch").value = roundTo(overallFlatness, 2)
document.getElementById("overallFlatnessInch").dispatchEvent(new Event('input', { 'bubbles': true }))
document.getElementById("overallFlatnessMetric").value = roundTo(overallFlatness * 0.0254, 2)
document.getElementById("overallFlatnessMetric").dispatchEvent(new Event('input', { 'bubbles': true }))
initialize3DTableGraphic(moodyReport)
document.getElementById("canvasContainer").style.display = "block"
lines.forEach(l => {
Array.from(document.getElementById(l + "Table").getElementsByTagName("tbody")[0].rows).forEach((tableRow, index) => {
const column3Input = document.createElement("input")
column3Input.readOnly = true
column3Input.value = moodyReport[l + "Table"].angularDisplacements[index]
if (tableRow.cells.length > 2) {
tableRow.deleteCell(2)
}
tableRow.insertCell(2).appendChild(column3Input)
const column4Input = document.createElement("input")
column4Input.readOnly = true
column4Input.value = moodyReport[l + "Table"].sumOfDisplacements[index]
if (tableRow.cells.length > 3) {
tableRow.deleteCell(3)
}
tableRow.insertCell(3).appendChild(column4Input)
const column5Input = document.createElement("input")
column5Input.readOnly = true
column5Input.value = moodyReport[l + "Table"].cumulativeCorrectionFactors[index]
if (tableRow.cells.length > 4) {
tableRow.deleteCell(4)
}
tableRow.insertCell(4).appendChild(column5Input)
const column6Input = document.createElement("input")
column6Input.readOnly = true
column6Input.value = moodyReport[l + "Table"].displacementsFromDatumPlane[index]
if (tableRow.cells.length > 5) {
tableRow.deleteCell(5)
}
tableRow.insertCell(5).appendChild(column6Input)
const column7Input = document.createElement("input")
column7Input.readOnly = true
column7Input.value = moodyReport[l + "Table"].displacementsFromBaseLine[index]
if (tableRow.cells.length > 6) {
tableRow.deleteCell(6)
}
tableRow.insertCell(6).appendChild(column7Input)
const column8Input = document.createElement("input")
column8Input.readOnly = true
column8Input.value = (moodyReport[l + "Table"].displacementsFromBaseLineLinear[index] * 10000).toFixed(4)
if (tableRow.cells.length > 7) {
tableRow.deleteCell(7)
}
tableRow.insertCell(7).appendChild(column8Input)
})
})
}
}
}
const keyMap = []
const boundingBoxCache = []
let startVectorMapped = null
let cumulativeZoomFactor = 1
let zMultiplier = -1
let tableVAO = null
let showLines = true
let showHeatmap = true
let lightingOn = true
let initialTableRotation = Mat4.create()
let tableRotationMatrix = Mat4.create()
let tableScaleMatrix = Mat4.create()
let tableTranslateMatrix = Mat4.create()
// The viewMatrix is calculated once when initializing the 3D table surface - it does not change between frames.
let viewMatrix = Mat4.create()
// The projectionMatrix is set on initialization of the 3D table surface and also when the canvas is resized.
let projectionMatrix = Mat4.create()
/**
* Converts a canvas-relative position (mouse coordinates) to clip space coordinates
* normalized by the maximum dimension of the canvas's bounding rectangle.
*
* Clip space coordinates range from -1 to 1, with the origin at the center.
* This method uses uniform scaling based on the largest dimension (width or height)
* of the canvas's bounding rectangle (thus making it aspect ratio independent).
*
* @param {HTMLCanvasElement} canvas - The canvas element to use as the reference.
* @param {number} mouseX - The x-coordinate of the mouse position relative to the canvas.
* @param {number} mouseY - The y-coordinate of the mouse position relative to the canvas.
* @returns {number[]} A 2D array containing the x and y coordinates in clip space.
*/
function toUniformClipSpace(canvas, mouseX, mouseY) {
const res = Math.max(canvas.getBoundingClientRect().width, canvas.getBoundingClientRect().height) - 1
return [
(2 * (mouseX - canvas.getBoundingClientRect().x) - canvas.getBoundingClientRect().width - 1) / res,
(2 * (mouseY - canvas.getBoundingClientRect().y) - canvas.getBoundingClientRect().height - 1) / res
]
}
/**
* Converts a canvas-relative position (mouse coordinates) to clip space coordinates
* normalized by the intrinsic dimensions of the canvas element.
*
* Clip space coordinates range from -1 to 1, with the origin at the center.
* This method scales the position using the canvas's intrinsic width and height.
*
* @param {HTMLCanvasElement} canvas - The canvas element to use as the reference.
* @param {number} mouseX - The x-coordinate of the mouse position relative to the canvas.
* @param {number} mouseY - The y-coordinate of the mouse position relative to the canvas.
* @returns {number[]} A 2D array containing the x and y coordinates in clip space.
*/
function toCanvasClipSpace(canvas, mouseX, mouseY) {
const cssX = mouseX - canvas.getBoundingClientRect().left
const cssY = mouseY - canvas.getBoundingClientRect().top
const normalizedX = cssX / canvas.getBoundingClientRect().width
const normalizedY = cssY / canvas.getBoundingClientRect().height
return [normalizedX * 2 - 1, normalizedY * -2 + 1]
}
function mapToSphere(mouseX, mouseY, canvas) {
const xy = toUniformClipSpace(canvas, mouseX, mouseY)
const x = xy[0]
const y = xy[1]
const lengthSquared = x * x + y * y
const radius = 3
// Map to sphere when x^2 + y^2 <= r^2 / 2 - otherwise map to the hyperbolic function f(x,y) = (r^2 / 2) / sqrt(x^2 + y^2).
if (2 * lengthSquared <= radius * radius) {
return new Vector3(x, y, Math.sqrt((radius * radius) - lengthSquared))
} else {
return new Vector3(x, y, ((radius * radius) / 2) / Math.sqrt(lengthSquared))
}
}
function getBoundingBox(moodyReport) {
const vertices = moodyReport.vertices(zMultiplier).map(vertex => new Vertex(vertex[0], vertex[1], vertex[2])).flat(1)
const minX = Math.min(...vertices.map(vertex => vertex.x))
const maxX = Math.max(...vertices.map(vertex => vertex.x))
const minY = Math.min(...vertices.map(vertex => vertex.y))
const maxY = Math.max(...vertices.map(vertex => vertex.y))
const minZ = Math.min(...vertices.map(vertex => vertex.z))
const maxZ = Math.max(...vertices.map(vertex => vertex.z))
return { "minX": minX, "maxX": maxX, "minY": minY, "maxY": maxY, "minZ": minZ, "maxZ": maxZ }
}
function initialize3DTableGraphic(moodyReport) {
const canvas = document.getElementById("glcanvas")
const gl = canvas.getContext("webgl2")
// const gl = WebGLDebugUtils.makeDebugContext(canvas.getContext("webgl2"))
if (gl === null) {
console.log("Unable to initialize WebGL. Your browser or machine may not support it.")
const ctx = canvas.getContext("2d")
ctx.font = "30px Arial"
ctx.fillStyle = "red"
ctx.textAlign = "center"
ctx.fillText("Unable to initialize WebGL!", canvas.width / 2, canvas.height / 2)
return
}
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height)
document.querySelector("#zMultiplier").addEventListener("input", event => {
zMultiplier = event.target.value
if (!(zMultiplier in boundingBoxCache)) {
boundingBoxCache[zMultiplier] = getBoundingBox(moodyReport)
}
createAndBindTableVAO(moodyReport, gl, programInfo)
})
document.getElementById("showLines").addEventListener("change", event => showLines = event.target.checked)
document.getElementById("showHeatmap").addEventListener("change", event => showHeatmap = event.target.checked)
document.getElementById("lightingOn").addEventListener("change", event => lightingOn = event.target.checked)
const resizeObserver = new ResizeObserver(entries => {
for (let entry of entries) {
const { width, height } = entry.contentRect
const canvas = document.getElementById("glcanvas")
let sizeChanged = false
if (width > document.getElementById("canvasContainer").style.minWidth) {
canvas.width = width
sizeChanged = true
}
if (height > document.getElementById("canvasContainer").style.minHeight) {
canvas.height = height
sizeChanged = true
}
if (sizeChanged) {
const fieldOfView = (45 * Math.PI) / 180 // radians
const aspect = canvas.width / canvas.height
const zNear = 0.1
const zFar = 1000.0
projectionMatrix.perspective(fieldOfView, aspect, zNear, zFar)
}
}
})
resizeObserver.observe(document.getElementById("canvasContainer"))
canvas.onmousedown = event => {
startVectorMapped = mapToSphere(event.clientX, event.clientY, canvas)
initialTableRotation = tableRotationMatrix
}
document.onmouseup = () => {
startVectorMapped = null
initialTableRotation = tableRotationMatrix
}
document.onmousemove = event => {
// http://hjemmesider.diku.dk/~kash/papers/DSAGM2002_henriksen.pdf
// https://graphicsinterface.org/wp-content/uploads/gi1992-18.pdf
if (startVectorMapped) {
// Map mouse displacement onto virtual hemi-sphere/hyperbola.
const currentVectorMapped = mapToSphere(event.clientX, event.clientY, canvas)
// Determine rotation axis.
const axis = startVectorMapped.cross(currentVectorMapped)
let rotationQuat = Quat.identity()
if (axis.magnitude > 0.000001) {
// FIXME: The strange order of this may be related to how toMatrix4 is currently not producing correct values.
// See tests/quat.spec.js toMatrix4 tests.
rotationQuat = new Quat(startVectorMapped.dot(currentVectorMapped), axis[0], -axis[1], 0)
}
tableRotationMatrix = Mat4.create()
tableRotationMatrix.multiply(initialTableRotation)
// We want rotation to be centered on the center of the table.
tableRotationMatrix.translate([(boundingBoxCache[zMultiplier].maxX - boundingBoxCache[zMultiplier].minX) / 2,
(boundingBoxCache[zMultiplier].maxY - boundingBoxCache[zMultiplier].minY) / 2,
(boundingBoxCache[zMultiplier].maxZ - boundingBoxCache[zMultiplier].minZ) / 2])
tableRotationMatrix.multiply(rotationQuat.toMatrix4())
tableRotationMatrix.translate([-((boundingBoxCache[zMultiplier].maxX - boundingBoxCache[zMultiplier].minX) / 2),
-((boundingBoxCache[zMultiplier].maxY - boundingBoxCache[zMultiplier].minY) / 2),
-((boundingBoxCache[zMultiplier].maxZ - boundingBoxCache[zMultiplier].minZ) / 2)])
}
}
canvas.onwheel = event => {
event.preventDefault()
const direction = event.deltaY < 0 ? 1 : -1
const zoomFactor = 1 + direction * 0.1
if (cumulativeZoomFactor < 0.16 || cumulativeZoomFactor > 10) {
// Max zoom level reached, don't zoom any more.
return
}
cumulativeZoomFactor *= zoomFactor
// TODO: Keep zoom centered at mouse cursor.
// See: https://stackoverflow.com/questions/57892652/webgl-2d-camera-zoom-to-mouse-point
tableScaleMatrix.scale([zoomFactor, zoomFactor, zoomFactor])
}
// Pretty weird hack that allows the canvas to be focused and thus receive keydown events.
canvas.tabIndex = 1
canvas.onkeyup = event => {
keyMap[event.key] = false
}
canvas.onkeydown = event => {
event.preventDefault()
keyMap[event.key] = true
const translateMatrix = Mat4.create()
if (keyMap['ArrowUp'] === true) {
translateMatrix.translate([0, -1.0, 0.0])
}
if (keyMap['ArrowDown'] === true) {
translateMatrix.translate([0, 1.0, 0.0])
}
if (keyMap['ArrowRight'] === true) {
translateMatrix.translate([-1.0, 0.0, 0.0])
}
if (keyMap['ArrowLeft'] === true) {
translateMatrix.translate([1.0, 0.0, 0.0])
}
if (keyMap['w'] === true) {
translateMatrix.translate([0.0, 0.0, -1.0])
}
if (keyMap['s'] === true) {
translateMatrix.translate([0.0, 0.0, 1.0])
}
if (keyMap['a'] === true) {
translateMatrix.translate([(boundingBoxCache[zMultiplier].maxX - boundingBoxCache[zMultiplier].minX) / 2,
(boundingBoxCache[zMultiplier].maxY - boundingBoxCache[zMultiplier].minY) / 2,
(boundingBoxCache[zMultiplier].maxZ - boundingBoxCache[zMultiplier].minZ) / 2])
translateMatrix.rotate(0.01, [0.0, 0.0, -1.0])
translateMatrix.translate([-((boundingBoxCache[zMultiplier].maxX - boundingBoxCache[zMultiplier].minX) / 2),
-((boundingBoxCache[zMultiplier].maxY - boundingBoxCache[zMultiplier].minY) / 2),
-((boundingBoxCache[zMultiplier].maxZ - boundingBoxCache[zMultiplier].minZ) / 2)])
}
if (keyMap['d'] === true) {
translateMatrix.translate([(boundingBoxCache[zMultiplier].maxX - boundingBoxCache[zMultiplier].minX) / 2,
(boundingBoxCache[zMultiplier].maxY - boundingBoxCache[zMultiplier].minY) / 2,
(boundingBoxCache[zMultiplier].maxZ - boundingBoxCache[zMultiplier].minZ) / 2])
translateMatrix.rotate(0.01, [0.0, 0.0, 1.0])
translateMatrix.translate([-((boundingBoxCache[zMultiplier].maxX - boundingBoxCache[zMultiplier].minX) / 2),
-((boundingBoxCache[zMultiplier].maxY - boundingBoxCache[zMultiplier].minY) / 2),
-((boundingBoxCache[zMultiplier].maxZ - boundingBoxCache[zMultiplier].minZ) / 2)])
}
tableTranslateMatrix.multiply(translateMatrix)
}
const texture = loadTexture(gl, "granite_2048x2048_compressed.png")
// Flip image pixels into the bottom-to-top order that WebGL expects.
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true)
gl.clearColor(0.0, 0.0, 0.0, 1.0)
gl.clear(gl.COLOR_BUFFER_BIT)
const shaderProgram = initShaderProgram(gl, vsSource, fsSource)
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, "vertexPosition"),
vertexNormal: gl.getAttribLocation(shaderProgram, "vertexNormal"),
vertexColor: gl.getAttribLocation(shaderProgram, "vertexColor"),
textureCoord: gl.getAttribLocation(shaderProgram, "vertexTextureCoord"),
vertexType: gl.getAttribLocation(shaderProgram, "vertexType"),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(shaderProgram, "projectionMatrix"),
modelMatrix: gl.getUniformLocation(shaderProgram, "modelMatrix"),
viewMatrix: gl.getUniformLocation(shaderProgram, "viewMatrix"),
normalMatrix: gl.getUniformLocation(shaderProgram, "normalMatrix"),
lightPos: gl.getUniformLocation(shaderProgram, "lightPos"),
lightPower: gl.getUniformLocation(shaderProgram, "lightPower"),
sampler: gl.getUniformLocation(shaderProgram, "sampler"),
showLines: gl.getUniformLocation(shaderProgram, "showLines"),
showHeatmap: gl.getUniformLocation(shaderProgram, "showHeatmap"),
lightingOn: gl.getUniformLocation(shaderProgram, "lightingOn"),
},
}
const buffers = createAndBindTableVAO(moodyReport, gl, programInfo)
function render(now) {
updateFps(now)
drawTableSurface(moodyReport, gl, programInfo, buffers, texture)
requestAnimationFrame(render)
}
requestAnimationFrame(render)
function updateFps(now) {
now *= 0.001
const deltaTime = now - then
then = now
const fps = 1 / deltaTime
fpsElem.textContent = fps.toFixed(1)
totalFPS += fps - (frameTimes[frameCursor] || 0)
frameTimes[frameCursor++] = fps
numFrames = Math.max(numFrames, frameCursor)
frameCursor %= maxFrames
const averageFPS = totalFPS / numFrames
avgElem.textContent = averageFPS.toFixed(1)
}
let then = 0
const frameTimes = []
let frameCursor = 0
let numFrames = 0
const maxFrames = 20
let totalFPS = 0
const fpsElem = document.querySelector("#fps")
const avgElem = document.querySelector("#avg")
boundingBoxCache[zMultiplier] = getBoundingBox(moodyReport)
viewMatrix.translate([-(boundingBoxCache[zMultiplier].maxX - boundingBoxCache[zMultiplier].minX) / 2,
-(boundingBoxCache[zMultiplier].maxY - boundingBoxCache[zMultiplier].minY) / 2,
-(boundingBoxCache[zMultiplier].maxZ - boundingBoxCache[zMultiplier].minZ) * 8])
gl.bindVertexArray(null)
gl.bindBuffer(gl.ARRAY_BUFFER, null)
}
function createAndBindTableVAO(moodyReport, gl, programInfo) {
tableVAO = gl.createVertexArray()
gl.bindVertexArray(tableVAO)
const buffers = getBuffers(gl, moodyReport, zMultiplier)
setPositionAttribute(gl, buffers, programInfo)
setNormalAttribute(gl, buffers, programInfo)
setColorAttribute(gl, buffers, programInfo)
setTextureAttribute(gl, buffers, programInfo)
setTypeAttribute(gl, buffers, programInfo)
return buffers
}
// Creates a 3D surface of the linear plate heights (calculated as Column #8 of the line tables).
function drawTableSurface(moodyReport, gl, programInfo, buffers, texture) {
// We must set the model matrix to identity here because we are using relative (incremental) transforms.
// We need to make it so that all of our event handlers only mess with currentTransformMatrix, and then that
// will be applied to the model matrix.
const tableModelMatrix = Mat4.create()
tableModelMatrix.multiply(tableScaleMatrix)
tableModelMatrix.multiply(tableTranslateMatrix)
tableModelMatrix.multiply(tableRotationMatrix)
gl.clearColor(0.0, 0.0, 0.0, 1.0)
gl.clearDepth(1.0)
gl.enable(gl.DEPTH_TEST)
gl.depthFunc(gl.LEQUAL)
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
const canvas = document.getElementById("glcanvas")
gl.viewport(0, 0, canvas.width, canvas.height)
gl.bindVertexArray(tableVAO)
gl.useProgram(programInfo.program)
const normalMatrix = Mat4.create()
Mat4.invert(normalMatrix, Mat4.multiply(normalMatrix, viewMatrix, tableModelMatrix))
Mat4.transpose(normalMatrix, normalMatrix)
const lightPos = [document.getElementById("lightPosX").value, document.getElementById("lightPosY").value, document.getElementById("lightPosZ").value]
const lightPower = document.getElementById("lightPower").value
gl.uniformMatrix4fv(programInfo.uniformLocations.projectionMatrix, false, projectionMatrix)
gl.uniformMatrix4fv(programInfo.uniformLocations.modelMatrix, false, tableModelMatrix)
gl.uniformMatrix4fv(programInfo.uniformLocations.viewMatrix, false, viewMatrix)
gl.uniformMatrix4fv(programInfo.uniformLocations.normalMatrix, false, normalMatrix)
gl.uniform3fv(programInfo.uniformLocations.lightPos, lightPos)
gl.uniform1f(programInfo.uniformLocations.lightPower, lightPower)
gl.activeTexture(gl.TEXTURE0)
gl.bindTexture(gl.TEXTURE_2D, texture)
gl.uniform1i(programInfo.uniformLocations.sampler, 0)
gl.uniform1i(programInfo.uniformLocations.showLines, showLines)
gl.uniform1i(programInfo.uniformLocations.showHeatmap, showHeatmap)
gl.uniform1i(programInfo.uniformLocations.lightingOn, lightingOn)
let offset = 0
let vertexCount = moodyReport.topStartingDiagonalTable.vertices().flat(1).length / 3
gl.drawArrays(gl.LINE_STRIP, offset, vertexCount)
offset += vertexCount
vertexCount = moodyReport.bottomStartingDiagonalTable.vertices().flat(1).length / 3
gl.drawArrays(gl.LINE_STRIP, offset, vertexCount)
offset += vertexCount
vertexCount = moodyReport.northPerimeterTable.vertices().flat(1).length / 3
gl.drawArrays(gl.LINE_STRIP, offset, vertexCount)
offset += vertexCount
vertexCount = moodyReport.eastPerimeterTable.vertices().flat(1).length / 3
gl.drawArrays(gl.LINE_STRIP, offset, vertexCount)
offset += vertexCount
vertexCount = moodyReport.southPerimeterTable.vertices().flat(1).length / 3
gl.drawArrays(gl.LINE_STRIP, offset, vertexCount)
offset += vertexCount
vertexCount = moodyReport.westPerimeterTable.vertices().flat(1).length / 3
gl.drawArrays(gl.LINE_STRIP, offset, vertexCount)
offset += vertexCount
vertexCount = moodyReport.horizontalCenterTable.vertices().flat(1).length / 3
gl.drawArrays(gl.LINE_STRIP, offset, vertexCount)
offset += vertexCount
vertexCount = moodyReport.verticalCenterTable.vertices().flat(1).length / 3
gl.drawArrays(gl.LINE_STRIP, offset, vertexCount)
offset += vertexCount
vertexCount = buffers.triangleVertices.length
gl.drawArrays(gl.TRIANGLES, offset, vertexCount / 3)
gl.uniformMatrix4fv(programInfo.uniformLocations.modelMatrix, false, Mat4.create())
offset += vertexCount / 3
vertexCount = 6
gl.drawArrays(gl.LINE_STRIP, offset, vertexCount)
gl.bindVertexArray(null)
gl.bindBuffer(gl.ARRAY_BUFFER, null)
}
const vsSource = `#version 300 es
in vec4 vertexPosition;
in vec3 vertexNormal;
in vec4 vertexColor;
in vec2 vertexTextureCoord;
in float vertexType;
uniform mat4 modelMatrix;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
uniform mat4 normalMatrix;
out lowp vec4 color;
out highp vec2 textureCoord;
out highp vec3 normalInterp;
out highp vec3 vertPos;
out highp float vVertexType;
void main() {
gl_Position = projectionMatrix * viewMatrix * modelMatrix * vertexPosition;
color = vertexColor;
textureCoord = vertexTextureCoord;
vVertexType = vertexType;
normalInterp = vec3(normalMatrix * vec4(vertexNormal, 0.0));
vec4 vertPos4 = viewMatrix * modelMatrix * vertexPosition;
vertPos = vec3(vertPos4) / vertPos4.w;
}
`
const fsSource = `#version 300 es
precision mediump float;
in lowp vec4 color;
in vec3 normalInterp;
in vec3 vertPos;
in highp vec2 textureCoord;
in highp float vVertexType;
const highp vec3 lightColor = vec3(1.0, 1.0, 1.0);
const highp vec3 ambientColor = vec3(0.4, 0.4, 0.4);
const highp vec3 diffuseColor = vec3(0.2, 0.2, 0.2);
const highp vec3 specColor = vec3(1.0, 1.0, 1.0);
const highp float shininess = 8.0;
const highp float screenGamma = 2.2; // Assume the monitor is calibrated to the sRGB color space
uniform vec3 lightPos;
uniform float lightPower;
uniform sampler2D sampler;
uniform bool showLines;
uniform bool showHeatmap;
uniform bool lightingOn;
out vec4 outputColor;
void main() {
if (vVertexType == 0.0) {
// This vertex belongs to one of the Union jack Moody lines.
if (showLines) {
outputColor = color;
} else {
discard;
}
} else {
// This vertex belongs to the table mesh.
vec3 normal = normalize(normalInterp);
vec3 lightDir = lightPos - vertPos;
float distance = length(lightDir);
distance = distance * distance;
lightDir = normalize(lightDir);
float lambertian = max(dot(lightDir, normal), 0.0);
float specular = 0.0;
if (lambertian > 0.0) {
vec3 viewDir = normalize(-vertPos);
vec3 halfDir = normalize(lightDir + viewDir);
float specAngle = max(dot(halfDir, normal), 0.0);
specular = pow(specAngle, shininess);
}
vec3 colorLinear = ambientColor +
diffuseColor * lambertian * lightColor * lightPower / distance +
specColor * specular * lightColor * lightPower / distance;
// apply gamma correction (assume ambientColor, diffuseColor and specColor
// have been linearized, i.e. have no gamma correction in them)
vec3 colorGammaCorrected = pow(colorLinear, vec3(1.0 / screenGamma));
if (!showHeatmap) {
if (lightingOn) {
outputColor = texture(sampler, textureCoord) * vec4(colorGammaCorrected, 1.0);
} else {
outputColor = texture(sampler, textureCoord);
}
} else {
if (lightingOn) {
// No heatmap - show the table with a granite texture.
outputColor = vec4(color.rgb * colorGammaCorrected, 1.0);
} else {
outputColor = color;
}
}
}
}
`
function getBuffers(gl, moodyReport, zMultiplier) {
const buffers = getNonColorBuffers(gl, moodyReport, zMultiplier)
const lineColorBuffer = getColorBuffer(gl, moodyReport, buffers.triangleVertices)
const areEqual = (x, y, z, w, v) => x === y && y === z && z === w && w === v
console.assert(areEqual(buffers.positions.length / 3, buffers.normals.length / 3, buffers.textureCoordinates.length / 2, buffers.types.length, lineColorBuffer.colors.length / 4),
`All buffers must be of the same size (per vertex) but were not. Position buffer: ${buffers.positions.length / 3},
Normal buffer: ${buffers.normals.length / 3}, Texture buffer: ${buffers.textureCoordinates.length / 2}, Type buffer: ${buffers.types.length},
Color buffer: ${lineColorBuffer.colors.length / 4}`)
return {
positionBuffer: buffers.positionBuffer,
normalBuffer: buffers.normalBuffer,
triangleVertices: buffers.triangleVertices,
textureBuffer: buffers.textureBuffer,
typeBuffer: buffers.typeBuffer,
lineColors: lineColorBuffer.colorBuffer,
}
}
function getNonColorBuffers(gl, moodyReport, zMultiplier) {
const vertices = moodyReport.vertices(zMultiplier).map(vertex => new Vertex(vertex[0], vertex[1], vertex[2])).flat(1)
const triangulation = bowyerWatson(vertices)
const triangulatedVertices = triangulation.map(triangle => [
triangle.v0.x, triangle.v0.y, triangle.v0.z,
triangle.v1.x, triangle.v1.y, triangle.v1.z,
triangle.v2.x, triangle.v2.y, triangle.v2.z]).flat(1)
const axisSize = 20
// FIXME: We want the line to always be on top of the surface but it can dip underneath it at extreme points. Adding 0.1 to z-coordinate is not good enough.
// We need to calculate the slope from point x -> y and use it to find amount to add so line is always on top or have the lines use the same slope as the
// points.
const positions = new Float32Array(
moodyReport.vertices(zMultiplier).map(v => [v[0], v[1], v[2] + 0.1]).flat(1) // "Union jack" colored lines.
.concat(triangulatedVertices)
.concat(0, 0, 0, axisSize, 0, 0,
0, 0, 0, 0, axisSize, 0,
0, 0, 0, 0, 0, axisSize)
)
const positionBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer)
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW)
// Calculate and create normal buffer.
const lineNormals = moodyReport.vertices(zMultiplier).map(() => [0.0, 0.0, 0.0]).flat(1)
// Each triangle has 3 vertices with the same surface normal.
const triangleNormals = triangulation.map(triangle => {
const length = Math.sqrt(triangle.surfaceNormal().x * triangle.surfaceNormal().x +
triangle.surfaceNormal().y * triangle.surfaceNormal().y +
triangle.surfaceNormal().z * triangle.surfaceNormal().z)
return [
triangle.surfaceNormal().x / length, triangle.surfaceNormal().y / length, triangle.surfaceNormal().z / length,
triangle.surfaceNormal().x / length, triangle.surfaceNormal().y / length, triangle.surfaceNormal().z / length,
triangle.surfaceNormal().x / length, triangle.surfaceNormal().y / length, triangle.surfaceNormal().z / length
]}).flat(1)
const normals = new Float32Array(lineNormals.concat(triangleNormals).concat(new Array(18).fill(0)))
const normalBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer)
gl.bufferData(gl.ARRAY_BUFFER, normals, gl.STATIC_DRAW)
// Calculate and create texture buffer.
const lineTextureCoords = moodyReport.vertices(zMultiplier).map(() => [0.0, 1.0]).flat(1)
if (!(zMultiplier in boundingBoxCache)) {
boundingBoxCache[zMultiplier] = getBoundingBox(moodyReport)
}
const tableSurfaceRatio = (boundingBoxCache[zMultiplier].maxY - boundingBoxCache[zMultiplier].minY) / (boundingBoxCache[zMultiplier].maxX - boundingBoxCache[zMultiplier].minX)
// Map [minX, maxX] => [0, 1] and [minY, maxY] => [0, 1]
// (val - A) * (b - a) / (B - A) + a
const numRepeatsX = 1
const numRepeatsY = numRepeatsX * tableSurfaceRatio
const triangleTextureCoords = triangulation.map((triangle) => [
((triangle.v0.x - boundingBoxCache[zMultiplier].minX) * numRepeatsX) / (boundingBoxCache[zMultiplier].maxX - boundingBoxCache[zMultiplier].minX),
((triangle.v0.y - boundingBoxCache[zMultiplier].minY) * numRepeatsY) / (boundingBoxCache[zMultiplier].maxY - boundingBoxCache[zMultiplier].minY),
((triangle.v1.x - boundingBoxCache[zMultiplier].minX) * numRepeatsX) / (boundingBoxCache[zMultiplier].maxX - boundingBoxCache[zMultiplier].minX),
((triangle.v1.y - boundingBoxCache[zMultiplier].minY) * numRepeatsY) / (boundingBoxCache[zMultiplier].maxY - boundingBoxCache[zMultiplier].minY),
((triangle.v2.x - boundingBoxCache[zMultiplier].minX) * numRepeatsX) / (boundingBoxCache[zMultiplier].maxX - boundingBoxCache[zMultiplier].minX),
((triangle.v2.y - boundingBoxCache[zMultiplier].minY) * numRepeatsY) / (boundingBoxCache[zMultiplier].maxY - boundingBoxCache[zMultiplier].minY),
]).flat(1)
const textureCoordinates = new Float32Array(lineTextureCoords.concat(triangleTextureCoords).concat(0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0))
const textureBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, textureBuffer)
gl.bufferData(gl.ARRAY_BUFFER, textureCoordinates, gl.STATIC_DRAW)
const types = new Float32Array(
moodyReport.vertices(zMultiplier).map(() => [0.0]).flat(1) // "Union jack" colored lines have type "0.0"
.concat(triangulation.map(() => [1.0, 1.0, 1.0]).flat(1)) // Table vertices have type "1.0"
.concat(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)) // Axis vertices have type "0.0"
const typeBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, typeBuffer)
gl.bufferData(gl.ARRAY_BUFFER, types, gl.STATIC_DRAW)
return { positionBuffer: positionBuffer, positions: positions, normalBuffer: normalBuffer, normals: normals,
textureBuffer: textureBuffer, textureCoordinates: textureCoordinates, typeBuffer: typeBuffer, types: types,
triangleVertices: triangulatedVertices }
}
function getColorBuffer(gl, moodyReport, triangleVertices) {
const triangleZValues = triangleVertices.filter((v, i) => (i + 1) % 3 == 0)
const minZ = Math.min(...triangleZValues)
const maxZ = Math.max(...triangleZValues)
// In case all values are the same minZ = maxZ (i.e. it is a totally flat plate with zero deviation) so we must avoid division by zero - just set all values to 0.0.
const normalizedTriangleZValues = minZ === maxZ ? triangleZValues.map(() => 0.0) : triangleZValues.map(value => (value - minZ) / (maxZ - minZ))
const colorMappedZValues = normalizedTriangleZValues.map(value => interpolate(turboColormapData, value))
console.log(colorMappedZValues)
const colors = new Array(moodyReport.topStartingDiagonalTable.numStations).fill([0.9568627450980393, 0.2627450980392157, 0.21176470588235294, 1.0]).flat(1)
.concat(new Array(moodyReport.bottomStartingDiagonalTable.numStations).fill([1.0, 0.9254901960784314, 0.2313725490196078, 1.0]).flat(1))
.concat(new Array(moodyReport.northPerimeterTable.numStations).fill([0.2980392156862745, 0.6862745098039216, 0.3137254901960784, 1.0]).flat(1))
.concat(new Array(moodyReport.eastPerimeterTable.numStations).fill([1.0, 0.4980392156862745, 0.3137254901960784, 1.0]).flat(1))
.concat(new Array(moodyReport.southPerimeterTable.numStations).fill([0.12941176470588237, 0.5882352941176471, 0.9529411764705882, 1.0]).flat(1))
.concat(new Array(moodyReport.westPerimeterTable.numStations).fill([1.0, 0.5019607843137255, 0.6745098039215687, 1.0]).flat(1))
.concat(new Array(moodyReport.horizontalCenterTable.numStations).fill([0.0, 0.749019607843137, 0.8470588235294118, 1.0]).flat(1))
.concat(new Array(moodyReport.verticalCenterTable.numStations).fill([0.607843137254902, 0.1568627450980392, 0.6862745098039216, 1.0]).flat(1))
.concat(colorMappedZValues.flat(1)) // Add color mapped colors for the triangles z-value.
.concat(1, 1, 1, 1, 1, 0, 0, 1,
1, 1, 1, 1, 0, 1, 0, 1,
1, 1, 1, 1, 0, 0, 1, 1) // Add colors for axes lines.
const colorBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW)
return { colorBuffer: colorBuffer, colors: colors }
}
function setPositionAttribute(gl, buffers, programInfo) {
const numComponents = 3
const type = gl.FLOAT
const normalize = false
const stride = 0
const offset = 0
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.positionBuffer)
gl.vertexAttribPointer(
programInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset)
gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition)
}
function setNormalAttribute(gl, buffers, programInfo) {
const numComponents = 3
const type = gl.FLOAT
const normalize = false
const stride = 0
const offset = 0
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.normalBuffer)
gl.vertexAttribPointer(
programInfo.attribLocations.vertexNormal,
numComponents,
type,
normalize,
stride,
offset,
)
gl.enableVertexAttribArray(programInfo.attribLocations.vertexNormal)
}
function setColorAttribute(gl, buffers, programInfo) {
const numComponents = 4
const type = gl.FLOAT
const normalize = false
const stride = 0
const offset = 0
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.lineColors)
gl.vertexAttribPointer(
programInfo.attribLocations.vertexColor,
numComponents,
type,
normalize,
stride,
offset,
)
gl.enableVertexAttribArray(programInfo.attribLocations.vertexColor)
}
function setTextureAttribute(gl, buffers, programInfo) {
const num = 2
const type = gl.FLOAT
const normalize = false
const stride = 0
const offset = 0
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureBuffer)
gl.vertexAttribPointer(
programInfo.attribLocations.textureCoord,
num,
type,
normalize,
stride,
offset,
)
gl.enableVertexAttribArray(programInfo.attribLocations.textureCoord)
}
function setTypeAttribute(gl, buffers, programInfo) {