@tetrascience-npm/ts-lib-viz 0.0.0-stage → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (278) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +2171 -2
  3. package/dist/src/builder/PlotPanel.d.ts +42 -0
  4. package/dist/src/builder/PlotPanel.js +433 -0
  5. package/dist/src/builder/Popover.d.ts +37 -0
  6. package/dist/src/builder/Popover.js +32 -0
  7. package/dist/src/builder/Stepper.d.ts +21 -0
  8. package/dist/src/builder/Stepper.js +41 -0
  9. package/dist/src/builder/index.d.ts +10 -0
  10. package/dist/src/builder/index.js +10 -0
  11. package/dist/src/core/adapters.d.ts +86 -0
  12. package/dist/src/core/adapters.js +219 -0
  13. package/dist/src/core/aggregate.d.ts +74 -0
  14. package/dist/src/core/aggregate.js +102 -0
  15. package/dist/src/core/annotations.d.ts +34 -0
  16. package/dist/src/core/annotations.js +71 -0
  17. package/dist/src/core/band-order.d.ts +86 -0
  18. package/dist/src/core/band-order.js +132 -0
  19. package/dist/src/core/binning.d.ts +123 -0
  20. package/dist/src/core/binning.js +193 -0
  21. package/dist/src/core/bounds.d.ts +40 -0
  22. package/dist/src/core/bounds.js +107 -0
  23. package/dist/src/core/brush.d.ts +73 -0
  24. package/dist/src/core/brush.js +102 -0
  25. package/dist/src/core/build.d.ts +322 -0
  26. package/dist/src/core/build.js +496 -0
  27. package/dist/src/core/camera.d.ts +152 -0
  28. package/dist/src/core/camera.js +303 -0
  29. package/dist/src/core/capabilities.d.ts +24 -0
  30. package/dist/src/core/capabilities.js +307 -0
  31. package/dist/src/core/chord.d.ts +49 -0
  32. package/dist/src/core/chord.js +57 -0
  33. package/dist/src/core/circular.d.ts +83 -0
  34. package/dist/src/core/circular.js +63 -0
  35. package/dist/src/core/cluster.d.ts +136 -0
  36. package/dist/src/core/cluster.js +607 -0
  37. package/dist/src/core/critique.d.ts +92 -0
  38. package/dist/src/core/critique.js +905 -0
  39. package/dist/src/core/density.d.ts +38 -0
  40. package/dist/src/core/density.js +82 -0
  41. package/dist/src/core/figure-set.d.ts +34 -0
  42. package/dist/src/core/figure-set.js +55 -0
  43. package/dist/src/core/finding-codes.d.ts +10 -0
  44. package/dist/src/core/finding-codes.js +1 -0
  45. package/dist/src/core/fit-types.d.ts +46 -0
  46. package/dist/src/core/fit-types.js +7 -0
  47. package/dist/src/core/fitter.d.ts +62 -0
  48. package/dist/src/core/fitter.js +102 -0
  49. package/dist/src/core/frame-geometry.d.ts +407 -0
  50. package/dist/src/core/frame-geometry.js +612 -0
  51. package/dist/src/core/frame.d.ts +329 -0
  52. package/dist/src/core/frame.js +1432 -0
  53. package/dist/src/core/geom-table.d.ts +503 -0
  54. package/dist/src/core/geom-table.js +484 -0
  55. package/dist/src/core/geom-types.d.ts +182 -0
  56. package/dist/src/core/geom-types.js +17 -0
  57. package/dist/src/core/grammar.d.ts +359 -0
  58. package/dist/src/core/grammar.js +397 -0
  59. package/dist/src/core/heat-reductions.d.ts +36 -0
  60. package/dist/src/core/heat-reductions.js +133 -0
  61. package/dist/src/core/hexbin.d.ts +84 -0
  62. package/dist/src/core/hexbin.js +168 -0
  63. package/dist/src/core/hierarchy.d.ts +59 -0
  64. package/dist/src/core/hierarchy.js +248 -0
  65. package/dist/src/core/hit.d.ts +75 -0
  66. package/dist/src/core/hit.js +37 -0
  67. package/dist/src/core/index.d.ts +33 -0
  68. package/dist/src/core/index.js +18 -0
  69. package/dist/src/core/internal.d.ts +58 -0
  70. package/dist/src/core/internal.js +58 -0
  71. package/dist/src/core/labels.d.ts +37 -0
  72. package/dist/src/core/labels.js +54 -0
  73. package/dist/src/core/layers.d.ts +594 -0
  74. package/dist/src/core/layers.js +2892 -0
  75. package/dist/src/core/load.d.ts +17 -0
  76. package/dist/src/core/load.js +356 -0
  77. package/dist/src/core/marginal.d.ts +65 -0
  78. package/dist/src/core/marginal.js +116 -0
  79. package/dist/src/core/mesh.d.ts +69 -0
  80. package/dist/src/core/mesh.js +237 -0
  81. package/dist/src/core/omission.d.ts +41 -0
  82. package/dist/src/core/omission.js +62 -0
  83. package/dist/src/core/palette-sets.d.ts +623 -0
  84. package/dist/src/core/palette-sets.js +1058 -0
  85. package/dist/src/core/palette.d.ts +871 -0
  86. package/dist/src/core/palette.js +511 -0
  87. package/dist/src/core/plot-data.d.ts +71 -0
  88. package/dist/src/core/plot-data.js +82 -0
  89. package/dist/src/core/predicate.d.ts +50 -0
  90. package/dist/src/core/predicate.js +20 -0
  91. package/dist/src/core/profile.d.ts +111 -0
  92. package/dist/src/core/profile.js +221 -0
  93. package/dist/src/core/readout.d.ts +108 -0
  94. package/dist/src/core/readout.js +215 -0
  95. package/dist/src/core/region.d.ts +56 -0
  96. package/dist/src/core/region.js +101 -0
  97. package/dist/src/core/rings.d.ts +96 -0
  98. package/dist/src/core/rings.js +171 -0
  99. package/dist/src/core/rules.d.ts +45 -0
  100. package/dist/src/core/rules.js +69 -0
  101. package/dist/src/core/sankey.d.ts +49 -0
  102. package/dist/src/core/sankey.js +96 -0
  103. package/dist/src/core/select.d.ts +52 -0
  104. package/dist/src/core/select.js +216 -0
  105. package/dist/src/core/side-track.d.ts +98 -0
  106. package/dist/src/core/side-track.js +197 -0
  107. package/dist/src/core/sizing.d.ts +54 -0
  108. package/dist/src/core/sizing.js +37 -0
  109. package/dist/src/core/spec-edit.d.ts +68 -0
  110. package/dist/src/core/spec-edit.js +105 -0
  111. package/dist/src/core/spec.d.ts +1111 -0
  112. package/dist/src/core/spec.js +39 -0
  113. package/dist/src/core/stats.d.ts +161 -0
  114. package/dist/src/core/stats.js +318 -0
  115. package/dist/src/core/tick-format.d.ts +21 -0
  116. package/dist/src/core/tick-format.js +87 -0
  117. package/dist/src/core/tokens.d.ts +47 -0
  118. package/dist/src/core/tokens.js +138 -0
  119. package/dist/src/core/transform.d.ts +21 -0
  120. package/dist/src/core/transform.js +19 -0
  121. package/dist/src/core/voxels.d.ts +53 -0
  122. package/dist/src/core/voxels.js +129 -0
  123. package/dist/src/core/zoom.d.ts +76 -0
  124. package/dist/src/core/zoom.js +103 -0
  125. package/dist/src/graph/GraphSurface.d.ts +127 -0
  126. package/dist/src/graph/GraphSurface.js +423 -0
  127. package/dist/src/graph/data.d.ts +103 -0
  128. package/dist/src/graph/data.js +140 -0
  129. package/dist/src/graph/index.d.ts +7 -0
  130. package/dist/src/graph/index.js +7 -0
  131. package/dist/src/mcp/data.d.ts +28 -0
  132. package/dist/src/mcp/data.js +131 -0
  133. package/dist/src/mcp/index.d.ts +7 -0
  134. package/dist/src/mcp/index.js +7 -0
  135. package/dist/src/mcp/paths.d.ts +12 -0
  136. package/dist/src/mcp/paths.js +30 -0
  137. package/dist/src/mcp/render.d.ts +67 -0
  138. package/dist/src/mcp/render.js +189 -0
  139. package/dist/src/mcp/server.d.ts +7 -0
  140. package/dist/src/mcp/server.js +25 -0
  141. package/dist/src/mcp/tools.d.ts +82 -0
  142. package/dist/src/mcp/tools.js +412 -0
  143. package/dist/src/react/BrushLayer.d.ts +20 -0
  144. package/dist/src/react/BrushLayer.js +98 -0
  145. package/dist/src/react/ColorLegend.d.ts +45 -0
  146. package/dist/src/react/ColorLegend.js +64 -0
  147. package/dist/src/react/Figure.d.ts +19 -0
  148. package/dist/src/react/Figure.js +6 -0
  149. package/dist/src/react/Frame.d.ts +87 -0
  150. package/dist/src/react/Frame.js +192 -0
  151. package/dist/src/react/MarkLegend.d.ts +32 -0
  152. package/dist/src/react/MarkLegend.js +24 -0
  153. package/dist/src/react/SeriesLegend.d.ts +38 -0
  154. package/dist/src/react/SeriesLegend.js +27 -0
  155. package/dist/src/react/SizeLegend.d.ts +24 -0
  156. package/dist/src/react/SizeLegend.js +25 -0
  157. package/dist/src/react/Toolbar.d.ts +109 -0
  158. package/dist/src/react/Toolbar.js +483 -0
  159. package/dist/src/react/Tooltip.d.ts +37 -0
  160. package/dist/src/react/Tooltip.js +59 -0
  161. package/dist/src/react/Viz.d.ts +112 -0
  162. package/dist/src/react/Viz.js +1311 -0
  163. package/dist/src/react/export.d.ts +32 -0
  164. package/dist/src/react/export.js +181 -0
  165. package/dist/src/react/geoms/Area.d.ts +38 -0
  166. package/dist/src/react/geoms/Area.js +48 -0
  167. package/dist/src/react/geoms/Bars.d.ts +130 -0
  168. package/dist/src/react/geoms/Bars.js +164 -0
  169. package/dist/src/react/geoms/Box.d.ts +50 -0
  170. package/dist/src/react/geoms/Box.js +32 -0
  171. package/dist/src/react/geoms/Chord.d.ts +60 -0
  172. package/dist/src/react/geoms/Chord.js +78 -0
  173. package/dist/src/react/geoms/Contour.d.ts +44 -0
  174. package/dist/src/react/geoms/Contour.js +78 -0
  175. package/dist/src/react/geoms/DensityCurve.d.ts +30 -0
  176. package/dist/src/react/geoms/DensityCurve.js +38 -0
  177. package/dist/src/react/geoms/FitCurve.d.ts +26 -0
  178. package/dist/src/react/geoms/FitCurve.js +52 -0
  179. package/dist/src/react/geoms/Freqpoly.d.ts +30 -0
  180. package/dist/src/react/geoms/Freqpoly.js +45 -0
  181. package/dist/src/react/geoms/Gauge.d.ts +42 -0
  182. package/dist/src/react/geoms/Gauge.js +90 -0
  183. package/dist/src/react/geoms/Heatmap.d.ts +79 -0
  184. package/dist/src/react/geoms/Heatmap.js +51 -0
  185. package/dist/src/react/geoms/Hexbin.d.ts +74 -0
  186. package/dist/src/react/geoms/Hexbin.js +89 -0
  187. package/dist/src/react/geoms/Icicle.d.ts +38 -0
  188. package/dist/src/react/geoms/Icicle.js +9 -0
  189. package/dist/src/react/geoms/Ideogram.d.ts +58 -0
  190. package/dist/src/react/geoms/Ideogram.js +77 -0
  191. package/dist/src/react/geoms/Interval.d.ts +28 -0
  192. package/dist/src/react/geoms/Interval.js +39 -0
  193. package/dist/src/react/geoms/Line.d.ts +39 -0
  194. package/dist/src/react/geoms/Line.js +52 -0
  195. package/dist/src/react/geoms/Parallel.d.ts +38 -0
  196. package/dist/src/react/geoms/Parallel.js +131 -0
  197. package/dist/src/react/geoms/Pie.d.ts +62 -0
  198. package/dist/src/react/geoms/Pie.js +59 -0
  199. package/dist/src/react/geoms/Points.d.ts +84 -0
  200. package/dist/src/react/geoms/Points.js +207 -0
  201. package/dist/src/react/geoms/Points3d.d.ts +49 -0
  202. package/dist/src/react/geoms/Points3d.js +58 -0
  203. package/dist/src/react/geoms/Radar.d.ts +39 -0
  204. package/dist/src/react/geoms/Radar.js +59 -0
  205. package/dist/src/react/geoms/Range.d.ts +31 -0
  206. package/dist/src/react/geoms/Range.js +20 -0
  207. package/dist/src/react/geoms/RingStack.d.ts +39 -0
  208. package/dist/src/react/geoms/RingStack.js +65 -0
  209. package/dist/src/react/geoms/Rule.d.ts +29 -0
  210. package/dist/src/react/geoms/Rule.js +51 -0
  211. package/dist/src/react/geoms/Sankey.d.ts +24 -0
  212. package/dist/src/react/geoms/Sankey.js +51 -0
  213. package/dist/src/react/geoms/Segment.d.ts +36 -0
  214. package/dist/src/react/geoms/Segment.js +39 -0
  215. package/dist/src/react/geoms/Sunburst.d.ts +46 -0
  216. package/dist/src/react/geoms/Sunburst.js +64 -0
  217. package/dist/src/react/geoms/Surface.d.ts +32 -0
  218. package/dist/src/react/geoms/Surface.js +49 -0
  219. package/dist/src/react/geoms/Text.d.ts +35 -0
  220. package/dist/src/react/geoms/Text.js +40 -0
  221. package/dist/src/react/geoms/Treemap.d.ts +39 -0
  222. package/dist/src/react/geoms/Treemap.js +16 -0
  223. package/dist/src/react/geoms/Violin.d.ts +56 -0
  224. package/dist/src/react/geoms/Violin.js +60 -0
  225. package/dist/src/react/geoms/Volume.d.ts +37 -0
  226. package/dist/src/react/geoms/Volume.js +40 -0
  227. package/dist/src/react/geoms/Waterfall.d.ts +43 -0
  228. package/dist/src/react/geoms/Waterfall.js +18 -0
  229. package/dist/src/react/geoms/cube-stage.d.ts +39 -0
  230. package/dist/src/react/geoms/cube-stage.js +85 -0
  231. package/dist/src/react/geoms/hierarchy-cells.d.ts +42 -0
  232. package/dist/src/react/geoms/hierarchy-cells.js +59 -0
  233. package/dist/src/react/geoms/sector-axis.d.ts +66 -0
  234. package/dist/src/react/geoms/sector-axis.js +99 -0
  235. package/dist/src/react/gl/GlMesh.d.ts +22 -0
  236. package/dist/src/react/gl/GlMesh.js +78 -0
  237. package/dist/src/react/gl/GlPoints.d.ts +45 -0
  238. package/dist/src/react/gl/GlPoints.js +117 -0
  239. package/dist/src/react/gl/GlVolume.d.ts +28 -0
  240. package/dist/src/react/gl/GlVolume.js +112 -0
  241. package/dist/src/react/gl/GlWalls.d.ts +24 -0
  242. package/dist/src/react/gl/GlWalls.js +55 -0
  243. package/dist/src/react/gl/context.d.ts +71 -0
  244. package/dist/src/react/gl/context.js +98 -0
  245. package/dist/src/react/gl/encode.d.ts +120 -0
  246. package/dist/src/react/gl/encode.js +215 -0
  247. package/dist/src/react/gl/index.d.ts +10 -0
  248. package/dist/src/react/gl/index.js +8 -0
  249. package/dist/src/react/gl/refresh.d.ts +7 -0
  250. package/dist/src/react/gl/refresh.js +19 -0
  251. package/dist/src/react/gl/renderer.d.ts +377 -0
  252. package/dist/src/react/gl/renderer.js +1081 -0
  253. package/dist/src/react/gl/shaders.d.ts +92 -0
  254. package/dist/src/react/gl/shaders.js +405 -0
  255. package/dist/src/react/gl/surface.d.ts +31 -0
  256. package/dist/src/react/gl/surface.js +73 -0
  257. package/dist/src/react/index.d.ts +12 -0
  258. package/dist/src/react/index.js +11 -0
  259. package/dist/src/react/orbit.d.ts +38 -0
  260. package/dist/src/react/orbit.js +81 -0
  261. package/dist/src/react/sides/DendrogramPanel.d.ts +32 -0
  262. package/dist/src/react/sides/DendrogramPanel.js +39 -0
  263. package/dist/src/react/sides/DensityPanel.d.ts +31 -0
  264. package/dist/src/react/sides/DensityPanel.js +37 -0
  265. package/dist/src/react/sides/HistogramPanel.d.ts +30 -0
  266. package/dist/src/react/sides/HistogramPanel.js +18 -0
  267. package/dist/src/react/sides/RugPanel.d.ts +28 -0
  268. package/dist/src/react/sides/RugPanel.js +21 -0
  269. package/dist/src/react/sides/TrackPanel.d.ts +37 -0
  270. package/dist/src/react/sides/TrackPanel.js +27 -0
  271. package/dist/src/react/theme.d.ts +48 -0
  272. package/dist/src/react/theme.js +148 -0
  273. package/dist/src/react/useFits.d.ts +26 -0
  274. package/dist/src/react/useFits.js +62 -0
  275. package/dist/src/react/useZoom.d.ts +50 -0
  276. package/dist/src/react/useZoom.js +141 -0
  277. package/package.json +164 -5
  278. package/theme/default.css +62 -0
@@ -0,0 +1,1081 @@
1
+ /**
2
+ * One WebGL2 context for the page, drawing every chart that asked for the GPU.
3
+ *
4
+ * A browser allows something between eight and sixteen contexts and drops the oldest past that, so
5
+ * a dashboard of thirty charts cannot have one each: plotly's own documentation puts its ceiling at
6
+ * four to eight GL figures a page for this reason. One context draws them all, each into its own
7
+ * scissored slice of a canvas that covers the viewport.
8
+ *
9
+ * The loop is the renderer's, outside React. A layer's buffers are uploaded when its data changes
10
+ * and nothing else, so a zoom moves two uniforms and a hover reads one pixel. React mounts the
11
+ * canvas once and stays out of the frame path.
12
+ */
13
+ import { cameraFor, colorToId, packIds, scissorFor, viewportFor, } from "./encode.js";
14
+ import { AMBIENT, cubeMatrix, cubeModel, eyeOf, CUBE_LIGHT, normalMatrix, restingDepth, } from "../../core/camera.js";
15
+ import { POINT_OUTLINE } from "../../core/geom-types.js";
16
+ import { CUBE_VERTEX, LINE_FRAGMENT, LINE_VERTEX, MESH_FRAGMENT, MESH_VERTEX, POINT_FRAGMENT, POINT_VERTEX, SHAPE_CODE, VOLUME_FRAGMENT, VOLUME_VERTEX, } from "./shaders.js";
17
+ /** Draw times kept per renderer, over a window long enough to hold a p95. */
18
+ const WINDOW = 240;
19
+ const PROGRAM_FAILED = "ts-lib-viz: the GL program failed to build";
20
+ /**
21
+ * One turn of the task queue.
22
+ *
23
+ * A timer is the obvious way to wait and it is the wrong one. A page the browser calls hidden
24
+ * clamps `setTimeout` to about a second, so a drain asking for a millisecond between reads spent
25
+ * its whole timeout inside the first wait and a run's last frames stayed out of the numbers. That
26
+ * is the same instrument fault as a throttled frame clock, one layer down. A message channel is not
27
+ * throttled. The timer stays as the fallback for a runtime without one.
28
+ */
29
+ const taskTurn = () => typeof MessageChannel === "function"
30
+ ? new Promise((resolve) => {
31
+ const channel = new MessageChannel();
32
+ channel.port1.onmessage = () => resolve();
33
+ channel.port2.postMessage(0);
34
+ })
35
+ : new Promise((resolve) => setTimeout(resolve, 1));
36
+ export class SharedRenderer {
37
+ host;
38
+ options;
39
+ gl = null;
40
+ program = null;
41
+ uniforms = {};
42
+ /** The cube's program, built beside the flat one and used by the layers that carry a camera. */
43
+ cubeProgram = null;
44
+ cubeUniforms = {};
45
+ /** The surface's program, which is the cube's with a light and triangles in place of sprites. */
46
+ meshProgram = null;
47
+ meshUniforms = {};
48
+ /** The raymarching program, which reads a field through the box instead of drawing its surface. */
49
+ volumeProgram = null;
50
+ volumeUniforms = {};
51
+ /** The line program, for rules drawn under the cube's camera. */
52
+ lineProgram = null;
53
+ lineUniforms = {};
54
+ /** Vertex attribute slots the context has, read once and used to clear the ones a layer skips. */
55
+ attribCount = 0;
56
+ layers = new Map();
57
+ nextId = 1;
58
+ frame = null;
59
+ lost = false;
60
+ /** Set once the owner disposed the renderer or the driver refused a program. Nothing is acquired after. */
61
+ retired = false;
62
+ /** The one-pixel framebuffer a picking pass draws into. Built on the first pick. */
63
+ picking = null;
64
+ times = [];
65
+ gpuTimes = [];
66
+ timer;
67
+ inFlight = [];
68
+ gpuProblem = null;
69
+ /** Borrowers holding the frame clock. */
70
+ clockLent = 0;
71
+ /**
72
+ * The boxes the last frame painted, so this one can clear what it is no longer drawing.
73
+ *
74
+ * A frame clears the rectangles its layers own and nothing else, which is what lets a borrower
75
+ * keep the rest of the canvas. The cost is that a released layer leaves its pixels behind: the
76
+ * canvas is fixed to the viewport and outlives any chart on it, so a page that swapped one figure
77
+ * for another would show the first one's geoms under the second's.
78
+ */
79
+ painted = [];
80
+ /** Whether the host drove the clock before any of them asked for it. */
81
+ ownClock;
82
+ constructor(host, options = {}) {
83
+ this.host = host;
84
+ this.options = options;
85
+ this.ownClock = options.driven === true;
86
+ this.host.canvas.addEventListener("webglcontextlost", this.onLost);
87
+ this.host.canvas.addEventListener("webglcontextrestored", this.onRestored);
88
+ }
89
+ /**
90
+ * Whether the GPU path is available at all.
91
+ *
92
+ * A caller that gets false draws its SVG treatment instead. A page with no WebGL2 is a real
93
+ * state, and a chart that answers with an empty canvas reads as a broken chart.
94
+ */
95
+ get available() {
96
+ return this.acquire() != null;
97
+ }
98
+ /** Layers this renderer is holding, so a borrower can see whether the canvas is already in use. */
99
+ layerCount() {
100
+ return this.layers.size;
101
+ }
102
+ /**
103
+ * Hands the frame clock to whoever borrowed the context, and takes it back on release.
104
+ *
105
+ * Two engines on one canvas need one clock or the frame is a race. cosmos clears the whole canvas
106
+ * every frame it draws, and this renderer clears the rectangles it owns and draws into them, so
107
+ * the charts survive only where they are drawn after the clear that would have taken them. On its
108
+ * own clock this renderer draws when something changes, which on a page with an animating graph
109
+ * means a chart is drawn once and cleared sixteen milliseconds later.
110
+ *
111
+ * So the borrower drives: it calls `drawNow` from its own frame callback, and the charts land in
112
+ * the same frame, after it. Released when the borrower stops drawing, since a clock nobody drives
113
+ * is a chart that never updates. Counted, so two borrowers cannot hand it back twice.
114
+ *
115
+ * See the ADR "The graph surface takes cosmos on the package's own context".
116
+ */
117
+ lendClock() {
118
+ this.clockLent += 1;
119
+ this.options = { ...this.options, driven: true };
120
+ let given = true;
121
+ return () => {
122
+ if (!given)
123
+ return;
124
+ given = false;
125
+ this.clockLent -= 1;
126
+ if (this.clockLent > 0)
127
+ return;
128
+ this.options = { ...this.options, driven: this.ownClock };
129
+ this.schedule();
130
+ };
131
+ }
132
+ /**
133
+ * The context this renderer owns, for a second engine to draw into.
134
+ *
135
+ * One shared WebGL2 context is the package's structural advantage, and a page holding charts and
136
+ * a physics graph would spend two of the eight to sixteen a browser allows if the graph made its
137
+ * own. Lending is the answer: the borrower attaches to this and does not destroy it, which is the
138
+ * path both luma and cosmos already support.
139
+ *
140
+ * Raw and not wrapped, so nothing in `/react` imports a second GL library. Whoever borrows it
141
+ * brings its own adapter. See the ADR "The graph surface takes cosmos on the package's own
142
+ * context".
143
+ */
144
+ context() {
145
+ const gl = this.acquire();
146
+ /* Sized before it is handed over. The canvas is sized inside this renderer's own frame, and a
147
+ page whose only GL client is the borrower would otherwise lend a canvas at its default 300
148
+ by 150 stretched over the viewport. */
149
+ if (gl)
150
+ this.sizeCanvas(gl);
151
+ return gl;
152
+ }
153
+ add(input) {
154
+ const id = this.nextId++;
155
+ const layer = { ...input, id, buffers: null, dirty: true };
156
+ this.layers.set(id, layer);
157
+ this.schedule();
158
+ return {
159
+ update: (next) => {
160
+ const held = this.layers.get(id);
161
+ if (!held)
162
+ return;
163
+ /*
164
+ A buffer is rebuilt where the array behind it is a different object, and left alone
165
+ where a caller handed back the one already held.
166
+
167
+ Presence was the test before this, and presence is what a geom component always
168
+ supplies: it passes its whole input on any change, so rewriting a domain marked the
169
+ layer dirty and `upload` then freed and rebuilt each buffer with `packIds` re-derived
170
+ on top of them. At ten million geoms that is the whole allocation paid at each frame
171
+ of a zoom, which is the cost one shared context and one upload exist to avoid.
172
+
173
+ The arrays and not their wrappers, since `depth`, `mesh` and `volume` each carry
174
+ camera or transfer settings beside the data: an orbit, a level, a step count. Those
175
+ reach the GPU as uniforms read fresh each frame, so a rotation or a level dragged
176
+ across a field re-reads them and uploads nothing. Compared ahead of the assign, which
177
+ is what would otherwise hide the difference.
178
+ */
179
+ const differs = (key) => key in next && next[key] !== held[key];
180
+ const rebuilt = differs("positions") ||
181
+ differs("colors") ||
182
+ differs("sizes") ||
183
+ differs("pickable") ||
184
+ ("depth" in next && next.depth?.offsets !== held.depth?.offsets) ||
185
+ ("mesh" in next &&
186
+ (next.mesh?.normals !== held.mesh?.normals || next.mesh?.indices !== held.mesh?.indices)) ||
187
+ ("volume" in next &&
188
+ (next.volume?.field !== held.volume?.field || next.volume?.ramp !== held.volume?.ramp)) ||
189
+ ("lines" in next && (next.lines?.other !== held.lines?.other || next.lines?.corners !== held.lines?.corners));
190
+ Object.assign(held, next);
191
+ if (rebuilt)
192
+ held.dirty = true;
193
+ this.schedule();
194
+ },
195
+ pick: (clientX, clientY) => this.pick(id, clientX, clientY),
196
+ release: () => {
197
+ const held = this.layers.get(id);
198
+ if (held?.buffers)
199
+ this.free(held.buffers);
200
+ this.layers.delete(id);
201
+ this.schedule();
202
+ },
203
+ };
204
+ }
205
+ /** Draws on the next frame. Repeated calls in one frame collapse into one draw. */
206
+ schedule() {
207
+ if (this.frame != null || this.lost || this.retired || this.options.driven)
208
+ return;
209
+ const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : null;
210
+ if (!raf) {
211
+ // A headless run or a hidden page has no frame clock, so draw straight away.
212
+ this.draw();
213
+ return;
214
+ }
215
+ this.frame = raf(() => {
216
+ this.frame = null;
217
+ this.draw();
218
+ });
219
+ }
220
+ /**
221
+ * Reads one pixel back, which waits for the GPU to have finished.
222
+ *
223
+ * A hard barrier for a harness timing a run of frames. `finish` is documented as waiting for
224
+ * completion and returns early on the Metal backend, while a read of the framebuffer cannot
225
+ * answer until the work that fills it has run.
226
+ */
227
+ readOnePixel() {
228
+ const gl = this.acquire();
229
+ if (!gl)
230
+ return;
231
+ const pixel = new Uint8Array(4);
232
+ gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
233
+ }
234
+ /**
235
+ * Draws a frame and reports whether anything landed on the canvas.
236
+ *
237
+ * A benchmark over a canvas that drew nothing reads as the fastest renderer ever written, and
238
+ * that is the shape of a real failure: a hidden page reporting a viewport of nought, a layer
239
+ * whose rectangle scissored away, a context that never came back after a loss. Sampling the
240
+ * canvas answers it.
241
+ *
242
+ * The draw happens here because the context holds no drawing buffer between tasks: reading a
243
+ * frame drawn earlier answers empty whether or not that frame worked. `readPixels` stalls the
244
+ * pipeline, so this is for a harness and not for a frame loop.
245
+ */
246
+ drewPixels(samples = 64) {
247
+ const gl = this.acquire();
248
+ if (!gl)
249
+ return false;
250
+ this.drawNow();
251
+ const width = gl.drawingBufferWidth;
252
+ const height = gl.drawingBufferHeight;
253
+ if (width === 0 || height === 0)
254
+ return false;
255
+ const pixel = new Uint8Array(4);
256
+ const step = Math.max(1, Math.floor(Math.min(width, height) / Math.sqrt(samples)));
257
+ for (let x = 0; x < width; x += step) {
258
+ for (let y = 0; y < height; y += step) {
259
+ gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
260
+ if (pixel[3] !== 0)
261
+ return true;
262
+ }
263
+ }
264
+ return false;
265
+ }
266
+ /**
267
+ * Draws now, on the caller's stack.
268
+ *
269
+ * `schedule` waits for a frame, and a page the browser calls hidden gets no frames at all, so a
270
+ * benchmark or an export asking for a frame there would wait forever. This is also what a caller
271
+ * wants before reading pixels back: the draw has happened by the time it returns.
272
+ */
273
+ drawNow() {
274
+ if (this.frame != null && typeof cancelAnimationFrame === "function") {
275
+ cancelAnimationFrame(this.frame);
276
+ }
277
+ this.frame = null;
278
+ this.draw();
279
+ }
280
+ dispose() {
281
+ this.host.canvas.removeEventListener("webglcontextlost", this.onLost);
282
+ this.host.canvas.removeEventListener("webglcontextrestored", this.onRestored);
283
+ if (this.frame != null && typeof cancelAnimationFrame === "function") {
284
+ cancelAnimationFrame(this.frame);
285
+ }
286
+ for (const layer of this.layers.values()) {
287
+ if (layer.buffers)
288
+ this.free(layer.buffers);
289
+ }
290
+ for (const query of this.inFlight)
291
+ this.gl?.deleteQuery(query);
292
+ this.inFlight = [];
293
+ this.layers.clear();
294
+ if (this.gl)
295
+ this.dropPrograms(this.gl);
296
+ if (this.gl && this.picking) {
297
+ this.gl.deleteFramebuffer(this.picking.framebuffer);
298
+ this.gl.deleteRenderbuffer(this.picking.color);
299
+ this.gl.deleteRenderbuffer(this.picking.depth);
300
+ }
301
+ this.picking = null;
302
+ this.gl = null;
303
+ this.timer = undefined;
304
+ this.retired = true;
305
+ }
306
+ /** Deletes the five programs and forgets them. */
307
+ dropPrograms(gl) {
308
+ for (const program of [this.program, this.cubeProgram, this.meshProgram, this.volumeProgram, this.lineProgram]) {
309
+ if (program)
310
+ gl.deleteProgram(program);
311
+ }
312
+ this.program = null;
313
+ this.cubeProgram = null;
314
+ this.meshProgram = null;
315
+ this.volumeProgram = null;
316
+ this.lineProgram = null;
317
+ }
318
+ onLost = (event) => {
319
+ // Preventing the default is what allows a restore to fire at all.
320
+ event.preventDefault();
321
+ this.lost = true;
322
+ this.gl = null;
323
+ this.program = null;
324
+ this.cubeProgram = null;
325
+ this.meshProgram = null;
326
+ this.volumeProgram = null;
327
+ this.lineProgram = null;
328
+ /* The lost context's objects go with it. A restored context builds its own. */
329
+ this.inFlight = [];
330
+ this.timer = undefined;
331
+ this.picking = null;
332
+ for (const layer of this.layers.values()) {
333
+ layer.buffers = null;
334
+ layer.dirty = true;
335
+ }
336
+ };
337
+ onRestored = () => {
338
+ this.lost = false;
339
+ this.schedule();
340
+ };
341
+ acquire() {
342
+ if (this.gl || this.lost || this.retired)
343
+ return this.gl;
344
+ const gl = this.host.canvas.getContext("webgl2", {
345
+ antialias: true,
346
+ /* Each layer's blend writes premultiplied color. A straight-alpha canvas composites it at alpha squared. */
347
+ premultipliedAlpha: true,
348
+ preserveDrawingBuffer: false,
349
+ // A cube resolves overlap by depth, and a context with no depth buffer has nothing to test.
350
+ depth: true,
351
+ });
352
+ if (!gl)
353
+ return null;
354
+ try {
355
+ this.build(gl);
356
+ }
357
+ catch {
358
+ /* A driver that rejects a program leaves the GPU path unavailable. The charts draw their fallback. */
359
+ this.dropPrograms(gl);
360
+ this.retired = true;
361
+ return null;
362
+ }
363
+ this.gl = gl;
364
+ return gl;
365
+ }
366
+ build(gl) {
367
+ this.attribCount = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
368
+ const program = compile(gl, POINT_VERTEX, POINT_FRAGMENT);
369
+ this.program = program;
370
+ this.uniforms = {
371
+ scale: gl.getUniformLocation(program, "u_scale"),
372
+ translate: gl.getUniformLocation(program, "u_translate"),
373
+ viewport: gl.getUniformLocation(program, "u_viewport"),
374
+ dpr: gl.getUniformLocation(program, "u_dpr"),
375
+ shape: gl.getUniformLocation(program, "u_shape"),
376
+ hollow: gl.getUniformLocation(program, "u_hollow"),
377
+ outline: gl.getUniformLocation(program, "u_outline"),
378
+ flat: gl.getUniformLocation(program, "u_flat"),
379
+ flatColor: gl.getUniformLocation(program, "u_flatColor"),
380
+ picking: gl.getUniformLocation(program, "u_picking"),
381
+ size: gl.getUniformLocation(program, "u_size"),
382
+ flatSize: gl.getUniformLocation(program, "u_flatSize"),
383
+ };
384
+ const cube = compile(gl, CUBE_VERTEX, POINT_FRAGMENT);
385
+ this.cubeProgram = cube;
386
+ this.cubeUniforms = {
387
+ mvp: gl.getUniformLocation(cube, "u_mvp"),
388
+ dpr: gl.getUniformLocation(cube, "u_dpr"),
389
+ depthRef: gl.getUniformLocation(cube, "u_depthRef"),
390
+ shape: gl.getUniformLocation(cube, "u_shape"),
391
+ hollow: gl.getUniformLocation(cube, "u_hollow"),
392
+ outline: gl.getUniformLocation(cube, "u_outline"),
393
+ flat: gl.getUniformLocation(cube, "u_flat"),
394
+ flatColor: gl.getUniformLocation(cube, "u_flatColor"),
395
+ picking: gl.getUniformLocation(cube, "u_picking"),
396
+ size: gl.getUniformLocation(cube, "u_size"),
397
+ flatSize: gl.getUniformLocation(cube, "u_flatSize"),
398
+ };
399
+ const mesh = compile(gl, MESH_VERTEX, MESH_FRAGMENT);
400
+ this.meshProgram = mesh;
401
+ this.meshUniforms = {
402
+ mvp: gl.getUniformLocation(mesh, "u_mvp"),
403
+ normalMatrix: gl.getUniformLocation(mesh, "u_normalMatrix"),
404
+ light: gl.getUniformLocation(mesh, "u_light"),
405
+ ambient: gl.getUniformLocation(mesh, "u_ambient"),
406
+ };
407
+ const volume = compile(gl, VOLUME_VERTEX, VOLUME_FRAGMENT);
408
+ this.volumeProgram = volume;
409
+ this.volumeUniforms = {
410
+ mvp: gl.getUniformLocation(volume, "u_mvp"),
411
+ model: gl.getUniformLocation(volume, "u_model"),
412
+ field: gl.getUniformLocation(volume, "u_field"),
413
+ ramp: gl.getUniformLocation(volume, "u_ramp"),
414
+ eye: gl.getUniformLocation(volume, "u_eye"),
415
+ steps: gl.getUniformLocation(volume, "u_steps"),
416
+ iso: gl.getUniformLocation(volume, "u_iso"),
417
+ level: gl.getUniformLocation(volume, "u_level"),
418
+ density: gl.getUniformLocation(volume, "u_density"),
419
+ light: gl.getUniformLocation(volume, "u_light"),
420
+ ambient: gl.getUniformLocation(volume, "u_ambient"),
421
+ };
422
+ const line = compile(gl, LINE_VERTEX, LINE_FRAGMENT);
423
+ this.lineProgram = line;
424
+ this.lineUniforms = {
425
+ mvp: gl.getUniformLocation(line, "u_mvp"),
426
+ viewport: gl.getUniformLocation(line, "u_viewport"),
427
+ width: gl.getUniformLocation(line, "u_width"),
428
+ color: gl.getUniformLocation(line, "u_color"),
429
+ };
430
+ }
431
+ free(buffers) {
432
+ const gl = this.gl;
433
+ if (!gl)
434
+ return;
435
+ gl.deleteBuffer(buffers.offsets);
436
+ gl.deleteBuffer(buffers.colors);
437
+ if (buffers.sizes)
438
+ gl.deleteBuffer(buffers.sizes);
439
+ if (buffers.depth)
440
+ gl.deleteBuffer(buffers.depth);
441
+ if (buffers.normals)
442
+ gl.deleteBuffer(buffers.normals);
443
+ if (buffers.faces)
444
+ gl.deleteBuffer(buffers.faces);
445
+ if (buffers.other)
446
+ gl.deleteBuffer(buffers.other);
447
+ if (buffers.corners)
448
+ gl.deleteBuffer(buffers.corners);
449
+ if (buffers.field)
450
+ gl.deleteTexture(buffers.field);
451
+ if (buffers.ramp)
452
+ gl.deleteTexture(buffers.ramp);
453
+ if (buffers.picks)
454
+ gl.deleteBuffer(buffers.picks);
455
+ }
456
+ upload(gl, layer) {
457
+ if (layer.buffers && !layer.dirty)
458
+ return layer.buffers;
459
+ if (layer.buffers)
460
+ this.free(layer.buffers);
461
+ const offsets = gl.createBuffer();
462
+ const colors = gl.createBuffer();
463
+ if (!offsets || !colors)
464
+ return null;
465
+ gl.bindBuffer(gl.ARRAY_BUFFER, offsets);
466
+ gl.bufferData(gl.ARRAY_BUFFER, layer.positions.offsets, gl.STATIC_DRAW);
467
+ if (layer.colors) {
468
+ gl.bindBuffer(gl.ARRAY_BUFFER, colors);
469
+ gl.bufferData(gl.ARRAY_BUFFER, layer.colors, gl.STATIC_DRAW);
470
+ }
471
+ let sizes = null;
472
+ if (layer.sizes) {
473
+ sizes = gl.createBuffer();
474
+ if (!sizes)
475
+ return null;
476
+ gl.bindBuffer(gl.ARRAY_BUFFER, sizes);
477
+ gl.bufferData(gl.ARRAY_BUFFER, layer.sizes, gl.STATIC_DRAW);
478
+ }
479
+ let depth = null;
480
+ if (layer.depth) {
481
+ depth = gl.createBuffer();
482
+ if (!depth)
483
+ return null;
484
+ gl.bindBuffer(gl.ARRAY_BUFFER, depth);
485
+ gl.bufferData(gl.ARRAY_BUFFER, layer.depth.offsets, gl.STATIC_DRAW);
486
+ }
487
+ let normals = null;
488
+ let faces = null;
489
+ if (layer.mesh) {
490
+ normals = gl.createBuffer();
491
+ faces = gl.createBuffer();
492
+ if (!normals || !faces)
493
+ return null;
494
+ gl.bindBuffer(gl.ARRAY_BUFFER, normals);
495
+ gl.bufferData(gl.ARRAY_BUFFER, layer.mesh.normals, gl.STATIC_DRAW);
496
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, faces);
497
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, layer.mesh.indices, gl.STATIC_DRAW);
498
+ }
499
+ let other = null;
500
+ let corners = null;
501
+ if (layer.lines) {
502
+ other = gl.createBuffer();
503
+ corners = gl.createBuffer();
504
+ if (!other || !corners)
505
+ return null;
506
+ gl.bindBuffer(gl.ARRAY_BUFFER, other);
507
+ gl.bufferData(gl.ARRAY_BUFFER, layer.lines.other, gl.STATIC_DRAW);
508
+ gl.bindBuffer(gl.ARRAY_BUFFER, corners);
509
+ gl.bufferData(gl.ARRAY_BUFFER, layer.lines.corners, gl.STATIC_DRAW);
510
+ }
511
+ let field = null;
512
+ let ramp = null;
513
+ if (layer.volume) {
514
+ field = uploadField(gl, layer.volume);
515
+ ramp = uploadRamp(gl, layer.volume.ramp);
516
+ if (!field || !ramp)
517
+ return null;
518
+ }
519
+ let picks = null;
520
+ if (layer.pickable) {
521
+ picks = gl.createBuffer();
522
+ if (!picks)
523
+ return null;
524
+ gl.bindBuffer(gl.ARRAY_BUFFER, picks);
525
+ gl.bufferData(gl.ARRAY_BUFFER, packIds(layer.positions.count), gl.STATIC_DRAW);
526
+ }
527
+ layer.buffers = {
528
+ offsets,
529
+ colors,
530
+ sizes,
531
+ depth,
532
+ normals,
533
+ faces,
534
+ other,
535
+ corners,
536
+ field,
537
+ ramp,
538
+ picks,
539
+ count: layer.positions.count,
540
+ };
541
+ layer.dirty = false;
542
+ return layer.buffers;
543
+ }
544
+ /**
545
+ * The canvas at the size its host asks for, and the rectangle that size was read from.
546
+ *
547
+ * The size is a shared resource the same way the context is. A borrower that resizes the canvas
548
+ * to suit itself, which is what luma's `autoResize` does, will fight a renderer that resizes it
549
+ * back every frame: the two write different numbers, the borrower recomputes its own screen from
550
+ * the change, and the picture warps once a frame. So while the clock is lent the borrower owns the
551
+ * size and this reads what is there.
552
+ */
553
+ sizeCanvas(gl) {
554
+ const rect = this.host.rect();
555
+ if (this.clockLent === 0) {
556
+ const dpr = this.host.dpr();
557
+ const width = Math.max(1, Math.round(rect.width * dpr));
558
+ const height = Math.max(1, Math.round(rect.height * dpr));
559
+ if (this.host.canvas.width !== width)
560
+ this.host.canvas.width = width;
561
+ if (this.host.canvas.height !== height)
562
+ this.host.canvas.height = height;
563
+ }
564
+ gl.viewport(0, 0, this.host.canvas.width, this.host.canvas.height);
565
+ return rect;
566
+ }
567
+ /**
568
+ * Device pixels a CSS pixel, as the drawing buffer actually stands.
569
+ *
570
+ * The host states one, and while the canvas belongs to a borrower the buffer may be another size
571
+ * entirely. Every scissor and viewport is computed against the buffer, so it is read off the
572
+ * buffer.
573
+ */
574
+ dprNow() {
575
+ if (this.clockLent === 0)
576
+ return this.host.dpr();
577
+ const width = this.host.rect().width;
578
+ return width > 0 ? this.host.canvas.width / width : this.host.dpr();
579
+ }
580
+ /**
581
+ * How long the recent frames took.
582
+ *
583
+ * Null before anything has been drawn. The budget in the design doc is 60fps at ten million
584
+ * client-resident geoms, which is 16.7ms a frame, and this is the number that answers it.
585
+ */
586
+ stats() {
587
+ if (this.times.length === 0)
588
+ return null;
589
+ const submission = distribution(this.times);
590
+ return {
591
+ ...submission,
592
+ gpu: distribution(this.gpuTimes),
593
+ gpuProblem: this.gpuTimes.length === 0 ? (this.gpuProblem ?? "no GPU reading arrived") : null,
594
+ };
595
+ }
596
+ resetStats() {
597
+ this.times = [];
598
+ this.gpuTimes = [];
599
+ this.gpuProblem = null;
600
+ /* Queries still in flight belong to frames before the reset. Left alone they answer later and
601
+ land in the next run's numbers, which is how a twenty-frame run reported twenty-eight. */
602
+ for (const query of this.inFlight)
603
+ this.gl?.deleteQuery(query);
604
+ this.inFlight = [];
605
+ }
606
+ /**
607
+ * Turns the per-frame finish on or off.
608
+ *
609
+ * A benchmark story wants it on for as long as it is reading; a chart in front of somebody wants
610
+ * it off, since a finish stalls the pipeline. Settable because the surface is shared: whichever
611
+ * chart mounts first builds the renderer, and a story measuring later cannot re-make it.
612
+ */
613
+ measure(on) {
614
+ this.options = { ...this.options, measure: on };
615
+ if (!on)
616
+ this.resetStats();
617
+ }
618
+ draw() {
619
+ const gl = this.acquire();
620
+ if (!gl || !this.program)
621
+ return;
622
+ if (this.options.measure)
623
+ this.collectGpuTimes(gl);
624
+ const query = this.options.measure ? this.beginGpuTime(gl) : null;
625
+ const started = performance.now();
626
+ const canvasRect = this.sizeCanvas(gl);
627
+ gl.clearColor(0, 0, 0, 0);
628
+ /* A depth buffer holding last frame's cube would hide this frame's geoms, and clearing one no
629
+ layer tests is work the flat path was measured without. */
630
+ const cubed = [...this.layers.values()].some((layer) => layer.depth);
631
+ if (cubed)
632
+ gl.depthMask(true);
633
+ const mask = cubed ? gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT : gl.COLOR_BUFFER_BIT;
634
+ /*
635
+ The rectangles this renderer owns, and nothing else. Clearing the whole canvas is what a
636
+ renderer that owns it does, and this one lends it: a second engine drawing on the same
637
+ context would be erased by a frame that cleared everything. Deduplicated, since a chart with
638
+ several layers has one rectangle and the second clear would wipe the first layer's geoms.
639
+ */
640
+ gl.enable(gl.SCISSOR_TEST);
641
+ const boxes = [];
642
+ const seen = new Set();
643
+ const keyOf = (box) => `${box.x}:${box.y}:${box.width}:${box.height}`;
644
+ for (const layer of this.layers.values()) {
645
+ const chartRect = layer.rect();
646
+ if (!chartRect)
647
+ continue;
648
+ const clip = scissorFor(chartRect, canvasRect, this.dprNow());
649
+ if (clip.width === 0 || clip.height === 0)
650
+ continue;
651
+ if (seen.has(keyOf(clip)))
652
+ continue;
653
+ seen.add(keyOf(clip));
654
+ boxes.push(clip);
655
+ }
656
+ /* Last frame's boxes as well, or a layer that has gone leaves its geoms on the canvas. Cleared
657
+ once and then forgotten, since a box nothing has drawn into since is already empty. */
658
+ const stale = this.painted.filter((box) => !seen.has(keyOf(box)));
659
+ for (const box of [...boxes, ...stale]) {
660
+ gl.scissor(box.x, box.y, box.width, box.height);
661
+ gl.clear(mask);
662
+ }
663
+ this.painted = boxes;
664
+ /* Panes, then rules, then the geoms. A translucent geom drawn last blends over the chrome behind it. */
665
+ const rank = (layer) => (!layer.lines ? 2 : layer.lines.width > 0 ? 1 : 0);
666
+ for (const layer of [...this.layers.values()].sort((one, other) => rank(one) - rank(other))) {
667
+ this.drawLayer(gl, layer, canvasRect, false);
668
+ }
669
+ gl.disable(gl.SCISSOR_TEST);
670
+ if (query)
671
+ this.endGpuTime(gl);
672
+ /* Flushed instead of finished. `finish` is documented as waiting for completion and on the
673
+ Metal backend it returns while the work is still queued, which is what made a frame at a
674
+ million geoms read as a tenth of a millisecond. The GPU clock below is the honest answer. */
675
+ if (this.options.measure)
676
+ gl.flush();
677
+ this.times.push(performance.now() - started);
678
+ if (this.times.length > WINDOW)
679
+ this.times.shift();
680
+ }
681
+ /** The GPU clock, asked for once and remembered as absent where it is. */
682
+ gpuClock(gl) {
683
+ if (this.timer !== undefined)
684
+ return this.timer;
685
+ this.timer = gl.getExtension("EXT_disjoint_timer_query_webgl2");
686
+ if (!this.timer)
687
+ this.gpuProblem = "EXT_disjoint_timer_query_webgl2 is not available here";
688
+ return this.timer;
689
+ }
690
+ beginGpuTime(gl) {
691
+ const ext = this.gpuClock(gl);
692
+ if (!ext)
693
+ return null;
694
+ /* One query at a time. Nesting is an error, and a frame that starts before the last one was
695
+ read is a frame whose reading nobody wanted. */
696
+ if (this.inFlight.length > 8)
697
+ return null;
698
+ const query = gl.createQuery();
699
+ if (!query)
700
+ return null;
701
+ gl.beginQuery(ext.TIME_ELAPSED_EXT, query);
702
+ this.inFlight.push(query);
703
+ return query;
704
+ }
705
+ endGpuTime(gl) {
706
+ const ext = this.gpuClock(gl);
707
+ if (ext)
708
+ gl.endQuery(ext.TIME_ELAPSED_EXT);
709
+ }
710
+ /**
711
+ * Reads whichever queries the GPU has finished with.
712
+ *
713
+ * A query answers a frame or two after the one it timed, so the readings arrive late and the
714
+ * window fills anyway. A disjoint event throws away everything in flight, since the timings
715
+ * either side of it are not comparable.
716
+ */
717
+ collectGpuTimes(gl) {
718
+ const ext = this.gpuClock(gl);
719
+ if (!ext || this.inFlight.length === 0)
720
+ return;
721
+ if (gl.getParameter(ext.GPU_DISJOINT_EXT)) {
722
+ for (const query of this.inFlight)
723
+ gl.deleteQuery(query);
724
+ this.inFlight = [];
725
+ this.gpuProblem = "a disjoint event dropped the queries in flight";
726
+ return;
727
+ }
728
+ const waiting = [];
729
+ for (const query of this.inFlight) {
730
+ if (!gl.getQueryParameter(query, gl.QUERY_RESULT_AVAILABLE)) {
731
+ waiting.push(query);
732
+ continue;
733
+ }
734
+ const nanoseconds = gl.getQueryParameter(query, gl.QUERY_RESULT);
735
+ gl.deleteQuery(query);
736
+ this.gpuTimes.push(nanoseconds / 1e6);
737
+ if (this.gpuTimes.length > WINDOW)
738
+ this.gpuTimes.shift();
739
+ }
740
+ this.inFlight = waiting;
741
+ }
742
+ /** Waits for the queries in flight, so a run's last frames are in the numbers. */
743
+ async drainGpuTimes(timeoutMs = 200) {
744
+ const gl = this.acquire();
745
+ if (!gl)
746
+ return;
747
+ const until = performance.now() + timeoutMs;
748
+ while (this.inFlight.length > 0 && performance.now() < until) {
749
+ this.collectGpuTimes(gl);
750
+ await taskTurn();
751
+ }
752
+ }
753
+ drawLayer(gl, layer, canvasRect, picking, shift = { x: 0, y: 0 }) {
754
+ const cube = layer.depth ?? null;
755
+ /* Neither has geoms to pick: an id buffer addresses vertices and a hover wants a datum. */
756
+ const field = cube && layer.volume && layer.mesh ? layer.volume : null;
757
+ const surface = cube && layer.mesh && !field ? layer.mesh : null;
758
+ const rules = cube && layer.lines ? layer.lines : null;
759
+ if (picking && (surface || field || rules))
760
+ return null;
761
+ const program = rules
762
+ ? this.lineProgram
763
+ : field
764
+ ? this.volumeProgram
765
+ : surface
766
+ ? this.meshProgram
767
+ : cube
768
+ ? this.cubeProgram
769
+ : this.program;
770
+ if (!program)
771
+ return null;
772
+ // A picking pass over a layer that uploaded no ids has nothing to read.
773
+ if (picking && !layer.pickable)
774
+ return null;
775
+ const chartRect = layer.rect();
776
+ if (!chartRect)
777
+ return null;
778
+ const dpr = this.dprNow();
779
+ /* The viewport carries the whole plot area so the projection is right; the scissor clips it. */
780
+ const box = viewportFor(chartRect, canvasRect, dpr);
781
+ const clip = scissorFor(chartRect, canvasRect, dpr);
782
+ if (clip.width === 0 || clip.height === 0)
783
+ return null;
784
+ const buffers = this.upload(gl, layer);
785
+ if (!buffers || buffers.count === 0)
786
+ return box;
787
+ gl.useProgram(program);
788
+ /* A picking pass shifts both by the pointer's pixel, which lands that pixel on the target's origin. */
789
+ gl.viewport(box.x - shift.x, box.y - shift.y, box.width, box.height);
790
+ gl.scissor(clip.x - shift.x, clip.y - shift.y, clip.width, clip.height);
791
+ /* A picking pass writes addresses, and blending two addresses together makes a third one that
792
+ names the wrong geom, so that pass is opaque whatever the layer says. */
793
+ if (picking || layer.opaque)
794
+ gl.disable(gl.BLEND);
795
+ else
796
+ gl.enable(gl.BLEND);
797
+ /* A ray writes premultiplied color and a geom writes straight color. */
798
+ gl.blendFuncSeparate(field ? gl.ONE : gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
799
+ if (!surface && !field && !rules) {
800
+ const flat = layer.color ?? [0.5, 0.5, 0.5, 1];
801
+ const shared = cube ? this.cubeUniforms : this.uniforms;
802
+ gl.uniform1f(shared.dpr, dpr);
803
+ gl.uniform1i(shared.shape, SHAPE_CODE[layer.shape ?? "circle"]);
804
+ gl.uniform1i(shared.hollow, layer.hollow ? 1 : 0);
805
+ gl.uniform1f(shared.outline, POINT_OUTLINE);
806
+ gl.uniform4f(shared.flat, flat[0], flat[1], flat[2], flat[3]);
807
+ gl.uniform1i(shared.flatColor, layer.colors ? 0 : 1);
808
+ gl.uniform1i(shared.picking, picking ? 1 : 0);
809
+ gl.uniform1f(shared.size, layer.size);
810
+ gl.uniform1i(shared.flatSize, buffers.sizes ? 0 : 1);
811
+ }
812
+ if (cube) {
813
+ const domains = { x: layer.xDomain, y: layer.yDomain, z: cube.domain };
814
+ const mvp = cubeMatrix(cube.orbit, chartRect.width / (chartRect.height || 1), domains, [
815
+ layer.positions.center[0],
816
+ layer.positions.center[1],
817
+ cube.center,
818
+ ]);
819
+ gl.enable(gl.DEPTH_TEST);
820
+ /*
821
+ Which of depth and blending wins, stated. An opaque cube writes depth, so the nearest
822
+ geom hides the ones behind it and a hover lands on the one the reader can see. A
823
+ translucent one tests against what is already there and writes nothing, since the geoms
824
+ arrive in buffer order and back-to-front sorting at ten million is a sort a frame cannot
825
+ afford.
826
+ */
827
+ /*
828
+ Rules and panes draw first and write no depth. Each geom is inside the box, on or in front
829
+ of a back wall, and covers them.
830
+ */
831
+ gl.depthMask(!rules && (picking || layer.opaque === true || surface != null));
832
+ if (field && buffers.field && buffers.ramp) {
833
+ /*
834
+ The box is the surface a ray starts on, so only its front faces produce fragments.
835
+ Without the cull each pixel is asked for twice and the far one starts its ray behind
836
+ the reader.
837
+ */
838
+ /*
839
+ The cube's model matrix swaps two axes, so a triangle wound outward arrives clockwise.
840
+
841
+ `cubeModel` sends data y to world z and data z to world y, which is a reflection: its
842
+ determinant is negative and every face's winding flips with it. Left at the default the
843
+ box's outward faces read as back faces and the cull below discards all twelve, which drew
844
+ an empty cube on both field kinds. Stating the winding here keeps the cull meaning what it
845
+ says, one fragment a pixel at the face where the ray enters.
846
+ */
847
+ gl.frontFace(gl.CW);
848
+ gl.enable(gl.CULL_FACE);
849
+ gl.cullFace(gl.BACK);
850
+ /* A field is read through itself, so its own samples do the occluding. */
851
+ gl.depthMask(false);
852
+ gl.enable(gl.BLEND);
853
+ gl.uniformMatrix4fv(this.volumeUniforms.mvp, false, mvp);
854
+ gl.uniformMatrix4fv(this.volumeUniforms.model, false, cubeModel(domains, [layer.positions.center[0], layer.positions.center[1], cube.center]));
855
+ const eye = eyeOf(cube.orbit);
856
+ gl.uniform3f(this.volumeUniforms.eye, eye[0], eye[1], eye[2]);
857
+ gl.uniform1i(this.volumeUniforms.steps, field.steps);
858
+ gl.uniform1i(this.volumeUniforms.iso, field.iso ? 1 : 0);
859
+ gl.uniform1f(this.volumeUniforms.level, field.level);
860
+ gl.uniform1f(this.volumeUniforms.density, field.density);
861
+ gl.uniform3f(this.volumeUniforms.light, CUBE_LIGHT[0], CUBE_LIGHT[1], CUBE_LIGHT[2]);
862
+ gl.uniform1f(this.volumeUniforms.ambient, AMBIENT);
863
+ gl.activeTexture(gl.TEXTURE0);
864
+ gl.bindTexture(gl.TEXTURE_3D, buffers.field);
865
+ gl.uniform1i(this.volumeUniforms.field, 0);
866
+ gl.activeTexture(gl.TEXTURE1);
867
+ gl.bindTexture(gl.TEXTURE_2D, buffers.ramp);
868
+ gl.uniform1i(this.volumeUniforms.ramp, 1);
869
+ }
870
+ else if (rules) {
871
+ const color = layer.color ?? [0.5, 0.5, 0.5, 1];
872
+ gl.uniformMatrix4fv(this.lineUniforms.mvp, false, mvp);
873
+ gl.uniform2f(this.lineUniforms.viewport, box.width, box.height);
874
+ gl.uniform1f(this.lineUniforms.width, rules.width * dpr);
875
+ gl.uniform4f(this.lineUniforms.color, color[0], color[1], color[2], color[3]);
876
+ }
877
+ else if (surface) {
878
+ gl.uniformMatrix4fv(this.meshUniforms.mvp, false, mvp);
879
+ gl.uniformMatrix3fv(this.meshUniforms.normalMatrix, false, normalMatrix(domains));
880
+ gl.uniform3f(this.meshUniforms.light, CUBE_LIGHT[0], CUBE_LIGHT[1], CUBE_LIGHT[2]);
881
+ gl.uniform1f(this.meshUniforms.ambient, AMBIENT);
882
+ }
883
+ else {
884
+ gl.uniformMatrix4fv(this.cubeUniforms.mvp, false, mvp);
885
+ gl.uniform1f(this.cubeUniforms.depthRef, restingDepth(cube.orbit));
886
+ }
887
+ }
888
+ else {
889
+ gl.disable(gl.DEPTH_TEST);
890
+ gl.disable(gl.CULL_FACE);
891
+ const camera = cameraFor(layer.positions.center, layer.xDomain, layer.yDomain, chartRect.width, chartRect.height);
892
+ gl.uniform2f(this.uniforms.scale, camera.scale[0], camera.scale[1]);
893
+ gl.uniform2f(this.uniforms.translate, camera.translate[0], camera.translate[1]);
894
+ gl.uniform2f(this.uniforms.viewport, chartRect.width, chartRect.height);
895
+ }
896
+ /* Attribute slots off ahead of the set this layer binds. One default vertex array serves every
897
+ layer, and a volume program enables two of the five a cube leaves on. */
898
+ for (let slot = 0; slot < this.attribCount; slot += 1)
899
+ gl.disableVertexAttribArray(slot);
900
+ bindVertex(gl, program, "a_offset", buffers.offsets, 2, gl.FLOAT, false);
901
+ if (buffers.depth)
902
+ bindVertex(gl, program, "a_depth", buffers.depth, 1, gl.FLOAT, false);
903
+ if (buffers.normals)
904
+ bindVertex(gl, program, "a_normal", buffers.normals, 3, gl.FLOAT, false);
905
+ if (buffers.other)
906
+ bindVertex(gl, program, "a_other", buffers.other, 3, gl.FLOAT, false);
907
+ if (buffers.corners)
908
+ bindVertex(gl, program, "a_corner", buffers.corners, 2, gl.FLOAT, false);
909
+ /*
910
+ Both color channels want a value bound whichever pass is running, since an unbound
911
+ attribute reads as zero and a picking pass reading zero would name the first geom.
912
+ */
913
+ if (layer.colors)
914
+ bindVertex(gl, program, "a_color", buffers.colors, 4, gl.UNSIGNED_BYTE, true);
915
+ /* An unbound attribute reads as zero, and a zero diameter draws nothing, so the uniform is
916
+ what a fixed-diameter layer falls back to. */
917
+ if (buffers.sizes)
918
+ bindVertex(gl, program, "a_size", buffers.sizes, 1, gl.FLOAT, false);
919
+ if (buffers.picks) {
920
+ bindVertex(gl, program, "a_pick", buffers.picks, 4, gl.UNSIGNED_BYTE, true);
921
+ }
922
+ const triangles = field ? layer.mesh : surface;
923
+ if (triangles && buffers.faces) {
924
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.faces);
925
+ gl.drawElements(gl.TRIANGLES, triangles.indices.length, gl.UNSIGNED_INT, 0);
926
+ }
927
+ else if (rules) {
928
+ gl.drawArrays(gl.TRIANGLES, 0, buffers.count);
929
+ }
930
+ else {
931
+ gl.drawArrays(gl.POINTS, 0, buffers.count);
932
+ }
933
+ if (field) {
934
+ gl.disable(gl.CULL_FACE);
935
+ gl.frontFace(gl.CCW);
936
+ }
937
+ return box;
938
+ }
939
+ /**
940
+ * The geom under the pointer, read off a picking pass.
941
+ *
942
+ * The pass draws the layer's ids into a cleared, single-sampled pixel of its own. The visible
943
+ * frame is untouched.
944
+ */
945
+ pick(id, clientX, clientY) {
946
+ const gl = this.acquire();
947
+ const layer = this.layers.get(id);
948
+ if (!gl || !layer || !(layer.depth ? this.cubeProgram : this.program))
949
+ return null;
950
+ const target = this.pickTarget(gl);
951
+ if (!target)
952
+ return null;
953
+ const canvasRect = this.sizeCanvas(gl);
954
+ const dpr = this.dprNow();
955
+ const at = {
956
+ x: Math.round((clientX - canvasRect.left) * dpr),
957
+ y: Math.round((canvasRect.height - (clientY - canvasRect.top)) * dpr),
958
+ };
959
+ gl.bindFramebuffer(gl.FRAMEBUFFER, target);
960
+ gl.disable(gl.SCISSOR_TEST);
961
+ gl.clearColor(0, 0, 0, 0);
962
+ gl.depthMask(true);
963
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
964
+ gl.enable(gl.SCISSOR_TEST);
965
+ const box = this.drawLayer(gl, layer, canvasRect, true, at);
966
+ const pixel = new Uint8Array(4);
967
+ if (box)
968
+ gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
969
+ gl.disable(gl.SCISSOR_TEST);
970
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
971
+ return box ? colorToId(pixel) : null;
972
+ }
973
+ /** The one-pixel color and depth target a picking pass draws into, built once per context. */
974
+ pickTarget(gl) {
975
+ if (this.picking)
976
+ return this.picking.framebuffer;
977
+ const framebuffer = gl.createFramebuffer();
978
+ const color = gl.createRenderbuffer();
979
+ const depth = gl.createRenderbuffer();
980
+ if (!framebuffer || !color || !depth)
981
+ return null;
982
+ gl.bindRenderbuffer(gl.RENDERBUFFER, color);
983
+ gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA8, 1, 1);
984
+ gl.bindRenderbuffer(gl.RENDERBUFFER, depth);
985
+ gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, 1, 1);
986
+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
987
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, color);
988
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depth);
989
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
990
+ this.picking = { framebuffer, color, depth };
991
+ return framebuffer;
992
+ }
993
+ }
994
+ /** Percentiles over a set of durations, or null where there are none. */
995
+ function distribution(times) {
996
+ if (times.length === 0)
997
+ return null;
998
+ const sorted = [...times].sort((a, b) => a - b);
999
+ const at = (q) => {
1000
+ const pos = (sorted.length - 1) * q;
1001
+ const lo = Math.floor(pos);
1002
+ return sorted[lo] + (sorted[Math.ceil(pos)] - sorted[lo]) * (pos - lo);
1003
+ };
1004
+ return { frames: sorted.length, p50: at(0.5), p95: at(0.95), max: sorted[sorted.length - 1] };
1005
+ }
1006
+ /**
1007
+ * The scalar field as a 3D texture.
1008
+ *
1009
+ * One byte a cell and linear filtering, which a byte texture gets without asking the context for
1010
+ * anything: a float 3D texture would need `OES_texture_float_linear` to be sampled smoothly, and a
1011
+ * field a ray reads in a couple of hundred steps has no use for the levels that would buy. Clamped
1012
+ * at the edges so a ray leaving the box reads the last cell instead of wrapping to the far side.
1013
+ */
1014
+ function uploadField(gl, volume) {
1015
+ const texture = gl.createTexture();
1016
+ if (!texture)
1017
+ return null;
1018
+ const [x, y, z] = volume.dims;
1019
+ gl.bindTexture(gl.TEXTURE_3D, texture);
1020
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
1021
+ gl.texImage3D(gl.TEXTURE_3D, 0, gl.R8, x, y, z, 0, gl.RED, gl.UNSIGNED_BYTE, volume.field);
1022
+ gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
1023
+ gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
1024
+ gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
1025
+ gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
1026
+ gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_R, gl.CLAMP_TO_EDGE);
1027
+ return texture;
1028
+ }
1029
+ /** The magnitude map as a strip the shader can index by value. */
1030
+ function uploadRamp(gl, ramp) {
1031
+ const texture = gl.createTexture();
1032
+ if (!texture)
1033
+ return null;
1034
+ gl.bindTexture(gl.TEXTURE_2D, texture);
1035
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
1036
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, ramp.length / 4, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, ramp);
1037
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
1038
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
1039
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
1040
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
1041
+ return texture;
1042
+ }
1043
+ /** One value per geom, read straight off the vertex stream. */
1044
+ function bindVertex(gl, program, name, buffer, size, type, normalized) {
1045
+ const location = gl.getAttribLocation(program, name);
1046
+ if (location < 0)
1047
+ return;
1048
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
1049
+ gl.enableVertexAttribArray(location);
1050
+ gl.vertexAttribPointer(location, size, type, normalized, 0, 0);
1051
+ }
1052
+ function compile(gl, vertex, fragment) {
1053
+ const program = gl.createProgram();
1054
+ const vs = stage(gl, gl.VERTEX_SHADER, vertex);
1055
+ const fs = stage(gl, gl.FRAGMENT_SHADER, fragment);
1056
+ if (!program || !vs || !fs)
1057
+ throw new Error(PROGRAM_FAILED);
1058
+ gl.attachShader(program, vs);
1059
+ gl.attachShader(program, fs);
1060
+ gl.linkProgram(program);
1061
+ gl.deleteShader(vs);
1062
+ gl.deleteShader(fs);
1063
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
1064
+ const log = gl.getProgramInfoLog(program);
1065
+ throw new Error(`${PROGRAM_FAILED}: ${log ?? "no log"}`);
1066
+ }
1067
+ return program;
1068
+ }
1069
+ function stage(gl, kind, source) {
1070
+ const shader = gl.createShader(kind);
1071
+ if (!shader)
1072
+ return null;
1073
+ gl.shaderSource(shader, source);
1074
+ gl.compileShader(shader);
1075
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
1076
+ const log = gl.getShaderInfoLog(shader);
1077
+ gl.deleteShader(shader);
1078
+ throw new Error(`${PROGRAM_FAILED}: ${log ?? "no log"}`);
1079
+ }
1080
+ return shader;
1081
+ }