From f5eabf5a8b835717c49fef3728ae648f01c3e2dc Mon Sep 17 00:00:00 2001 From: Dominik Date: Thu, 3 Dec 2026 22:53:10 -0800 Subject: [PATCH 01/45] Skip glyph outline vertices of scatter3d markers without an outline The outline of a glyph marker draws only when lineWidth is above 0, but gl-scatter3d built its vertices for every point. Count and fill them only when lineWidth is above 0. A circle marker drops from 104 to 60 vertices. --- draftlogs/XXXX_fix.md | 1 + stackgl_modules/index.js | 4 ++-- stackgl_modules/package-lock.json | 5 ++-- stackgl_modules/package.json | 2 +- test/jasmine/tests/scatter3d_test.js | 34 ++++++++++++++++++++++++++++ 5 files changed, 40 insertions(+), 6 deletions(-) create mode 100644 draftlogs/XXXX_fix.md diff --git a/draftlogs/XXXX_fix.md b/draftlogs/XXXX_fix.md new file mode 100644 index 00000000000..2dad55d224c --- /dev/null +++ b/draftlogs/XXXX_fix.md @@ -0,0 +1 @@ +- Fix `scatter3d` allocating glyph outline vertices for markers without an outline, which cuts the vertex count of a circle marker from 104 to 60 [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index b812d41f949..a6585c2c826 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -20379,7 +20379,7 @@ proto.update = function(options) { var glyphBounds = glyphData.bounds triVertexCount += glyphMesh.cells.length * 3 - lineVertexCount += glyphLines.edges.length * 2 + if(this.lineWidth > 0) lineVertexCount += glyphLines.edges.length * 2 } } @@ -20575,7 +20575,7 @@ proto.update = function(options) { } } - var cells = glyphLines.edges + var cells = this.lineWidth > 0 ? glyphLines.edges : [] var verts = glyphLines.positions for(var j=0; j Date: Thu, 3 Dec 2026 23:13:40 -0800 Subject: [PATCH 02/45] Add scene.markerrender to draw scatter3d circle markers as discs A circle marker is a vectorized glyph mesh of 60 to 104 vertices, about 4,160 bytes in the vertex buffers. With scene.markerrender set to disc or auto, circle and circle-open markers draw as one gl.POINTS vertex with a round cutout in the fragment shader, with an outline ring for marker.line.width. Other symbols, projections on the axes and sprites larger than the point size limit keep the glyph path. The default is glyph, so rendering does not change unless the attribute is set. gl-scatter3d is pinned to a fork commit, and stackgl_modules/index.js is rebuilt from it. --- draftlogs/XXXX_add.md | 1 + src/plots/gl3d/layout/defaults.js | 1 + src/plots/gl3d/layout/layout_attributes.js | 15 + src/plots/gl3d/scene.js | 5 +- src/traces/scatter3d/convert.js | 1 + src/types/generated/schema.d.ts | 5 + stackgl_modules/index.js | 455 +++++++++++++++++++++ stackgl_modules/package-lock.json | 5 +- stackgl_modules/package.json | 2 +- test/jasmine/tests/gl3dlayout_test.js | 16 + test/jasmine/tests/scatter3d_test.js | 170 ++++++++ test/plot-schema.json | 11 + 12 files changed, 682 insertions(+), 5 deletions(-) create mode 100644 draftlogs/XXXX_add.md diff --git a/draftlogs/XXXX_add.md b/draftlogs/XXXX_add.md new file mode 100644 index 00000000000..a4056f1fa90 --- /dev/null +++ b/draftlogs/XXXX_add.md @@ -0,0 +1 @@ +- Add `scene.markerrender` to draw `scatter3d` circle markers as one-vertex discs instead of glyph meshes, which cuts the memory of a marker from 4,160 bytes to 36 bytes [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/src/plots/gl3d/layout/defaults.js b/src/plots/gl3d/layout/defaults.js index 311ad2fe919..fc71c144408 100644 --- a/src/plots/gl3d/layout/defaults.js +++ b/src/plots/gl3d/layout/defaults.js @@ -62,6 +62,7 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { } coerce('camera.projection.type'); + coerce('markerrender'); /* * coerce to positive number (min 0) but also do not accept 0 (>0 not >=0) diff --git a/src/plots/gl3d/layout/layout_attributes.js b/src/plots/gl3d/layout/layout_attributes.js index 3666d33e741..0259f4f8ddd 100644 --- a/src/plots/gl3d/layout/layout_attributes.js +++ b/src/plots/gl3d/layout/layout_attributes.js @@ -133,6 +133,21 @@ module.exports = { yaxis: gl3dAxisAttrs, zaxis: gl3dAxisAttrs, + markerrender: { + valType: 'enumerated', + values: ['glyph', 'disc', 'auto'], + dflt: 'glyph', + editType: 'plot', + description: [ + 'Sets how circle markers of *scatter3d* traces are drawn.', + 'The symbols *circle* and *circle-open* have two forms.', + '*glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default.', + '*disc* draws each marker as one round point sprite. It needs far less memory and draws faster.', + 'The edge of a disc differs from the edge of a glyph by about one pixel.', + '*auto* draws discs where it can.', + 'It draws glyphs for other symbols, for projections on the axes, and for markers that exceed the point size limit of the GPU.' + ].join(' ') + }, dragmode: { valType: 'enumerated', values: ['orbit', 'turntable', 'zoom', 'pan', false], diff --git a/src/plots/gl3d/scene.js b/src/plots/gl3d/scene.js index e320fe9e780..b76514d335a 100644 --- a/src/plots/gl3d/scene.js +++ b/src/plots/gl3d/scene.js @@ -1093,8 +1093,11 @@ proto.toImage = function(format) { if(!format) format = 'png'; if(scene.staticMode) scene.container.appendChild(STATIC_CANVAS); - // Force redraw + // Force redraw. Disc markers take a slower, smoother edge path on targets without multisampling. + var exportObjs = scene.glplot.objects; + for(var oi = 0; oi < exportObjs.length; oi++) exportObjs[oi].discExport = true; scene.glplot.redraw(); + for(var oj = 0; oj < exportObjs.length; oj++) exportObjs[oj].discExport = false; // Grab context and yank out pixels var gl = scene.glplot.gl; diff --git a/src/traces/scatter3d/convert.js b/src/traces/scatter3d/convert.js index 019d362e5fe..45c9778a286 100644 --- a/src/traces/scatter3d/convert.js +++ b/src/traces/scatter3d/convert.js @@ -421,6 +421,7 @@ proto.update = function (data) { glyph: options.scatterMarker, opacity: scatterOpacity, orthographic: true, + markerRender: this.scene.fullSceneLayout.markerrender, lineWidth: options.scatterLineWidth, lineColor: options.scatterLineColor, project: options.project, diff --git a/src/types/generated/schema.d.ts b/src/types/generated/schema.d.ts index 853b8c815f9..642cd0f8a24 100644 --- a/src/types/generated/schema.d.ts +++ b/src/types/generated/schema.d.ts @@ -13742,6 +13742,11 @@ export interface Scene { * @default 'closest' */ hovermode?: 'closest' | false; + /** + * Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. *auto* draws discs where it can. It draws glyphs for other symbols, for projections on the axes, and for markers that exceed the point size limit of the GPU. + * @default 'glyph' + */ + markerrender?: 'glyph' | 'disc' | 'auto'; /** Controls persistence of user-driven changes in camera attributes. Defaults to `layout.uirevision`. */ uirevision?: any; xaxis?: { diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index b812d41f949..33c1ff2b948 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -19794,6 +19794,7 @@ var createVAO = __webpack_require__(8116) var pool = __webpack_require__(1888) var mat4mult = __webpack_require__(6760) var shaders = __webpack_require__(1283) +var createShaderWrapper = __webpack_require__(9405) var getGlyph = __webpack_require__(9366) var getSimpleString = __webpack_require__(5964) @@ -19874,6 +19875,18 @@ function PointCloud( this.vertexCount = 0 this.lineVertexCount = 0 + // disc markers (see _updateDisc): 'glyph' keeps the vectorised glyph meshes + this.markerRender = 'glyph' + this.discActive = false + this.discBlocker = '' + this.discHardEdge = false + this.discSet = null + this.discCur = null + this.discOutline = false + this.lineColorBuffer = null + this.sizeBuffer = null + this.pointSizeRange = null + this.opacity = 1 this.hasAlpha = false @@ -20099,6 +20112,421 @@ var NEG_INFINITY3 = [-1e8, -1e8, -1e8] var POS_INFINITY3 = [1e8, 1e8, 1e8] var CLIP_GROUP = [NEG_INFINITY3, POS_INFINITY3] +// --------------------------------------------------------------------------- +// Disc markers: a circle marker drawn as one gl.POINTS vertex (round cutout in the fragment shader) +// instead of a vectorised "●" glyph mesh of 60 to 104 vertices. The disc has the same screen-aligned constant +// pixel size as the glyph. +// '●' circle: filled disc, with an outline ring when marker.line.width is above 0 (lineColor attribute) +// '○' circle-open: hollow ring in the marker colour +// The edge of the disc in the opaque pass is chosen at draw time, see drawDisc. +// --------------------------------------------------------------------------- +var DISC_FILL = '●' +var DISC_OPEN = '○' + +var DISC_OUT_OF_RANGE = [ + 'bool outOfRange(float a, float b, float p) {', + ' return ((p > max(a, b)) || (p < min(a, b)));', + '}', + 'bool outOfRange(vec3 a, vec3 b, vec3 p) {', + ' return (outOfRange(a.x, b.x, p.x) || outOfRange(a.y, b.y, p.y) || outOfRange(a.z, b.z, p.z));', + '}' +].join('\n') + +function discVert(outline) { + return [ + outline ? '#define OUTLINE' : '', + 'precision highp float;', + DISC_OUT_OF_RANGE, + 'attribute vec3 position;', + 'attribute vec4 color;', + 'attribute float size;', + 'attribute vec4 id;', + '#ifdef OUTLINE', + 'attribute vec4 lineColor;', + 'varying vec4 interpLine;', + '#endif', + 'uniform mat4 model, view, projection;', + 'uniform vec2 screenSize;', + 'uniform vec3 clipBounds[2];', + 'uniform float highlightScale, pixelRatio, unitA, unitB, lineHalf;', + 'uniform vec2 unitCenter;', + 'uniform vec4 highlightId;', + 'varying vec4 interpColor;', + 'varying vec4 pickId;', + 'varying float vA;', + 'varying float vB;', + 'varying float vHalf;', + 'void main() {', + ' if (outOfRange(clipBounds[0], clipBounds[1], position)) {', + ' gl_Position = vec4(0, 0, 0, 0);', + ' gl_PointSize = 1.0;', + ' vA = -1.0; vB = 0.0; vHalf = 1.0;', + ' } else {', + ' float scale = pixelRatio;', + ' if (distance(highlightId.bgr, id.bgr) < 0.001) {', + ' scale *= highlightScale;', + ' }', + ' vec4 clipPosition = projection * (view * (model * vec4(position, 1.0)));', + ' clipPosition /= clipPosition.w;', + ' gl_Position = clipPosition + vec4(screenSize * scale * size * vec2(unitCenter.x, -unitCenter.y), 0.0, 0.0);', + ' vB = scale * size * unitB;', + ' vA = unitA < 0.0 ? -1.0 : scale * size * unitA;', + ' vHalf = vB + lineHalf + 1.0;', + ' gl_PointSize = 2.0 * vHalf;', + ' interpColor = color;', + ' pickId = id;', + '#ifdef OUTLINE', + ' interpLine = lineColor;', + '#endif', + ' }', + '}' + ].join('\n') +} + +function discFrag(outline) { + return [ + outline ? '#define OUTLINE' : '', + 'precision highp float;', + 'uniform float opacity, hardEdge, lineHalf, a2c, rim;', + 'varying vec4 interpColor;', + 'varying float vA;', + 'varying float vB;', + 'varying float vHalf;', + '#ifdef OUTLINE', + 'varying vec4 interpLine;', + '#endif', + 'void main() {', + ' float d = length((gl_PointCoord - 0.5) * 2.0 * vHalf);', + ' float cf = hardEdge > 0.5 ? step(d, vB) * step(vA, d)', + ' : clamp(vB - d + 0.5, 0.0, 1.0) * clamp(d - vA + 0.5, 0.0, 1.0);', + ' if (interpColor.a * opacity == 0.) cf = 0.;', + ' vec4 c = interpColor * (opacity * cf);', + '#ifdef OUTLINE', + ' float e = min(abs(d - vB), vA < 0.0 ? 1e6 : abs(d - vA));', // outer edge, plus the inner edge of a ring + ' float cl = hardEdge > 0.5 ? step(e, lineHalf) : clamp(lineHalf - e + 0.5, 0.0, 1.0);', + ' c = c * (1.0 - cl) + interpLine * (opacity * cl);', + ' if (cf + cl <= 0.0) discard;', + '#else', + ' if (cf <= 0.0) discard;', + '#endif', + ' if (rim > -0.5) {', + ' if (rim < 0.5 && c.a < 0.999) discard;', // pass 0: fully covered pixels only (opaque cores, depth written) + ' if (rim > 0.5 && (c.a >= 0.999 || c.a <= 0.0)) discard;', // pass 1: partial-coverage rim pixels, blended over + ' }', + ' gl_FragColor = a2c > 0.5 ? vec4(c.rgb / max(c.a, 1e-4), c.a) : c;', // pure a2c: full colour, alpha = coverage (alpha channel is masked) + '}' + ].join('\n') +} + +var DISC_PICK_FRAG = [ + 'precision highp float;', + 'uniform float pickGroup, lineHalf;', + 'varying vec4 pickId;', + 'varying float vA;', + 'varying float vB;', + 'varying float vHalf;', + 'void main() {', + ' float d = length((gl_PointCoord - 0.5) * 2.0 * vHalf);', + ' if (d > vB + lineHalf || d < (vA < 0.0 ? vA : vA - lineHalf)) discard;', + ' gl_FragColor = vec4(pickGroup, pickId.bgr);', + '}' +].join('\n') + +function createDiscShader(gl, outline, pick) { + var shader = createShaderWrapper(gl, {vertex: discVert(outline), fragment: pick ? DISC_PICK_FRAG : discFrag(outline)}) + var attr = shader.attributes + attr.position.location = 0 + attr.color.location = 1 + attr.size.location = 2 + attr.id.location = 3 + if(outline && attr.lineColor) attr.lineColor.location = 4 + return shader +} + +// 'fill', 'open', or '' when the symbols are anything else +function discKind(glyphs, n) { + var first + if(isArrayOrTypedArray(glyphs)) { + if(glyphs.length < n || n === 0) return '' + first = glyphs[0] + for(var i = 0; i < n; ++i) if(glyphs[i] !== first) return '' + } else { + first = glyphs + } + return first === DISC_FILL ? 'fill' : first === DISC_OPEN ? 'open' : '' +} + +// Returns '' when the disc path can draw this update, otherwise the reason it cannot +proto._discBlocker = function(options) { + var mode = this.markerRender + if(mode !== 'disc' && mode !== 'auto') return 'markerRender is ' + mode + if(!options.position) return 'no positions' + if(!this.useOrtho) return 'perspective sizing' + for(var i = 0; i < 3; ++i) if(this.axesProject[i]) return 'axes projection' + var angles = options.angle + if(angles && (!isArrayOrTypedArray(angles) || angles.length)) return 'marker angle' + var al = options.alignment + if(al && (al.length !== 2 || al[0] || al[1])) return 'alignment' + var kind = discKind(options.glyph, options.position.length) + if(!kind) return 'symbol is not circle or circle-open' + return '' +} + +proto._discSetup = function(kind, outline) { + var gl = this.gl + if(!this.sizeBuffer) this.sizeBuffer = createBuffer(gl) + if(outline && !this.lineColorBuffer) this.lineColorBuffer = createBuffer(gl) + var key = outline ? 'outline' : 'plain' + if(!this.discSet) this.discSet = {} + if(!this.discSet[key]) { + var attrs = [ + { buffer: this.pointBuffer, size: 3, type: gl.FLOAT }, + { buffer: this.colorBuffer, size: 4, type: gl.FLOAT }, + { buffer: this.sizeBuffer, size: 1, type: gl.FLOAT }, + { buffer: this.idBuffer, size: 4, type: gl.UNSIGNED_BYTE, normalized: true } + ] + if(outline) attrs.push({ buffer: this.lineColorBuffer, size: 4, type: gl.FLOAT }) + this.discSet[key] = { + shader: createDiscShader(gl, outline, false), + pickShader: createDiscShader(gl, outline, true), + vao: createVAO(gl, attrs) + } + } + this.discCur = this.discSet[key] + this.discOutline = outline + // Radii of the glyph, in the units the glyph shaders use (already divided by the pixelRatio the glyph was cached with). + // The disc is centred on the point: the glyph's own centre sits a little off (font bearings, up to ~0.012 * size px) + // and differs between glyph cache entries, so it is not reproduced. + var font = {family: 'normal', style: 'normal', weight: 'normal', variant: 'normal'} + var g = get_glyphData(kind === 'open' ? DISC_OPEN : DISC_FILL, font, this.pixelRatio) + var b = g.bounds + var cx = 0.5 * (b[0][0] + b[1][0]) + var cy = 0.5 * (b[0][1] + b[1][1]) + var lp = g.lines.positions + var rs = [] + var i + if(kind === 'fill') { + var s = 0 + for(i = 0; i < lp.length; ++i) s += Math.hypot(lp[i][0] - cx, lp[i][1] - cy) + this.discUnit = {cx: 0, cy: 0, a: -1, b: s / lp.length} + } else { + // ring: outer and inner polygon radii + var mp = g.mesh.positions + var rmin = Infinity, rmax = -Infinity + for(i = 0; i < mp.length; ++i) { + var r = Math.hypot(mp[i][0] - cx, mp[i][1] - cy) + rs.push(r); rmin = Math.min(rmin, r); rmax = Math.max(rmax, r) + } + var mid = 0.5 * (rmin + rmax), so = 0, no = 0, si = 0, ni = 0 + for(i = 0; i < rs.length; ++i) { + if(rs[i] > mid) { so += rs[i]; no++ } else { si += rs[i]; ni++ } + } + this.discUnit = {cx: 0, cy: 0, a: si / ni, b: so / no} + } +} + +// Fill the disc buffers, 1 vertex per point. Returns false if the disc path cannot be used. +proto._updateDisc = function(options) { + var gl = this.gl + var points = options.position + var n = points.length + var kind = discKind(options.glyph, n) + var outline = this.lineWidth > 0 + try { + this._discSetup(kind, outline) + } catch(e) { + this.discBlocker = 'disc shader failed: ' + e + return false + } + + var colors = options.color + var lineColors = options.lineColor + var sizes = options.size + + var positionArray = pool.mallocFloat(3 * n) + var colorArray = pool.mallocFloat(4 * n) + var sizeArray = pool.mallocFloat(n) + var idArray = pool.mallocUint32(n) + var lineArray = outline ? pool.mallocFloat(4 * n) : null + + var lowerBound = [ Infinity, Infinity, Infinity] + var upperBound = [-Infinity,-Infinity,-Infinity] + var color = [0, 0, 0, 1] + var lineColor = [0, 0, 0, 1] + var isColorArray = isArrayOrTypedArray(colors) && isArrayOrTypedArray(colors[0]) + var isLineColorArray = isArrayOrTypedArray(lineColors) && isArrayOrTypedArray(lineColors[0]) + var sizeIsArray = isArrayOrTypedArray(sizes) + var sizeScalar = sizeIsArray ? 0 : sizes ? +sizes : 12 + var maxSize = 0 + var m = 0 + + fill_loop: + for(var i = 0; i < n; ++i) { + var x = points[i] + for(var j = 0; j < 3; ++j) { + if(isNaN(x[j]) || !isFinite(x[j])) continue fill_loop + } + + if(isArrayOrTypedArray(colors)) { + var c + if(isColorArray) c = i < colors.length ? colors[i] : [0, 0, 0, 0] + else c = colors + if(c.length === 3) { + color[0] = c[0]; color[1] = c[1]; color[2] = c[2]; color[3] = 1 + } else if(c.length === 4) { + color[0] = c[0]; color[1] = c[1]; color[2] = c[2]; color[3] = c[3] + // a fully transparent fill under an outline draws nothing: the outline ring stays opaque + if(!this.hasAlpha && c[3] < 1 && !(c[3] === 0 && outline)) this.hasAlpha = true + } + } else { + color[0] = color[1] = color[2] = 0 + color[3] = 1 + } + + if(outline) { + if(isArrayOrTypedArray(lineColors)) { + var lc + if(isLineColorArray) lc = i < lineColors.length ? lineColors[i] : [0, 0, 0, 0] + else lc = lineColors + if(lc.length === 3) { + lineColor[0] = lc[0]; lineColor[1] = lc[1]; lineColor[2] = lc[2]; lineColor[3] = 1 + } else if(lc.length === 4) { + lineColor[0] = lc[0]; lineColor[1] = lc[1]; lineColor[2] = lc[2]; lineColor[3] = lc[3] + if(!this.hasAlpha && lc[3] < 1) this.hasAlpha = true + } + } else { + lineColor[0] = lineColor[1] = lineColor[2] = 0 + lineColor[3] = 1 + } + lineArray[4 * m] = lineColor[0] + lineArray[4 * m + 1] = lineColor[1] + lineArray[4 * m + 2] = lineColor[2] + lineArray[4 * m + 3] = lineColor[3] + } + + var size = sizeIsArray ? (i < sizes.length ? +sizes[i] : 12) : sizeScalar + if(size > maxSize) maxSize = size + + for(var j = 0; j < 3; ++j) { + positionArray[3 * m + j] = x[j] + if(x[j] > upperBound[j]) upperBound[j] = x[j] + if(x[j] < lowerBound[j]) lowerBound[j] = x[j] + } + colorArray[4 * m] = color[0] + colorArray[4 * m + 1] = color[1] + colorArray[4 * m + 2] = color[2] + colorArray[4 * m + 3] = color[3] + sizeArray[m] = size + idArray[m] = i + m += 1 + } + + // Largest sprite in device pixels (+2 for the antialiasing margin) against the driver's point size cap + var range = gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE) + this.pointSizeRange = [range[0], range[1]] + var maxPx = 2 * (maxSize * this.discUnit.b * this.pixelRatio * Math.max(1, this.highlightScale || 1) + + this._discLineHalf(this.pixelRatio) + 1) + if(maxPx > range[1]) { + this.discBlocker = 'marker size ' + maxPx.toFixed(0) + ' px exceeds point size cap ' + range[1] + pool.free(positionArray) + pool.free(colorArray) + pool.free(sizeArray) + pool.free(idArray) + if(lineArray) pool.free(lineArray) + return false + } + + this.bounds = [lowerBound, upperBound] + this.points = points + this.pointCount = n + this.vertexCount = m + this.lineVertexCount = 0 + + this.pointBuffer.update(positionArray.subarray(0, 3 * m)) + this.colorBuffer.update(colorArray.subarray(0, 4 * m)) + this.sizeBuffer.update(sizeArray.subarray(0, m)) + this.idBuffer.update(idArray.subarray(0, m)) + if(outline) this.lineColorBuffer.update(lineArray.subarray(0, 4 * m)) + else if(this.lineColorBuffer) this.lineColorBuffer.update(1) + this.glyphBuffer.update(1) // release the glyph buffer, it is not used by discs + + pool.free(positionArray) + pool.free(colorArray) + pool.free(sizeArray) + pool.free(idArray) + if(lineArray) pool.free(lineArray) + return true +} + +// Half width in device pixels of the outline ring. The ring is drawn in the fragment shader, not with GL lines, so +// marker.line.width applies as requested: ALIASED_LINE_WIDTH_RANGE only limits the glyph path. +proto._discLineHalf = function(pixelRatio) { + if(!this.discOutline) return 0 + return 0.5 * this.lineWidth * pixelRatio +} + +function drawDisc(points, camera, pixelRatio, pick, hard) { + var gl = points.gl + var set = points.discCur + var shader = pick ? set.pickShader : set.shader + var uniforms = shader.uniforms + shader.bind() + uniforms.model = camera.model || IDENTITY + uniforms.view = camera.view || IDENTITY + uniforms.projection = camera.projection || IDENTITY + VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth + VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight + uniforms.screenSize = VIEW_SHAPE + uniforms.highlightId = points.highlightId + uniforms.highlightScale = points.highlightScale + uniforms.clipBounds = points.axes.bounds + uniforms.opacity = points.opacity + uniforms.pickGroup = points.pickId / 255.0 + uniforms.pixelRatio = pixelRatio + uniforms.unitA = points.discUnit.a + uniforms.unitB = points.discUnit.b + uniforms.unitCenter = [points.discUnit.cx, points.discUnit.cy] + uniforms.lineHalf = points._discLineHalf(pixelRatio) + // Opaque pass, soft edges, in order of preference: + // 1. Multisampled target and an opaque clear alpha: pure alpha-to-coverage. Full colour, blending off, alpha written as + // coverage only (the alpha channel is masked off, it stays 1). Every sample is either fully this disc (with depth) or + // untouched, so the result does not depend on draw order, exactly like MSAA of the glyph meshes. + // 2. Transparent canvas (the plotly default scene background) or an export: hard cores with depth write, then the + // antialiased rim blended over (premultiplied) with the depth test and no depth write. This doubles the draw cost, so + // interactive draws only use it when points.discRimScreen is set; otherwise they keep the hard alpha-1 edge. + var samples = hard && !pick ? gl.getParameter(gl.SAMPLES) : 0 + var clearAlpha = hard && !pick ? gl.getParameter(gl.COLOR_CLEAR_VALUE)[3] : 0 + var a2c = !!(hard && !pick && points.discA2C !== false && samples > 0 && clearAlpha >= 0.999) + var rimPass = !!(hard && !pick && !a2c && !points.discHardEdge && + (points.discExport || (points.discRimScreen === true && samples > 0))) + uniforms.hardEdge = (hard && !a2c && !rimPass || points.discHardEdge) ? 1 : 0 + points.discPath = pick ? 'pick' : a2c ? 'a2c' : rimPass ? 'rim' : (hard || points.discHardEdge) ? 'hard' : 'smooth' // last draw path, for diagnostics + uniforms.a2c = a2c ? 1 : 0 + uniforms.rim = rimPass ? 0 : -1 + if(a2c) { + gl.enable(gl.SAMPLE_ALPHA_TO_COVERAGE) + gl.disable(gl.BLEND) + gl.colorMask(true, true, true, false) + } + + set.vao.bind() + set.vao.draw(gl.POINTS, points.vertexCount) + if(rimPass) { + uniforms.rim = 1 + gl.enable(gl.BLEND) + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + gl.depthMask(false) + set.vao.draw(gl.POINTS, points.vertexCount) + gl.depthMask(true) + gl.disable(gl.BLEND) + } + set.vao.unbind() + if(a2c) { + gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE) + gl.colorMask(true, true, true, true) + } +} + function drawFull(shader, pshader, points, camera, pixelRatio, transparent, forceDraw) { var gl = points.gl @@ -20108,6 +20536,12 @@ function drawFull(shader, pshader, points, camera, pixelRatio, transparent, forc if(transparent === points.hasAlpha || forceDraw) { + if(points.discActive) { + var isPick = pshader === points.pickProjectShader + drawDisc(points, camera, pixelRatio, isPick, isPick || !transparent) + return + } + shader.bind() var uniforms = shader.uniforms @@ -20314,6 +20748,18 @@ proto.update = function(options) { //Create new buffers var points = options.position + //Circle markers as 1 vertex discs + if('markerRender' in options) this.markerRender = options.markerRender + if('discHardEdge' in options) this.discHardEdge = !!options.discHardEdge + this.discBlocker = this._discBlocker(options) + this.discActive = false + if(!this.discBlocker && this._updateDisc(options)) { + this.discActive = true + return + } + if(this.sizeBuffer) this.sizeBuffer.update(1) // release the disc buffers while glyphs are in use + if(this.lineColorBuffer) this.lineColorBuffer.update(1) + //Text font var font = { family: options.font || 'normal', @@ -20635,6 +21081,15 @@ proto.dispose = function() { //Vertex array this.vao.dispose() + if(this.discSet) { + for(var k in this.discSet) { + this.discSet[k].shader.dispose() + this.discSet[k].pickShader.dispose() + this.discSet[k].vao.dispose() + } + this.sizeBuffer.dispose() + if(this.lineColorBuffer) this.lineColorBuffer.dispose() + } //Buffers this.pointBuffer.dispose() diff --git a/stackgl_modules/package-lock.json b/stackgl_modules/package-lock.json index 0961819ddab..36e50d1169a 100644 --- a/stackgl_modules/package-lock.json +++ b/stackgl_modules/package-lock.json @@ -17,7 +17,7 @@ "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", "gl-plot3d": "^2.4.7", - "gl-scatter3d": "^1.4.1", + "gl-scatter3d": "github:settylab/gl-scatter3d#25590f6d72f6f98b91f283d4d5614933657bfb6a", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", "gl-streamtube3d": "^1.4.2", @@ -1347,8 +1347,7 @@ }, "node_modules/gl-scatter3d": { "version": "1.4.1", - "resolved": "https://registry.npmjs.org/gl-scatter3d/-/gl-scatter3d-1.4.1.tgz", - "integrity": "sha512-v2nQWSPr9/smu2YB4erhHuUkk+8w2q59CsTPvcK72vFYWCSgU6eeTnu0UlmN634bblbTTa5ap/xrbxJGiKLyrw==", + "resolved": "git+ssh://git@github.com/settylab/gl-scatter3d.git#25590f6d72f6f98b91f283d4d5614933657bfb6a", "license": "MIT", "dependencies": { "gl-buffer": "^2.1.2", diff --git a/stackgl_modules/package.json b/stackgl_modules/package.json index a145e05bf6b..f8ec311abc1 100644 --- a/stackgl_modules/package.json +++ b/stackgl_modules/package.json @@ -20,7 +20,7 @@ "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", "gl-plot3d": "^2.4.7", - "gl-scatter3d": "^1.4.1", + "gl-scatter3d": "github:settylab/gl-scatter3d#25590f6d72f6f98b91f283d4d5614933657bfb6a", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", "gl-streamtube3d": "^1.4.2", diff --git a/test/jasmine/tests/gl3dlayout_test.js b/test/jasmine/tests/gl3dlayout_test.js index 75d271f7b6c..32f6e6591e1 100644 --- a/test/jasmine/tests/gl3dlayout_test.js +++ b/test/jasmine/tests/gl3dlayout_test.js @@ -341,6 +341,22 @@ describe('Test Gl3d layout defaults', function() { .toBe('closest', 'to default if not valid'); }); + it('should coerce markerrender', function() { + layoutIn = { scene: {} }; + supplyLayoutDefaults(layoutIn, layoutOut, fullData); + expect(layoutOut.scene.markerrender).toBe('glyph', 'to glyph by default'); + + ['auto', 'disc', 'glyph'].forEach(function(v) { + layoutIn = { scene: { markerrender: v } }; + supplyLayoutDefaults(layoutIn, layoutOut, fullData); + expect(layoutOut.scene.markerrender).toBe(v, 'to user val if valid'); + }); + + layoutIn = { scene: { markerrender: 'sphere' } }; + supplyLayoutDefaults(layoutIn, layoutOut, fullData); + expect(layoutOut.scene.markerrender).toBe('glyph', 'to glyph if invalid'); + }); + it('should add data-only scenes into layoutIn', function() { layoutIn = {}; fullData = [{ type: 'scatter3d', scene: 'scene' }]; diff --git a/test/jasmine/tests/scatter3d_test.js b/test/jasmine/tests/scatter3d_test.js index a5f1a7f8b4d..1ec44ef21ce 100644 --- a/test/jasmine/tests/scatter3d_test.js +++ b/test/jasmine/tests/scatter3d_test.js @@ -9,6 +9,7 @@ var createGraphDiv = require('../assets/create_graph_div'); var destroyGraphDiv = require('../assets/destroy_graph_div'); var delay = require('../assets/delay'); +var mouseEvent = require('../assets/mouse_event'); function countCanvases() { return d3SelectAll('canvas').size(); @@ -345,4 +346,173 @@ describe('Test scatter3d interactions:', function() { }) .then(done, done.fail); }); + describe('circle markers as discs:', function() { + function point(marker, extra) { + return Lib.extendFlat({ + type: 'scatter3d', + mode: 'markers', + x: [1, 2, 3], + y: [2, 3, 1], + z: [3, 1, 2], + marker: marker + }, extra || {}); + } + + function scatterPlot() { + return gd._fullLayout.scene._scene.traces[gd._fullData[0].uid].scatterPlot; + } + + function plot(marker, markerrender, extra) { + return Plotly.newPlot(gd, [point(marker, extra)], {scene: {markerrender: markerrender}}); + } + + it('@gl should draw glyph meshes by default', function(done) { + Plotly.newPlot(gd, [point({size: 10})]) + .then(function() { + expect(scatterPlot().discActive).toBe(false); + expect(scatterPlot().vertexCount).toBeGreaterThan(3, '# of vertices'); + }) + .then(done, done.fail); + }); + + it('@gl should draw one vertex per circle with markerrender auto and disc, and a glyph mesh with glyph', function(done) { + plot({size: 10}, 'auto') + .then(function() { + var o = scatterPlot(); + expect(o.discActive).toBe(true, 'auto'); + expect(o.vertexCount).toBe(3, 'auto, # of vertices'); + expect(o.lineVertexCount).toBe(0, 'auto, # of outline vertices'); + return plot({size: 10}, 'disc'); + }) + .then(function() { + expect(scatterPlot().discActive).toBe(true, 'disc'); + expect(scatterPlot().vertexCount).toBe(3, 'disc, # of vertices'); + return plot({size: 10}, 'glyph'); + }) + .then(function() { + var o = scatterPlot(); + expect(o.discActive).toBe(false, 'glyph'); + expect(o.vertexCount).toBeGreaterThan(3, 'glyph, # of vertices'); + }) + .then(done, done.fail); + }); + + it('@gl should switch between disc and glyph on relayout', function(done) { + plot({size: 10}, 'disc') + .then(function() { + expect(scatterPlot().discActive).toBe(true); + return Plotly.relayout(gd, 'scene.markerrender', 'glyph'); + }) + .then(function() { + expect(scatterPlot().discActive).toBe(false); + return Plotly.relayout(gd, 'scene.markerrender', 'auto'); + }) + .then(function() { + expect(scatterPlot().discActive).toBe(true); + }) + .then(done, done.fail); + }); + + it('@gl should fall back to glyphs, with a reason, where a disc cannot draw the marker', function(done) { + plot({size: 10, symbol: 'square'}, 'disc') + .then(function() { + expect(scatterPlot().discActive).toBe(false, 'square'); + expect(scatterPlot().discBlocker).toBe('symbol is not circle or circle-open', 'square'); + return plot({size: 10}, 'disc', {projection: {z: {show: true}}}); + }) + .then(function() { + expect(scatterPlot().discActive).toBe(false, 'projection'); + expect(scatterPlot().discBlocker).toBe('axes projection', 'projection'); + return plot({size: 5000}, 'disc'); + }) + .then(function() { + expect(scatterPlot().discActive).toBe(false, 'oversize'); + expect(scatterPlot().discBlocker).toMatch(/exceeds point size cap/, 'oversize'); + }) + .then(done, done.fail); + }); + + it('@gl should draw circle-open and marker.line as discs', function(done) { + plot({size: 10, symbol: 'circle-open'}, 'disc') + .then(function() { + expect(scatterPlot().discActive).toBe(true, 'circle-open'); + return plot({size: 10, line: {width: 2, color: 'black'}}, 'disc'); + }) + .then(function() { + expect(scatterPlot().discActive).toBe(true, 'marker.line'); + expect(scatterPlot().vertexCount).toBe(3, 'marker.line, # of vertices'); + }) + .then(done, done.fail); + }); + + it('@gl should draw marker.line.width as requested, not clamped to the GL line width range', function(done) { + plot({size: 40, color: 'red', line: {color: 'cyan', width: 6}}, 'disc') + .then(function() { + var o = scatterPlot(); + expect(o.discActive).toBe(true); + expect(o._discLineHalf(2)).toBe(6); + expect(o._discLineHalf(1)).toBe(3); + return Plotly.restyle(gd, 'marker.line.width', 0); + }) + .then(function() { + expect(scatterPlot()._discLineHalf(2)).toBe(0); + }) + .then(done, done.fail); + }); + + it('@gl should keep a transparent fill with an opaque outline in the opaque pass', function(done) { + plot({size: 40, color: 'rgba(0,0,0,0)', line: {color: 'cyan', width: 2}}, 'disc') + .then(function() { + expect(scatterPlot().discActive).toBe(true); + expect(scatterPlot().hasAlpha).toBe(false, 'ring'); + return Plotly.restyle(gd, 'marker.line.width', 0); + }) + .then(function() { + expect(scatterPlot().hasAlpha).toBe(true, 'no outline'); + return Plotly.restyle(gd, {'marker.color': 'rgba(255,0,0,0.5)', 'marker.line.width': 2}); + }) + .then(function() { + expect(scatterPlot().hasAlpha).toBe(true, 'half transparent fill'); + }) + .then(done, done.fail); + }); + + ['disc', 'glyph'].forEach(function(markerrender) { + it('@gl should pick the original point number past a missing point with markerrender ' + markerrender, function(done) { + var hover; + + Plotly.newPlot(gd, [{ + type: 'scatter3d', + mode: 'markers', + x: [null, 0], + y: [0, 0], + z: [0, 0], + marker: {size: 20} + }], { + width: 400, + height: 400, + margin: {l: 0, r: 0, t: 0, b: 0}, + scene: { + markerrender: markerrender, + xaxis: {range: [-1, 1]}, + yaxis: {range: [-1, 1]}, + zaxis: {range: [-1, 1]}, + camera: {projection: {type: 'orthographic'}} + } + }) + .then(delay(20)) + .then(function() { + gd.on('plotly_hover', function(eventData) { hover = eventData.points[0]; }); + mouseEvent('mouseover', 0, 0); + mouseEvent('mouseover', 200, 200); + }) + .then(delay(100)) + .then(function() { + expect(hover).toBeDefined('hover fired'); + expect(hover.pointNumber).toBe(1, 'point number'); + }) + .then(done, done.fail); + }); + }); + }); }); diff --git a/test/plot-schema.json b/test/plot-schema.json index 7ab1ae48d50..4fc83116d33 100644 --- a/test/plot-schema.json +++ b/test/plot-schema.json @@ -6708,6 +6708,17 @@ false ] }, + "markerrender": { + "description": "Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. *auto* draws discs where it can. It draws glyphs for other symbols, for projections on the axes, and for markers that exceed the point size limit of the GPU.", + "dflt": "glyph", + "editType": "plot", + "valType": "enumerated", + "values": [ + "glyph", + "disc", + "auto" + ] + }, "role": "object", "uirevision": { "description": "Controls persistence of user-driven changes in camera attributes. Defaults to `layout.uirevision`.", From 563f8d41bdbf2ac8a4f0624072748ede79ae239a Mon Sep 17 00:00:00 2001 From: Dominik Date: Thu, 3 Dec 2026 23:37:34 -0800 Subject: [PATCH 03/45] Skip the recalc after a range change of constrained axes of regl traces _relayout set flags.calc when a relayout altered the range of an axis in a constraint group. For regl traces, each zoom step then recalculated every trace and uploaded every point again. The replot applies the constraints from the axes. Only an autorange needs the extremes of a new calc. The relayout now sets flags.plot, if every trace is a regl trace and every axis of the group has a fixed range. --- draftlogs/XXXX_change.md | 1 + src/plot_api/plot_api.js | 32 ++++++++++- test/jasmine/tests/gl2d_plot_interact_test.js | 56 +++++++++++++++++++ test/jasmine/tests/plot_api_test.js | 49 ++++++++++++++++ 4 files changed, 137 insertions(+), 1 deletion(-) create mode 100644 draftlogs/XXXX_change.md diff --git a/draftlogs/XXXX_change.md b/draftlogs/XXXX_change.md new file mode 100644 index 00000000000..83d0f64addf --- /dev/null +++ b/draftlogs/XXXX_change.md @@ -0,0 +1 @@ +- Skip the recalculation after a range change of axes with `scaleanchor`, if every trace is a regl trace and the ranges of the constrained axes are fixed [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 5eea5fc4806..ddaa2eab7aa 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -2205,7 +2205,8 @@ function _relayout(gd, aobj) { // specifying arbitrary ranges for all axes in the group. // this way some ranges may expand beyond what's specified, // as they do at first draw, to satisfy the constraints. - flags.calc = true; + // The replot applies the constraints from the axes. A recalc uploads every regl trace again. + flags[constraintsNeedCalc(gd, group) ? 'calc' : 'plot'] = true; for (var groupAxId in group) { if (!rangesAltered[groupAxId]) { Axes.getFromId(gd, groupAxId)._constraintShrinkable = true; @@ -2245,6 +2246,35 @@ function _relayout(gd, aobj) { }; } +/** + * Decide if a relayout that alters the ranges of a constraint group needs a recalc. + * + * @param gd - the graph div + * @param group - the constraint group, keyed by axis id + * @returns false if every trace is a regl trace and every axis of the group has a fixed range, else true + */ +function constraintsNeedCalc(gd, group) { + const fullData = gd._fullData || []; + for (let i = 0; i < fullData.length; i++) { + if (!Registry.traceIs(fullData[i], 'regl')) return true; + } + for (const axId in group) { + const axIn = Axes.getFromId(gd, axId)?._input; + if (!axIn) return true; + const range = axIn.range; + const fixed = + axIn.autorange === false || + (axIn.autorange === undefined && + Array.isArray(range) && + range.length === 2 && + range[0] !== null && + range[1] !== null); + // An autorange needs the extremes of a new calc + if (!fixed) return true; + } + return false; +} + /* * updateAutosize: we made a change, does it change the autosize result? * puts the new size into fullLayout diff --git a/test/jasmine/tests/gl2d_plot_interact_test.js b/test/jasmine/tests/gl2d_plot_interact_test.js index 1ee3b711a77..35d33ef0a49 100644 --- a/test/jasmine/tests/gl2d_plot_interact_test.js +++ b/test/jasmine/tests/gl2d_plot_interact_test.js @@ -622,6 +622,62 @@ describe('Test gl2d plot interactions:', function() { .then(done, done.fail); }); + it('@gl keeps axis constraints on zoom and pan without a recalc', (done) => { + let centerX; + let centerY; + let calcdata; + + function assertScale(msg) { + let xa = gd._fullLayout.xaxis; + let ya = gd._fullLayout.yaxis; + // With scaleratio 2, y has two times the pixels per unit of x + expect(-ya._m).toBeCloseTo(2 * xa._m, 6, msg); + expect(gd.calcdata).toBe(calcdata, 'no recalc - ' + msg); + } + + Plotly.newPlot(gd, [{ + type: 'scattergl', x: [1, 15], y: [1, 15] + }], { + width: 400, + height: 400, + margin: {t: 100, b: 100, l: 100, r: 100}, + xaxis: {range: [-8, 24]}, + yaxis: {range: [0, 16], scaleanchor: 'x', scaleratio: 2} + }) + .then(() => { + let bBox = gd.getBoundingClientRect(); + centerX = bBox.left + 200; + centerY = bBox.top + 200; + calcdata = gd.calcdata; + + return mouseTo([centerX, centerY], [centerX - 1, centerY - 50]); + }) + .then(() => { + expect(gd.layout.xaxis.range).toBeCloseToArray([0, 8], 3); + expect(gd.layout.yaxis.range).toBeCloseToArray([8, 12], 3); + assertScale('zoom'); + + return Plotly.relayout(gd, 'dragmode', 'pan'); + }) + .then(() => { + return mouseTo([centerX, centerY], [centerX + 50, centerY]); + }) + .then(() => { + expect(gd.layout.xaxis.range).toBeCloseToArray([-2, 6], 3); + expect(gd.layout.yaxis.range).toBeCloseToArray([8, 12], 3); + assertScale('pan'); + + return Plotly.relayout(gd, 'xaxis.range', [0, 4]); + }) + .then(() => { + // The y range changes to keep the ratio, about the same center + expect(gd.layout.xaxis.range).toBeCloseToArray([0, 4], 3); + expect(gd.layout.yaxis.range).toBeCloseToArray([9, 11], 3); + assertScale('relayout of one axis'); + }) + .then(done, done.fail); + }); + it('@gl data-referenced annotations should update on drag', function(done) { function assertAnnotation(xy) { var ann = d3Select('g.annotation-text-g').select('g'); diff --git a/test/jasmine/tests/plot_api_test.js b/test/jasmine/tests/plot_api_test.js index 40c75212cda..8b2431109b4 100644 --- a/test/jasmine/tests/plot_api_test.js +++ b/test/jasmine/tests/plot_api_test.js @@ -754,6 +754,55 @@ describe('Test plot api', function () { }) .then(done, done.fail); }); + + it('should trigger replot (but not recalc) on constrained axis range updates when every trace is regl', (done) => { + function regl(layout) { + return mock({ + data: [{type: 'scattergl', x: [1, 2, 3], y: [1, 2, 1]}], + layout: layout + }); + } + function fixed() { + return {xaxis: {range: [0, 4]}, yaxis: {range: [0, 3], scaleanchor: 'x'}}; + } + + gd = regl(fixed()); + Plotly.relayout(gd, 'xaxis.range', [1, 3]) + .then(() => { + expectReplot('range'); + + gd = regl(fixed()); + return Plotly.relayout(gd, {'xaxis.range': [1, 3], 'yaxis.range': [0, 2]}); + }) + .then(() => { + expectReplot('both ranges'); + + gd = regl({xaxis: {}, yaxis: {range: [0, 3], scaleanchor: 'x'}}); + return Plotly.relayout(gd, 'yaxis.range', [0, 2]); + }) + .then(() => { + expect(gd.calcdata).toBeUndefined('an axis of the group autoranges'); + + gd = regl(fixed()); + return Plotly.relayout(gd, 'xaxis.autorange', true); + }) + .then(() => { + expect(gd.calcdata).toBeUndefined('autorange'); + + gd = mock({ + data: [ + {type: 'scattergl', x: [1, 2, 3], y: [1, 2, 1]}, + {x: [1, 2, 3], y: [2, 1, 2]} + ], + layout: fixed() + }); + return Plotly.relayout(gd, 'xaxis.range', [1, 3]); + }) + .then(() => { + expect(gd.calcdata).toBeUndefined('a trace that is not regl'); + }) + .then(done, done.fail); + }); }); describe('Plotly.restyle subroutines switchboard', function () { From 60d91da6cb683f0866bab22f410476bdbb133d6e Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:18:50 -0800 Subject: [PATCH 04/45] Pin gl-plot3d and gl-scatter3d to the forks with order independent transparency The forks add an optional pass that blends translucent objects by depth. Nothing changes until a scene turns it on. Rebuild stackgl_modules/index.js with npm run bundle-stackgl. --- stackgl_modules/index.js | 965 +++++++++++++++++++++++++++++- stackgl_modules/package-lock.json | 10 +- stackgl_modules/package.json | 4 +- 3 files changed, 967 insertions(+), 12 deletions(-) diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index b812d41f949..e984b19404e 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -18665,6 +18665,488 @@ function createCamera(element, options) { } +/***/ }, + +/***/ 2971 +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; + + +// Order independent transparency for gl-plot3d: probe, render targets, composite shader and depth extent. +// The render loop (scene.js) drives the passes; objects draw themselves through obj.drawOIT. + +var createGLShader = __webpack_require__(9405) +var drawTriangle = __webpack_require__(7169) + +// ---- Order independent transparency: per-pixel transmittance binning ---- +// D: anchor pass (nearest transparent depth) + optical-depth pass + colour pass + composite. +// D2: the same without the anchor (global nodes over the depth extent of the transparent data). +// Everything is additive (or MIN for the anchor), so draw order does not matter. +var OIT_VARIANTS = { + 'D8': {K: 8, anchored: true}, + 'D16': {K: 16, anchored: true}, + 'D2-8': {K: 8, anchored: false}, + 'D2-16': {K: 16, anchored: false} +} + +// TEST HOOKS ONLY. window.__plotlyOITTestHooks = {disableExt: ['WEBGL_draw_buffers', ...] (pretend these extensions +// are missing), failAlloc: true (make the render target allocation fail), anchorF32: true (32 bit anchor instead of +// 16 bit), noReuse: true (own colour and depth targets instead of sharing the accumBuffer's), timerLog: [] (record +// per-pass EXT_disjoint_timer_query timers; costs nothing when unset)}. The object is read when a scene is created +// and again on scene.setOIT() / scene.resetOIT(), never per frame. variant: 'D8' | 'D2-8' | 'D2-16' selects another +// node count or the variant without the anchor pass (default 'D16'). Nothing here is a supported API. +var OIT_HOOKS = {} + +function oitLoadHooks() { + OIT_HOOKS = (typeof window !== 'undefined' && window.__plotlyOITTestHooks) || {} +} + +function oitDisabledExt() { + return OIT_HOOKS.disableExt || [] +} + +// getExtension that honours the test hook disableExt +function oitExt(gl, name) { + if(oitDisabledExt().indexOf(name) >= 0) return null + return gl.getExtension(name) +} + +var OIT_VERT = 'precision mediump float;\nattribute vec2 position;\nvoid main() {\n gl_Position = vec4(position, 0, 1);\n}' + +function oitMakeTex(gl, w, h, type) { + var t = gl.createTexture() + gl.bindTexture(gl.TEXTURE_2D, t) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, type, null) + return t +} + +function oitProbeShader(gl, body, withMRT) { + var frag = (withMRT ? '#extension GL_EXT_draw_buffers : require\n' : '') + + 'precision highp float;\nuniform float v;\nvoid main() {\n' + body + '\n}' + return createGLShader(gl, OIT_VERT, frag, null, [{name: 'position', type: 'vec2'}]) +} + +// reads the 2x2 float texture `tex` through a decoding pass into an RGBA8 target +function oitReadTex(gl, decode, rgba8Fbo, tex, scale) { + gl.bindFramebuffer(gl.FRAMEBUFFER, rgba8Fbo) + gl.viewport(0, 0, 2, 2) + gl.disable(gl.BLEND) + gl.activeTexture(gl.TEXTURE0) + gl.bindTexture(gl.TEXTURE_2D, tex) + decode.bind() + decode.uniforms.tex = 0 + decode.uniforms.scale = scale + drawTriangle(gl) + var px = new Uint8Array(4) + gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px) + return px +} + +function oitClose(px, want, tol) { + for(var i = 0; i < 4; ++i) { + if(Math.abs(px[i] - want[i]) > tol) return false + } + return true +} + +// Functional 2x2 render-and-blend test of one float format. Returns what actually works. +function oitTestFormat(gl, type, mm, db) { + var out = {complete: false, add: false, clear: false, minmax: false, mrt: false} + var tmp = [] + var fbo = gl.createFramebuffer() + var fbo2 = gl.createFramebuffer() + var dfbo = gl.createFramebuffer() + var texA = oitMakeTex(gl, 2, 2, type) + var texB = oitMakeTex(gl, 2, 2, type) + var texD = oitMakeTex(gl, 2, 2, gl.UNSIGNED_BYTE) + var decode = null, draw = null, drawMRT = null + try { + while(gl.getError() !== gl.NO_ERROR) { /* flush */ } + gl.bindFramebuffer(gl.FRAMEBUFFER, dfbo) + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texD, 0) + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo) + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texA, 0) + if(gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) return out + out.complete = true + + decode = createGLShader(gl, OIT_VERT, + 'precision highp float;\nuniform sampler2D tex;\nuniform vec4 scale;\nvoid main() {\n gl_FragColor = texture2D(tex, vec2(0.5)) * scale;\n}', + null, [{name: 'position', type: 'vec2'}]) + draw = oitProbeShader(gl, 'gl_FragColor = vec4(v, 2.0 * v, v / 3.0, 1.0);') + + gl.disable(gl.DEPTH_TEST) + gl.disable(gl.CULL_FACE) + gl.colorMask(true, true, true, true) + gl.depthMask(false) + + // 1. additive blending keeps values above 1 and sums three draws + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo) + gl.viewport(0, 0, 2, 2) + gl.clearColor(0, 0, 0, 0) + gl.clear(gl.COLOR_BUFFER_BIT) + gl.enable(gl.BLEND) + gl.blendEquation(gl.FUNC_ADD) + gl.blendFunc(gl.ONE, gl.ONE) + draw.bind() + draw.uniforms.v = 0.75 + for(var i = 0; i < 3; ++i) drawTriangle(gl) + var px = oitReadTex(gl, decode, dfbo, texA, [0.25, 0.125, 0.5, 0.25]) + out.add = oitClose(px, [143, 143, 96, 191], 4) && gl.getError() === gl.NO_ERROR + + // 2. clear values above 1 are kept (the anchor is cleared to a large depth) + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo) + gl.viewport(0, 0, 2, 2) + gl.clearColor(5, 5, 5, 5) + gl.clear(gl.COLOR_BUFFER_BIT) + px = oitReadTex(gl, decode, dfbo, texA, [0.125, 0.125, 0.125, 0.125]) + out.clear = oitClose(px, [159, 159, 159, 159], 4) + + // 3. MIN blending (the anchor) on this format + if(mm) { + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo) + gl.viewport(0, 0, 2, 2) + gl.enable(gl.BLEND) + gl.blendEquation(mm.MIN_EXT) + gl.blendFunc(gl.ONE, gl.ONE) + draw.bind() + draw.uniforms.v = 0.7 + drawTriangle(gl) + draw.uniforms.v = 0.3 + drawTriangle(gl) + draw.uniforms.v = 0.9 + drawTriangle(gl) + gl.blendEquation(gl.FUNC_ADD) + px = oitReadTex(gl, decode, dfbo, texA, [1, 0.5, 1, 1]) + out.minmax = oitClose(px, [77, 77, 26, 255], 4) && gl.getError() === gl.NO_ERROR + } + + // 4. two colour attachments written by one draw (WEBGL_draw_buffers) + if(db && gl.getParameter(db.MAX_DRAW_BUFFERS_WEBGL) >= 2) { + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo2) + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texA, 0) + gl.framebufferTexture2D(gl.FRAMEBUFFER, db.COLOR_ATTACHMENT1_WEBGL, gl.TEXTURE_2D, texB, 0) + if(gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) { + drawMRT = oitProbeShader(gl, 'gl_FragData[0] = vec4(0.5);\n gl_FragData[1] = vec4(0.25);', true) + db.drawBuffersWEBGL([db.COLOR_ATTACHMENT0_WEBGL, db.COLOR_ATTACHMENT1_WEBGL]) + gl.viewport(0, 0, 2, 2) + gl.clearColor(0, 0, 0, 0) + gl.clear(gl.COLOR_BUFFER_BIT) + gl.enable(gl.BLEND) + gl.blendFunc(gl.ONE, gl.ONE) + drawMRT.bind() + drawTriangle(gl) + drawTriangle(gl) + var pa = oitReadTex(gl, decode, dfbo, texA, [0.5, 0.5, 0.5, 0.5]) + var pb = oitReadTex(gl, decode, dfbo, texB, [0.5, 0.5, 0.5, 0.5]) + out.mrt = oitClose(pa, [128, 128, 128, 128], 4) && oitClose(pb, [64, 64, 64, 64], 4) && + gl.getError() === gl.NO_ERROR + } + } + } catch(e) { + out.error = String(e && e.message || e) + } finally { + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + gl.bindTexture(gl.TEXTURE_2D, null) + gl.disable(gl.BLEND) + gl.blendEquation(gl.FUNC_ADD) + gl.deleteFramebuffer(fbo) + gl.deleteFramebuffer(fbo2) + gl.deleteFramebuffer(dfbo) + gl.deleteTexture(texA) + gl.deleteTexture(texB) + gl.deleteTexture(texD) + if(decode) decode.dispose() + if(draw) draw.dispose() + if(drawMRT) drawMRT.dispose() + while(gl.getError() !== gl.NO_ERROR) { /* flush */ } + } + return out +} + +var oitProbeCache = [] + +// Capability probe: functional, per context, cached. Never throws. +function oitProbe(gl) { + var key = oitDisabledExt().join(',') + for(var i = oitProbeCache.length - 1; i >= 0; --i) { + var e = oitProbeCache[i] + if(e.gl.isContextLost()) oitProbeCache.splice(i, 1) + else if(e.gl === gl && e.key === key) return e.result + } + var res + try { + res = oitRunProbe(gl) + } catch(err) { + res = {ok: false, reason: 'probe-failed', error: String(err && err.message || err)} + } + oitProbeCache.push({gl: gl, key: key, result: res}) + return res +} + +function oitRunProbe(gl) { + var res = {ok: false, reason: null, accFmt: null, tauFmt: null, anchorOK: {}, mrtOK: false, maxDraw: 1, tests: {}} + if(typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext) { + res.reason = 'webgl2-context' + return res + } + var hp = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT) + if(!hp || !hp.precision) { + res.reason = 'no-highp-fragment' + return res + } + if(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS) < 6) { + res.reason = 'few-texture-units' + return res + } + var mm = oitExt(gl, 'EXT_blend_minmax') + var db = oitExt(gl, 'WEBGL_draw_buffers') + if(db) res.maxDraw = Math.min(gl.getParameter(db.MAX_DRAW_BUFFERS_WEBGL), gl.getParameter(db.MAX_COLOR_ATTACHMENTS_WEBGL)) + + var hTex = oitExt(gl, 'OES_texture_half_float') + var hCb = oitExt(gl, 'EXT_color_buffer_half_float') + var fTex = oitExt(gl, 'OES_texture_float') + var fCb = oitExt(gl, 'WEBGL_color_buffer_float') + oitExt(gl, 'EXT_float_blend') + var t16 = (hTex && hCb) ? oitTestFormat(gl, hTex.HALF_FLOAT_OES, mm, db) : null + var t32 = (fTex && fCb) ? oitTestFormat(gl, gl.FLOAT, mm, db) : null + res.tests = {f16: t16, f32: t32} + var ok16 = !!(t16 && t16.complete && t16.add) + var ok32 = !!(t32 && t32.complete && t32.add && t32.clear) + if(ok16) res.hType = hTex.HALF_FLOAT_OES + if(ok32) res.fType = gl.FLOAT + if(!ok16 && !ok32) { + res.reason = (!hTex || !hCb) && (!fTex || !fCb) ? 'no-float-target' : + ((t32 && t32.complete && !t32.add) || (t16 && t16.complete && !t16.add)) ? 'no-float-blend' : 'probe-failed' + return res + } + // accumulation (and anchor) in 32 bit floats when they blend, else 16 bit + res.accFmt = ok32 ? 'f32' : 'f16' + // optical depth is safe in 16 bit floats: use them whenever they work + res.tauFmt = ok16 ? 'f16' : 'f32' + res.anchorOK.f32 = !!(ok32 && mm && t32.minmax) + res.anchorOK.f16 = !!(ok16 && mm && t16.minmax && t16.clear) + res.mrtOK = !!(db && ((res.tauFmt === 'f16' ? t16 : t32).mrt)) + res.ok = true + return res +} + +// Optional per-pass GPU timers for measurements (test hook timerLog). +function oitTimerEnd(gl) { + var log = OIT_HOOKS.timerLog + if(!log || !log._open) return + log._open.ext.endQueryEXT(log._open.ext.TIME_ELAPSED_EXT) + log.push(log._open) + log._open = null +} + +function oitTimerBegin(gl, label) { + var log = OIT_HOOKS.timerLog + if(!log) return + var ext = gl.getExtension('EXT_disjoint_timer_query') + if(!ext) return + oitTimerEnd(gl) + var q = ext.createQueryEXT() + ext.beginQueryEXT(ext.TIME_ELAPSED_EXT, q) + log._open = {label: label, q: q, ext: ext} +} + +function oitBytesPerPixel(fmt) { + return fmt === 'f32' ? 16 : 8 +} + +function oitFreeTargets(gl, T) { + if(!T) return + var i + if(T.anchorFbo) gl.deleteFramebuffer(T.anchorFbo) + if(T.anchorTex) gl.deleteTexture(T.anchorTex) + for(i = 0; i < T.tauFbo.length; ++i) gl.deleteFramebuffer(T.tauFbo[i]) + for(i = 0; i < T.tauTex.length; ++i) gl.deleteTexture(T.tauTex[i]) + gl.deleteFramebuffer(T.accFbo) + if(!T.accShared) gl.deleteTexture(T.accTex) + if(T.depthRB) gl.deleteRenderbuffer(T.depthRB) +} + +// Allocates the render targets for one configuration; throws on failure. +function oitAllocTargets(gl, caps, cfg, w, h, accum) { + var T = {accShared: false, w: w, h: h, reusedBytes: 0, anchorFbo: null, anchorTex: null, tauFbo: [], tauTex: [], accFbo: null, accTex: null, depthRB: null, bytes: 0} + var nT = cfg.K / 4 + var db = cfg.db + var typeOf = function(f) { return f === 'f32' ? caps.fType : caps.hType } + try { + if(OIT_HOOKS.failAlloc) throw new Error('forced allocation failure (test hook)') + while(gl.getError() !== gl.NO_ERROR) { /* flush */ } + // memory diet: share the depth buffer (and the float colour buffer) of the legacy accumulation FBO, + // which exists at full size anyway. Its depth is 16 bit, as in today's pass (only used for occlusion). + var sharedDepth = !!(cfg.reuse && accum && (accum.depth || accum._depth_rb)) + var sharedColour = !!(sharedDepth && accum._colorType === gl.FLOAT && cfg.accFmt === 'f32' && accum.color[0]) + if(sharedDepth) accum.shape = [w, h] + var attachDepth + if(sharedDepth) { + attachDepth = function() { + if(accum.depth) gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, accum.depth.handle, 0) + else gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, accum._depth_rb) + } + T.reusedBytes += w * h * 2 + (sharedColour ? w * h * 16 : 0) + } else { + T.depthRB = gl.createRenderbuffer() + gl.bindRenderbuffer(gl.RENDERBUFFER, T.depthRB) + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h) + attachDepth = function() { + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, T.depthRB) + } + T.bytes += w * h * 4 + } + var check = function(what) { + if(gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) throw new Error('incomplete ' + what) + } + if(cfg.anchored) { + T.anchorTex = oitMakeTex(gl, w, h, typeOf(cfg.anchorFmt)) + T.anchorFbo = gl.createFramebuffer() + gl.bindFramebuffer(gl.FRAMEBUFFER, T.anchorFbo) + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, T.anchorTex, 0) + attachDepth() + check('anchor') + T.bytes += w * h * oitBytesPerPixel(cfg.anchorFmt) + } + for(var t = 0; t < nT; ++t) { + T.tauTex.push(oitMakeTex(gl, w, h, typeOf(cfg.tauFmt))) + T.bytes += w * h * oitBytesPerPixel(cfg.tauFmt) + } + if(cfg.mrt) { + var f = gl.createFramebuffer() + T.tauFbo.push(f) + gl.bindFramebuffer(gl.FRAMEBUFFER, f) + for(t = 0; t < nT; ++t) { + gl.framebufferTexture2D(gl.FRAMEBUFFER, db.COLOR_ATTACHMENT0_WEBGL + t, gl.TEXTURE_2D, T.tauTex[t], 0) + } + attachDepth() + check('tau (mrt)') + } else { + for(t = 0; t < nT; ++t) { + var f2 = gl.createFramebuffer() + T.tauFbo.push(f2) + gl.bindFramebuffer(gl.FRAMEBUFFER, f2) + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, T.tauTex[t], 0) + attachDepth() + check('tau') + } + } + if(sharedColour) { + T.accTex = accum.color[0].handle + T.accShared = true + } else { + T.accTex = oitMakeTex(gl, w, h, typeOf(cfg.accFmt)) + T.bytes += w * h * oitBytesPerPixel(cfg.accFmt) + } + T.accFbo = gl.createFramebuffer() + gl.bindFramebuffer(gl.FRAMEBUFFER, T.accFbo) + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, T.accTex, 0) + attachDepth() + check('accumulation') + if(sharedDepth) { + // the accumulation FBO may reallocate its attachments: re-attach when the handles change + var handles = function() { return [accum.depth ? accum.depth.handle : accum._depth_rb, accum.color[0].handle] } + var seen = handles() + T.resync = function() { + accum.shape = [w, h] + var now = handles() + if(now[0] === seen[0] && now[1] === seen[1]) return + seen = now + var fbos = T.tauFbo.concat([T.accFbo]) + if(T.anchorFbo) fbos.push(T.anchorFbo) + for(var i = 0; i < fbos.length; ++i) { + gl.bindFramebuffer(gl.FRAMEBUFFER, fbos[i]) + attachDepth() + } + if(sharedColour) { + T.accTex = now[1] + gl.bindFramebuffer(gl.FRAMEBUFFER, T.accFbo) + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, now[1], 0) + } + } + } + if(gl.getError() !== gl.NO_ERROR) throw new Error('gl error while allocating') + } catch(e) { + oitFreeTargets(gl, T) + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + gl.bindRenderbuffer(gl.RENDERBUFFER, null) + gl.bindTexture(gl.TEXTURE_2D, null) + throw e + } + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + gl.bindRenderbuffer(gl.RENDERBUFFER, null) + gl.bindTexture(gl.TEXTURE_2D, null) + return T +} + +function oitCompositeSrc(K) { + var s = 'precision highp float;\nuniform sampler2D oitAcc;\nuniform vec2 oitInvSize;\n' + var i, nT = K / 4 + for(i = 0; i < nT; ++i) s += 'uniform sampler2D oitTau' + i + ';\n' + s += 'void main() {\n vec2 uv = gl_FragCoord.xy * oitInvSize;\n float S = 0.0;\n' + for(i = 0; i < nT; ++i) { + s += ' vec4 t' + i + ' = texture2D(oitTau' + i + ', uv);\n S += t' + i + '.x + t' + i + '.y + t' + i + '.z + t' + i + '.w;\n' + } + s += ' if(S <= 0.0) discard;\n float A = 1.0 - exp(-S);\n vec4 acc = texture2D(oitAcc, uv);\n' + s += ' gl_FragColor = vec4(acc.rgb / max(acc.a, 1e-30) * A, A);\n}\n' + return s +} + +// Depth (distance along the view direction) range of the transparent data's bounding boxes. +function oitDepthExtent(objs, cp, sceneBounds) { + var m = cp.model, v = cp.view + var mn = Infinity, mx = -Infinity + for(var i = 0; i < objs.length; ++i) { + var b = objs[i].bounds + if(!b) continue + var lo = [0, 0, 0], hi = [0, 0, 0] + var useScene = objs[i].projectHasAlpha + for(var j = 0; j < 3; ++j) { + lo[j] = useScene ? sceneBounds[0][j] : Math.max(b[0][j], sceneBounds[0][j]) + hi[j] = useScene ? sceneBounds[1][j] : Math.min(b[1][j], sceneBounds[1][j]) + } + if(lo[0] > hi[0] || lo[1] > hi[1] || lo[2] > hi[2]) continue + for(var c = 0; c < 8; ++c) { + var x = (c & 1) ? hi[0] : lo[0] + var y = (c & 2) ? hi[1] : lo[1] + var z = (c & 4) ? hi[2] : lo[2] + var wx = m[0] * x + m[4] * y + m[8] * z + m[12] + var wy = m[1] * x + m[5] * y + m[9] * z + m[13] + var wz = m[2] * x + m[6] * y + m[10] * z + m[14] + var ww = m[3] * x + m[7] * y + m[11] * z + m[15] + var d = -(v[2] * wx + v[6] * wy + v[10] * wz + v[14] * ww) + if(d < mn) mn = d + if(d > mx) mx = d + } + } + if(!(mn <= mx)) { mn = 0; mx = 1 } + var range = Math.max(mx - mn, 1e-6) + return {min: mn, inv: 1 / range} +} + +module.exports = { + OIT_VARIANTS: OIT_VARIANTS, + loadHooks: oitLoadHooks, + hooks: function() { return OIT_HOOKS }, + ext: oitExt, + probe: oitProbe, + probeCache: oitProbeCache, + freeTargets: oitFreeTargets, + allocTargets: oitAllocTargets, + compositeSrc: oitCompositeSrc, + depthExtent: oitDepthExtent, + timerBegin: oitTimerBegin, + timerEnd: oitTimerEnd, + VERT: OIT_VERT, + createGLShader: createGLShader +} + + /***/ }, /***/ 799 @@ -18700,6 +19182,7 @@ var mouseChange = __webpack_require__(351) var perspective = __webpack_require__(4772) var ortho = __webpack_require__(4040) var createShader = __webpack_require__(799) +var oit = __webpack_require__(2971) var isMobile = __webpack_require__(2431)({ tablet: true, featureDetect: true }) module.exports = { @@ -18751,6 +19234,7 @@ function defaultBool(x) { } function createScene(options) { + oit.loadHooks() options = options || {} options.camera = options.camera || {} @@ -19054,6 +19538,8 @@ function createScene(options) { } //Clean up buffers + oitRelease() + if(oitState.composite) oitState.composite.shader.dispose() accumBuffer.dispose() for(var i=0; i= 0; --i) { + if(oit.probeCache[i].gl === gl) oit.probeCache.splice(i, 1) + } + oitState.cfg = null + oitState.failedSize = null + dirty = true + } + + // Decide the configuration for the requested mode and the probed capabilities. + function oitConfigure() { + var caps = oit.probe(gl) + if(!caps.ok) return {cfg: null, reason: caps.reason} + var name = oit.hooks().variant || 'D16' + var v = oit.OIT_VARIANTS[name] || oit.OIT_VARIANTS.D16 + var cfg = {variant: name, K: v.K, anchored: v.anchored, accFmt: caps.accFmt, tauFmt: caps.tauFmt, caps: caps, notes: []} + cfg.mm = oit.ext(gl, 'EXT_blend_minmax') + cfg.db = oit.ext(gl, 'WEBGL_draw_buffers') + // anchor in 16 bit floats unless asked otherwise (memory); test hook anchorF32 + cfg.anchorFmt = oit.hooks().anchorF32 ? cfg.accFmt : (caps.anchorOK.f16 ? 'f16' : cfg.accFmt) + cfg.reuse = !oit.hooks().noReuse + if(cfg.anchored && !caps.anchorOK[cfg.anchorFmt]) { + cfg.anchored = false + cfg.notes.push('no-minmax-anchor') + cfg.variant = 'D2-' + cfg.K + } + cfg.mrt = !!(caps.mrtOK && cfg.db && caps.maxDraw >= cfg.K / 4) + cfg.tier = !cfg.mrt ? 3 : (cfg.accFmt === 'f32' ? 1 : 2) + var nT = cfg.K / 4 + cfg.passes = (cfg.anchored ? 1 : 0) + (cfg.mrt ? 1 : nT) + 1 + return {cfg: cfg, reason: cfg.notes.length ? cfg.notes.join(',') : null} + } + + var OIT_LEGACY = function(reason, mixed) { + return {mode: 'legacy', variant: null, tier: 4, reason: reason, format: null, mrt: false, nodes: 0, passes: 1, mixed: !!mixed, targetBytes: 0} + } + + // Returns true if this frame's transparent OIT objects should use the OIT passes. + function oitPrepare(width, height) { + if(oitState.mode === 'off') { + oitSetStatus(OIT_LEGACY('off')) + return false + } + if(!oitState.cfg && !oitState.reason) { + var c = oitConfigure() + oitState.cfg = c.cfg + oitState.reason = c.reason + // the probe leaves GL state behind; put the opaque pass state back + oitRestoreState(width, height) + } + var cfg = oitState.cfg + if(!cfg) { + oitSetStatus(OIT_LEGACY(oitState.reason)) + return false + } + var T = oitState.targets + var sizeKey = width + 'x' + height + if(!T && oitState.failedSize === sizeKey) { + oitSetStatus(OIT_LEGACY('alloc-failed')) + return false + } + if(!T || T.w !== width || T.h !== height) { + oitRelease() + try { + oitState.targets = oit.allocTargets(gl, cfg.caps, cfg, width, height, accumBuffer) + } catch(e) { + // no MRT, then give up for this size + if(cfg.mrt) { + cfg.mrt = false + cfg.tier = 3 + cfg.passes = (cfg.anchored ? 1 : 0) + cfg.K / 4 + 1 + cfg.notes.push('mrt-alloc-failed') + try { + oitState.targets = oit.allocTargets(gl, cfg.caps, cfg, width, height, accumBuffer) + } catch(e2) { + oitState.targets = null + } + } + if(!oitState.targets) { + oitRestoreState(width, height) + oitState.failedSize = sizeKey + oitSetStatus(OIT_LEGACY('alloc-failed')) + return false + } + } + oitRestoreState(width, height) + if(cfg.accFmt && !cfg.formatStr) { + cfg.formatStr = 'acc=' + cfg.accFmt + ',tau=' + cfg.tauFmt + (cfg.anchored ? ',anchor=' + cfg.anchorFmt : '') + (cfg.reuse ? ',shared=accumBuffer' : '') + } + } + oitSetStatus({ + mode: cfg.anchored ? 'D' : 'D2', + variant: cfg.variant, + tier: cfg.tier, + reason: cfg.notes.length ? cfg.notes.join(',') : null, + format: cfg.formatStr, + mrt: cfg.mrt, + nodes: cfg.K, + passes: cfg.passes, + mixed: !!oitState.mixed, + targetBytes: oitState.targets.bytes, + reusedBytes: oitState.targets.reusedBytes + }) + return true + } + + function oitRestoreState(width, height) { + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + gl.viewport(0, 0, width, height) + gl.disable(gl.BLEND) + gl.blendEquation(gl.FUNC_ADD) + gl.colorMask(true, true, true, true) + gl.depthMask(true) + gl.enable(gl.DEPTH_TEST) + gl.depthFunc(gl.LEQUAL) + gl.disable(gl.CULL_FACE) + gl.activeTexture(gl.TEXTURE0) + gl.bindTexture(gl.TEXTURE_2D, null) + } + + function oitDrawObjs(objs, ctx) { + for(var i = 0; i < objs.length; ++i) { + objs[i].drawOIT(cameraParams, ctx) + } + } + + function renderOIT(objs, width, height) { + var cfg = oitState.cfg + var T = oitState.targets + var db = cfg.db + var nT = cfg.K / 4 + var t + var ext = oit.depthExtent(objs, cameraParams, scene.bounds) + var ctx = { + pass: 0, K: cfg.K, anchored: cfg.anchored, mrt: cfg.mrt, group: 0, + map: [ext.min, ext.inv], invSize: [1 / width, 1 / height], + anchorUnit: 0, tauUnit: 1 + } + var depthFbo = cfg.anchored ? T.anchorFbo : T.tauFbo[0] + if(T.resync) T.resync() + + gl.viewport(0, 0, width, height) + + oit.timerBegin(gl, 'depth') + //1. depth of the opaque objects (as the legacy pre-pass does), into the shared depth buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, depthFbo) + gl.enable(gl.DEPTH_TEST) + gl.disable(gl.BLEND) + gl.colorMask(false, false, false, false) + gl.depthMask(true) + gl.depthFunc(gl.LESS) + gl.clear(gl.DEPTH_BUFFER_BIT) + if(axes.enable && axes.isTransparent()) { + axes.drawTransparent(cameraParams) + } + for(var i = 0; i < numObjsNow(); ++i) { + var o = objects[i] + if(o.isOpaque && o.isOpaque()) o.draw(cameraParams) + } + + gl.colorMask(true, true, true, true) + gl.depthMask(false) + gl.enable(gl.BLEND) + + //2. anchor: nearest transparent depth per pixel (MIN blending) + oit.timerBegin(gl, 'anchor') + if(cfg.anchored) { + gl.bindFramebuffer(gl.FRAMEBUFFER, T.anchorFbo) + gl.clearColor(1000, 1000, 1000, 1000) + gl.clear(gl.COLOR_BUFFER_BIT) + gl.blendEquation(cfg.mm.MIN_EXT) + gl.blendFunc(gl.ONE, gl.ONE) + ctx.pass = 0 + oitDrawObjs(objs, ctx) + gl.blendEquation(gl.FUNC_ADD) + } + + //3. optical depth tau = -ln(1-alpha), tent-splatted into K nodes + oit.timerBegin(gl, 'tau') + gl.blendFunc(gl.ONE, gl.ONE) + gl.clearColor(0, 0, 0, 0) + if(cfg.anchored) { + gl.activeTexture(gl.TEXTURE0) + gl.bindTexture(gl.TEXTURE_2D, T.anchorTex) + } + ctx.pass = 1 + if(cfg.mrt) { + var list = [] + for(t = 0; t < nT; ++t) list.push(db.COLOR_ATTACHMENT0_WEBGL + t) + gl.bindFramebuffer(gl.FRAMEBUFFER, T.tauFbo[0]) + db.drawBuffersWEBGL(list) + gl.clear(gl.COLOR_BUFFER_BIT) + oitDrawObjs(objs, ctx) + } else { + for(t = 0; t < nT; ++t) { + gl.bindFramebuffer(gl.FRAMEBUFFER, T.tauFbo[t]) + gl.clear(gl.COLOR_BUFFER_BIT) + ctx.group = t + oitDrawObjs(objs, ctx) + } + ctx.group = 0 + } + + //4. colour weighted by the transmittance in front of each fragment, accumulated + oit.timerBegin(gl, 'colour') + for(t = 0; t < nT; ++t) { + gl.activeTexture(gl.TEXTURE1 + t) + gl.bindTexture(gl.TEXTURE_2D, T.tauTex[t]) + } + gl.bindFramebuffer(gl.FRAMEBUFFER, T.accFbo) + gl.clear(gl.COLOR_BUFFER_BIT) + ctx.pass = 2 + oitDrawObjs(objs, ctx) + + //5. composite over the screen: normalise, apply the exact coverage 1 - exp(-sum tau) + oit.timerBegin(gl, 'composite') + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + gl.disable(gl.DEPTH_TEST) + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + if(!oitState.composite || oitState.composite.K !== cfg.K) { + if(oitState.composite) oitState.composite.shader.dispose() + oitState.composite = { + K: cfg.K, + shader: oit.createGLShader(gl, oit.VERT, oit.compositeSrc(cfg.K), null, [{name: 'position', type: 'vec2'}]) + } + } + var cs = oitState.composite.shader + cs.bind() + gl.activeTexture(gl.TEXTURE0) + gl.bindTexture(gl.TEXTURE_2D, T.accTex) + cs.uniforms.oitAcc = 0 + cs.uniforms.oitInvSize = ctx.invSize + for(t = 0; t < nT; ++t) cs.uniforms['oitTau' + t] = 1 + t + drawTriangle(gl) + + for(t = nT; t >= 0; --t) { + gl.activeTexture(gl.TEXTURE0 + t) + gl.bindTexture(gl.TEXTURE_2D, null) + } + gl.activeTexture(gl.TEXTURE0) + gl.disable(gl.BLEND) + oit.timerEnd(gl) + } + + function numObjsNow() { + return objects.length + } + function redraw() { if(checkContextLoss()) { return @@ -19398,6 +20182,28 @@ function createScene(options) { } if(hasTransparent) { + // objects that can draw order independently are split off + var oitObjs = [] + var legacyObjs = false + for(var i=0; i 0) { + oitUse = oitPrepare(width, height) + } else { + oitSetStatus(OIT_LEGACY(oitState.mode === 'off' ? 'off' : 'no-oit-objects')) + } + + if(!oitUse || legacyObjs || axes.isTransparent()) { //Render transparent pass accumBuffer.shape = viewShape accumBuffer.bind() @@ -19432,7 +20238,7 @@ function createScene(options) { for(var i=0; i 0 && o.anchored) s += 'uniform sampler2D oitAnchor;\n' + if(o.pass === 2) { + for(i = 0; i < T; ++i) s += 'uniform sampler2D oitTau' + i + ';\n' + } + s += 'varying vec4 interpColor;\nvarying vec3 dataCoordinate;\nvarying float oitZ;\n' + + if(o.pass > 0) { + // node coordinate in [0, K-1]: log-plus-linear warp of the distance to the anchor (D), + // or linear in the depth extent of the transparent data (D2) + s += 'float oitX(float f) {\n' + if(o.anchored) { + var Klog = K === 8 ? 4 : 8 + var delta = K === 8 ? 1 / 1024 : 1 / 8192 + s += ' float u = max(f - texture2D(oitAnchor, gl_FragCoord.xy * oitInvSize).r, 0.0);\n' + s += ' float x = ' + f1(Klog) + ' * log(1.0 + u * ' + f1(1 / delta) + ') / ' + f1(Math.log(1 + 1 / delta)) + ' + ' + f1(K - 1 - Klog) + ' * u;\n' + } else { + s += ' float x = clamp(f, 0.0, 1.0) * ' + f1(K - 1) + ';\n' + } + s += ' return clamp(x, 0.0, ' + f1(K - 1) + ');\n}\n' + } + if(o.pass === 2) { + s += 'float oitPhi(float N) {\n return N < 0.01 ? 1.0 - N * (0.5 - N * (0.16666667 - N * 0.041666668)) : (1.0 - exp(-N)) / N;\n}\n' + } + + s += 'void main() {\n' + s += ' if (outOfRange(fragClipBounds[0], fragClipBounds[1], dataCoordinate) || interpColor.a * opacity == 0.) discard;\n' + s += ' float f = (-oitZ - oitMap.x) * oitMap.y;\n' + if(o.pass === 0) { + s += ' gl_FragColor = vec4(f, f, f, f);\n}\n' + return s + } + s += ' float a = min(interpColor.a * opacity, 0.99609375);\n' + s += ' float tau = -log(1.0 - a);\n' + s += ' float x = oitX(f);\n' + s += ' float k = min(floor(x), ' + f1(K - 2) + ');\n' + s += ' float fr = x - k;\n' + if(o.pass === 1) { + var tent = function(nv) { + return 'tau * ((1.0 - fr) * (1.0 - step(0.5, abs(' + nv + ' - k))) + fr * (1.0 - step(0.5, abs(' + nv + ' - k - 1.0))))' + } + if(o.mrt) { + for(i = 0; i < T; ++i) { + s += ' gl_FragData[' + i + '] = ' + tent('(vec4(0.0, 1.0, 2.0, 3.0) + ' + f1(4 * i) + ')') + ';\n' + } + } else { + s += ' gl_FragColor = ' + tent('(vec4(0.0, 1.0, 2.0, 3.0) + 4.0 * oitGroup)') + ';\n' + } + s += '}\n' + return s + } + // colour pass: telescoping weights from the optical-depth nodes + s += ' vec2 uv = gl_FragCoord.xy * oitInvSize;\n' + s += ' float Tb = 1.0, Wk = 0.0, Wk1 = 0.0, N, W;\n' + for(i = 0; i < T; ++i) { + s += ' vec4 t' + i + ' = texture2D(oitTau' + i + ', uv);\n' + for(c = 0; c < 4; ++c) { + j = 4 * i + c + s += ' N = t' + i + '.' + 'xyzw'.charAt(c) + '; W = Tb * oitPhi(N);\n' + s += ' if(abs(k - ' + f1(j) + ') < 0.5) Wk = W;\n' + s += ' if(abs(k + 1.0 - ' + f1(j) + ') < 0.5) Wk1 = W;\n' + s += ' Tb *= exp(-N);\n' + } + } + s += ' float w = tau * ((1.0 - fr) * Wk + fr * Wk1);\n' + s += ' gl_FragColor = vec4(interpColor.rgb * w, w);\n}\n' + return s +} + +var oitShaderCache = [] + +// o: {pass: 0|1|2, K, anchored, mrt} +function getOITShaders(gl, o) { + var entry = null + for(var i = oitShaderCache.length - 1; i >= 0; --i) { + if(oitShaderCache[i].gl === gl) entry = oitShaderCache[i] + else if(oitShaderCache[i].gl.isContextLost()) oitShaderCache.splice(i, 1) + } + if(!entry) { + entry = {gl: gl, map: {}} + oitShaderCache.push(entry) + } + var key = o.pass === 0 ? '0' : [o.pass, o.K, o.anchored ? 1 : 0, o.mrt ? 1 : 0].join('-') + if(!entry.map[key]) { + var frag = oitFragSrc(o) + var mk = function(vert) { + return createShader(gl, {vertex: vert, fragment: frag, attributes: ATTRIBUTES}) + } + entry.map[key] = { + perspective: mk(oitPatchVertex(perspectiveVertSrc, 'dataCoordinate = position;', 'viewPosition.z')), + ortho: mk(oitPatchVertex(orthographicVertSrc, 'dataCoordinate = position;', 'viewPosition.z')), + project: mk(oitPatchVertex(projectionVertSrc, 'dataCoordinate = dataPosition;', '(view * (model * vec4(dataPosition, 1))).z')) + } + } + return entry.map[key] +} + + +exports.getOITShaders = getOITShaders + /***/ }, @@ -19980,7 +20915,7 @@ function getClipBounds(bounds) { return result } -function drawProject(shader, points, camera, pixelRatio) { +function drawProject(shader, points, camera, pixelRatio, oit) { var axesProject = points.axesProject var gl = points.gl @@ -20002,6 +20937,7 @@ function drawProject(shader, points, camera, pixelRatio) { VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight shader.bind() + if(oit) setOITUniforms(shader, oit) uniforms.view = view uniforms.projection = projection uniforms.screenSize = VIEW_SHAPE @@ -20099,17 +21035,18 @@ var NEG_INFINITY3 = [-1e8, -1e8, -1e8] var POS_INFINITY3 = [1e8, 1e8, 1e8] var CLIP_GROUP = [NEG_INFINITY3, POS_INFINITY3] -function drawFull(shader, pshader, points, camera, pixelRatio, transparent, forceDraw) { +function drawFull(shader, pshader, points, camera, pixelRatio, transparent, forceDraw, oit) { var gl = points.gl if(transparent === points.projectHasAlpha || forceDraw) { - drawProject(pshader, points, camera, pixelRatio) + drawProject(pshader, points, camera, pixelRatio, oit) } if(transparent === points.hasAlpha || forceDraw) { shader.bind() var uniforms = shader.uniforms + if(oit) setOITUniforms(shader, oit) uniforms.model = camera.model || IDENTITY uniforms.view = camera.view || IDENTITY @@ -20157,6 +21094,26 @@ proto.drawTransparent = function(camera) { drawFull(shader, this.projectShader, this, camera, this.pixelRatio, true, false) } +// ---- draw this object into one of the order independent passes ---- +proto.isOIT = true + +function setOITUniforms(shader, oit) { + var u = shader.uniforms + u.oitMap = oit.map + u.oitInvSize = oit.invSize + u.oitGroup = oit.group + if(oit.pass > 0 && oit.anchored) u.oitAnchor = oit.anchorUnit + if(oit.pass === 2) { + for(var i = 0; i < oit.K / 4; ++i) u['oitTau' + i] = oit.tauUnit + i + } +} + +proto.drawOIT = function(camera, oit) { + var sh = shaders.getOITShaders(this.gl, oit) + var shader = this.useOrtho ? sh.ortho : sh.perspective + drawFull(shader, sh.project, this, camera, this.pixelRatio, true, false, oit) +} + proto.drawPick = function(camera) { var shader = this.useOrtho ? this.pickOrthoShader : this.pickPerspectiveShader drawFull(shader, this.pickProjectShader, this, camera, 1, true, true) diff --git a/stackgl_modules/package-lock.json b/stackgl_modules/package-lock.json index 0961819ddab..8a14bf524b6 100644 --- a/stackgl_modules/package-lock.json +++ b/stackgl_modules/package-lock.json @@ -16,8 +16,8 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "^2.4.7", - "gl-scatter3d": "^1.4.1", + "gl-plot3d": "github:settylab/gl-plot3d#bb627feee546a8caf13f21e4c91271643f85c1fa", + "gl-scatter3d": "github:settylab/gl-scatter3d#c557d17091c96b5c674a1c67d10db378f3ae54b3", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", "gl-streamtube3d": "^1.4.2", @@ -1312,8 +1312,7 @@ }, "node_modules/gl-plot3d": { "version": "2.4.7", - "resolved": "https://registry.npmjs.org/gl-plot3d/-/gl-plot3d-2.4.7.tgz", - "integrity": "sha512-mLDVWrl4Dj0O0druWyHUK5l7cBQrRIJRn2oROEgrRuOgbbrLAzsREKefwMO0bA0YqkiZMFMnV5VvPA9j57X5Xg==", + "resolved": "git+ssh://git@github.com/settylab/gl-plot3d.git#bb627feee546a8caf13f21e4c91271643f85c1fa", "license": "MIT", "dependencies": { "3d-view": "^2.0.0", @@ -1347,8 +1346,7 @@ }, "node_modules/gl-scatter3d": { "version": "1.4.1", - "resolved": "https://registry.npmjs.org/gl-scatter3d/-/gl-scatter3d-1.4.1.tgz", - "integrity": "sha512-v2nQWSPr9/smu2YB4erhHuUkk+8w2q59CsTPvcK72vFYWCSgU6eeTnu0UlmN634bblbTTa5ap/xrbxJGiKLyrw==", + "resolved": "git+ssh://git@github.com/settylab/gl-scatter3d.git#c557d17091c96b5c674a1c67d10db378f3ae54b3", "license": "MIT", "dependencies": { "gl-buffer": "^2.1.2", diff --git a/stackgl_modules/package.json b/stackgl_modules/package.json index a145e05bf6b..006bc19b529 100644 --- a/stackgl_modules/package.json +++ b/stackgl_modules/package.json @@ -19,8 +19,8 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "^2.4.7", - "gl-scatter3d": "^1.4.1", + "gl-plot3d": "github:settylab/gl-plot3d#bb627feee546a8caf13f21e4c91271643f85c1fa", + "gl-scatter3d": "github:settylab/gl-scatter3d#c557d17091c96b5c674a1c67d10db378f3ae54b3", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", "gl-streamtube3d": "^1.4.2", From 426f2b82f013b433d28907e20a9f2574666ade6e Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:18:50 -0800 Subject: [PATCH 05/45] Add scene.oit to blend translucent scatter3d markers by depth Translucent markers blend in draw order, so the last trace lies on top from every camera angle. With scene.oit set to auto, the markers blend by depth and the draw order has no effect. The default is off and keeps the existing pass and pixels. The scene reports the result with getOITStatus() and the plotly_oitstatus event. --- draftlogs/XXXX_add.md | 1 + src/plots/gl3d/layout/defaults.js | 1 + src/plots/gl3d/layout/layout_attributes.js | 16 ++ src/plots/gl3d/scene.js | 18 ++ src/types/generated/schema.d.ts | 5 + test/jasmine/tests/gl3dlayout_test.js | 14 ++ test/jasmine/tests/scatter3d_test.js | 197 +++++++++++++++++++++ test/plot-schema.json | 10 ++ 8 files changed, 262 insertions(+) create mode 100644 draftlogs/XXXX_add.md diff --git a/draftlogs/XXXX_add.md b/draftlogs/XXXX_add.md new file mode 100644 index 00000000000..943d469f43e --- /dev/null +++ b/draftlogs/XXXX_add.md @@ -0,0 +1 @@ +- Add `scene.oit` to blend translucent `scatter3d` markers by depth in place of draw order [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/src/plots/gl3d/layout/defaults.js b/src/plots/gl3d/layout/defaults.js index 311ad2fe919..eecbf6446f3 100644 --- a/src/plots/gl3d/layout/defaults.js +++ b/src/plots/gl3d/layout/defaults.js @@ -51,6 +51,7 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { */ var bgcolor = coerce('bgcolor'); + coerce('oit'); var bgColorCombined = Color.combine(bgcolor, opts.paper_bgcolor); var cameraKeys = ['up', 'center', 'eye']; diff --git a/src/plots/gl3d/layout/layout_attributes.js b/src/plots/gl3d/layout/layout_attributes.js index 3666d33e741..79b1d629eec 100644 --- a/src/plots/gl3d/layout/layout_attributes.js +++ b/src/plots/gl3d/layout/layout_attributes.js @@ -150,6 +150,22 @@ module.exports = { 'Determines the mode of hover interactions for this scene.' ].join(' ') }, + oit: { + valType: 'enumerated', + values: ['off', 'auto'], + dflt: 'off', + editType: 'plot', + description: [ + 'Determines how translucent `scatter3d` markers blend.', + 'With *off*, the markers blend in draw order.', + 'The picture then depends on the order of the traces and of the points.', + 'With *auto*, the markers blend by depth and the draw order has no effect.', + 'This uses extra render passes and float render targets.', + 'The targets need memory in proportion to the size of the plot.', + 'If the graphics hardware lacks a feature, plotly.js falls back to *off*.', + 'The scene reports the result in `getOITStatus()` and in the `plotly_oitstatus` event.' + ].join(' ') + }, uirevision: { valType: 'any', editType: 'none', diff --git a/src/plots/gl3d/scene.js b/src/plots/gl3d/scene.js index e320fe9e780..2c912149bfd 100644 --- a/src/plots/gl3d/scene.js +++ b/src/plots/gl3d/scene.js @@ -293,9 +293,21 @@ proto.initializeGLPlot = function() { scene.render(); }; + scene.glplot.onoitstatus = function(status) { + var gd = scene.graphDiv; + if(gd && gd.emit) gd.emit('plotly_oitstatus', Lib.extendFlat({scene: scene.id}, status)); + }; + scene.oitMode = scene.fullSceneLayout.oit; + scene.glplot.setOIT(scene.oitMode); + return true; }; +// order independent transparency status: {mode, tier, reason, format, mrt, nodes, passes, ...} +proto.getOITStatus = function() { + return this.glplot && this.glplot.getOITStatus ? this.glplot.getOITStatus() : null; +}; + proto.render = function() { var scene = this; var gd = scene.graphDiv; @@ -583,6 +595,12 @@ proto.plot = function(sceneData, fullLayout, layout) { // Update scene background scene.glplot.setClearColor(str2RGBAarray(fullSceneLayout.bgcolor)); + // Update order independent transparency mode + if(scene.oitMode !== fullSceneLayout.oit) { + scene.oitMode = fullSceneLayout.oit; + scene.glplot.setOIT(scene.oitMode); + } + // Update axes functions BEFORE updating traces scene.setConvert(axis); diff --git a/src/types/generated/schema.d.ts b/src/types/generated/schema.d.ts index 853b8c815f9..d47452f3464 100644 --- a/src/types/generated/schema.d.ts +++ b/src/types/generated/schema.d.ts @@ -13742,6 +13742,11 @@ export interface Scene { * @default 'closest' */ hovermode?: 'closest' | false; + /** + * Determines how translucent `scatter3d` markers blend. With *off*, the markers blend in draw order. The picture then depends on the order of the traces and of the points. With *auto*, the markers blend by depth and the draw order has no effect. This uses extra render passes and float render targets. The targets need memory in proportion to the size of the plot. If the graphics hardware lacks a feature, plotly.js falls back to *off*. The scene reports the result in `getOITStatus()` and in the `plotly_oitstatus` event. + * @default 'off' + */ + oit?: 'off' | 'auto'; /** Controls persistence of user-driven changes in camera attributes. Defaults to `layout.uirevision`. */ uirevision?: any; xaxis?: { diff --git a/test/jasmine/tests/gl3dlayout_test.js b/test/jasmine/tests/gl3dlayout_test.js index 75d271f7b6c..3ac1e679a8b 100644 --- a/test/jasmine/tests/gl3dlayout_test.js +++ b/test/jasmine/tests/gl3dlayout_test.js @@ -341,6 +341,20 @@ describe('Test Gl3d layout defaults', function() { .toBe('closest', 'to default if not valid'); }); + it('should coerce oit', function() { + layoutIn = { scene: {} }; + supplyLayoutDefaults(layoutIn, layoutOut, fullData); + expect(layoutOut.scene.oit).toBe('off', 'to off by default'); + + layoutIn = { scene: { oit: 'auto' } }; + supplyLayoutDefaults(layoutIn, layoutOut, fullData); + expect(layoutOut.scene.oit).toBe('auto', 'to user val if valid'); + + layoutIn = { scene: { oit: 'sorted' } }; + supplyLayoutDefaults(layoutIn, layoutOut, fullData); + expect(layoutOut.scene.oit).toBe('off', 'to off if invalid'); + }); + it('should add data-only scenes into layoutIn', function() { layoutIn = {}; fullData = [{ type: 'scatter3d', scene: 'scene' }]; diff --git a/test/jasmine/tests/scatter3d_test.js b/test/jasmine/tests/scatter3d_test.js index a5f1a7f8b4d..96f6e818d0e 100644 --- a/test/jasmine/tests/scatter3d_test.js +++ b/test/jasmine/tests/scatter3d_test.js @@ -345,4 +345,201 @@ describe('Test scatter3d interactions:', function() { }) .then(done, done.fail); }); + + describe('order independent transparency', function() { + // a red marker at z=+0.5 and a blue marker at z=-0.5 on the line of sight + function plot(eyez, opacity, oit) { + const scene = { + xaxis: { range: [-1, 1], visible: false }, + yaxis: { range: [-1, 1], visible: false }, + zaxis: { range: [-1, 1], visible: false }, + bgcolor: 'white', + aspectmode: 'cube', + camera: { + eye: { x: 0, y: 0, z: eyez }, + up: { x: 0, y: 1, z: 0 }, + projection: { type: 'orthographic' } + } + }; + if (oit) scene.oit = oit; + return Plotly.react( + gd, + [ + { + type: 'scatter3d', + mode: 'markers', + x: [0, 0], + y: [0, 0], + z: [0.5, -0.5], + marker: { size: 60, opacity: opacity, color: ['red', 'blue'], line: { width: 0 } } + } + ], + { + width: 400, + height: 400, + margin: { l: 0, r: 0, t: 0, b: 0 }, + paper_bgcolor: 'white', + uirevision: Math.random(), + scene: scene + } + ).then(delay(400)); + } + + const glplot = () => gd._fullLayout.scene._scene.glplot; + const status = () => gd._fullLayout.scene._scene.getOITStatus(); + + function readPixels() { + const gl = glplot().gl; + glplot().redraw(); + const px = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, px); + return px; + } + + // mean colour of the 11 by 11 pixels at the centre + function centre() { + const gl = glplot().gl; + glplot().redraw(); + const px = new Uint8Array(11 * 11 * 4); + gl.readPixels((gl.drawingBufferWidth / 2 | 0) - 5, (gl.drawingBufferHeight / 2 | 0) - 5, 11, 11, gl.RGBA, gl.UNSIGNED_BYTE, px); + const mean = [0, 0, 0]; + for (let i = 0; i < 121; i++) for (let c = 0; c < 3; c++) mean[c] += px[4 * i + c] / 121; + return mean; + } + + function expectNear(got, want) { + for (let i = 0; i < 3; i++) expect(got[i]).toBeCloseTo(want[i], -0.8, 'channel ' + i + ': ' + got + ' vs ' + want); + } + + afterEach(function() { + window.__plotlyOITTestHooks = null; + }); + + it('@gl scene.oit auto orders red over blue from either side', function(done) { + plot(2.5, 0.5, 'auto') + .then(function() { + expect(status().mode).toBe('D'); + expectNear(centre(), [192, 64, 128]); + return plot(-2.5, 0.5, 'auto'); + }) + .then(function() { + expectNear(centre(), [128, 64, 192]); + }) + .then(done, done.fail); + }); + + it('@gl scene.oit auto gives the exact over operator at opacity 0.3 and 0.8', function(done) { + plot(2.5, 0.3, 'auto') + .then(function() { + expectNear(centre(), [201, 125, 179]); + return plot(2.5, 0.8, 'auto'); + }) + .then(function() { + expectNear(centre(), [214, 10, 51]); + }) + .then(done, done.fail); + }); + + it('@gl scene.oit off blends in draw order and opaque scenes skip the new passes', function(done) { + plot(2.5, 0.5) + .then(function() { + expect(status().mode).toBe('legacy'); + expect(status().reason).toBe('off'); + expectNear(centre(), [128, 64, 192]); + return plot(2.5, 1, 'auto'); + }) + .then(function() { + expect(status().mode).toBe('none'); + }) + .then(done, done.fail); + }); + + it('@gl scene.oit auto falls back to the draw order pass without float render targets', function(done) { + let off; + const events = []; + plot(2.5, 0.5, 'off') + .then(function() { + off = readPixels(); + window.__plotlyOITTestHooks = { disableExt: ['WEBGL_color_buffer_float', 'EXT_color_buffer_half_float'] }; + gd.on('plotly_oitstatus', (s) => events.push(s)); + glplot().resetOIT(); + glplot().setOIT('auto'); + }) + .then(delay(200)) + .then(function() { + expect(status().mode).toBe('legacy'); + expect(status().tier).toBe(4); + expect(status().reason).toBe('no-float-target'); + expect(events.length).toBeGreaterThan(0); + const px = readPixels(); + let diff = 0; + for (let i = 0; i < px.length; i++) if (px[i] !== off[i]) diff++; + expect(diff).toBe(0, 'the last tier must equal the draw order pixels'); + }) + .then(done, done.fail); + }); + + it('@gl scene.oit auto falls back when the render targets cannot be allocated', function(done) { + plot(2.5, 0.5, 'off') + .then(function() { + window.__plotlyOITTestHooks = { failAlloc: true }; + glplot().resetOIT(); + glplot().setOIT('auto'); + }) + .then(delay(200)) + .then(function() { + expect(status().mode).toBe('legacy'); + expect(status().reason).toBe('alloc-failed'); + }) + .then(done, done.fail); + }); + + it('@gl scene.oit auto uses global depth nodes without MIN blending', function(done) { + window.__plotlyOITTestHooks = { disableExt: ['EXT_blend_minmax'] }; + plot(2.5, 0.5, 'auto') + .then(function() { + expect(status().mode).toBe('D2'); + expect(status().reason).toBe('no-minmax-anchor'); + expectNear(centre(), [192, 64, 128]); + }) + .then(done, done.fail); + }); + + it('@gl scene.oit auto without multiple render targets takes extra passes for the same picture', function(done) { + let ref; + plot(2.5, 0.5, 'auto') + .then(function() { + ref = readPixels(); + window.__plotlyOITTestHooks = { disableExt: ['WEBGL_draw_buffers'] }; + glplot().resetOIT(); + glplot().setOIT('auto'); + }) + .then(delay(200)) + .then(function() { + expect(status().mrt).toBe(false); + expect(status().passes).toBeGreaterThan(3); + const px = readPixels(); + let worst = 0; + for (let i = 0; i < px.length; i++) worst = Math.max(worst, Math.abs(px[i] - ref[i])); + expect(worst).not.toBeGreaterThan(1); + }) + .then(done, done.fail); + }); + + it('@gl scene.oit switches at run time and emits plotly_oitstatus', function(done) { + const modes = []; + plot(2.5, 0.5, 'off') + .then(function() { + gd.on('plotly_oitstatus', (s) => modes.push(s.mode)); + return Plotly.relayout(gd, 'scene.oit', 'auto'); + }) + .then(delay(300)) + .then(function() { + expect(status().mode).toBe('D'); + expect(modes).toContain('D'); + expectNear(centre(), [192, 64, 128]); + }) + .then(done, done.fail); + }); + }); }); diff --git a/test/plot-schema.json b/test/plot-schema.json index 7ab1ae48d50..6d57eef60ff 100644 --- a/test/plot-schema.json +++ b/test/plot-schema.json @@ -6708,6 +6708,16 @@ false ] }, + "oit": { + "description": "Determines how translucent `scatter3d` markers blend. With *off*, the markers blend in draw order. The picture then depends on the order of the traces and of the points. With *auto*, the markers blend by depth and the draw order has no effect. This uses extra render passes and float render targets. The targets need memory in proportion to the size of the plot. If the graphics hardware lacks a feature, plotly.js falls back to *off*. The scene reports the result in `getOITStatus()` and in the `plotly_oitstatus` event.", + "dflt": "off", + "editType": "plot", + "valType": "enumerated", + "values": [ + "off", + "auto" + ] + }, "role": "object", "uirevision": { "description": "Controls persistence of user-driven changes in camera attributes. Defaults to `layout.uirevision`.", From f39fb94e097ea23ac7ea185cfa61e5dc1b0585f4 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:24:50 -0800 Subject: [PATCH 06/45] Pin gl-plot3d to the fork that draws alwaysOnTop objects last The fork skips objects with alwaysOnTop in the depth, opaque and transparent passes and draws them after the composite. Rebuild stackgl_modules/index.js with npm run bundle-stackgl. --- stackgl_modules/index.js | 35 +++++++++++++++++++++++++------ stackgl_modules/package-lock.json | 4 ++-- stackgl_modules/package.json | 2 +- 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index e984b19404e..fea9559400f 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -19901,7 +19901,7 @@ function createScene(options) { } for(var i = 0; i < numObjsNow(); ++i) { var o = objects[i] - if(o.isOpaque && o.isOpaque()) o.draw(cameraParams) + if(o.isOpaque && o.isOpaque() && !o.alwaysOnTop) o.draw(cameraParams) } gl.colorMask(true, true, true, true) @@ -20173,10 +20173,10 @@ function createScene(options) { var obj = objects[i] obj.axes = axes obj.pixelRatio = scene.pixelRatio - if(obj.isOpaque && obj.isOpaque()) { + if(obj.isOpaque && obj.isOpaque() && !obj.alwaysOnTop) { obj.draw(cameraParams) } - if(obj.isTransparent && obj.isTransparent()) { + if(obj.isTransparent && obj.isTransparent() && !obj.alwaysOnTop) { hasTransparent = true } } @@ -20187,7 +20187,7 @@ function createScene(options) { var legacyObjs = false for(var i=0; i Date: Fri, 4 Dec 2026 00:24:50 -0800 Subject: [PATCH 07/45] Add alwaysontop to scatter3d traces to keep a highlight visible Points in front hide a highlighted marker inside a dense cloud. The markers of a trace with alwaysontop true draw last, over everything else, with no depth test. The default is false and changes no pixel. The markers stay pickable. --- draftlogs/XXXX_add_alwaysontop.md | 1 + src/traces/scatter3d/attributes.js | 12 +++ src/traces/scatter3d/convert.js | 1 + src/traces/scatter3d/defaults.js | 1 + src/types/generated/schema.d.ts | 5 + test/jasmine/tests/scatter3d_test.js | 152 +++++++++++++++++++++++++++ test/plot-schema.json | 6 ++ 7 files changed, 178 insertions(+) create mode 100644 draftlogs/XXXX_add_alwaysontop.md diff --git a/draftlogs/XXXX_add_alwaysontop.md b/draftlogs/XXXX_add_alwaysontop.md new file mode 100644 index 00000000000..5aee154ea17 --- /dev/null +++ b/draftlogs/XXXX_add_alwaysontop.md @@ -0,0 +1 @@ +- Add `alwaysontop` to `scatter3d` traces to draw their markers last, over everything else [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/src/traces/scatter3d/attributes.js b/src/traces/scatter3d/attributes.js index 7191d73c1b6..70dd21209a8 100644 --- a/src/traces/scatter3d/attributes.js +++ b/src/traces/scatter3d/attributes.js @@ -172,6 +172,18 @@ var attrs = (module.exports = overrideAll( opacity: baseAttrs.opacity, + alwaysontop: { + valType: 'boolean', + dflt: false, + editType: 'calc', + description: [ + 'If *true*, the markers of this trace are drawn last, on top of everything else', + 'in the scene, without depth testing, in trace order.', + 'Use it for a highlight that must never be hidden by other points.', + 'The markers stay pickable.' + ].join(' ') + }, + hoverinfo: extendFlat({}, baseAttrs.hoverinfo) }, 'calc', diff --git a/src/traces/scatter3d/convert.js b/src/traces/scatter3d/convert.js index 019d362e5fe..bbd875522bf 100644 --- a/src/traces/scatter3d/convert.js +++ b/src/traces/scatter3d/convert.js @@ -436,6 +436,7 @@ proto.update = function (data) { this.scatterPlot.highlightScale = 1; this.scene.glplot.add(this.scatterPlot); } + this.scatterPlot.alwaysOnTop = !!data.alwaysontop; } else if (this.scatterPlot) { this.scene.glplot.remove(this.scatterPlot); this.scatterPlot.dispose(); diff --git a/src/traces/scatter3d/defaults.js b/src/traces/scatter3d/defaults.js index eb366090612..73e10033819 100644 --- a/src/traces/scatter3d/defaults.js +++ b/src/traces/scatter3d/defaults.js @@ -30,6 +30,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout coerce('zhoverformat'); coerce('mode'); + coerce('alwaysontop'); if (subTypes.hasMarkers(traceOut)) { handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, { diff --git a/src/types/generated/schema.d.ts b/src/types/generated/schema.d.ts index d47452f3464..6056000dce8 100644 --- a/src/types/generated/schema.d.ts +++ b/src/types/generated/schema.d.ts @@ -7447,6 +7447,11 @@ export interface ScatterData { } export interface Scatter3dData { + /** + * If *true*, the markers of this trace are drawn last, on top of everything else in the scene, without depth testing, in trace order. Use it for a highlight that must never be hidden by other points. The markers stay pickable. + * @default false + */ + alwaysontop?: boolean; /** * Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. * @default false diff --git a/test/jasmine/tests/scatter3d_test.js b/test/jasmine/tests/scatter3d_test.js index 96f6e818d0e..597316cda6c 100644 --- a/test/jasmine/tests/scatter3d_test.js +++ b/test/jasmine/tests/scatter3d_test.js @@ -9,6 +9,7 @@ var createGraphDiv = require('../assets/create_graph_div'); var destroyGraphDiv = require('../assets/destroy_graph_div'); var delay = require('../assets/delay'); +var mouseEvent = require('../assets/mouse_event'); function countCanvases() { return d3SelectAll('canvas').size(); @@ -77,6 +78,11 @@ describe('Scatter3D defaults', function() { expect(out.marker.line.color).toBe(Color.defaultLine); }); + it('should default alwaysontop to false', function() { + expect(_supply(Lib.extendFlat({}, base)).alwaysontop).toBe(false); + expect(_supply(Lib.extendFlat({ alwaysontop: true }, base)).alwaysontop).toBe(true); + }); + it('should inherit layout.calendar', function() { var out = _supply(base, {calendar: 'islamic'}); @@ -542,4 +548,150 @@ describe('Test scatter3d interactions:', function() { .then(done, done.fail); }); }); + + describe('alwaysontop', function() { + const W = 300; + const H = 300; + + // 3000 translucent red markers around the origin and one opaque black marker behind most of them + function traces(top, onlyMarker) { + const x = []; + const y = []; + const z = []; + let seed = 7; + const rnd = () => { + seed = (seed * 16807) % 2147483647; + return seed / 2147483647 - 0.5; + }; + for (let i = 0; i < 3000; i++) { + x.push(rnd() * 1.6); + y.push(rnd() * 1.6); + z.push(rnd() * 1.6); + } + const cloud = { + type: 'scatter3d', + mode: 'markers', + x: x, + y: y, + z: z, + hoverinfo: 'skip', + marker: { size: 8, color: 'rgb(220,40,40)', opacity: 0.6, line: { width: 0 } } + }; + const focus = { + type: 'scatter3d', + mode: 'markers', + x: [0], + y: [0], + z: [-0.3], + alwaysontop: top, + marker: { size: 30, color: 'black', line: { width: 0 } } + }; + return onlyMarker ? [focus] : [cloud, focus]; + } + + function plot(data, oit) { + return Plotly.react(gd, data, { + width: W, + height: H, + margin: { l: 0, r: 0, t: 0, b: 0 }, + paper_bgcolor: 'white', + showlegend: false, + uirevision: Math.random(), + scene: { + oit: oit, + bgcolor: 'white', + xaxis: { range: [-1, 1], visible: false }, + yaxis: { range: [-1, 1], visible: false }, + zaxis: { range: [-1, 1], visible: false }, + aspectmode: 'cube', + camera: { + eye: { x: 0, y: 0, z: 2.5 }, + up: { x: 0, y: 1, z: 0 }, + projection: { type: 'orthographic' } + } + } + }).then(delay(400)); + } + + function pixels() { + const glplot = gd._fullLayout.scene._scene.glplot; + const gl = glplot.gl; + glplot.redraw(); + const px = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, px); + return { w: gl.drawingBufferWidth, h: gl.drawingBufferHeight, px: px }; + } + + const isBlack = (p, i) => p.px[4 * i] === 0 && p.px[4 * i + 1] === 0 && p.px[4 * i + 2] === 0; + + ['off', 'auto'].forEach(function(oit) { + it('@gl draws the marker on top of the translucent cloud with scene.oit ' + oit, function(done) { + let without; + let footprint; + plot(traces(false), oit) + .then(function() { + without = pixels(); + return plot(traces(false, true), oit); + }) + .then(function() { + const p = pixels(); + footprint = []; + for (let i = 0; i < p.w * p.h; i++) footprint.push(isBlack(p, i)); + const covered = footprint.filter(Boolean).length; + expect(covered).toBeGreaterThan(400); + const hidden = footprint.filter((f, i) => f && !isBlack(without, i)).length; + expect(hidden).toBeGreaterThan(covered * 0.5); + return plot(traces(true), oit); + }) + .then(function() { + const withTop = pixels(); + const notBlack = footprint.filter((f, i) => f && !isBlack(withTop, i)).length; + expect(notBlack).toBe(0, 'every pixel of the marker shows its own color'); + + // outside the marker, dilated by 2 px for the soft edge, nothing changes + let changed = 0; + for (let i = 0; i < withTop.w * withTop.h; i++) { + const cx = i % withTop.w; + const cy = (i / withTop.w) | 0; + let near = false; + for (let dy = -2; dy <= 2 && !near; dy++) { + for (let dx = -2; dx <= 2; dx++) { + if (footprint[(cy + dy) * withTop.w + cx + dx]) { + near = true; + break; + } + } + } + if (near) continue; + for (let c = 0; c < 3; c++) { + if (withTop.px[4 * i + c] !== without.px[4 * i + c]) { + changed++; + break; + } + } + } + expect(changed).toBe(0, 'pixels outside the marker are unchanged'); + }) + .then(done, done.fail); + }); + }); + + it('@gl a marker with alwaysontop stays pickable', function(done) { + const hovered = []; + plot(traces(true, true), 'off') + .then(function() { + gd.on('plotly_hover', (e) => hovered.push(e.points[0].curveNumber)); + }) + .then(delay(20)) + .then(function() { + mouseEvent('mouseover', 0, 0); + mouseEvent('mouseover', W / 2, H / 2); + }) + .then(delay(100)) + .then(function() { + expect(hovered.length).toBeGreaterThan(0); + }) + .then(done, done.fail); + }); + }); }); diff --git a/test/plot-schema.json b/test/plot-schema.json index 6d57eef60ff..c70d9443716 100644 --- a/test/plot-schema.json +++ b/test/plot-schema.json @@ -55204,6 +55204,12 @@ "scatter3d": { "animatable": false, "attributes": { + "alwaysontop": { + "description": "If *true*, the markers of this trace are drawn last, on top of everything else in the scene, without depth testing, in trace order. Use it for a highlight that must never be hidden by other points. The markers stay pickable.", + "dflt": false, + "editType": "calc", + "valType": "boolean" + }, "connectgaps": { "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected.", "dflt": false, From 8f7bedae00db1f059c193a0e1758f1cd1fc72ff9 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:24:52 -0800 Subject: [PATCH 08/45] Pin gl-plot3d, gl-select-static, and gl-scatter3d to the pick pass branches The scene drew its pick buffer in each frame that moved the camera. The new gl-plot3d draws the buffer when a pointer event queries it, and draws none if no object permits a pick. stackgl_modules/index.js is the webpack output of the pinned commits. The pins go away when the gl-vis pull requests merge and release. --- stackgl_modules/index.js | 129 ++++++++++++++++++++++++++++-- stackgl_modules/package-lock.json | 16 ++-- stackgl_modules/package.json | 5 +- 3 files changed, 135 insertions(+), 15 deletions(-) diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index b812d41f949..45cc7a132f3 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -18881,6 +18881,14 @@ function createScene(options) { mouseListener: null, _stopped: false, + // The pick pass. 'lazy': drawn when a pointer event queries it, or pickIdleDelay ms after the last + // frame that changed it (0: never ahead of the query). 'eager': drawn in every frame that changed it (upstream). + pickMode: options.pickMode || 'lazy', + pickIdleDelay: options.pickIdleDelay === undefined ? 120 : options.pickIdleDelay, + // Query the pick buffers only when the main button goes down (hover is off): pointer moves draw nothing + pickOnPress: false, + pickStats: {draws: 0}, + getAspectratio: function() { return { x: this.aspect[0], @@ -19037,6 +19045,10 @@ function createScene(options) { } scene._stopped = true + if(pickTimer) { + clearTimeout(pickTimer) + pickTimer = null + } window.removeEventListener('resize', resizeListener) canvas.removeEventListener('webglcontextlost', checkContextLoss) @@ -19101,7 +19113,12 @@ function createScene(options) { } scene._mouseRotating = false - for(var i=0; i selection.distance) { @@ -19129,17 +19146,27 @@ function createScene(options) { } } + // A hover that changes nothing in the picture needs no frame: the axis spikes are off and the + // hovered cloud is not drawn larger (highlightScale 1, as plotly sets it). The render callback alone + // then gives the hover label and events, as it does from the frame. + var e = spikes.enabled + var still = !e[0] && !e[1] && !e[2] && !!scene.onrender && pickFrameSeen && + (!prevObj || prevObj.highlightScale === 1) && + (!selection.object || selection.object.highlightScale === 1) if(prevObj && prevObj !== selection.object) { if(prevObj.highlight) { prevObj.highlight(null) } - dirty = true + dirty = dirty || !still } if(selection.object) { if(selection.object.highlight) { selection.object.highlight(selection.data) } - dirty = true + dirty = dirty || !still + } + if(still && !dirty && (prevObj || selection.object)) { + scene.onrender() } change = change || (selection.object !== prevObj) @@ -19170,12 +19197,78 @@ function createScene(options) { canvas.addEventListener('webglcontextlost', checkContextLoss) + var pickTimer = null + var pickFrameSeen = false + var pickEmpty = false + + // True if some object that is drawn into a pick buffer can be picked + function anyPickable() { + for(var i=0; i= 0 && objects[i].drawPick && !objects[i].noPick) { + return true + } + } + return false + } + + // Draw the pick buffers and read them back now, if they are out of date + function ensurePick() { + if(pickTimer) { + clearTimeout(pickTimer) + pickTimer = null + } + if(!pickDirty || !pickFrameSeen || scene._stopped || scene.contextLost) { + return + } + pickDirty = false + renderPick() + // the pick pass draws at pixel ratio 1; objects read their own ratio when a query follows (mesh pick) + for(var i=0; i 0) || scene.pickOnPress) { + return + } + pickTimer = setTimeout(function() { + pickTimer = null + if(scene._prevButtons) { + // nothing is queried while a button is held: look again later + schedulePick() + } else { + ensurePick() + } + }, scene.pickIdleDelay) + } + //Render the scene for mouse picking function renderPick() { if(checkContextLoss()) { return } + // Nothing can be picked (every trace has hoverinfo 'skip'): no pass, and no query reads the buffers + pickEmpty = !anyPickable() + if(pickEmpty) { + return + } + + scene.pickStats.draws++ + gl.colorMask(true, true, true, true) gl.depthMask(true) gl.disable(gl.BLEND) @@ -19340,9 +19433,15 @@ function createScene(options) { } //If state changed, then redraw pick buffers + pickFrameSeen = true if(pickDirty) { - pickDirty = false - renderPick() + if(scene.pickMode === 'lazy') { + // Not in this frame: a pointer event that queries the buffer draws it, or the idle timer does + schedulePick() + } else { + pickDirty = false + renderPick() + } } //Recalculate pixel data @@ -20169,6 +20268,11 @@ proto.pick = function(selected) { if(selected.id !== this.pickId) { return null } + // A cloud that is never picked gives no hit. Nor does one with more points than the 24 bits of the point index + // in the pick buffer can tell apart (the last value means none): its ids would name other points + if(this.noPick || this.pointCount > 16777215) { + return null + } var x = selected.value[2] + (selected.value[1]<<8) + (selected.value[0]<<16) if(x >= this.pointCount || x < 0) { return null @@ -20311,6 +20415,9 @@ proto.update = function(options) { //Set dirty flag this.dirty = true + // A cloud that is never picked (hoverinfo 'skip'). The scene draws no pick pass when no object can be picked. + if('pick' in options) this.noPick = options.pick === false + //Create new buffers var points = options.position @@ -20870,6 +20977,18 @@ proto.query = function(x, y, radius) { Math.sqrt(closest[2])) } +// Read the buffer back now (a pick pass drawn on demand is queried at once) +proto.sync = function() { + if(!this.gl) { + return + } + if(this._readTimeout) { + clearTimeout(this._readTimeout) + } + this._readCallback() + this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null) +} + proto.dispose = function() { if(!this.gl) { return diff --git a/stackgl_modules/package-lock.json b/stackgl_modules/package-lock.json index 0961819ddab..e250c874603 100644 --- a/stackgl_modules/package-lock.json +++ b/stackgl_modules/package-lock.json @@ -16,8 +16,8 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "^2.4.7", - "gl-scatter3d": "^1.4.1", + "gl-plot3d": "github:settylab/gl-plot3d#af538fec50f8e212bde2cdfbfcf733bad5d7c771", + "gl-scatter3d": "github:settylab/gl-scatter3d#370d619a7ec1351f87989c9963a37cd4ccb06e5b", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", "gl-streamtube3d": "^1.4.2", @@ -1312,8 +1312,8 @@ }, "node_modules/gl-plot3d": { "version": "2.4.7", - "resolved": "https://registry.npmjs.org/gl-plot3d/-/gl-plot3d-2.4.7.tgz", - "integrity": "sha512-mLDVWrl4Dj0O0druWyHUK5l7cBQrRIJRn2oROEgrRuOgbbrLAzsREKefwMO0bA0YqkiZMFMnV5VvPA9j57X5Xg==", + "resolved": "git+ssh://git@github.com/settylab/gl-plot3d.git#af538fec50f8e212bde2cdfbfcf733bad5d7c771", + "integrity": "sha512-ilgUga590Ge94vR4MMFtq/NWjoTB99XrXnuyNCXFLPcLixAM3gHNMlN2ktcF19dlYKXtQNMA19xCLpkB/BSJXA==", "license": "MIT", "dependencies": { "3d-view": "^2.0.0", @@ -1347,8 +1347,8 @@ }, "node_modules/gl-scatter3d": { "version": "1.4.1", - "resolved": "https://registry.npmjs.org/gl-scatter3d/-/gl-scatter3d-1.4.1.tgz", - "integrity": "sha512-v2nQWSPr9/smu2YB4erhHuUkk+8w2q59CsTPvcK72vFYWCSgU6eeTnu0UlmN634bblbTTa5ap/xrbxJGiKLyrw==", + "resolved": "git+ssh://git@github.com/settylab/gl-scatter3d.git#370d619a7ec1351f87989c9963a37cd4ccb06e5b", + "integrity": "sha512-kyGOqNcQPAiKtDbKqVYRkPFkGsCiMTL7NR3cWqC1f/CsVqWFnCBC3TyHhlMdm1c/m6Ls/naxpysYdv6Jcw/hhw==", "license": "MIT", "dependencies": { "gl-buffer": "^2.1.2", @@ -1364,8 +1364,8 @@ }, "node_modules/gl-select-static": { "version": "2.0.7", - "resolved": "https://registry.npmjs.org/gl-select-static/-/gl-select-static-2.0.7.tgz", - "integrity": "sha512-OvpYprd+ngl3liEatBTdXhSyNBjwvjMSvV2rN0KHpTU+BTi4viEETXNZXFgGXY37qARs0L28ybk3UQEW6C5Nnw==", + "resolved": "git+ssh://git@github.com/settylab/gl-select-static.git#4375784bfd498a0de58a766f4518840df183a99d", + "integrity": "sha512-+qsKdpPCUp8TpeqgqE32Eqd22U5pp9nbTikXePGWQYlapQ9oB9EU6RkxIzw3J0hugpOZ+KE4djSCIN+A7BC3Gg==", "license": "MIT", "dependencies": { "bit-twiddle": "^1.0.2", diff --git a/stackgl_modules/package.json b/stackgl_modules/package.json index a145e05bf6b..0acffbece66 100644 --- a/stackgl_modules/package.json +++ b/stackgl_modules/package.json @@ -19,8 +19,8 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "^2.4.7", - "gl-scatter3d": "^1.4.1", + "gl-plot3d": "github:settylab/gl-plot3d#af538fec50f8e212bde2cdfbfcf733bad5d7c771", + "gl-scatter3d": "github:settylab/gl-scatter3d#370d619a7ec1351f87989c9963a37cd4ccb06e5b", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", "gl-streamtube3d": "^1.4.2", @@ -52,6 +52,7 @@ "webpack-cli": "7.2.3" }, "overrides": { + "gl-select-static": "github:settylab/gl-select-static#4375784bfd498a0de58a766f4518840df183a99d", "is-mobile": "^5.0.0", "to-px": "1.0.1" } From 4f93087425c4679110ff31baa5b5c8ef2d6464b0 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:24:52 -0800 Subject: [PATCH 09/45] Draw the gl3d pick pass on demand, and none for scenes without hover A scatter3d trace with hoverinfo skip tells the scene that no pointer event can select it. A scene with hovermode false queries the pick buffer only on a button press and emits no hover events. A trace with more points than the 24 bits of a pick id gets no hover and no click, because its ids name other points. --- draftlogs/XXXX_change.md | 1 + draftlogs/XXXX_fix.md | 1 + src/plots/gl3d/scene.js | 10 +- src/traces/scatter3d/convert.js | 25 ++ test/jasmine/tests/gl3d_hover_click_test.js | 341 ++++++++++++++++++++ 5 files changed, 376 insertions(+), 2 deletions(-) create mode 100644 draftlogs/XXXX_change.md create mode 100644 draftlogs/XXXX_fix.md diff --git a/draftlogs/XXXX_change.md b/draftlogs/XXXX_change.md new file mode 100644 index 00000000000..675efb90412 --- /dev/null +++ b/draftlogs/XXXX_change.md @@ -0,0 +1 @@ +- Draw the gl3d pick pass when a pointer event needs it instead of in every frame that moves the camera, skip it when no trace of the scene can be picked, draw no frame for a hover that changes nothing in the picture, and make `scene.hovermode: false` pick only on a button press without emitting hover events [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/draftlogs/XXXX_fix.md b/draftlogs/XXXX_fix.md new file mode 100644 index 00000000000..24e45e3c675 --- /dev/null +++ b/draftlogs/XXXX_fix.md @@ -0,0 +1 @@ +- Fix hover and click on `scatter3d` traces with more than 16,777,215 points naming other points: such a trace is drawn but not picked, with a console warning [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/src/plots/gl3d/scene.js b/src/plots/gl3d/scene.js index e320fe9e780..1f01726f181 100644 --- a/src/plots/gl3d/scene.js +++ b/src/plots/gl3d/scene.js @@ -99,6 +99,8 @@ proto.prepareOptions = function() { axes: scene.axesOptions, spikes: scene.spikeOptions, pickRadius: 10, + // Nothing queries a static scene, so no pick pass runs before a query + pickIdleDelay: scene.staticMode ? 0 : 120, snapToData: true, autoScale: true, autoBounds: false, @@ -456,13 +458,14 @@ proto.render = function() { pointData.bbox = bbox[0]; } + const hoverOn = !!scene.fullSceneLayout.hovermode; if(selection.distance < 5 && (selection.buttons || tabletmode)) { gd.emit('plotly_click', eventData); - } else { + } else if(hoverOn) { gd.emit('plotly_hover', eventData); } - this.oldEventData = eventData; + this.oldEventData = hoverOn ? eventData : undefined; } else { Fx.loneUnhover(svgContainer); if(this.oldEventData) gd.emit('plotly_unhover', this.oldEventData); @@ -1054,6 +1057,9 @@ proto.updateFx = function(dragmode, hovermode) { // to put dragmode and hovermode on the same grounds from relayout scene.fullSceneLayout.hovermode = hovermode; + + // Without hover, only a button press queries the pick buffer, for plotly_click + if (scene.glplot) scene.glplot.pickOnPress = !hovermode; }; function flipPixels(pixels, w, h) { diff --git a/src/traces/scatter3d/convert.js b/src/traces/scatter3d/convert.js index 019d362e5fe..9e14fdd36f4 100644 --- a/src/traces/scatter3d/convert.js +++ b/src/traces/scatter3d/convert.js @@ -186,6 +186,27 @@ function formatParam(paramIn, len, calculate, dflt, extraFn) { return paramOut; } +/** + * Tell if hover and click can never select a point of the trace. + * + * The pick buffer holds 24 bits of the point index. The ids of a longer trace + * name other points, so such a trace gets no hover and no click. The function logs a warning for it. + * + * @param data - the full trace + * @param len - the number of points + * @returns true for `hoverinfo: 'skip'` and for a trace above `maxPickPoints` + */ +function neverPicked(data, len) { + if (data.hoverinfo === 'skip') return true; + const max = createLineWithMarkers.maxPickPoints; + if (len <= max) return false; + Lib.warn( + `scatter3d trace ${data.index} has ${len} points. Hover and click cannot tell more than ${max} apart, ` + + 'so the trace gets neither. Split the trace, or set hoverinfo to *skip*.' + ); + return true; +} + function convertPlotlyOptions(scene, data) { var points = []; var sceneLayout = scene.fullSceneLayout; @@ -421,6 +442,7 @@ proto.update = function (data) { glyph: options.scatterMarker, opacity: scatterOpacity, orthographic: true, + pick: !neverPicked(data, (data.x || []).length), lineWidth: options.scatterLineWidth, lineColor: options.scatterLineColor, project: options.project, @@ -547,4 +569,7 @@ function createLineWithMarkers(scene, data) { return plot; } +// The pick ids of one trace: 0 to 2^24 - 2. The last value means no point. +createLineWithMarkers.maxPickPoints = 16777215; + module.exports = createLineWithMarkers; diff --git a/test/jasmine/tests/gl3d_hover_click_test.js b/test/jasmine/tests/gl3d_hover_click_test.js index 1499eebbf5d..5b5d41d43e1 100644 --- a/test/jasmine/tests/gl3d_hover_click_test.js +++ b/test/jasmine/tests/gl3d_hover_click_test.js @@ -1503,3 +1503,344 @@ describe('hover on traces with (x|y|z|u|v|w)hoverformat and valuehoverformat', f }); }); }); + +function f32(n, seed) { + var a = new Float32Array(n); + var s = seed; + for(var i = 0; i < n; i++) { + s = (s * 1664525 + 1013904223) >>> 0; + a[i] = s / 4294967296; + } + return a; +} + +function cloud(n, extra, seed) { + seed = seed || 0; + var t = {type: 'scatter3d', mode: 'markers', x: f32(n, 1 + seed), y: f32(n, 2 + seed), z: f32(n, 3 + seed), + marker: {size: 10, color: 'blue', line: {width: 0}}}; + for(var k in extra) t[k] = extra[k]; + return t; +} + +var PICK_LAYOUT = {width: 600, height: 400, margin: {l: 0, r: 0, t: 0, b: 0}, showlegend: false, + scene: {camera: {eye: {x: 1.4, y: 1.2, z: 0.9}, projection: {type: 'orthographic'}}}}; +var EYE2 = {x: 0.9, y: 1.6, z: 0.8}; + +describe('Test gl3d pick pass:', function() { + var gd; + + beforeEach(function() { gd = createGraphDiv(); }); + afterEach(function() { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function glplot() { return gd._fullLayout.scene._scene.glplot; } + function draws() { return glplot().pickStats.draws; } + function layout() { return JSON.parse(JSON.stringify(PICK_LAYOUT)); } + // the points of the hover events of pointer moves over the cloud + function hoverTrail() { + var out = []; + gd.on('plotly_hover', function(e) { + // every frame with a hovered point emits the event again: keep the changes + var p = e.points[0].curveNumber + ':' + e.points[0].pointNumber; + if(out[out.length - 1] !== p) out.push(p); + }); + return out; + } + function moves(list) { + var p = Promise.resolve(); + list.forEach(function(xy) { + p = p.then(function() { mouseEvent('mousemove', xy[0], xy[1]); }).then(delay(60)); + }); + return p; + } + var PATH = [[300, 200], [280, 190], [320, 215], [305, 230]]; + + it('@gl draws no pick pass in the frames of a camera change; the first pointer query draws one', function(done) { + var n0; + Plotly.newPlot(gd, [cloud(3000)], layout()) + .then(delay(100)) + .then(function() { + glplot().pickIdleDelay = 0; + mouseEvent('mousemove', 300, 200); + n0 = draws(); + return Plotly.relayout(gd, 'scene.camera.eye', EYE2); + }) + .then(delay(150)) + .then(function() { + expect(draws()).toBe(n0, 'no pass in the frames after the camera change'); + mouseEvent('mousemove', 310, 205); + expect(draws()).toBe(n0 + 1, 'the pointer query draws it'); + mouseEvent('mousemove', 320, 210); + mouseEvent('mousemove', 290, 190); + expect(draws()).toBe(n0 + 1, 'later queries read the same buffer'); + }) + .then(done, done.fail); + }); + + it('@gl draws the pick pass once the scene has been at rest for pickIdleDelay', function(done) { + var n0; + Plotly.newPlot(gd, [cloud(3000)], layout()) + .then(delay(900)) + .then(function() { + expect(glplot().pickIdleDelay).toBe(120); + n0 = draws(); + expect(n0).toBeGreaterThan(0); + return Plotly.relayout(gd, 'scene.camera.eye', EYE2); + }) + .then(delay(900)) + .then(function() { + expect(draws()).toBe(n0 + 1); + mouseEvent('mousemove', 310, 205); + expect(draws()).toBe(n0 + 1); + }) + .then(done, done.fail); + }); + + it('@gl draws no pick pass during a drag', function(done) { + var n0; + Plotly.newPlot(gd, [cloud(3000)], layout()) + .then(delay(300)) + .then(function() { + mouseEvent('mousemove', 300, 200); + n0 = draws(); + mouseEvent('mousedown', 300, 200, {buttons: 1}); + }) + .then(delay(30)) + .then(function() { mouseEvent('mousemove', 320, 205, {buttons: 1}); }) + .then(delay(200)) + .then(function() { mouseEvent('mousemove', 340, 210, {buttons: 1}); }) + .then(delay(200)) + .then(function() { + expect(draws()).toBe(n0, 'none while the button is held, also past the idle delay'); + mouseEvent('mouseup', 340, 210); + expect(draws()).toBe(n0 + 1, 'the release queries the buffer'); + }) + .then(done, done.fail); + }); + + it('@gl gives the hover points of the eager pick pass after a camera change', function(done) { + var lazy, eager; + Plotly.newPlot(gd, [cloud(3000), cloud(3000, {marker: {size: 10, color: 'red', line: {width: 0}}}, 7)], layout()) + .then(delay(700)) + .then(function() { + glplot().pickIdleDelay = 0; + lazy = hoverTrail(); + return Plotly.relayout(gd, 'scene.camera.eye', EYE2); + }) + .then(delay(700)) + .then(function() { return moves(PATH); }) + .then(function() { + return Plotly.newPlot(gd, [cloud(3000), cloud(3000, {marker: {size: 10, color: 'red', line: {width: 0}}}, 7)], layout()); + }) + .then(delay(700)) + .then(function() { + glplot().pickMode = 'eager'; + eager = hoverTrail(); + return Plotly.relayout(gd, 'scene.camera.eye', EYE2); + }) + .then(delay(700)) + .then(function() { return moves(PATH); }) + .then(function() { + expect(lazy.length).toBeGreaterThan(1); + expect(lazy).toEqual(eager); + }) + .then(done, done.fail); + }); + + it('@gl draws no pick pass when every trace has hoverinfo skip', function(done) { + var trail; + Plotly.newPlot(gd, [cloud(3000, {hoverinfo: 'skip'}), cloud(3000, {hoverinfo: 'skip'}, 7)], layout()) + .then(delay(900)) + .then(function() { + trail = hoverTrail(); + expect(draws()).toBe(0); + return Plotly.relayout(gd, 'scene.camera.eye', EYE2); + }) + .then(delay(700)) + .then(function() { return moves(PATH); }) + .then(function() { + expect(draws()).toBe(0); + expect(trail.length).toBe(0); + // a pickable trace brings the pass back + return Plotly.restyle(gd, {hoverinfo: 'all'}, [1]); + }) + .then(delay(300)) + .then(function() { return moves(PATH); }) + .then(function() { + expect(draws()).toBeGreaterThan(0); + expect(trail.length).toBeGreaterThan(0); + trail.forEach(function(p) { expect(p.charAt(0)).toBe('1'); }); + }) + .then(done, done.fail); + }); + + it('@gl a skip trace in a mixed scene is still drawn into the pick buffer and hides the points behind it', function(done) { + // a wall of skip points in front of a pickable wall, seen along x + function wall(xv, extra) { + var t = cloud(4000, extra); + for(var i = 0; i < 4000; i++) t.x[i] = xv; + t.marker.size = 14; + return t; + } + var L = layout(); + L.scene.camera.eye = {x: 2, y: 0, z: 0}; + var trail; + Plotly.newPlot(gd, [wall(0), wall(1, {hoverinfo: 'skip'})], L) + .then(delay(900)) + .then(function() { + trail = hoverTrail(); + return moves(PATH); + }) + .then(function() { + expect(draws()).toBe(1); + expect(trail.length).toBe(0); + }) + .then(done, done.fail); + }); + + it('@gl hovermode false picks only when the button goes down: no hover events, plotly_click works', function(done) { + var ev = []; + var L = layout(); + L.scene.hovermode = false; + Plotly.newPlot(gd, [cloud(3000)], L) + .then(delay(900)) + .then(function() { + ['plotly_hover', 'plotly_unhover', 'plotly_click'].forEach(function(n) { + gd.on(n, function(e) { ev.push(n.slice(7) + (e && e.points ? ':' + e.points[0].pointNumber : '')); }); + }); + expect(glplot().pickOnPress).toBe(true); + expect(draws()).toBe(0, 'no pass ahead of a query'); + return moves(PATH); + }) + .then(function() { + expect(draws()).toBe(0, 'pointer moves query nothing'); + expect(ev).toEqual([]); + mouseEvent('mousedown', 300, 200, {buttons: 1}); + }) + .then(delay(100)) + .then(function() { + expect(draws()).toBe(1); + expect(ev.length).toBeGreaterThan(0); + ev.forEach(function(e) { expect(e.slice(0, 6)).toBe('click:'); }); + mouseEvent('mouseup', 300, 200); + }) + .then(delay(100)) + .then(function() { + ev.length = 0; + return Plotly.relayout(gd, 'scene.hovermode', 'closest'); + }) + .then(function() { + expect(glplot().pickOnPress).toBe(false); + return moves(PATH); + }) + .then(function() { + expect(ev.filter(function(e) { return e.slice(0, 6) === 'hover:'; }).length).toBeGreaterThan(0); + }) + .then(done, done.fail); + }); + + it('@gl a hover move draws no frame when the axis spikes are off, and gives the same events', function(done) { + function run(spikes) { + var L = layout(); + ['xaxis', 'yaxis', 'zaxis'].forEach(function(a) { L.scene[a] = {showspikes: spikes}; }); + var ev = []; + var frames = 0; + return Plotly.newPlot(gd, [cloud(3000)], L) + .then(delay(900)) + .then(function() { + var o = glplot().objects[0]; + var draw = o.draw; + o.draw = function() { + frames++; + return draw.apply(this, arguments); + }; + gd.on('plotly_hover', function(e) { ev.push('hover:' + e.points[0].pointNumber); }); + gd.on('plotly_unhover', function() { ev.push('unhover'); }); + gd.on('plotly_click', function(e) { ev.push('click:' + e.points[0].pointNumber); }); + return moves(PATH); + }) + .then(function() { mouseEvent('mousedown', 305, 230, {buttons: 1}); }) + .then(delay(60)) + .then(function() { mouseEvent('mouseup', 305, 230); }) + .then(delay(60)) + .then(function() { return moves([[5, 5]]); }) + .then(function() { + expect(document.querySelectorAll('g.hovertext').length).toBe(0); + return {ev: ev, frames: frames}; + }); + } + var off; + run(false) + .then(function(r) { + off = r; + expect(r.frames).toBe(0, 'no frame for the hover moves, the click and the unhover'); + expect(r.ev.length).toBeGreaterThan(PATH.length); + expect(r.ev[r.ev.length - 1]).toBe('unhover'); + return run(true); + }) + .then(function(on) { + expect(on.frames).toBeGreaterThan(PATH.length - 1, 'with spikes every hover move draws a frame'); + expect(off.ev).toEqual(on.ev); + }) + .then(done, done.fail); + }); + + it('@gl a trace with more points than a pick id can tell apart is drawn but never picked, and says so', function(done) { + var convert = require('../../../src/traces/scatter3d/convert'); + var max = convert.maxPickPoints; + expect(max).toBe(16777215); + convert.maxPickPoints = 2000; + spyOn(Lib, 'warn'); + var trail; + Plotly.newPlot(gd, [cloud(3000)], layout()) + .then(delay(900)) + .then(function() { + var o = glplot().objects[0]; + expect(Lib.warn).toHaveBeenCalled(); + expect(Lib.warn.calls.argsFor(0)[0]).toMatch(/3000 points/); + expect(o.pointCount).toBe(3000); + expect(o.noPick).toBe(true); + trail = hoverTrail(); + return moves(PATH); + }) + .then(function() { + expect(trail.length).toBe(0); + expect(draws()).toBe(0); + Lib.warn.calls.reset(); + return Plotly.newPlot(gd, [cloud(2000)], layout()); + }) + .then(delay(900)) + .then(function() { + expect(Lib.warn).not.toHaveBeenCalled(); + trail = hoverTrail(); + return moves(PATH); + }) + .then(function() { + expect(trail.length).toBeGreaterThan(0); + // gl-scatter3d itself gives no hit for a cloud above 2^24 - 1 points + var o = glplot().objects[0]; + var n = o.pointCount; + expect(o.pick({id: o.pickId, value: [0, 0, 7]})).not.toBe(null); + o.pointCount = 16777216; + expect(o.pick({id: o.pickId, value: [0, 0, 7]})).toBe(null); + o.pointCount = n; + }) + .then(function() { convert.maxPickPoints = max; }, function(e) { + convert.maxPickPoints = max; + throw e; + }) + .then(done, done.fail); + }); + + it('@gl a purge with a pending idle timer does not throw', function(done) { + Plotly.newPlot(gd, [cloud(3000)], layout()) + .then(delay(50)) + .then(function() { return Plotly.relayout(gd, 'scene.camera.eye', EYE2); }) + .then(delay(30)) + .then(function() { Plotly.purge(gd); }) + .then(delay(300)) + .then(done, done.fail); + }); +}); From 8de1f27eb3111ad5cbf978abf8108fe0b9690f85 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:25:45 -0800 Subject: [PATCH 10/45] Pin regl-scatter2d to a fork commit with typed positions The next commits pass Float32Array data to regl-scatter2d without a copy. The pinned commit holds the changes that regl-scatter2d needs for that, and a built bundle.js. regl-scatter2d builds bundle.js at publish time, so a plain git commit holds no entry file. A regl-scatter2d release replaces this pin. --- package-lock.json | 6 +++--- package.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index 41ff510cdf1..684d2505d3e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,7 +44,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "^3.4.0", + "regl-scatter2d": "github:settylab/regl-scatter2d#e2db766d5f8032210289a86a3bbef883e9f6ef10", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", @@ -6231,8 +6231,8 @@ }, "node_modules/regl-scatter2d": { "version": "3.4.0", - "resolved": "https://registry.npmjs.org/regl-scatter2d/-/regl-scatter2d-3.4.0.tgz", - "integrity": "sha512-DavKQlHsI+iHZuLgOL+yGkg+sPd94CS+7FCBWkcQ6s/TbaNfUsF9eN591fjjSWIoKrGNfb/SEGhsXR5lXjqZ2w==", + "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#e2db766d5f8032210289a86a3bbef883e9f6ef10", + "integrity": "sha512-UuCLyCo03l/d0TxnXvlg+iYwad/IrtCk5cin9oIZXEM1xilGQHXLFz2InrGNyUryafwo2bSnTKShNbX/fEQE1A==", "license": "MIT", "dependencies": { "@plotly/point-cluster": "^3.1.9", diff --git a/package.json b/package.json index 8db841d331a..a0169cef81d 100644 --- a/package.json +++ b/package.json @@ -118,7 +118,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "^3.4.0", + "regl-scatter2d": "github:settylab/regl-scatter2d#e2db766d5f8032210289a86a3bbef883e9f6ef10", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", From 0811d513137b541bd23f5ee4f81a65502a36ed66 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:25:46 -0800 Subject: [PATCH 11/45] Pass Float32Array x and y of scattergl traces to regl-scatter2d calc wrote x and y of each trace to a plain Array of doubles and built an Array of point ids. regl-scatter2d then copied the positions and uploaded 16 bytes for each point. Each restyle or moveTraces repeated the copies and the upload. For a markers-only trace on linear axes with Float32Array data, calc now passes {x, y, count, rev} to regl-scatter2d. regl-scatter2d uploads 8 bytes for each point one time. The same buffer range with the same layout.datarevision is the same data. calc reads the axis extremes from a cache and builds the point ids at the first read. If you refill a typed array in place, set a new layout.datarevision. --- src/traces/scattergl/calc.js | 148 ++++++++++-- test/jasmine/tests/scattergl_test.js | 329 ++++++++++++++++++++++++++- 2 files changed, 455 insertions(+), 22 deletions(-) diff --git a/src/traces/scattergl/calc.js b/src/traces/scattergl/calc.js index 240418b07af..f9de62a22ba 100644 --- a/src/traces/scattergl/calc.js +++ b/src/traces/scattergl/calc.js @@ -16,6 +16,7 @@ var convert = require('./convert'); var sceneUpdate = require('./scene_update'); var BADNUM = require('../../constants/numerical').BADNUM; +const FP_SAFE = require('../../constants/numerical').FP_SAFE; var TOO_MANY_POINTS = require('./constants').TOO_MANY_POINTS; module.exports = function calc(gd, trace) { @@ -50,25 +51,31 @@ module.exports = function calc(gd, trace) { trace._yEnds = yObj.ends; } - // we need hi-precision for scatter2d, - // regl-scatter2d uses NaNs for bad/missing values - var positions = new Array(len2); - var _ids = new Array(len); - for(i = 0; i < len; i++) { - positions[i * 2] = x[i] === BADNUM ? NaN : x[i]; - positions[i * 2 + 1] = y[i] === BADNUM ? NaN : y[i]; - // Pre-compute ids. - _ids[i] = i; - } + // regl-scatter2d uploads Float32Array x and y without a copy, so calc builds no positions for them + const xy = xyPositions(gd, trace, xa, ya, x, y, len); + let positions = xy; + let _ids; + if (!xy) { + // we need hi-precision for scatter2d, + // regl-scatter2d uses NaNs for bad/missing values + positions = new Array(len2); + _ids = new Array(len); + for(i = 0; i < len; i++) { + positions[i * 2] = x[i] === BADNUM ? NaN : x[i]; + positions[i * 2 + 1] = y[i] === BADNUM ? NaN : y[i]; + // Pre-compute ids. + _ids[i] = i; + } - if(xa.type === 'log') { - for(i = 0; i < len2; i += 2) { - positions[i] = xa.c2l(positions[i]); + if(xa.type === 'log') { + for(i = 0; i < len2; i += 2) { + positions[i] = xa.c2l(positions[i]); + } } - } - if(ya.type === 'log') { - for(i = 1; i < len2; i += 2) { - positions[i] = ya.c2l(positions[i]); + if(ya.type === 'log') { + for(i = 1; i < len2; i += 2) { + positions[i] = ya.c2l(positions[i]); + } } } @@ -76,7 +83,13 @@ module.exports = function calc(gd, trace) { // and it is also if(hasTooManyPoints && (xa.type !== 'log' && ya.type !== 'log')) { // FIXME: delegate this to webworker - stash.tree = cluster(positions); + stash.tree = cluster(xy ? interleaved(x, y, len) : positions); + } else if (xy) { + lazyProp(stash, 'ids', () => { + const ids = new Uint32Array(len); + for (let k = 0; k < len; k++) ids[k] = k; + return ids; + }); } else { stash.ids = _ids; } @@ -96,7 +109,12 @@ module.exports = function calc(gd, trace) { } else if(opts.marker) { ppad = opts.marker.sizeAvg || Math.max(opts.marker.size, 3); } - calcAxisExpansion(gd, trace, xa, ya, x, y, ppad); + // A restyle recalculates every trace, so the extremes of Float32Array data come from a cache + if (xy && !Array.isArray(ppad)) { + calcAxisExpansion(gd, trace, xa, ya, extremesOf(x, len, xy.rev), extremesOf(y, len, xy.rev), ppad); + } else { + calcAxisExpansion(gd, trace, xa, ya, x, y, ppad); + } if(opts.errorX) expandForErrorBars(trace, xa, opts.errorX); if(opts.errorY) expandForErrorBars(trace, ya, opts.errorY); @@ -125,12 +143,102 @@ module.exports = function calc(gd, trace) { stash.index = scene.count; stash.x = x; stash.y = y; - stash.positions = positions; + if (!xy) stash.positions = positions; scene.count++; return [{x: false, y: false, t: stash, trace: trace}]; }; +/** + * Get the positions of a trace that regl-scatter2d can upload without a copy. + * + * @param gd - the graph div + * @param trace - the full trace + * @param xa - the full x axis + * @param ya - the full y axis + * @param x - the calc x values + * @param y - the calc y values + * @param len - the number of points + * @returns `{x, y, count, rev}` for a markers-only trace on linear axes with Float32Array x and y, else null. + * `rev` is `layout.datarevision`. The same buffer range with the same `rev` is the same data. + */ +function xyPositions(gd, trace, xa, ya, x, y, len) { + if (!isFloat32Array(x) || !isFloat32Array(y)) return null; + if (xa.type !== 'linear' || ya.type !== 'linear') return null; + if (trace.xperiodalignment || trace.yperiodalignment) return null; + if (trace.mode !== 'markers') return null; + if (trace.fill && trace.fill !== 'none') return null; + if (trace.error_x?.visible || trace.error_y?.visible) return null; + if (x.length < len || y.length < len) return null; + return { x, y, count: len, rev: gd.layout?.datarevision }; +} + +const extremesCache = new WeakMap(); + +/** + * Get the finite extremes of a Float32Array. The function scans the array one time per buffer range and `rev`. + * + * @param v - the Float32Array + * @param len - the number of values to read + * @param rev - the revision of the data (`layout.datarevision`) + * @returns `[min, max]`, with the limits that `findExtremes` applies + */ +function extremesOf(v, len, rev) { + let byBuffer = extremesCache.get(v.buffer); + if (!byBuffer || byBuffer.rev !== rev) { + byBuffer = { rev, extremes: {} }; + extremesCache.set(v.buffer, byBuffer); + } + const key = `${v.byteOffset}:${len}`; + let extremes = byBuffer.extremes[key]; + if (extremes) return extremes; + let min = Infinity; + let max = -Infinity; + for (let i = 0; i < len; i++) { + const vi = v[i]; + if (vi < min && vi > -FP_SAFE) min = vi; + if (vi > max && vi < FP_SAFE) max = vi; + } + extremes = byBuffer.extremes[key] = [min, max]; + return extremes; +} + +// `instanceof` fails for an array from another window +function isFloat32Array(v) { + return Object.prototype.toString.call(v) === '[object Float32Array]'; +} + +function interleaved(x, y, len) { + const positions = new Float64Array(len * 2); + for (let i = 0; i < len; i++) { + positions[i * 2] = x[i]; + positions[i * 2 + 1] = y[i]; + } + return positions; +} + +/** + * Define a property that computes its value at the first read. + * + * @param stash - the object that gets the property + * @param key - the property name + * @param make - the function that returns the value + */ +function lazyProp(stash, key, make) { + let value; + Object.defineProperty(stash, key, { + configurable: true, + enumerable: true, + get: () => { + if (value === undefined) value = make(); + return value; + }, + set: (newValue) => { + value = newValue; + } + }); +} + function expandForErrorBars(trace, ax, opts) { var extremes = trace._extremes[ax._id]; var errExt = findExtremes(ax, opts._bnds, {padded: true}); diff --git a/test/jasmine/tests/scattergl_test.js b/test/jasmine/tests/scattergl_test.js index 1e8b904ed28..ea57ad0a281 100644 --- a/test/jasmine/tests/scattergl_test.js +++ b/test/jasmine/tests/scattergl_test.js @@ -567,8 +567,10 @@ describe('end-to-end scattergl tests', function() { [1, 0, 0, 1] ]); - expect(opts.positions) - .toBeCloseToArray([1, 1, 2, 2, 3, 1]); + // calc passes Float32Array x and y of a markers-only trace without a copy + expect(opts.positions.x).toBe(gd._fullData[0].x); + expect(opts.positions.y).toBe(gd._fullData[0].y); + expect(opts.positions.count).toBe(3); }) .then(done, done.fail); }); @@ -974,3 +976,326 @@ describe('Test texttemplate for scattergl', function() { ['%{x} is %{y}', ['*0* is $1000.00 !', '*1* is $1200.00 !']] ]); }); + +function f32(n, seed) { + let a = new Float32Array(n); + let s = seed; + for (let i = 0; i < n; i++) { + s = (s * 1664525 + 1013904223) >>> 0; + a[i] = s / 4294967296; + } + return a; +} + +describe('scattergl Float32Array positions', () => { + let gd; + + beforeEach(() => { gd = createGraphDiv(); }); + afterEach(() => { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function trace(x, y, extra) { + let t = {type: 'scattergl', mode: 'markers', x: x, y: y}; + for (let k in extra) t[k] = extra[k]; + return t; + } + function stash(i) { return gd.calcdata[i][0].t; } + function groups() { return gd._fullLayout._plots.xy._scene.scatter2d.groups; } + + function options(i) { return gd._fullLayout._plots.xy._scene.markerOptions[i]; } + // Record the byte length of each Float32Array that goes to the GPU + function countUploads() { + let uploads = []; + ['bufferData', 'bufferSubData'].forEach((name) => { + let orig = WebGLRenderingContext.prototype[name]; + spyOn(WebGLRenderingContext.prototype, name).and.callFake(function () { + let d = arguments[name === 'bufferData' ? 1 : 2]; + if (d instanceof Float32Array && d.byteLength) uploads.push(d.byteLength); + return orig.apply(this, arguments); + }); + }); + return uploads; + } + function pixels() { + let canvas = gd.querySelector('.gl-canvas-context'); + let gl = canvas.getContext('webgl'); + let px = new Uint8Array(canvas.width * canvas.height * 4); + gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, px); + return px; + } + + it('@gl gives Float32 x and y of a markers-only trace to regl-scatter2d as they are: no calc positions, lazy ids', (done) => { + let x = f32(1000, 1); + let y = f32(1000, 2); + Plotly.newPlot(gd, [trace(x, y)]) + .then(() => { + let t = stash(0); + expect(t.positions).toBeUndefined(); + expect(options(0).positions.x).toBe(x); + expect(options(0).positions.y).toBe(y); + expect(options(0).positions.count).toBe(1000); + expect(t.ids instanceof Uint32Array).toBe(true); + expect(t.ids[999]).toBe(999); + // The group reads x and y from GPU segments + expect(groups()[0].xy.x).toBe(x); + expect(groups()[0].xAttr.stride).toBe(4); + expect(groups()[0].count).toBe(1000); + }) + .then(done, done.fail); + }); + + it('@gl keeps plain positions for plain arrays, lines, and log axes', (done) => { + let x = f32(100, 3); + let y = f32(100, 4); + Plotly.newPlot(gd, [ + trace(Array.from(x), Array.from(y)), + trace(x, y, {mode: 'lines+markers'}), + trace(x, y, {xaxis: 'x2'}) + ], {xaxis2: {type: 'log', overlaying: 'x'}}) + .then(() => { + expect(Array.isArray(stash(0).positions)).toBe(true); + expect(Array.isArray(stash(1).positions)).toBe(true); + expect(Array.isArray(stash(2).positions)).toBe(true); + }) + .then(done, done.fail); + }); + + it('@gl uploads chunks of one buffer once per axis, and nothing on a reorder, a restyle or new views of the same data', (done) => { + let X = f32(1500, 5); + let Y = f32(1500, 6); + function chunks() { + return [0, 500, 1000].map((a) => { return trace(X.subarray(a, a + 500), Y.subarray(a, a + 500)); }); + } + let uploads = countUploads(); + Plotly.newPlot(gd, chunks()) + .then(() => { + // 1,500 points of 4 bytes, for x and for y + expect(uploads).toEqual([6000, 6000]); + uploads.length = 0; + return Plotly.moveTraces(gd, [0], [2]); + }) + .then(() => { + return Plotly.restyle(gd, {'marker.color': 'red'}, [1]); + }) + .then(() => { + return Plotly.restyle(gd, {visible: 'legendonly'}, [0]); + }) + .then(() => { + return Plotly.restyle(gd, {visible: true}, [0]); + }) + .then(() => { + // New views of the same bytes are the same data + return Plotly.react(gd, chunks(), gd.layout); + }) + .then(() => { + return Plotly.relayout(gd, {'xaxis.range': [0, 0.5]}); + }) + .then(() => { + expect(uploads).toEqual([]); + // New data uploads only its own bytes + return Plotly.restyle(gd, {x: [f32(500, 9)]}, [1]); + }) + .then(() => { + expect(uploads).toEqual([2000]); + }) + .then(done, done.fail); + }); + + it('@gl a new datarevision uploads the same arrays again', (done) => { + let x = f32(100, 10); + let y = f32(100, 11); + let uploads = countUploads(); + Plotly.newPlot(gd, [trace(x, y)], {datarevision: 1}) + .then(() => { + uploads.length = 0; + x[0] = 0.5; + // Without a new datarevision, the same bytes are the same data + return Plotly.react(gd, [trace(x.subarray(0), y)], {datarevision: 1}); + }) + .then(() => { + expect(uploads).toEqual([]); + return Plotly.react(gd, [trace(x, y)], {datarevision: 2}); + }) + .then(() => { + expect(uploads).toEqual([400, 400]); + expect(groups()[0].xy.rev).toBe(2); + }) + .then(done, done.fail); + }); + + it('@gl draws a trace across segments in pieces with the same pixels, selection included', (done) => { + let createScatter = require('regl-scatter2d'); + let segment = createScatter.xySegment; + let x = f32(3000, 12); + let y = f32(3000, 13); + let sel = []; + for (let i = 0; i < 3000; i += 7) sel.push(i); + let layout = {width: 400, height: 300, xaxis: {range: [0, 1]}, yaxis: {range: [0, 1]}}; + let whole, wholeSel; + Plotly.newPlot(gd, [trace(x, y)], layout) + .then(() => { + expect(groups()[0].pieces).toBe(null); + whole = pixels(); + return Plotly.restyle(gd, {selectedpoints: [sel]}); + }) + .then(() => { + wholeSel = pixels(); + Plotly.purge(gd); + // A segment holds 1,024 points + createScatter.xySegment = 4096; + return Plotly.newPlot(gd, [trace(x, y)], layout); + }) + .then(() => { + expect(groups()[0].pieces.length).toBe(3); + expect(pixels()).toEqual(whole); + return Plotly.restyle(gd, {selectedpoints: [sel]}); + }) + .then(() => { + expect(pixels()).toEqual(wholeSel); + }) + .then(() => { createScatter.xySegment = segment; }, (e) => { createScatter.xySegment = segment; throw e; }) + .then(done, done.fail); + }); + + it('@gl autoranges as plain arrays do, and scans an array for its extremes once', (done) => { + let x = f32(2000, 14); + let y = f32(2000, 15); + x[3] = NaN; + let range; + Plotly.newPlot(gd, [trace(Array.from(x), Array.from(y))]) + .then(() => { + range = [gd._fullLayout.xaxis.range.slice(), gd._fullLayout.yaxis.range.slice()]; + return Plotly.react(gd, [trace(x, y)]); + }) + .then(() => { + expect([gd._fullLayout.xaxis.range, gd._fullLayout.yaxis.range]).toEqual(range); + // A new datarevision makes calc read the changed value + x[0] = 5; + return Plotly.restyle(gd, {'marker.color': 'red'}); + }) + .then(() => { + expect(gd._fullLayout.xaxis.range).toEqual(range[0]); + return Plotly.react(gd, [trace(x, y)], {datarevision: 1}); + }) + .then(() => { + expect(gd._fullLayout.xaxis.range[1]).toBeGreaterThan(5); + }) + .then(done, done.fail); + }); + + it('@gl keeps the fract32 half for doubles a float32 cannot hold', (done) => { + Plotly.newPlot(gd, [trace([1000.0000001, 1000.0000002], [1, 2])]) + .then(() => { + expect(groups()[0].fractZero).toBe(false); + return Plotly.restyle(gd, {x: [[1, 2]]}); + }) + .then(() => { + expect(groups()[0].fractZero).toBe(true); + }) + .then(done, done.fail); + }); +}); + +describe('regl-scatter2d positions as regl buffers (splom)', () => { + let gd; + + beforeEach(() => { gd = createGraphDiv(); }); + afterEach(() => { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + it('@gl still draws a splom, whose positions are {x, y} with a regl buffer, offset and count', (done) => { + Plotly.newPlot(gd, [{ + type: 'splom', + dimensions: [{values: Array.from(f32(300, 31))}, {values: Array.from(f32(300, 32))}, {values: Array.from(f32(300, 33))}], + marker: {color: 'rgb(255, 0, 0)', size: 6} + }], {width: 400, height: 400}) + .then(() => { + let canvas = gd.querySelector('.gl-canvas-context'); + let gl = canvas.getContext('webgl'); + let px = new Uint8Array(canvas.width * canvas.height * 4); + gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, px); + let red = 0; + for (let i = 0; i < px.length; i += 4) if (px[i] > 200 && px[i + 1] < 60 && px[i + 3] > 200) red++; + expect(red).toBeGreaterThan(1000); + }) + .then(done, done.fail); + }); +}); + +describe('regl-scatter2d {x, y} positions', () => { + let createScatter = require('regl-scatter2d'); + let gd, regl, sc, uploads, segment; + + beforeEach((done) => { + gd = createGraphDiv(); + segment = createScatter.xySegment; + uploads = []; + Plotly.newPlot(gd, [{type: 'scattergl', mode: 'markers', x: [0, 1], y: [0, 1]}]).then(() => { + regl = gd._fullLayout._glcanvas.data()[0].regl; + sc = createScatter(regl); + ['bufferData', 'bufferSubData'].forEach((name) => { + let orig = WebGLRenderingContext.prototype[name]; + spyOn(WebGLRenderingContext.prototype, name).and.callFake(function () { + let d = arguments[name === 'bufferData' ? 1 : 2]; + if (d instanceof Float32Array && d.byteLength) uploads.push(d.byteLength); + return orig.apply(this, arguments); + }); + }); + }).then(done, done.fail); + }); + afterEach(() => { + createScatter.xySegment = segment; + sc.destroy(); + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function opts(x, y, a, b, rev) { + return {positions: {x: x.subarray(a, b), y: y.subarray(a, b), count: b - a, rev: rev}, size: 5, color: 'red'}; + } + function sum() { return uploads.reduce((a, b) => { return a + b; }, 0); } + + it('@gl uploads the views of one buffer once per axis, and the same bytes never again', () => { + let X = f32(1500, 21); + let Y = f32(1500, 22); + sc.update([opts(X, Y, 0, 500), opts(X, Y, 500, 1000)]); + expect(uploads).toEqual([4000, 4000]); + + // New views of the same bytes, then the two groups in the other order + uploads = []; + sc.update([opts(X, Y, 0, 500), opts(X, Y, 500, 1000)]); + sc.update([opts(X, Y, 500, 1000), opts(X, Y, 0, 500)]); + sc.update([{color: 'blue'}, {size: 3}]); + expect(uploads).toEqual([]); + + // A view of new bytes uploads the segment again + sc.update([opts(X, Y, 500, 1000), opts(X, Y, 1000, 1500)]); + expect(uploads).toEqual([6000, 6000]); + + // A new revision uploads the same arrays + uploads = []; + sc.update([opts(X, Y, 500, 1000, 2), opts(X, Y, 1000, 1500, 2)]); + expect(sum()).toBe(8000); + }); + + it('@gl uploads by segment, never more than the segment size at once', () => { + createScatter.xySegment = 1024; + let X = f32(1000, 23); + let Y = f32(1000, 24); + sc.update([opts(X, Y, 0, 1000)]); + // Each axis holds 4,000 bytes in segments of 1,024 + expect(uploads.length).toBe(8); + expect(Math.max.apply(null, uploads)).toBe(1024); + expect(sum()).toBe(8000); + + // A view inside the uploaded bytes uploads nothing, and the unused segments go away + uploads = []; + sc.update([opts(X, Y, 100, 300)]); + sc.update([opts(X, Y, 0, 1000)]); + expect(sum()).toBe(2 * (1024 + 928)); + }); +}); From b34d913c4389b28d34e0315f77cbf2755c551063 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:25:46 -0800 Subject: [PATCH 12/45] Build the hover tree of a large scattergl trace at the first read calc built a point-cluster tree for each trace of 100,000 points or more, at every calc. Only hoverPoints reads the tree. If layout.hovermode is false, or the trace has hoverinfo 'skip', the first read now builds the tree. With hover, calc builds the tree as before. --- src/traces/scattergl/calc.js | 8 +++++- test/jasmine/tests/scattergl_test.js | 40 ++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/traces/scattergl/calc.js b/src/traces/scattergl/calc.js index f9de62a22ba..922f379a0f1 100644 --- a/src/traces/scattergl/calc.js +++ b/src/traces/scattergl/calc.js @@ -83,7 +83,13 @@ module.exports = function calc(gd, trace) { // and it is also if(hasTooManyPoints && (xa.type !== 'log' && ya.type !== 'log')) { // FIXME: delegate this to webworker - stash.tree = cluster(xy ? interleaved(x, y, len) : positions); + // Only hover reads the tree. Without hover, the first read builds the tree. + const makeTree = () => cluster(xy ? interleaved(x, y, len) : positions); + if (fullLayout.hovermode === false || trace.hoverinfo === 'skip') { + lazyProp(stash, 'tree', makeTree); + } else { + stash.tree = makeTree(); + } } else if (xy) { lazyProp(stash, 'ids', () => { const ids = new Uint32Array(len); diff --git a/test/jasmine/tests/scattergl_test.js b/test/jasmine/tests/scattergl_test.js index ea57ad0a281..d10a94c22bf 100644 --- a/test/jasmine/tests/scattergl_test.js +++ b/test/jasmine/tests/scattergl_test.js @@ -1185,6 +1185,46 @@ describe('scattergl Float32Array positions', () => { .then(done, done.fail); }); + it('@gl builds the hover tree of a big trace in calc only when there is hover, else on first read', (done) => { + let n = 150000; + let x = f32(n, 16); + let y = f32(n, 17); + function lazy(i) { return typeof Object.getOwnPropertyDescriptor(stash(i), 'tree').get === 'function'; } + function hoverAt() { + Plotly.Fx.hover(gd, {xval: x[777], yval: y[777]}); + return gd._hoverdata && gd._hoverdata[0].pointNumber; + } + let found; + Plotly.newPlot(gd, [trace(x, y), trace(Array.from(x.subarray(0, 100000)), Array.from(y.subarray(0, 100000)))], {hovermode: 'closest'}) + .then(() => { + // With hover, calc builds the tree + expect(lazy(0)).toBe(false); + expect(lazy(1)).toBe(false); + expect(typeof stash(0).tree.range).toBe('function'); + found = hoverAt(); + expect(found).toBe(777); + return Plotly.react(gd, [trace(x, y, {hoverinfo: 'skip'}), trace(x, y)], {hovermode: 'closest'}); + }) + .then(() => { + expect(lazy(0)).toBe(true); + expect(lazy(1)).toBe(false); + Plotly.purge(gd); + return Plotly.newPlot(gd, [trace(x, y), trace(Array.from(x.subarray(0, 100000)), Array.from(y.subarray(0, 100000)))], {hovermode: false}); + }) + .then(() => { + expect(lazy(0)).toBe(true); + expect(lazy(1)).toBe(true); + // A relayout does not recalculate, so the first hover builds the tree + return Plotly.relayout(gd, {hovermode: 'closest'}); + }) + .then(() => { + expect(lazy(0)).toBe(true); + expect(hoverAt()).toBe(found); + expect(typeof stash(0).tree.range).toBe('function'); + }) + .then(done, done.fail); + }); + it('@gl keeps the fract32 half for doubles a float32 cannot hold', (done) => { Plotly.newPlot(gd, [trace([1000.0000001, 1000.0000002], [1, 2])]) .then(() => { From a019f2282179e9d975384a24e7310b65ed5bd075 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:25:46 -0800 Subject: [PATCH 13/45] Add the draftlog for the scattergl Float32Array changes --- draftlogs/XXXX_change.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 draftlogs/XXXX_change.md diff --git a/draftlogs/XXXX_change.md b/draftlogs/XXXX_change.md new file mode 100644 index 00000000000..239500711b8 --- /dev/null +++ b/draftlogs/XXXX_change.md @@ -0,0 +1 @@ +- Upload `Float32Array` `x` and `y` of markers-only `scattergl` traces without a copy, and build the hover index of large traces only when the graph has hover [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] From 6cec460a3440c2c15599b9e53b55431bf6efea17 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:26:04 -0800 Subject: [PATCH 14/45] State the fallback of scene.markerrender in its description The value disc draws a glyph where a disc cannot draw the marker, and auto is the same as disc for now. The first description left both out. --- src/plots/gl3d/layout/layout_attributes.js | 4 ++-- src/types/generated/schema.d.ts | 2 +- test/plot-schema.json | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/plots/gl3d/layout/layout_attributes.js b/src/plots/gl3d/layout/layout_attributes.js index 0259f4f8ddd..026f471bee2 100644 --- a/src/plots/gl3d/layout/layout_attributes.js +++ b/src/plots/gl3d/layout/layout_attributes.js @@ -144,8 +144,8 @@ module.exports = { '*glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default.', '*disc* draws each marker as one round point sprite. It needs far less memory and draws faster.', 'The edge of a disc differs from the edge of a glyph by about one pixel.', - '*auto* draws discs where it can.', - 'It draws glyphs for other symbols, for projections on the axes, and for markers that exceed the point size limit of the GPU.' + 'A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph.', + '*auto* is currently the same as *disc*.' ].join(' ') }, dragmode: { diff --git a/src/types/generated/schema.d.ts b/src/types/generated/schema.d.ts index 642cd0f8a24..dd813ebf803 100644 --- a/src/types/generated/schema.d.ts +++ b/src/types/generated/schema.d.ts @@ -13743,7 +13743,7 @@ export interface Scene { */ hovermode?: 'closest' | false; /** - * Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. *auto* draws discs where it can. It draws glyphs for other symbols, for projections on the axes, and for markers that exceed the point size limit of the GPU. + * Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph. *auto* is currently the same as *disc*. * @default 'glyph' */ markerrender?: 'glyph' | 'disc' | 'auto'; diff --git a/test/plot-schema.json b/test/plot-schema.json index 4fc83116d33..6cd634d633d 100644 --- a/test/plot-schema.json +++ b/test/plot-schema.json @@ -6709,7 +6709,7 @@ ] }, "markerrender": { - "description": "Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. *auto* draws discs where it can. It draws glyphs for other symbols, for projections on the axes, and for markers that exceed the point size limit of the GPU.", + "description": "Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph. *auto* is currently the same as *disc*.", "dflt": "glyph", "editType": "plot", "valType": "enumerated", From 4bbc57a7342b7a1c89512f593cf6feeafb450381 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:26:29 -0800 Subject: [PATCH 15/45] Pin gl-scatter3d to the typed positions branch The new gl-scatter3d takes positions as one Float32Array and keeps its position buffer when the caller sends no positions. stackgl_modules/index.js is the webpack output of the pinned commit. The pin goes away when the gl-vis pull request merges and releases. --- stackgl_modules/index.js | 207 ++++++++++++++++++++++++++++-- stackgl_modules/package-lock.json | 5 +- stackgl_modules/package.json | 2 +- 3 files changed, 199 insertions(+), 15 deletions(-) diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index 33c1ff2b948..8e10e248e56 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -20260,14 +20260,14 @@ function discKind(glyphs, n) { proto._discBlocker = function(options) { var mode = this.markerRender if(mode !== 'disc' && mode !== 'auto') return 'markerRender is ' + mode - if(!options.position) return 'no positions' + if(!options.position && !options.positionsKept) return 'no positions' if(!this.useOrtho) return 'perspective sizing' for(var i = 0; i < 3; ++i) if(this.axesProject[i]) return 'axes projection' var angles = options.angle if(angles && (!isArrayOrTypedArray(angles) || angles.length)) return 'marker angle' var al = options.alignment if(al && (al.length !== 2 || al[0] || al[1])) return 'alignment' - var kind = discKind(options.glyph, options.position.length) + var kind = discKind(options.glyph, this._count(options)) if(!kind) return 'symbol is not circle or circle-open' return '' } @@ -20325,12 +20325,161 @@ proto._discSetup = function(kind, outline) { } } +// Whether a sprite of this marker size (device pixels, +2 for the antialiasing margin) fits the driver's point size cap +proto._discSizeFits = function(maxSize) { + var gl = this.gl + var range = gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE) + this.pointSizeRange = [range[0], range[1]] + var maxPx = 2 * (maxSize * this.discUnit.b * this.pixelRatio * Math.max(1, this.highlightScale || 1) + + this._discLineHalf(this.pixelRatio) + 1) + if(maxPx > range[1]) { + this.discBlocker = 'marker size ' + maxPx.toFixed(0) + ' px exceeds point size cap ' + range[1] + return false + } + return true +} + +// Positions given as one flat Float32Array (x, y, z per point) +function isFlatPositions(points) { + return !!points && ArrayBuffer.isView(points) +} +function positionCount(points) { + return isFlatPositions(points) ? Math.floor(points.length / 3) : points.length +} +function unflattenPositions(flat) { + var n = positionCount(flat) + var out = new Array(n) + for(var i = 0; i < n; ++i) out[i] = [flat[3 * i], flat[3 * i + 1], flat[3 * i + 2]] + out.bounds = flat.bounds + return out +} + +// One colour, one size or no pick ids for every point of a trace are +// drawn from constant vertex attributes instead of per-point buffers (16, 4 +// and 4 bytes a point); the values are the same floats the buffers held +proto._discConstAttrs = function(gl) { + var c = this.discConst + if(c && c.color) { + gl.disableVertexAttribArray(1) + gl.vertexAttrib4f(1, c.color[0], c.color[1], c.color[2], c.color[3]) + } else gl.enableVertexAttribArray(1) + if(c && c.size !== null) { + gl.disableVertexAttribArray(2) + gl.vertexAttrib1f(2, c.size) + } else gl.enableVertexAttribArray(2) + if(c && c.noPick) { + // the "no highlight" id: hover is off for this trace, so it is never picked + gl.disableVertexAttribArray(3) + gl.vertexAttrib4f(3, 1, 1, 1, 1) + } else gl.enableVertexAttribArray(3) +} + +// The disc path for flat positions with one colour and one size: +// the positions are uploaded as given when every point is finite +proto._updateDiscFlat = function(options, points, n, outline) { + var colors = options.color + var sizes = options.size + var color = [0, 0, 0, 1] + if(isArrayOrTypedArray(colors)) { + if(colors.length === 3) { color[0] = colors[0]; color[1] = colors[1]; color[2] = colors[2] } + else if(colors.length === 4) { + color[0] = colors[0]; color[1] = colors[1]; color[2] = colors[2]; color[3] = colors[3] + if(!this.hasAlpha && colors[3] < 1) this.hasAlpha = true + } + } + var size = sizes ? +sizes : 12 + var pick = options.pick !== false + + // The same positions as at the last update (positionsKept): the position and id buffers stay, and so does + // the pick buffer when the size is the same (the pick pass reads neither colour nor opacity) + if(options.positionsKept) { + var fs = this.flatState + if(fs.n !== n || fs.pick !== pick || outline || fs.outline) return false + fs.size = size + fs.kind = this._kind + fs.kept++ + this.discConst = {color: color, size: size, noPick: !pick} + return true + } + + var lowerBound = [ Infinity, Infinity, Infinity] + var upperBound = [-Infinity,-Infinity,-Infinity] + var finite = true + // The caller has scanned the points (every point finite, bounds given) + var scanned = points.finite === true && !!points.bounds + for(var i = 0; i < n && !scanned; ++i) { + var x0 = points[3 * i], x1 = points[3 * i + 1], x2 = points[3 * i + 2] + if(x0 - x0 !== 0 || x1 - x1 !== 0 || x2 - x2 !== 0) { finite = false; continue } // NaN or infinite + if(x0 < lowerBound[0]) lowerBound[0] = x0 + if(x0 > upperBound[0]) upperBound[0] = x0 + if(x1 < lowerBound[1]) lowerBound[1] = x1 + if(x1 > upperBound[1]) upperBound[1] = x1 + if(x2 < lowerBound[2]) lowerBound[2] = x2 + if(x2 > upperBound[2]) upperBound[2] = x2 + } + + var m = n + var positionArray = null + var idArray = null + if(!finite) { + // drop the points that are not finite, as the per-point path does; ids keep the original index + positionArray = pool.mallocFloat(3 * n) + if(pick) idArray = pool.mallocUint32(n) + m = 0 + for(var i = 0; i < n; ++i) { + var x0 = points[3 * i], x1 = points[3 * i + 1], x2 = points[3 * i + 2] + if(x0 - x0 !== 0 || x1 - x1 !== 0 || x2 - x2 !== 0) continue + positionArray[3 * m] = x0; positionArray[3 * m + 1] = x1; positionArray[3 * m + 2] = x2 + if(idArray) idArray[m] = i + m += 1 + } + } else if(pick) { + idArray = pool.mallocUint32(n) + for(var i = 0; i < n; ++i) idArray[i] = i + } + + // bounds from the doubles the positions were rounded from, when the caller kept them (scatter3d convert) + this.bounds = points.bounds || [lowerBound, upperBound] + this.points = pick ? points : null // a trace that is never picked does not keep its positions + this.pointCount = n + this.vertexCount = m + this.lineVertexCount = 0 + this.discConst = {color: color, size: size, noPick: !pick} + + this.pointBuffer.update(positionArray ? positionArray.subarray(0, 3 * m) : points) + this.colorBuffer.update(1) + this.sizeBuffer.update(1) + if(idArray) this.idBuffer.update(idArray.subarray(0, m)) + else this.idBuffer.update(1) + if(outline) { + var lc = options.lineColor, lca = new Float32Array(4 * m), l = [0, 0, 0, 1] + if(isArrayOrTypedArray(lc) && (lc.length === 3 || lc.length === 4)) { + l[0] = lc[0]; l[1] = lc[1]; l[2] = lc[2]; l[3] = lc.length === 4 ? lc[3] : 1 + if(!this.hasAlpha && l[3] < 1) this.hasAlpha = true + } + for(var i = 0; i < m; ++i) { lca[4 * i] = l[0]; lca[4 * i + 1] = l[1]; lca[4 * i + 2] = l[2]; lca[4 * i + 3] = l[3] } + this.lineColorBuffer.update(lca) + } else if(this.lineColorBuffer) this.lineColorBuffer.update(1) + this.glyphBuffer.update(1) + + if(positionArray) pool.free(positionArray) + if(idArray) pool.free(idArray) + this.flatState = {n: n, pick: pick, outline: !!outline, size: size, kind: this._kind, kept: 0} + return true +} + // Fill the disc buffers, 1 vertex per point. Returns false if the disc path cannot be used. +// The number of points of an update; with positionsKept, that of the buffers kept from the last one +proto._count = function(options) { + return options.positionsKept ? this.flatState.n : positionCount(options.position) +} + proto._updateDisc = function(options) { var gl = this.gl var points = options.position - var n = points.length + var n = this._count(options) var kind = discKind(options.glyph, n) + this._kind = kind var outline = this.lineWidth > 0 try { this._discSetup(kind, outline) @@ -20339,6 +20488,19 @@ proto._updateDisc = function(options) { return false } + if(isFlatPositions(points) || options.positionsKept) { + var fc = options.color + var flc = options.lineColor + var perPoint = (isArrayOrTypedArray(fc) && isArrayOrTypedArray(fc[0])) || isArrayOrTypedArray(options.size) || + (outline && isArrayOrTypedArray(flc) && isArrayOrTypedArray(flc[0])) + if(!perPoint) { + if(!this._discSizeFits(options.size ? +options.size : 12)) return false + return this._updateDiscFlat(options, points, n, outline) + } + if(options.positionsKept) return false + points = unflattenPositions(points) + } + var colors = options.color var lineColors = options.lineColor var sizes = options.size @@ -20422,12 +20584,7 @@ proto._updateDisc = function(options) { } // Largest sprite in device pixels (+2 for the antialiasing margin) against the driver's point size cap - var range = gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE) - this.pointSizeRange = [range[0], range[1]] - var maxPx = 2 * (maxSize * this.discUnit.b * this.pixelRatio * Math.max(1, this.highlightScale || 1) + - this._discLineHalf(this.pixelRatio) + 1) - if(maxPx > range[1]) { - this.discBlocker = 'marker size ' + maxPx.toFixed(0) + ' px exceeds point size cap ' + range[1] + if(!this._discSizeFits(maxSize)) { pool.free(positionArray) pool.free(colorArray) pool.free(sizeArray) @@ -20436,11 +20593,12 @@ proto._updateDisc = function(options) { return false } - this.bounds = [lowerBound, upperBound] + this.bounds = points.bounds || [lowerBound, upperBound] this.points = points this.pointCount = n this.vertexCount = m this.lineVertexCount = 0 + this.discConst = null this.pointBuffer.update(positionArray.subarray(0, 3 * m)) this.colorBuffer.update(colorArray.subarray(0, 4 * m)) @@ -20510,6 +20668,7 @@ function drawDisc(points, camera, pixelRatio, pick, hard) { } set.vao.bind() + points._discConstAttrs(gl) set.vao.draw(gl.POINTS, points.vertexCount) if(rimPass) { uniforms.rim = 1 @@ -20608,10 +20767,18 @@ proto.pick = function(selected) { return null } + if(!this.points) return null + //Unpack result - var coord = this.points[x] var result = this._selectResult result.index = x + if(isFlatPositions(this.points)) { + for(var i=0; i<3; ++i) { + result.position[i] = result.dataCoordinate[i] = this.points[3 * x + i] + } + return result + } + var coord = this.points[x] for(var i=0; i<3; ++i) { result.position[i] = result.dataCoordinate[i] = coord[i] } @@ -20751,14 +20918,30 @@ proto.update = function(options) { //Circle markers as 1 vertex discs if('markerRender' in options) this.markerRender = options.markerRender if('discHardEdge' in options) this.discHardEdge = !!options.discHardEdge + // With positionsKept the caller sends no positions; if the buffers of the last update cannot serve + // this one, positionsMissing asks for them + var kept = !!options.positionsKept + this.positionsMissing = false + if(!kept) this.flatState = null + else if(!this.flatState) { + this.positionsMissing = true + return + } this.discBlocker = this._discBlocker(options) this.discActive = false if(!this.discBlocker && this._updateDisc(options)) { this.discActive = true return } + if(kept) { + this.flatState = null + this.positionsMissing = true + return + } if(this.sizeBuffer) this.sizeBuffer.update(1) // release the disc buffers while glyphs are in use if(this.lineColorBuffer) this.lineColorBuffer.update(1) + this.discConst = null + if(isFlatPositions(points)) points = unflattenPositions(points) //Text font var font = { @@ -21048,7 +21231,7 @@ proto.update = function(options) { } //Update bounds - this.bounds = [lowerBound, upperBound] + this.bounds = points.bounds || [lowerBound, upperBound] //Save points this.points = points diff --git a/stackgl_modules/package-lock.json b/stackgl_modules/package-lock.json index 36e50d1169a..2ae8ab2e135 100644 --- a/stackgl_modules/package-lock.json +++ b/stackgl_modules/package-lock.json @@ -17,7 +17,7 @@ "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", "gl-plot3d": "^2.4.7", - "gl-scatter3d": "github:settylab/gl-scatter3d#25590f6d72f6f98b91f283d4d5614933657bfb6a", + "gl-scatter3d": "github:settylab/gl-scatter3d#910ab7614b177f96891386843107f035ca21e50a", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", "gl-streamtube3d": "^1.4.2", @@ -1347,7 +1347,8 @@ }, "node_modules/gl-scatter3d": { "version": "1.4.1", - "resolved": "git+ssh://git@github.com/settylab/gl-scatter3d.git#25590f6d72f6f98b91f283d4d5614933657bfb6a", + "resolved": "git+ssh://git@github.com/settylab/gl-scatter3d.git#910ab7614b177f96891386843107f035ca21e50a", + "integrity": "sha512-DZL/j73bpbT3nXkHB1vMdUS9hhALzvSJd92HEl3b4aNG9yckf5EU+U8SVIY1I78CAM92GD2WQNTPV52Kc6hQGQ==", "license": "MIT", "dependencies": { "gl-buffer": "^2.1.2", diff --git a/stackgl_modules/package.json b/stackgl_modules/package.json index f8ec311abc1..23760e4b999 100644 --- a/stackgl_modules/package.json +++ b/stackgl_modules/package.json @@ -20,7 +20,7 @@ "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", "gl-plot3d": "^2.4.7", - "gl-scatter3d": "github:settylab/gl-scatter3d#25590f6d72f6f98b91f283d4d5614933657bfb6a", + "gl-scatter3d": "github:settylab/gl-scatter3d#910ab7614b177f96891386843107f035ca21e50a", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", "gl-streamtube3d": "^1.4.2", From 2c178c8366e5be6eda18713c3f559610e03e517e Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:26:29 -0800 Subject: [PATCH 16/45] Keep typed scatter3d positions flat, and on the GPU between plot calls A scatter3d trace made one small array for each point, also for typed x, y, and z. Each plot call scanned the data three times and uploaded all positions again, also for a color change of one trace. Typed data of a trace with markers only, on linear axes, now converts to one Float32Array. The scene scans the data one time for the bounds. A later plot call with the same buffer ranges, scale, and layout.datarevision sends no positions. --- draftlogs/XXXX_change.md | 1 + src/plots/gl3d/scene.js | 69 +++++ src/traces/scatter3d/convert.js | 135 +++++++++- test/jasmine/tests/scatter3d_test.js | 365 +++++++++++++++++++++++++++ 4 files changed, 556 insertions(+), 14 deletions(-) create mode 100644 draftlogs/XXXX_change.md diff --git a/draftlogs/XXXX_change.md b/draftlogs/XXXX_change.md new file mode 100644 index 00000000000..d2e25d00eb3 --- /dev/null +++ b/draftlogs/XXXX_change.md @@ -0,0 +1 @@ +- Convert typed `x`, `y`, and `z` of a `scatter3d` trace with markers only to one `Float32Array`, scan the data one time for the bounds, and keep the positions on the GPU when a later plot call gives the same data [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/src/plots/gl3d/scene.js b/src/plots/gl3d/scene.js index b76514d335a..ec0b46943f1 100644 --- a/src/plots/gl3d/scene.js +++ b/src/plots/gl3d/scene.js @@ -494,9 +494,75 @@ proto.recoverContext = function() { var axisProperties = [ 'xaxis', 'yaxis', 'zaxis' ]; +const rangeOf = (a) => ({ buffer: a.buffer, offset: a.byteOffset, length: a.length }); +const sameRange = (r, a) => r.buffer === a.buffer && r.offset === a.byteOffset && r.length === a.length; + +/** + * Add the bounds of a scatter3d trace with typed x, y, and z on linear axes. + * + * One loop reads the three arrays. The scene keeps the result for the next plot call + * with the same buffer ranges and `layout.datarevision`. If every point is finite, + * `trace._typedBounds` gives the bounds to the conversion of the trace. + * + * @param scene - the scene + * @param trace - the full trace + * @param bounds - the bounds of the scene data, which this function extends + * @returns false if the trace needs the conversion of one value at a time + */ +function typedTraceBounds(scene, trace, bounds) { + const { x, y, z } = trace; + const layout = scene.fullSceneLayout; + if (trace.type !== 'scatter3d') return false; + if (!Lib.isTypedArray(x) || !Lib.isTypedArray(y) || !Lib.isTypedArray(z)) return false; + if (layout.xaxis.type !== 'linear' || layout.yaxis.type !== 'linear' || layout.zaxis.type !== 'linear') return false; + const n = x.length; + if ((trace._xlength || n) !== n || (trace._ylength || n) !== n || (trace._zlength || n) !== n) return false; + if (y.length !== n || z.length !== n) return false; + + const rev = scene.fullLayout.datarevision; + let b = scene._typedBounds?.[trace.uid]; + if (!(b && b.n === n && b.rev === rev && sameRange(b.x, x) && sameRange(b.y, y) && sameRange(b.z, z))) { + let x0 = Infinity; + let x1 = -Infinity; + let y0 = Infinity; + let y1 = -Infinity; + let z0 = Infinity; + let z1 = -Infinity; + let finite = true; + for (let i = 0; i < n; i++) { + const u = x[i]; + const v = y[i]; + const w = z[i]; + if (u - u === 0) { + if (u < x0) x0 = u; + if (u > x1) x1 = u; + } else finite = false; + if (v - v === 0) { + if (v < y0) y0 = v; + if (v > y1) y1 = v; + } else finite = false; + if (w - w === 0) { + if (w < z0) z0 = w; + if (w > z1) z1 = w; + } else finite = false; + } + b = { x: rangeOf(x), y: rangeOf(y), z: rangeOf(z), n, rev, lo: [x0, y0, z0], hi: [x1, y1, z1], finite }; + } + if (scene._typedBoundsNext) scene._typedBoundsNext[trace.uid] = b; + + for (let d = 0; d < 3; d++) { + if (b.lo[d] < bounds[0][d]) bounds[0][d] = b.lo[d]; + if (b.hi[d] > bounds[1][d]) bounds[1][d] = b.hi[d]; + } + trace._typedBounds = b.finite ? { x, y, z, lo: b.lo, hi: b.hi } : null; + return true; +} + function computeTraceBounds(scene, trace, bounds) { var fullSceneLayout = scene.fullSceneLayout; + if (typedTraceBounds(scene, trace, bounds)) return; + for(var d = 0; d < 3; d++) { var axisName = axisProperties[d]; var axLetter = axisName.charAt(0); @@ -596,12 +662,15 @@ proto.plot = function(sceneData, fullLayout, layout) { [-Infinity, -Infinity, -Infinity] ]; + scene._typedBoundsNext = {}; for(i = 0; i < sceneData.length; ++i) { data = sceneData[i]; if(data.visible !== true || data._length === 0) continue; computeTraceBounds(this, data, dataBounds); } + scene._typedBounds = scene._typedBoundsNext; + scene._typedBoundsNext = null; computeAnnotationBounds(this, dataBounds); var dataScale = [1, 1, 1]; diff --git a/src/traces/scatter3d/convert.js b/src/traces/scatter3d/convert.js index 45c9778a286..79254686dcf 100644 --- a/src/traces/scatter3d/convert.js +++ b/src/traces/scatter3d/convert.js @@ -186,7 +186,67 @@ function formatParam(paramIn, len, calculate, dflt, extraFn) { return paramOut; } -function convertPlotlyOptions(scene, data) { +// Typed x, y, and z of a trace with markers only, on linear axes, convert to +// one Float32Array (x, y, z for each point) and not to one array for each point. +function isFlat(data, sceneLayout, x, y, z, len) { + if (!Lib.isTypedArray(x) || !Lib.isTypedArray(y) || !Lib.isTypedArray(z)) return false; + if (sceneLayout.xaxis.type !== 'linear' || sceneLayout.yaxis.type !== 'linear' || sceneLayout.zaxis.type !== 'linear') { + return false; + } + if (data.mode !== 'markers' || data.surfaceaxis >= 0) return false; + if (['error_x', 'error_y', 'error_z'].some((e) => data[e]?.visible)) return false; + const p = data.projection; + if (p && (p.x?.show || p.y?.show || p.z?.show)) return false; + return y.length >= len && z.length >= len; +} + +function flatPositions(data, scaleFactor, x, y, z, len) { + const [sx, sy, sz] = scaleFactor; + const out = new Float32Array(3 * len); + // The scene scanned these arrays for its bounds, and every point is finite. + // The scale is positive, so the bounds of the products are the products of the bounds. + const tb = data._typedBounds; + if (tb && tb.x === x && tb.y === y && tb.z === z && x.length === len && sx > 0 && sy > 0 && sz > 0) { + for (let i = 0, o = 0; i < len; i++, o += 3) { + out[o] = x[i] * sx; + out[o + 1] = y[i] * sy; + out[o + 2] = z[i] * sz; + } + out.bounds = [ + [tb.lo[0] * sx, tb.lo[1] * sy, tb.lo[2] * sz], + [tb.hi[0] * sx, tb.hi[1] * sy, tb.hi[2] * sz] + ]; + out.finite = true; + return out; + } + // Bounds of the finite points, from the same doubles as the conversion of one point at a time + const lo = [Infinity, Infinity, Infinity]; + const hi = [-Infinity, -Infinity, -Infinity]; + for (let i = 0, o = 0; i < len; i++, o += 3) { + const a = x[i] * sx; + const b = y[i] * sy; + const c = z[i] * sz; + out[o] = a; + out[o + 1] = b; + out[o + 2] = c; + if (a - a === 0 && b - b === 0 && c - c === 0) { + if (a < lo[0]) lo[0] = a; + if (a > hi[0]) hi[0] = a; + if (b < lo[1]) lo[1] = b; + if (b > hi[1]) hi[1] = b; + if (c < lo[2]) lo[2] = c; + if (c > hi[2]) hi[2] = c; + } + } + out.bounds = [lo, hi]; + return out; +} + +// The same range of the same buffer holds the same data, also in a new view object. +const rangeOf = (a) => ({ buffer: a.buffer, offset: a.byteOffset, length: a.length }); +const sameRange = (r, a) => r.buffer === a.buffer && r.offset === a.byteOffset && r.length === a.length; + +function convertPlotlyOptions(scene, data, self, sendPositions) { var points = []; var sceneLayout = scene.fullSceneLayout; var scaleFactor = scene.dataScale; @@ -206,18 +266,52 @@ function convertPlotlyOptions(scene, data) { var params, i; var text; - // Convert points - for (i = 0; i < len; i++) { - // sanitize numbers and apply transforms based on axes.type - xc = xaxis.d2l(x[i], 0, xcalendar) * scaleFactor[0]; - yc = yaxis.d2l(y[i], 0, ycalendar) * scaleFactor[1]; - zc = zaxis.d2l(z[i], 0, zcalendar) * scaleFactor[2]; + // gl-scatter3d keeps the positions of the last update when the same data + // comes again at the same scale: the same buffer ranges and `layout.datarevision`. + const flat = isFlat(data, sceneLayout, x, y, z, len); + const skip = data.hoverinfo === 'skip'; + const rev = scene.fullLayout.datarevision; + const key = self?._flatKey; + const kept = + flat && + !sendPositions && + !!key && + !!self.scatterPlot?.flatState && + key.n === len && + key.rev === rev && + key.skip === skip && + key.scale.every((s, j) => s === scaleFactor[j]) && + sameRange(key.x, x) && + sameRange(key.y, y) && + sameRange(key.z, z); + if (self && !kept) { + self._flatKey = flat + ? { x: rangeOf(x), y: rangeOf(y), z: rangeOf(z), n: len, rev, skip, scale: scaleFactor.slice() } + : null; + } - points[i] = [xc, yc, zc]; + if (kept) { + // A trace with hover keeps the flat positions for the hover label + points = skip ? null : self.dataPoints; + } else if (flat) { + points = flatPositions(data, scaleFactor, x, y, z, len); + } else { + // Convert points + for (i = 0; i < len; i++) { + // sanitize numbers and apply transforms based on axes.type + xc = xaxis.d2l(x[i], 0, xcalendar) * scaleFactor[0]; + yc = yaxis.d2l(y[i], 0, ycalendar) * scaleFactor[1]; + zc = zaxis.d2l(z[i], 0, zcalendar) * scaleFactor[2]; + + points[i] = [xc, yc, zc]; + } } // convert text - if (Array.isArray(data.text)) { + if (flat && !Lib.isArrayOrTypedArray(data.text)) { + // One text for all the points of a trace with markers only needs no array + text = data.text; + } else if (Array.isArray(data.text)) { text = data.text; } else if (Lib.isTypedArray(data.text)) { text = Array.from(data.text); @@ -270,6 +364,8 @@ function convertPlotlyOptions(scene, data) { // Build object parameters params = { position: points, + positionsKept: kept, + skip: flat && skip, mode: data.mode, text: text }; @@ -369,7 +465,7 @@ proto.update = function (data) { this.data = data; // Run data conversion - var options = convertPlotlyOptions(this.scene, data); + var options = convertPlotlyOptions(this.scene, data, this); if ('mode' in options) { this.mode = options.mode; @@ -382,8 +478,8 @@ proto.update = function (data) { this.color = arrayToColor(options.scatterColor) || arrayToColor(options.lineColor); - // Save data points - this.dataPoints = options.position; + // Save data points. A flat trace without hover keeps none. + if (!options.positionsKept) this.dataPoints = options.skip ? [] : options.position; lineOptions = { gl: this.scene.glplot.gl, @@ -422,6 +518,8 @@ proto.update = function (data) { opacity: scatterOpacity, orthographic: true, markerRender: this.scene.fullSceneLayout.markerrender, + positionsKept: options.positionsKept, + pick: !options.skip, lineWidth: options.scatterLineWidth, lineColor: options.scatterLineColor, project: options.project, @@ -430,8 +528,17 @@ proto.update = function (data) { }; if (this.mode.indexOf('markers') !== -1) { - if (this.scatterPlot) this.scatterPlot.update(scatterOptions); - else { + if (this.scatterPlot) { + this.scatterPlot.update(scatterOptions); + if (this.scatterPlot.positionsMissing) { + // gl-scatter3d draws this update on another marker path, which needs the positions + options = convertPlotlyOptions(this.scene, data, this, true); + this.dataPoints = options.skip ? [] : options.position; + scatterOptions.position = options.position; + scatterOptions.positionsKept = false; + this.scatterPlot.update(scatterOptions); + } + } else { this.scatterPlot = createScatterPlot(scatterOptions); this.scatterPlot._trace = this; this.scatterPlot.highlightScale = 1; diff --git a/test/jasmine/tests/scatter3d_test.js b/test/jasmine/tests/scatter3d_test.js index 1ec44ef21ce..0167972e392 100644 --- a/test/jasmine/tests/scatter3d_test.js +++ b/test/jasmine/tests/scatter3d_test.js @@ -516,3 +516,368 @@ describe('Test scatter3d interactions:', function() { }); }); }); + +describe('Test scatter3d typed positions:', function() { + var DISC = {scene: {markerrender: 'disc'}}; + + function f32(n, seed) { + var a = new Float32Array(n); + var s = seed; + for(var i = 0; i < n; i++) { + s = (s * 1664525 + 1013904223) >>> 0; + a[i] = s / 4294967296; + } + return a; + } + + function cloud10(n, extra, seed) { + seed = seed || 0; + var t = {type: 'scatter3d', mode: 'markers', x: f32(n, 1 + seed), y: f32(n, 2 + seed), z: f32(n, 3 + seed), + marker: {size: 10, color: 'blue', line: {width: 0}}}; + for(var k in extra) t[k] = extra[k]; + return t; + } + + describe('scatter3d flat typed positions', function() { + var gd; + + beforeEach(function() { gd = createGraphDiv(); }); + afterEach(function() { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function cloud(n, extra) { + var t = {type: 'scatter3d', mode: 'markers', x: f32(n, 1), y: f32(n, 2), z: f32(n, 3), + marker: {size: 4, color: 'blue', line: {width: 0}}}; + for(var k in extra) t[k] = extra[k]; + return t; + } + function obj(i) { return gd._fullLayout.scene._scene.traces[gd._fullData[i].uid].scatterPlot; } + + it('@gl draws typed x, y and z from one Float32Array with constant colour and size', function(done) { + Plotly.newPlot(gd, [cloud(1000)], DISC) + .then(function() { + var o = obj(0); + expect(o.discActive).toBe(true); + expect(o.points instanceof Float32Array).toBe(true); + expect(o.points.length).toBe(3000); + expect(o.discConst).toBeTruthy(); + expect(o.discConst.noPick).toBe(false); + expect(o.vertexCount).toBe(1000); + }) + .then(done, done.fail); + }); + + it('@gl drops NaN points and keeps the original index for picking', function(done) { + var t = cloud(10); + t.x[3] = NaN; + Plotly.newPlot(gd, [t], DISC) + .then(function() { + var o = obj(0); + expect(o.pointCount).toBe(10); + expect(o.vertexCount).toBe(9); + var sel = {id: o.pickId, value: [0, 0, 7]}; + var r = o.pick(sel); + expect(r.index).toBe(7); + expect(r.position[1]).toBe(o.points[22]); + }) + .then(done, done.fail); + }); + + it('@gl keeps neither pick ids nor positions for hoverinfo skip', function(done) { + Plotly.newPlot(gd, [cloud(1000, {hoverinfo: 'skip'})], DISC) + .then(function() { + var o = obj(0); + expect(o.discConst.noPick).toBe(true); + expect(o.points).toBe(null); + expect(o.pick({id: o.pickId, value: [0, 0, 1]})).toBe(null); + }) + .then(done, done.fail); + }); + + it('@gl falls back to per-point arrays for per-point colours and other symbols', function(done) { + var c = []; + for(var i = 0; i < 100; i++) c.push(i % 2 ? 'red' : 'blue'); + Plotly.newPlot(gd, [ + cloud(100, {marker: {color: c, size: 4, line: {width: 0}}}), + cloud(100, {marker: {symbol: 'square', size: 4, color: 'red', line: {width: 0}}}) + ], DISC) + .then(function() { + expect(obj(0).discActive).toBe(true); + expect(obj(0).discConst).toBe(null); + expect(Array.isArray(obj(0).points)).toBe(true); + expect(obj(1).discActive).toBe(false); + expect(Array.isArray(obj(1).points)).toBe(true); + }) + .then(done, done.fail); + }); + + it('@gl draws typed arrays as glyphs with the default markerrender', function(done) { + Plotly.newPlot(gd, [cloud(100)]) + .then(function() { + expect(gd._fullLayout.scene.markerrender).toBe('glyph'); + expect(obj(0).discActive).toBe(false); + expect(obj(0).flatState).toBe(null); + expect(Array.isArray(obj(0).points)).toBe(true); + expect(obj(0).points.length).toBe(100); + return Plotly.restyle(gd, 'marker.color', 'red'); + }) + .then(function() { + expect(obj(0).positionsMissing).toBe(false); + expect(obj(0).points.length).toBe(100); + }) + .then(done, done.fail); + }); + + it('@gl takes the per-point path for plain arrays', function(done) { + var t = cloud(100); + t.x = Array.from(t.x); + Plotly.newPlot(gd, [t], DISC) + .then(function() { + expect(Array.isArray(obj(0).points)).toBe(true); + expect(obj(0).discConst).toBe(null); + }) + .then(done, done.fail); + }); + }); + + describe('scatter3d typed bounds, one scan', function() { + var gd; + + beforeEach(function() { gd = createGraphDiv(); }); + afterEach(function() { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function cloud(n, seed) { + return {type: 'scatter3d', mode: 'markers', x: f32(n, seed), y: f32(n, seed + 1), z: f32(n, seed + 2), + marker: {size: 4, color: 'blue', line: {width: 0}}}; + } + function scene() { return gd._fullLayout.scene._scene; } + function obj(i) { return scene().traces[gd._fullData[i].uid].scatterPlot; } + // the bounds the per-point path gives: the finite points, scaled as doubles + function expected(t, len) { + var s = scene().dataScale; + var lo = [Infinity, Infinity, Infinity]; + var hi = [-Infinity, -Infinity, -Infinity]; + for(var i = 0; i < len; i++) { + var p = [t.x[i] * s[0], t.y[i] * s[1], t.z[i] * s[2]]; + if(isFinite(p[0]) && isFinite(p[1]) && isFinite(p[2])) { + for(var d = 0; d < 3; d++) { + if(p[d] < lo[d]) lo[d] = p[d]; + if(p[d] > hi[d]) hi[d] = p[d]; + } + } + } + return [lo, hi]; + } + + it('@gl gives the bounds of the per-point path for finite data, NaN data and arrays of unequal length', function(done) { + var a = cloud(500, 1); + var b = cloud(500, 11); + b.y[7] = NaN; + b.x[499] = 50; + b.z[499] = NaN; + var c = cloud(300, 21); + c.x = f32(400, 31); + Plotly.newPlot(gd, [a, b, c], DISC) + .then(function() { + expect(gd._fullData[0]._typedBounds).toBeTruthy(); + expect(gd._fullData[1]._typedBounds).toBe(null, 'a trace with a NaN keeps its own scan'); + expect(gd._fullData[2]._typedBounds).toBeUndefined('unequal lengths keep the scan per axis'); + expect(obj(0).bounds).toEqual(expected(a, 500)); + expect(obj(1).bounds).toEqual(expected(b, 500)); + expect(obj(2).bounds).toEqual(expected(c, 300)); + // the scene's scale counts every finite coordinate, as before: x = 50 of the point whose z is NaN + expect(scene().dataScale[0]).toBeCloseTo(1 / 50, 3); + expect(obj(0).vertexCount).toBe(500); + expect(obj(1).vertexCount).toBe(498); + }) + .then(done, done.fail); + }); + + it('@gl keeps the scan while the same buffer ranges and datarevision come again', function(done) { + var a = cloud(500, 1); + var first; + function scan() { return scene()._typedBounds[gd._fullData[0].uid]; } + Plotly.newPlot(gd, [a], {datarevision: 1, scene: {markerrender: 'disc'}}) + .then(function() { + first = scan(); + return Plotly.restyle(gd, 'marker.color', 'red'); + }) + .then(function() { + expect(scan()).toBe(first); + // new view objects of the same range are the same data + return Plotly.restyle(gd, {x: [a.x.subarray(0)], y: [a.y.subarray(0)], z: [a.z.subarray(0)]}); + }) + .then(function() { + expect(scan()).toBe(first); + a.x[3] = 9; + return Plotly.relayout(gd, 'datarevision', 2); + }) + .then(function() { + expect(scan()).not.toBe(first); + expect(scan().hi[0]).toBe(9); + first = scan(); + return Plotly.restyle(gd, {x: [f32(500, 77)]}); + }) + .then(function() { + expect(scan()).not.toBe(first); + expect(scan().hi[0]).toBeLessThan(1); + }) + .then(done, done.fail); + }); + }); + + describe('scatter3d positions kept across edits', function() { + var gd; + var N = 2000; + + beforeEach(function() { gd = createGraphDiv(); }); + afterEach(function() { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function scene() { return gd._fullLayout.scene._scene; } + function obj(i) { return scene().traces[gd._fullData[i].uid].scatterPlot; } + function layout() { + return {width: 600, height: 400, margin: {l: 0, r: 0, t: 0, b: 0}, showlegend: false, scene: {markerrender: 'disc'}}; + } + // bytes given to the GPU by a step + function uploaded(step) { + var gl = scene().glplot.gl; + var bytes = 0; + var bd = gl.bufferData; + var bsd = gl.bufferSubData; + gl.bufferData = function(t, d) { + if(d && d.byteLength) bytes += d.byteLength; + return bd.apply(this, arguments); + }; + gl.bufferSubData = function(t, o, d) { + if(d && d.byteLength) bytes += d.byteLength; + return bsd.apply(this, arguments); + }; + return Promise.resolve(step()).then(function() { + gl.bufferData = bd; + gl.bufferSubData = bsd; + return bytes; + }); + } + function expectKept(step, msg) { + var before = obj(0).flatState.kept; + var buffer = obj(0).pointBuffer.handle; + return uploaded(step).then(function(bytes) { + // nothing per point (the first translucent frame makes the 24 bytes of a full-screen triangle) + expect(bytes).toBeLessThan(100, msg); + expect(obj(0).flatState.kept).toBe(before + 1, msg); + expect(obj(0).pointBuffer.handle).toBe(buffer, msg); + expect(obj(0).discActive).toBe(true, msg); + }); + } + function expectSent(step, atLeast, msg) { + return uploaded(step).then(function(bytes) { + expect(bytes).not.toBeLessThan(atLeast, msg); + expect(obj(0).positionsMissing).toBe(false, msg); + }); + } + + [false, true].forEach(function(skip) { + var extra = skip ? {hoverinfo: 'skip'} : {}; + var name = skip ? ' (hoverinfo skip)' : ''; + + it('@gl colour, size, opacity and layout edits upload nothing' + name, function(done) { + var a = cloud10(N, extra); + Plotly.newPlot(gd, [a, cloud10(N, extra, 7)], layout()) + .then(function() { + return expectKept(function() { return Plotly.restyle(gd, 'marker.color', 'red', [0]); }, 'colour'); + }) + .then(function() { + expect(obj(0).discConst.color.slice(0, 3)).toEqual([1, 0, 0]); + return expectKept(function() { return Plotly.restyle(gd, 'marker.size', 6); }, 'size'); + }) + .then(function() { + expect(obj(0).discConst.size).not.toBe(10); + return expectKept(function() { return Plotly.restyle(gd, 'marker.opacity', 0.5); }, 'opacity'); + }) + .then(function() { + expect(obj(0).hasAlpha).toBe(true); + return expectKept(function() { return Plotly.relayout(gd, 'scene.bgcolor', '#eee'); }, 'background'); + }) + .then(function() { + // new view objects of the same buffer ranges are the same data + return expectKept(function() { + return Plotly.restyle(gd, {x: [a.x.subarray(0)], y: [a.y.subarray(0)], z: [a.z.subarray(0)]}, [0]); + }, 'new views'); + }) + .then(function() { + expect(obj(0).vertexCount).toBe(N); + expect(obj(0).points === null).toBe(skip); + }) + .then(done, done.fail); + }); + + it('@gl new data, a new scale, datarevision and other marker paths send the positions' + name, function(done) { + var a = cloud10(N, extra); + var P = 12 * N; + Plotly.newPlot(gd, [a], layout()) + .then(function() { + return expectSent(function() { return Plotly.restyle(gd, {x: [f32(N, 99)]}, [0]); }, P, 'new array'); + }) + .then(function() { + expect(obj(0).flatState.kept).toBe(0); + var x2 = f32(N, 99); + x2[0] = 3; + return expectSent(function() { return Plotly.restyle(gd, {x: [x2]}, [0]); }, P, 'new scale'); + }) + .then(function() { + gd.data[0].y[5] = 0.123; + return expectSent(function() { return Plotly.relayout(gd, 'datarevision', 5); }, P, 'datarevision'); + }) + .then(function() { + expect(obj(0).flatState.kept).toBe(0); + return expectSent(function() { return Plotly.restyle(gd, 'marker.line.width', 2); }, P, 'outline'); + }) + .then(function() { + expect(obj(0).discOutline).toBe(true); + // an outlined cloud keeps nothing + return expectSent(function() { return Plotly.restyle(gd, 'marker.color', 'green'); }, P, 'colour with outline'); + }) + .then(function() { + return expectSent(function() { return Plotly.restyle(gd, 'marker.line.width', 0); }, P, 'outline off'); + }) + .then(function() { + var colours = []; + for(var i = 0; i < N; i++) colours.push(i % 2 ? 'red' : 'blue'); + return expectSent(function() { return Plotly.restyle(gd, {'marker.color': [colours]}); }, P, 'colour array'); + }) + .then(function() { + expect(obj(0).discConst).toBe(null); + expect(obj(0).flatState).toBe(null); + return expectSent(function() { return Plotly.restyle(gd, 'marker.color', 'blue'); }, P, 'back to one colour'); + }) + .then(function() { + expect(obj(0).flatState.kept).toBe(0); + return expectSent(function() { return Plotly.restyle(gd, 'marker.symbol', 'square'); }, P, 'glyph symbol'); + }) + .then(function() { + expect(obj(0).discActive).toBe(false); + return expectSent(function() { return Plotly.restyle(gd, 'marker.symbol', 'circle'); }, P, 'back to discs'); + }) + .then(function() { + expect(obj(0).discActive).toBe(true); + return expectSent(function() { + return Plotly.restyle(gd, 'hoverinfo', skip ? 'all' : 'skip'); + }, skip ? 4 * N : 0, 'pick ids come and go with hoverinfo skip'); + }) + .then(function() { + expect(obj(0).discConst.noPick).toBe(!skip); + expect(obj(0).flatState.kept).toBe(0); + }) + .then(done, done.fail); + }); + }); + }); +}); From 7d11ad7479af6e48d269a9fcf306d4287c2273aa Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:26:29 -0800 Subject: [PATCH 17/45] Add scene.datascale to keep the scale of a 3D scene for legendonly traces A scene scales its data by the extent of the visible traces. A trace that the legend hides or shows can change that extent, and then every other trace converts and uploads its positions again. With datascale 'all', legendonly traces count for the scale, so the other traces keep their positions on the GPU. The default, 'visible', does not change. --- draftlogs/XXXX-datascale_add.md | 1 + src/plots/gl3d/layout/defaults.js | 1 + src/plots/gl3d/layout/layout_attributes.js | 13 ++++ src/plots/gl3d/scene.js | 4 +- src/types/generated/schema.d.ts | 5 ++ test/jasmine/tests/scatter3d_test.js | 73 ++++++++++++++++++++++ test/plot-schema.json | 10 +++ 7 files changed, 106 insertions(+), 1 deletion(-) create mode 100644 draftlogs/XXXX-datascale_add.md diff --git a/draftlogs/XXXX-datascale_add.md b/draftlogs/XXXX-datascale_add.md new file mode 100644 index 00000000000..29380df1f73 --- /dev/null +++ b/draftlogs/XXXX-datascale_add.md @@ -0,0 +1 @@ +- Add `scene.datascale` to let traces hidden in the legend keep the scale of a 3D scene, so that the positions of the other traces stay on the GPU [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/src/plots/gl3d/layout/defaults.js b/src/plots/gl3d/layout/defaults.js index fc71c144408..a66005d5caa 100644 --- a/src/plots/gl3d/layout/defaults.js +++ b/src/plots/gl3d/layout/defaults.js @@ -63,6 +63,7 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { coerce('camera.projection.type'); coerce('markerrender'); + coerce('datascale'); /* * coerce to positive number (min 0) but also do not accept 0 (>0 not >=0) diff --git a/src/plots/gl3d/layout/layout_attributes.js b/src/plots/gl3d/layout/layout_attributes.js index 026f471bee2..1c62b457e2b 100644 --- a/src/plots/gl3d/layout/layout_attributes.js +++ b/src/plots/gl3d/layout/layout_attributes.js @@ -148,6 +148,19 @@ module.exports = { '*auto* is currently the same as *disc*.' ].join(' ') }, + datascale: { + valType: 'enumerated', + values: ['visible', 'all'], + dflt: 'visible', + editType: 'plot', + description: [ + 'Determines which traces set the scale that the data of this scene is drawn at.', + 'With *visible*, hiding or showing a trace that changes the extent of the data', + 'changes the scale, and the positions of every trace are converted and uploaded again.', + 'With *all*, traces that are hidden with `visible: *legendonly*` count as well,', + 'so hiding and showing them leaves the positions of the other traces as they are.' + ].join(' ') + }, dragmode: { valType: 'enumerated', values: ['orbit', 'turntable', 'zoom', 'pan', false], diff --git a/src/plots/gl3d/scene.js b/src/plots/gl3d/scene.js index ec0b46943f1..91dc4ea23bb 100644 --- a/src/plots/gl3d/scene.js +++ b/src/plots/gl3d/scene.js @@ -663,9 +663,11 @@ proto.plot = function(sceneData, fullLayout, layout) { ]; scene._typedBoundsNext = {}; + const legendOnly = fullSceneLayout.datascale === 'all'; for(i = 0; i < sceneData.length; ++i) { data = sceneData[i]; - if(data.visible !== true || data._length === 0) continue; + const counts = data.visible === true || (legendOnly && data.visible === 'legendonly'); + if(!counts || data._length === 0) continue; computeTraceBounds(this, data, dataBounds); } diff --git a/src/types/generated/schema.d.ts b/src/types/generated/schema.d.ts index dd813ebf803..e2f9f88c82f 100644 --- a/src/types/generated/schema.d.ts +++ b/src/types/generated/schema.d.ts @@ -13734,6 +13734,11 @@ export interface Scene { z?: number; }; }; + /** + * Determines which traces set the scale that the data of this scene is drawn at. With *visible*, hiding or showing a trace that changes the extent of the data changes the scale, and the positions of every trace are converted and uploaded again. With *all*, traces that are hidden with `visible: *legendonly*` count as well, so hiding and showing them leaves the positions of the other traces as they are. + * @default 'visible' + */ + datascale?: 'visible' | 'all'; domain?: Domain; /** Determines the mode of drag interactions for this scene. */ dragmode?: 'orbit' | 'turntable' | 'zoom' | 'pan' | false; diff --git a/test/jasmine/tests/scatter3d_test.js b/test/jasmine/tests/scatter3d_test.js index 0167972e392..7c77e80fbc5 100644 --- a/test/jasmine/tests/scatter3d_test.js +++ b/test/jasmine/tests/scatter3d_test.js @@ -879,5 +879,78 @@ describe('Test scatter3d typed positions:', function() { .then(done, done.fail); }); }); + + it('@gl scene.datascale all: hiding a trace in the legend keeps the scale and the other positions', function(done) { + function wide() { + var t = cloud10(N, {}, 7); + t.x[0] = 4; + return t; + } + var scale; + var L = layout(); + L.scene.datascale = 'all'; + // the axes upload new ticks when the range changes, so this looks at the cloud's own buffers + function expectCloudKept(step, msg) { + var before = obj(0).flatState.kept; + var buffer = obj(0).pointBuffer.handle; + var update = obj(0).pointBuffer.update; + var uploads = 0; + obj(0).pointBuffer.update = function() { + uploads++; + return update.apply(this, arguments); + }; + return Promise.resolve(step()).then(function() { + expect(uploads).toBe(0, msg); + expect(obj(0).flatState.kept).toBe(before + 1, msg); + expect(obj(0).pointBuffer.handle).toBe(buffer, msg); + obj(0).pointBuffer.update = update; + }); + } + Plotly.newPlot(gd, [cloud10(N), wide()], L) + .then(function() { + scale = scene().dataScale.slice(); + expect(scale[0]).toBeCloseTo(0.25, 2); + return expectCloudKept(function() { return Plotly.restyle(gd, 'visible', 'legendonly', [1]); }, 'hide'); + }) + .then(function() { + expect(scene().dataScale).toEqual(scale); + expect(scene().glplot.objects.length).toBe(1); + return expectCloudKept(function() { return Plotly.restyle(gd, 'visible', true, [1]); }, 'show'); + }) + .then(function() { + expect(scene().dataScale).toEqual(scale); + expect(scene().glplot.objects.length).toBe(2); + // the default: the visible traces set the scale + return Plotly.newPlot(gd, [cloud10(N), wide()], layout()); + }) + .then(function() { + expect(gd._fullLayout.scene.datascale).toBe('visible'); + return expectSent(function() { return Plotly.restyle(gd, 'visible', 'legendonly', [1]); }, 12 * N, 'hide, default'); + }) + .then(function() { + expect(scene().dataScale[0]).toBeCloseTo(1, 1); + }) + .then(done, done.fail); + }); + + it('@gl scene.datascale all keeps the scale for legendonly traces, and not for removed traces', function(done) { + function scale() { return scene().dataScale.slice(); } + Plotly.newPlot(gd, [ + {type: 'scatter3d', mode: 'markers', x: [0, 1], y: [0, 1], z: [0, 1]}, + {type: 'scatter3d', mode: 'markers', x: [0, 4], y: [0, 2], z: [0, 1]} + ], {scene: {datascale: 'all'}}) + .then(function() { + expect(scale()).toEqual([1 / 4, 1 / 2, 1]); + return Plotly.restyle(gd, 'visible', 'legendonly', [1]); + }) + .then(function() { + expect(scale()).toEqual([1 / 4, 1 / 2, 1]); + return Plotly.restyle(gd, 'visible', false, [1]); + }) + .then(function() { + expect(scale()).toEqual([1, 1, 1]); + }) + .then(done, done.fail); + }); }); }); diff --git a/test/plot-schema.json b/test/plot-schema.json index 6cd634d633d..51753567a19 100644 --- a/test/plot-schema.json +++ b/test/plot-schema.json @@ -6621,6 +6621,16 @@ } } }, + "datascale": { + "description": "Determines which traces set the scale that the data of this scene is drawn at. With *visible*, hiding or showing a trace that changes the extent of the data changes the scale, and the positions of every trace are converted and uploaded again. With *all*, traces that are hidden with `visible: *legendonly*` count as well, so hiding and showing them leaves the positions of the other traces as they are.", + "dflt": "visible", + "editType": "plot", + "valType": "enumerated", + "values": [ + "visible", + "all" + ] + }, "domain": { "column": { "description": "If there is a layout grid, use the domain for this column in the grid for this scene subplot.", From bae041e7abd9af0a41e9da8364cc6e9493f10ec0 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 12:10:59 -0800 Subject: [PATCH 18/45] Create the WebGL context of the focus layer only for selections Each graph with a regl trace created two WebGL contexts. In scattergl and splom graphs, the focus layer shows only the selected points. Most graphs never select, but the browser counts the second context against its limit of about 16 for each page. prepareRegl now creates the context of the focus layer on request, or if the graph has parcoords. scattergl sends the request when a selection drag mode starts, or when the first selection draw comes. The selected points appear on the focus layer as before. --- draftlogs/XXXX_change.md | 1 + src/lib/prepare_regl.js | 7 ++- src/traces/scattergl/plot.js | 5 ++ test/jasmine/tests/gl2d_plot_interact_test.js | 55 +++++++++++++++++-- 4 files changed, 63 insertions(+), 5 deletions(-) create mode 100644 draftlogs/XXXX_change.md diff --git a/draftlogs/XXXX_change.md b/draftlogs/XXXX_change.md new file mode 100644 index 00000000000..8e469f2cf8f --- /dev/null +++ b/draftlogs/XXXX_change.md @@ -0,0 +1 @@ +- Create the WebGL context of the `scattergl` and `splom` focus layer only when a selection starts (a selection drag mode or selected points) [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/src/lib/prepare_regl.js b/src/lib/prepare_regl.js index d81c7f83a3a..c66c9add1bc 100644 --- a/src/lib/prepare_regl.js +++ b/src/lib/prepare_regl.js @@ -15,10 +15,13 @@ var createRegl = require('@plotly/regl'); * * @param {DOM node or object} gd : graph div object * @param {array} extensions : list of extension to pass to createRegl + * @param {object} reglPrecompiled : precompiled regl code for strict bundles + * @param {boolean} needsFocusLayer : if true, also create the regl instance of the focus layer. + * A graph with parcoords always gets that instance. * * @return {boolean} true if all createRegl calls succeeded, false otherwise */ -module.exports = function prepareRegl(gd, extensions, reglPrecompiled) { +module.exports = function prepareRegl(gd, extensions, reglPrecompiled, needsFocusLayer) { var fullLayout = gd._fullLayout; var success = true; @@ -29,6 +32,8 @@ module.exports = function prepareRegl(gd, extensions, reglPrecompiled) { } // only parcoords needs pick layer if(d.pick && !fullLayout._has('parcoords')) return; + // Browsers limit the WebGL contexts of a page, so the focus layer gets a context only on request + if (d.key === 'focusLayer' && !needsFocusLayer && !fullLayout._has('parcoords')) return; try { d.regl = createRegl({ diff --git a/src/traces/scattergl/plot.js b/src/traces/scattergl/plot.js index d271f8dda8a..7c0e259284f 100644 --- a/src/traces/scattergl/plot.js +++ b/src/traces/scattergl/plot.js @@ -319,6 +319,11 @@ var exports = module.exports = function plot(gd, subplot, cdata) { if(isSelectMode) { // create scatter instance by cloning scatter2d if(!scene.select2d) { + // The focus layer shows the selected points and gets its WebGL context here + if (!prepareRegl(gd, ['ANGLE_instanced_arrays', 'OES_element_index_uint'], reglPrecompiled, true)) { + scene.init(); + return; + } scene.select2d = createScatter(fullLayout._glcanvas.data()[1].regl); } diff --git a/test/jasmine/tests/gl2d_plot_interact_test.js b/test/jasmine/tests/gl2d_plot_interact_test.js index 1ee3b711a77..b825c78acf5 100644 --- a/test/jasmine/tests/gl2d_plot_interact_test.js +++ b/test/jasmine/tests/gl2d_plot_interact_test.js @@ -228,6 +228,18 @@ describe('Test gl plot side effects', function() { expect((eventData || {}).event).toBeDefined(); expect((eventData || {}).layer).toBe('contextLayer'); }) + .then(function() { + return new Promise(function(resolve, reject) { + gd.once('plotly_webglcontextlost', reject); + setTimeout(resolve, 10); + _trigger('focus'); + }); + }) + .then(function(eventData) { + // The focus canvas gets its WebGL context and its listener with the first selection + expect(eventData).toBeUndefined(); + return Plotly.relayout(gd, 'dragmode', 'select'); + }) .then(function() { return new Promise(function(resolve, reject) { gd.once('plotly_webglcontextlost', resolve); @@ -330,15 +342,50 @@ describe('Test gl plot side effects', function() { .then(done, done.fail); }); - it('@gl should create two WebGL contexts per graph', function(done) { + it('@gl should create one WebGL context per graph, and a second one when a selection is drawn', function(done) { var fig = Lib.extendDeep({}, require('../../image/mocks/gl2d_stacked_subplots.json')); - Plotly.newPlot(gd, fig).then(function() { + function countContexts() { var cnt = 0; d3Select(gd).selectAll('canvas').each(function(d) { if(d.regl) cnt++; }); - expect(cnt).toBe(2); + return cnt; + } + + Plotly.newPlot(gd, fig).then(function() { + expect(countContexts()).toBe(1); + expect(gd._fullLayout._glcanvas.data()[0].regl).toBeDefined(); + expect(gd._fullLayout._glcanvas.data()[1].regl).toBeUndefined(); + return Plotly.relayout(gd, 'dragmode', 'pan'); + }) + .then(function() { + expect(countContexts()).toBe(1); + return Plotly.relayout(gd, 'dragmode', 'lasso'); + }) + .then(function() { + // The focus layer shows the selected points + expect(countContexts()).toBe(2); + expect(gd._fullLayout._glcanvas.data()[1].regl).toBeDefined(); + return Plotly.relayout(gd, 'dragmode', 'zoom'); + }) + .then(function() { + expect(countContexts()).toBe(2); + }) + .then(done, done.fail); + }); + + it('@gl should create the focus layer context for traces with selectedpoints', function(done) { + Plotly.newPlot(gd, [{ + type: 'scattergl', + mode: 'markers', + y: [1, 2, 1], + selectedpoints: [1] + }]) + .then(function() { + expect(gd._fullLayout._glcanvas.data()[0].regl).toBeDefined(); + expect(gd._fullLayout._glcanvas.data()[1].regl).toBeDefined(); + expect(gd._fullLayout._glcanvas.data()[2].regl).toBeUndefined(); }) .then(done, done.fail); }); @@ -350,7 +397,7 @@ describe('Test gl plot side effects', function() { }, { type: 'scattergl', y: [2, 1, 2] - }]) + }], {dragmode: 'select'}) .then(function() { expect(gd._fullLayout._glcanvas).toBeDefined(); expect(gd._fullLayout._glcanvas.size()).toBe(3); From ff9da140de0b23a8a3945a8b955115e4681a4c98 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 12:14:03 -0800 Subject: [PATCH 19/45] Pin the combined package branches and rebuild the stackgl bundle The combined branch needs every package change at one time. gl-plot3d, gl-scatter3d, and regl-scatter2d point at the all branches of the forks. --- package-lock.json | 6 +- package.json | 2 +- stackgl_modules/index.js | 980 +++++++++++++++++++++++++++++- stackgl_modules/package-lock.json | 14 +- stackgl_modules/package.json | 5 +- 5 files changed, 978 insertions(+), 29 deletions(-) diff --git a/package-lock.json b/package-lock.json index 684d2505d3e..d9072789cdb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,7 +44,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "github:settylab/regl-scatter2d#e2db766d5f8032210289a86a3bbef883e9f6ef10", + "regl-scatter2d": "github:settylab/regl-scatter2d#f1147d82758075373f2719a081bd51f4ab69e62c", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", @@ -6231,8 +6231,8 @@ }, "node_modules/regl-scatter2d": { "version": "3.4.0", - "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#e2db766d5f8032210289a86a3bbef883e9f6ef10", - "integrity": "sha512-UuCLyCo03l/d0TxnXvlg+iYwad/IrtCk5cin9oIZXEM1xilGQHXLFz2InrGNyUryafwo2bSnTKShNbX/fEQE1A==", + "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#f1147d82758075373f2719a081bd51f4ab69e62c", + "integrity": "sha512-XMR0qBcf1cWR+EmLECwGQF5KtuN66YeEGZ/FDra9q5EkZ5xtfGr/98NZZxPguucnTOeWof6csl4ibo1c0TAcTw==", "license": "MIT", "dependencies": { "@plotly/point-cluster": "^3.1.9", diff --git a/package.json b/package.json index a0169cef81d..6a0fd0d8990 100644 --- a/package.json +++ b/package.json @@ -118,7 +118,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "github:settylab/regl-scatter2d#e2db766d5f8032210289a86a3bbef883e9f6ef10", + "regl-scatter2d": "github:settylab/regl-scatter2d#f1147d82758075373f2719a081bd51f4ab69e62c", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index fea9559400f..b9840c3e632 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -19365,6 +19365,24 @@ function createScene(options) { mouseListener: null, _stopped: false, + // The pick pass. 'lazy': drawn when a pointer event queries it, or pickIdleDelay ms after the last + // frame that changed it (0: never ahead of the query). 'eager': drawn in every frame that changed it (upstream). + pickMode: options.pickMode || 'lazy', + pickIdleDelay: options.pickIdleDelay === undefined ? 120 : options.pickIdleDelay, + // Query the pick buffers only when the main button goes down (hover is off): pointer moves draw nothing + pickOnPress: false, + pickStats: {draws: 0}, + + // Level of detail while the camera moves. lod = {minpoints, budget, maxstride, settle} (or null): + // with at least minpoints thinnable points in the scene (objects with lodPoints()), a frame in which + // the view changed draws every k-th point of every such object (k: the smallest power of two, at + // least 2 and at most maxstride, that brings them within budget) and no pick pass, and the first + // frame settle ms after the view last changed draws them all. + // lodState = {state: 'off', 'preview' or 'full', stride, shown, total}; onlod(state and reason) on a change. + lod: options.lod || null, + lodState: {state: 'off', stride: 0, shown: 0, total: 0}, + onlod: options.onlod || null, + getAspectratio: function() { return { x: this.aspect[0], @@ -19521,6 +19539,10 @@ function createScene(options) { } scene._stopped = true + if(pickTimer) { + clearTimeout(pickTimer) + pickTimer = null + } window.removeEventListener('resize', resizeListener) canvas.removeEventListener('webglcontextlost', checkContextLoss) @@ -19587,7 +19609,13 @@ function createScene(options) { } scene._mouseRotating = false - for(var i=0; i selection.distance) { @@ -19615,17 +19643,27 @@ function createScene(options) { } } + // A hover that changes nothing in the picture needs no frame: the axis spikes are off and the + // hovered cloud is not drawn larger (highlightScale 1, as plotly sets it). The render callback alone + // then gives the hover label and events, as it does from the frame. + var e = spikes.enabled + var still = !e[0] && !e[1] && !e[2] && !!scene.onrender && pickFrameSeen && + (!prevObj || prevObj.highlightScale === 1) && + (!selection.object || selection.object.highlightScale === 1) if(prevObj && prevObj !== selection.object) { if(prevObj.highlight) { prevObj.highlight(null) } - dirty = true + dirty = dirty || !still } if(selection.object) { if(selection.object.highlight) { selection.object.highlight(selection.data) } - dirty = true + dirty = dirty || !still + } + if(still && !dirty && (prevObj || selection.object)) { + scene.onrender() } change = change || (selection.object !== prevObj) @@ -19656,12 +19694,78 @@ function createScene(options) { canvas.addEventListener('webglcontextlost', checkContextLoss) + var pickTimer = null + var pickFrameSeen = false + var pickEmpty = false + + // True if some object that is drawn into a pick buffer can be picked + function anyPickable() { + for(var i=0; i= 0 && objects[i].drawPick && !objects[i].noPick) { + return true + } + } + return false + } + + // Draw the pick buffers and read them back now, if they are out of date + function ensurePick() { + if(pickTimer) { + clearTimeout(pickTimer) + pickTimer = null + } + if(!pickDirty || !pickFrameSeen || lodOn || scene._stopped || scene.contextLost) { + return + } + pickDirty = false + renderPick() + // the pick pass draws at pixel ratio 1; objects read their own ratio when a query follows (mesh pick) + for(var i=0; i 0) || scene.pickOnPress) { + return + } + pickTimer = setTimeout(function() { + pickTimer = null + if(scene._prevButtons) { + // nothing is queried while a button is held: look again later + schedulePick() + } else { + ensurePick() + } + }, scene.pickIdleDelay) + } + //Render the scene for mouse picking function renderPick() { if(checkContextLoss()) { return } + // Nothing can be picked (every trace has hoverinfo 'skip'): no pass, and no query reads the buffers + pickEmpty = !anyPickable() + if(pickEmpty) { + return + } + + scene.pickStats.draws++ + gl.colorMask(true, true, true, true) gl.depthMask(true) gl.disable(gl.BLEND) @@ -19992,6 +20096,72 @@ function createScene(options) { return objects.length } + // Level of detail while the camera moves (scene.lod) + var lodMoved = 0 // when the camera last moved in a preview, ms + var lodOn = false // the frames are previews + var lodView = new Float64Array(16) // the view matrix of the last frame + var lodForce = false // lodSettle: this frame draws every disc + + function lodFrame(cameraMoved) { + var o = scene.lod + var n = 0 + var k = 0 + var i + // the camera can report a move after it has reached its place: only a view that changed is a move here. + // (After a plot the camera glides to its place for about 0.4 s: those frames are previews too.) + var view = scene.camera.matrix + var moved = false + for(i=0; i<16; ++i) { + if(lodView[i] !== view[i]) { + moved = true + lodView[i] = view[i] + } + } + cameraMoved = cameraMoved && moved + if(o && o.minpoints > 0) { + for(i=0; i= o.minpoints) { + k = 2 + while(k < o.maxstride && n / k > o.budget) k *= 2 + } + } + var now = Date.now() + if(k && cameraMoved) lodMoved = now + var preview = k > 0 && !lodForce && lodMoved > 0 && now - lodMoved < o.settle + lodForce = false + if(!preview) lodMoved = 0 + var toggled = preview !== lodOn + lodOn = preview + // the frame that draws every disc again + if(toggled && !preview) dirty = true + if(preview || toggled) { + for(i=0; i 0 && o.anchored) s += 'uniform sampler2D oitAnchor;\n' if(o.pass === 2) { for(i = 0; i < T; ++i) s += 'uniform sampler2D oitTau' + i + ';\n' } - s += 'varying vec4 interpColor;\nvarying vec3 dataCoordinate;\nvarying float oitZ;\n' + s += 'varying vec4 interpColor;\n' + (o.disc ? '' : 'varying vec3 dataCoordinate;\n') + 'varying float oitZ;\n' if(o.pass > 0) { // node coordinate in [0, K-1]: log-plus-linear warp of the distance to the anchor (D), @@ -20663,13 +20852,31 @@ function oitFragSrc(o) { } s += 'void main() {\n' - s += ' if (outOfRange(fragClipBounds[0], fragClipBounds[1], dataCoordinate) || interpColor.a * opacity == 0.) discard;\n' + if(o.disc) { + // the coverage of the transparent disc pass (smooth 1 px edge), the same in all three passes + s += ' float d = length((gl_PointCoord - 0.5) * 2.0 * vHalf);\n' + s += ' float cf = clamp(vB - d + 0.5, 0.0, 1.0) * clamp(d - vA + 0.5, 0.0, 1.0);\n' + s += ' if (interpColor.a * opacity == 0.) cf = 0.;\n' + s += ' vec3 col = interpColor.rgb;\n float araw = interpColor.a * opacity * cf;\n' + s += '#ifdef OUTLINE\n' + s += ' float e = min(abs(d - vB), vA < 0.0 ? 1e6 : abs(d - vA));\n' + s += ' float cl = clamp(lineHalf - e + 0.5, 0.0, 1.0);\n' + s += ' float wf = cf * (1.0 - cl);\n' + s += ' araw = (interpColor.a * wf + interpLine.a * cl) * opacity;\n' + s += ' col = (interpColor.rgb * wf + interpLine.rgb * cl) / max(wf + cl, 1e-6);\n' + s += '#endif\n' + s += ' if (araw <= 0.0) discard;\n' + } else { + s += ' if (outOfRange(fragClipBounds[0], fragClipBounds[1], dataCoordinate) || interpColor.a * opacity == 0.) discard;\n' + } s += ' float f = (-oitZ - oitMap.x) * oitMap.y;\n' if(o.pass === 0) { + // the faint edge fragments of a disc must not set the anchor depth + if(o.disc) s += ' if (araw < 0.5 * interpColor.a * opacity) discard;\n' s += ' gl_FragColor = vec4(f, f, f, f);\n}\n' return s } - s += ' float a = min(interpColor.a * opacity, 0.99609375);\n' + s += ' float a = min(' + araw + ', 0.99609375);\n' s += ' float tau = -log(1.0 - a);\n' s += ' float x = oitX(f);\n' s += ' float k = min(floor(x), ' + f1(K - 2) + ');\n' @@ -20702,14 +20909,14 @@ function oitFragSrc(o) { } } s += ' float w = tau * ((1.0 - fr) * Wk + fr * Wk1);\n' - s += ' gl_FragColor = vec4(interpColor.rgb * w, w);\n}\n' + s += ' gl_FragColor = vec4(' + col + ' * w, w);\n}\n' return s } var oitShaderCache = [] -// o: {pass: 0|1|2, K, anchored, mrt} -function getOITShaders(gl, o) { +// the OIT shaders of one WebGL context +function oitCacheEntry(gl) { var entry = null for(var i = oitShaderCache.length - 1; i >= 0; --i) { if(oitShaderCache[i].gl === gl) entry = oitShaderCache[i] @@ -20719,6 +20926,12 @@ function getOITShaders(gl, o) { entry = {gl: gl, map: {}} oitShaderCache.push(entry) } + return entry +} + +// o: {pass: 0|1|2, K, anchored, mrt} +function getOITShaders(gl, o) { + var entry = oitCacheEntry(gl) var key = o.pass === 0 ? '0' : [o.pass, o.K, o.anchored ? 1 : 0, o.mrt ? 1 : 0].join('-') if(!entry.map[key]) { var frag = oitFragSrc(o) @@ -20736,6 +20949,8 @@ function getOITShaders(gl, o) { exports.getOITShaders = getOITShaders +exports.oitFragSrc = oitFragSrc +exports.oitCacheEntry = oitCacheEntry /***/ }, @@ -20752,6 +20967,7 @@ var createVAO = __webpack_require__(8116) var pool = __webpack_require__(1888) var mat4mult = __webpack_require__(6760) var shaders = __webpack_require__(1283) +var createShaderWrapper = __webpack_require__(9405) var getGlyph = __webpack_require__(9366) var getSimpleString = __webpack_require__(5964) @@ -20832,6 +21048,19 @@ function PointCloud( this.vertexCount = 0 this.lineVertexCount = 0 + // disc markers (see _updateDisc): 'glyph' keeps the vectorised glyph meshes + this.markerRender = 'glyph' + this.discActive = false + this.discBlocker = '' + this.discHardEdge = false + this.discSet = null + this.discCur = null + this.lodStride = 0 // > 1 draws every lodStride-th disc (a preview; never the pick pass) + this.discOutline = false + this.lineColorBuffer = null + this.sizeBuffer = null + this.pointSizeRange = null + this.opacity = 1 this.hasAlpha = false @@ -21058,6 +21287,621 @@ var NEG_INFINITY3 = [-1e8, -1e8, -1e8] var POS_INFINITY3 = [1e8, 1e8, 1e8] var CLIP_GROUP = [NEG_INFINITY3, POS_INFINITY3] +// --------------------------------------------------------------------------- +// Disc markers: a circle marker drawn as one gl.POINTS vertex (round cutout in the fragment shader) +// instead of a vectorised "●" glyph mesh of 60 to 104 vertices. The disc has the same screen-aligned constant +// pixel size as the glyph. +// '●' circle: filled disc, with an outline ring when marker.line.width is above 0 (lineColor attribute) +// '○' circle-open: hollow ring in the marker colour +// The edge of the disc in the opaque pass is chosen at draw time, see drawDisc. +// --------------------------------------------------------------------------- +var DISC_FILL = '●' +var DISC_OPEN = '○' + +var DISC_OUT_OF_RANGE = [ + 'bool outOfRange(float a, float b, float p) {', + ' return ((p > max(a, b)) || (p < min(a, b)));', + '}', + 'bool outOfRange(vec3 a, vec3 b, vec3 p) {', + ' return (outOfRange(a.x, b.x, p.x) || outOfRange(a.y, b.y, p.y) || outOfRange(a.z, b.z, p.z));', + '}' +].join('\n') + +function discVert(outline) { + return [ + outline ? '#define OUTLINE' : '', + 'precision highp float;', + DISC_OUT_OF_RANGE, + 'attribute vec3 position;', + 'attribute vec4 color;', + 'attribute float size;', + 'attribute vec4 id;', + '#ifdef OUTLINE', + 'attribute vec4 lineColor;', + 'varying vec4 interpLine;', + '#endif', + 'uniform mat4 model, view, projection;', + 'uniform vec2 screenSize;', + 'uniform vec3 clipBounds[2];', + 'uniform float highlightScale, pixelRatio, unitA, unitB, lineHalf;', + 'uniform vec2 unitCenter;', + 'uniform vec4 highlightId;', + 'varying vec4 interpColor;', + 'varying vec4 pickId;', + 'varying float vA;', + 'varying float vB;', + 'varying float vHalf;', + 'void main() {', + ' if (outOfRange(clipBounds[0], clipBounds[1], position)) {', + ' gl_Position = vec4(0, 0, 0, 0);', + ' gl_PointSize = 1.0;', + ' vA = -1.0; vB = 0.0; vHalf = 1.0;', + ' } else {', + ' float scale = pixelRatio;', + ' if (distance(highlightId.bgr, id.bgr) < 0.001) {', + ' scale *= highlightScale;', + ' }', + ' vec4 clipPosition = projection * (view * (model * vec4(position, 1.0)));', + ' clipPosition /= clipPosition.w;', + ' gl_Position = clipPosition + vec4(screenSize * scale * size * vec2(unitCenter.x, -unitCenter.y), 0.0, 0.0);', + ' vB = scale * size * unitB;', + ' vA = unitA < 0.0 ? -1.0 : scale * size * unitA;', + ' vHalf = vB + lineHalf + 1.0;', + ' gl_PointSize = 2.0 * vHalf;', + ' interpColor = color;', + ' pickId = id;', + '#ifdef OUTLINE', + ' interpLine = lineColor;', + '#endif', + ' }', + '}' + ].join('\n') +} + +function discFrag(outline) { + return [ + outline ? '#define OUTLINE' : '', + 'precision highp float;', + 'uniform float opacity, hardEdge, lineHalf, a2c, rim;', + 'varying vec4 interpColor;', + 'varying float vA;', + 'varying float vB;', + 'varying float vHalf;', + '#ifdef OUTLINE', + 'varying vec4 interpLine;', + '#endif', + 'void main() {', + ' float d = length((gl_PointCoord - 0.5) * 2.0 * vHalf);', + ' float cf = hardEdge > 0.5 ? step(d, vB) * step(vA, d)', + ' : clamp(vB - d + 0.5, 0.0, 1.0) * clamp(d - vA + 0.5, 0.0, 1.0);', + ' if (interpColor.a * opacity == 0.) cf = 0.;', + ' vec4 c = interpColor * (opacity * cf);', + '#ifdef OUTLINE', + ' float e = min(abs(d - vB), vA < 0.0 ? 1e6 : abs(d - vA));', // outer edge, plus the inner edge of a ring + ' float cl = hardEdge > 0.5 ? step(e, lineHalf) : clamp(lineHalf - e + 0.5, 0.0, 1.0);', + ' c = c * (1.0 - cl) + interpLine * (opacity * cl);', + ' if (cf + cl <= 0.0) discard;', + '#else', + ' if (cf <= 0.0) discard;', + '#endif', + ' if (rim > -0.5) {', + ' if (rim < 0.5 && c.a < 0.999) discard;', // pass 0: fully covered pixels only (opaque cores, depth written) + ' if (rim > 0.5 && (c.a >= 0.999 || c.a <= 0.0)) discard;', // pass 1: partial-coverage rim pixels, blended over + ' }', + ' gl_FragColor = a2c > 0.5 ? vec4(c.rgb / max(c.a, 1e-4), c.a) : c;', // pure a2c: full colour, alpha = coverage (alpha channel is masked) + '}' + ].join('\n') +} + +var DISC_PICK_FRAG = [ + 'precision highp float;', + 'uniform float pickGroup, lineHalf;', + 'varying vec4 pickId;', + 'varying float vA;', + 'varying float vB;', + 'varying float vHalf;', + 'void main() {', + ' float d = length((gl_PointCoord - 0.5) * 2.0 * vHalf);', + ' if (d > vB + lineHalf || d < (vA < 0.0 ? vA : vA - lineHalf)) discard;', + ' gl_FragColor = vec4(pickGroup, pickId.bgr);', + '}' +].join('\n') + +function createDiscShader(gl, outline, pick) { + var shader = createShaderWrapper(gl, {vertex: discVert(outline), fragment: pick ? DISC_PICK_FRAG : discFrag(outline)}) + var attr = shader.attributes + attr.position.location = 0 + attr.color.location = 1 + attr.size.location = 2 + attr.id.location = 3 + if(outline && attr.lineColor) attr.lineColor.location = 4 + return shader +} + +// 'fill', 'open', or '' when the symbols are anything else +function discKind(glyphs, n) { + var first + if(isArrayOrTypedArray(glyphs)) { + if(glyphs.length < n || n === 0) return '' + first = glyphs[0] + for(var i = 0; i < n; ++i) if(glyphs[i] !== first) return '' + } else { + first = glyphs + } + return first === DISC_FILL ? 'fill' : first === DISC_OPEN ? 'open' : '' +} + +// Returns '' when the disc path can draw this update, otherwise the reason it cannot +proto._discBlocker = function(options) { + var mode = this.markerRender + if(mode !== 'disc' && mode !== 'auto') return 'markerRender is ' + mode + if(!options.position && !options.positionsKept) return 'no positions' + if(!this.useOrtho) return 'perspective sizing' + for(var i = 0; i < 3; ++i) if(this.axesProject[i]) return 'axes projection' + var angles = options.angle + if(angles && (!isArrayOrTypedArray(angles) || angles.length)) return 'marker angle' + var al = options.alignment + if(al && (al.length !== 2 || al[0] || al[1])) return 'alignment' + var kind = discKind(options.glyph, this._count(options)) + if(!kind) return 'symbol is not circle or circle-open' + return '' +} + +proto._discSetup = function(kind, outline) { + var gl = this.gl + if(!this.sizeBuffer) this.sizeBuffer = createBuffer(gl) + if(outline && !this.lineColorBuffer) this.lineColorBuffer = createBuffer(gl) + var key = outline ? 'outline' : 'plain' + if(!this.discSet) this.discSet = {} + if(!this.discSet[key]) { + var attrs = [ + { buffer: this.pointBuffer, size: 3, type: gl.FLOAT }, + { buffer: this.colorBuffer, size: 4, type: gl.FLOAT }, + { buffer: this.sizeBuffer, size: 1, type: gl.FLOAT }, + { buffer: this.idBuffer, size: 4, type: gl.UNSIGNED_BYTE, normalized: true } + ] + if(outline) attrs.push({ buffer: this.lineColorBuffer, size: 4, type: gl.FLOAT }) + this.discSet[key] = { + shader: createDiscShader(gl, outline, false), + pickShader: createDiscShader(gl, outline, true), + vao: createVAO(gl, attrs), + attrs: attrs, + lod: null + } + } + this.discCur = this.discSet[key] + this.discOutline = outline + // Radii of the glyph, in the units the glyph shaders use (already divided by the pixelRatio the glyph was cached with). + // The disc is centred on the point: the glyph's own centre sits a little off (font bearings, up to ~0.012 * size px) + // and differs between glyph cache entries, so it is not reproduced. + var font = {family: 'normal', style: 'normal', weight: 'normal', variant: 'normal'} + var g = get_glyphData(kind === 'open' ? DISC_OPEN : DISC_FILL, font, this.pixelRatio) + var b = g.bounds + var cx = 0.5 * (b[0][0] + b[1][0]) + var cy = 0.5 * (b[0][1] + b[1][1]) + var lp = g.lines.positions + var rs = [] + var i + if(kind === 'fill') { + var s = 0 + for(i = 0; i < lp.length; ++i) s += Math.hypot(lp[i][0] - cx, lp[i][1] - cy) + this.discUnit = {cx: 0, cy: 0, a: -1, b: s / lp.length} + } else { + // ring: outer and inner polygon radii + var mp = g.mesh.positions + var rmin = Infinity, rmax = -Infinity + for(i = 0; i < mp.length; ++i) { + var r = Math.hypot(mp[i][0] - cx, mp[i][1] - cy) + rs.push(r); rmin = Math.min(rmin, r); rmax = Math.max(rmax, r) + } + var mid = 0.5 * (rmin + rmax), so = 0, no = 0, si = 0, ni = 0 + for(i = 0; i < rs.length; ++i) { + if(rs[i] > mid) { so += rs[i]; no++ } else { si += rs[i]; ni++ } + } + this.discUnit = {cx: 0, cy: 0, a: si / ni, b: so / no} + } +} + +// Whether a sprite of this marker size (device pixels, +2 for the antialiasing margin) fits the driver's point size cap +proto._discSizeFits = function(maxSize) { + var gl = this.gl + var range = gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE) + this.pointSizeRange = [range[0], range[1]] + var maxPx = 2 * (maxSize * this.discUnit.b * this.pixelRatio * Math.max(1, this.highlightScale || 1) + + this._discLineHalf(this.pixelRatio) + 1) + if(maxPx > range[1]) { + this.discBlocker = 'marker size ' + maxPx.toFixed(0) + ' px exceeds point size cap ' + range[1] + return false + } + return true +} + +// Positions given as one flat Float32Array (x, y, z per point) +function isFlatPositions(points) { + return !!points && ArrayBuffer.isView(points) +} +function positionCount(points) { + return isFlatPositions(points) ? Math.floor(points.length / 3) : points.length +} +function unflattenPositions(flat) { + var n = positionCount(flat) + var out = new Array(n) + for(var i = 0; i < n; ++i) out[i] = [flat[3 * i], flat[3 * i + 1], flat[3 * i + 2]] + out.bounds = flat.bounds + return out +} + +// One colour, one size or no pick ids for every point of a trace are +// drawn from constant vertex attributes instead of per-point buffers (16, 4 +// and 4 bytes a point); the values are the same floats the buffers held +proto._discConstAttrs = function(gl) { + var c = this.discConst + if(c && c.color) { + gl.disableVertexAttribArray(1) + gl.vertexAttrib4f(1, c.color[0], c.color[1], c.color[2], c.color[3]) + } else gl.enableVertexAttribArray(1) + if(c && c.size !== null) { + gl.disableVertexAttribArray(2) + gl.vertexAttrib1f(2, c.size) + } else gl.enableVertexAttribArray(2) + if(c && c.noPick) { + // the "no highlight" id: hover is off for this trace, so it is never picked + gl.disableVertexAttribArray(3) + gl.vertexAttrib4f(3, 1, 1, 1, 1) + } else gl.enableVertexAttribArray(3) +} + +// The disc path for flat positions with one colour and one size: +// the positions are uploaded as given when every point is finite +proto._updateDiscFlat = function(options, points, n, outline) { + var colors = options.color + var sizes = options.size + var color = [0, 0, 0, 1] + if(isArrayOrTypedArray(colors)) { + if(colors.length === 3) { color[0] = colors[0]; color[1] = colors[1]; color[2] = colors[2] } + else if(colors.length === 4) { + color[0] = colors[0]; color[1] = colors[1]; color[2] = colors[2]; color[3] = colors[3] + if(!this.hasAlpha && colors[3] < 1) this.hasAlpha = true + } + } + var size = sizes ? +sizes : 12 + var pick = options.pick !== false + + // The same positions as at the last update (positionsKept): the position and id buffers stay, and so does + // the pick buffer when the size is the same (the pick pass reads neither colour nor opacity) + if(options.positionsKept) { + var fs = this.flatState + if(fs.n !== n || fs.pick !== pick || outline || fs.outline) return false + fs.size = size + fs.kind = this._kind + fs.kept++ + this.discConst = {color: color, size: size, noPick: !pick} + return true + } + + var lowerBound = [ Infinity, Infinity, Infinity] + var upperBound = [-Infinity,-Infinity,-Infinity] + var finite = true + // The caller has scanned the points (every point finite, bounds given) + var scanned = points.finite === true && !!points.bounds + for(var i = 0; i < n && !scanned; ++i) { + var x0 = points[3 * i], x1 = points[3 * i + 1], x2 = points[3 * i + 2] + if(x0 - x0 !== 0 || x1 - x1 !== 0 || x2 - x2 !== 0) { finite = false; continue } // NaN or infinite + if(x0 < lowerBound[0]) lowerBound[0] = x0 + if(x0 > upperBound[0]) upperBound[0] = x0 + if(x1 < lowerBound[1]) lowerBound[1] = x1 + if(x1 > upperBound[1]) upperBound[1] = x1 + if(x2 < lowerBound[2]) lowerBound[2] = x2 + if(x2 > upperBound[2]) upperBound[2] = x2 + } + + var m = n + var positionArray = null + var idArray = null + if(!finite) { + // drop the points that are not finite, as the per-point path does; ids keep the original index + positionArray = pool.mallocFloat(3 * n) + if(pick) idArray = pool.mallocUint32(n) + m = 0 + for(var i = 0; i < n; ++i) { + var x0 = points[3 * i], x1 = points[3 * i + 1], x2 = points[3 * i + 2] + if(x0 - x0 !== 0 || x1 - x1 !== 0 || x2 - x2 !== 0) continue + positionArray[3 * m] = x0; positionArray[3 * m + 1] = x1; positionArray[3 * m + 2] = x2 + if(idArray) idArray[m] = i + m += 1 + } + } else if(pick) { + idArray = pool.mallocUint32(n) + for(var i = 0; i < n; ++i) idArray[i] = i + } + + // bounds from the doubles the positions were rounded from, when the caller kept them (scatter3d convert) + this.bounds = points.bounds || [lowerBound, upperBound] + this.points = pick ? points : null // a trace that is never picked does not keep its positions + this.pointCount = n + this.vertexCount = m + this.lineVertexCount = 0 + this.discConst = {color: color, size: size, noPick: !pick} + + this.pointBuffer.update(positionArray ? positionArray.subarray(0, 3 * m) : points) + this.colorBuffer.update(1) + this.sizeBuffer.update(1) + if(idArray) this.idBuffer.update(idArray.subarray(0, m)) + else this.idBuffer.update(1) + if(outline) { + var lc = options.lineColor, lca = new Float32Array(4 * m), l = [0, 0, 0, 1] + if(isArrayOrTypedArray(lc) && (lc.length === 3 || lc.length === 4)) { + l[0] = lc[0]; l[1] = lc[1]; l[2] = lc[2]; l[3] = lc.length === 4 ? lc[3] : 1 + if(!this.hasAlpha && l[3] < 1) this.hasAlpha = true + } + for(var i = 0; i < m; ++i) { lca[4 * i] = l[0]; lca[4 * i + 1] = l[1]; lca[4 * i + 2] = l[2]; lca[4 * i + 3] = l[3] } + this.lineColorBuffer.update(lca) + } else if(this.lineColorBuffer) this.lineColorBuffer.update(1) + this.glyphBuffer.update(1) + + if(positionArray) pool.free(positionArray) + if(idArray) pool.free(idArray) + this.flatState = {n: n, pick: pick, outline: !!outline, size: size, kind: this._kind, kept: 0} + return true +} + +// Fill the disc buffers, 1 vertex per point. Returns false if the disc path cannot be used. +// The number of points of an update; with positionsKept, that of the buffers kept from the last one +proto._count = function(options) { + return options.positionsKept ? this.flatState.n : positionCount(options.position) +} + +proto._updateDisc = function(options) { + var gl = this.gl + var points = options.position + var n = this._count(options) + var kind = discKind(options.glyph, n) + this._kind = kind + var outline = this.lineWidth > 0 + try { + this._discSetup(kind, outline) + } catch(e) { + this.discBlocker = 'disc shader failed: ' + e + return false + } + + if(isFlatPositions(points) || options.positionsKept) { + var fc = options.color + var flc = options.lineColor + var perPoint = (isArrayOrTypedArray(fc) && isArrayOrTypedArray(fc[0])) || isArrayOrTypedArray(options.size) || + (outline && isArrayOrTypedArray(flc) && isArrayOrTypedArray(flc[0])) + if(!perPoint) { + if(!this._discSizeFits(options.size ? +options.size : 12)) return false + return this._updateDiscFlat(options, points, n, outline) + } + if(options.positionsKept) return false + points = unflattenPositions(points) + } + + var colors = options.color + var lineColors = options.lineColor + var sizes = options.size + + var positionArray = pool.mallocFloat(3 * n) + var colorArray = pool.mallocFloat(4 * n) + var sizeArray = pool.mallocFloat(n) + var idArray = pool.mallocUint32(n) + var lineArray = outline ? pool.mallocFloat(4 * n) : null + + var lowerBound = [ Infinity, Infinity, Infinity] + var upperBound = [-Infinity,-Infinity,-Infinity] + var color = [0, 0, 0, 1] + var lineColor = [0, 0, 0, 1] + var isColorArray = isArrayOrTypedArray(colors) && isArrayOrTypedArray(colors[0]) + var isLineColorArray = isArrayOrTypedArray(lineColors) && isArrayOrTypedArray(lineColors[0]) + var sizeIsArray = isArrayOrTypedArray(sizes) + var sizeScalar = sizeIsArray ? 0 : sizes ? +sizes : 12 + var maxSize = 0 + var m = 0 + + fill_loop: + for(var i = 0; i < n; ++i) { + var x = points[i] + for(var j = 0; j < 3; ++j) { + if(isNaN(x[j]) || !isFinite(x[j])) continue fill_loop + } + + if(isArrayOrTypedArray(colors)) { + var c + if(isColorArray) c = i < colors.length ? colors[i] : [0, 0, 0, 0] + else c = colors + if(c.length === 3) { + color[0] = c[0]; color[1] = c[1]; color[2] = c[2]; color[3] = 1 + } else if(c.length === 4) { + color[0] = c[0]; color[1] = c[1]; color[2] = c[2]; color[3] = c[3] + // a fully transparent fill under an outline draws nothing: the outline ring stays opaque + if(!this.hasAlpha && c[3] < 1 && !(c[3] === 0 && outline)) this.hasAlpha = true + } + } else { + color[0] = color[1] = color[2] = 0 + color[3] = 1 + } + + if(outline) { + if(isArrayOrTypedArray(lineColors)) { + var lc + if(isLineColorArray) lc = i < lineColors.length ? lineColors[i] : [0, 0, 0, 0] + else lc = lineColors + if(lc.length === 3) { + lineColor[0] = lc[0]; lineColor[1] = lc[1]; lineColor[2] = lc[2]; lineColor[3] = 1 + } else if(lc.length === 4) { + lineColor[0] = lc[0]; lineColor[1] = lc[1]; lineColor[2] = lc[2]; lineColor[3] = lc[3] + if(!this.hasAlpha && lc[3] < 1) this.hasAlpha = true + } + } else { + lineColor[0] = lineColor[1] = lineColor[2] = 0 + lineColor[3] = 1 + } + lineArray[4 * m] = lineColor[0] + lineArray[4 * m + 1] = lineColor[1] + lineArray[4 * m + 2] = lineColor[2] + lineArray[4 * m + 3] = lineColor[3] + } + + var size = sizeIsArray ? (i < sizes.length ? +sizes[i] : 12) : sizeScalar + if(size > maxSize) maxSize = size + + for(var j = 0; j < 3; ++j) { + positionArray[3 * m + j] = x[j] + if(x[j] > upperBound[j]) upperBound[j] = x[j] + if(x[j] < lowerBound[j]) lowerBound[j] = x[j] + } + colorArray[4 * m] = color[0] + colorArray[4 * m + 1] = color[1] + colorArray[4 * m + 2] = color[2] + colorArray[4 * m + 3] = color[3] + sizeArray[m] = size + idArray[m] = i + m += 1 + } + + // Largest sprite in device pixels (+2 for the antialiasing margin) against the driver's point size cap + if(!this._discSizeFits(maxSize)) { + pool.free(positionArray) + pool.free(colorArray) + pool.free(sizeArray) + pool.free(idArray) + if(lineArray) pool.free(lineArray) + return false + } + + this.bounds = points.bounds || [lowerBound, upperBound] + this.points = points + this.pointCount = n + this.vertexCount = m + this.lineVertexCount = 0 + this.discConst = null + + this.pointBuffer.update(positionArray.subarray(0, 3 * m)) + this.colorBuffer.update(colorArray.subarray(0, 4 * m)) + this.sizeBuffer.update(sizeArray.subarray(0, m)) + this.idBuffer.update(idArray.subarray(0, m)) + if(outline) this.lineColorBuffer.update(lineArray.subarray(0, 4 * m)) + else if(this.lineColorBuffer) this.lineColorBuffer.update(1) + this.glyphBuffer.update(1) // release the glyph buffer, it is not used by discs + + pool.free(positionArray) + pool.free(colorArray) + pool.free(sizeArray) + pool.free(idArray) + if(lineArray) pool.free(lineArray) + return true +} + +// Half width in device pixels of the outline ring. The ring is drawn in the fragment shader, not with GL lines, so +// marker.line.width applies as requested: ALIASED_LINE_WIDTH_RANGE only limits the glyph path. +proto._discLineHalf = function(pixelRatio) { + if(!this.discOutline) return 0 + return 0.5 * this.lineWidth * pixelRatio +} + +// the discs a preview can thin out (0 when the markers are not discs) +proto.lodPoints = function() { + return this.discActive ? this.vertexCount : 0 +} + +// A second vertex array of the same buffers with the element indices 0, k, 2k, ... for a preview of every +// k-th disc; kept until k or the number of discs changes. Null when 32-bit element indices are missing. +proto._discLod = function(set, k) { + var gl = this.gl + var count = Math.ceil(this.vertexCount / k) + var lod = set.lod + if(lod && lod.k === k && lod.count === count) return lod + if(this.lodIndex32 === undefined) { + this.lodIndex32 = !!((typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext) || + gl.getExtension('OES_element_index_uint')) + } + if(!this.lodIndex32 || !count) return null + var index = new Uint32Array(count) + for(var i = 0; i < count; ++i) index[i] = i * k + if(lod) { + lod.elements.update(index) + } else { + lod = set.lod = {elements: createBuffer(gl, index, gl.ELEMENT_ARRAY_BUFFER)} + lod.vao = createVAO(gl, set.attrs, lod.elements, gl.UNSIGNED_INT) + } + lod.k = k + lod.count = count + return lod +} + +function drawDisc(points, camera, pixelRatio, pick, hard, oitShader, oit) { + var gl = points.gl + var set = points.discCur + var shader = oitShader || (pick ? set.pickShader : set.shader) + var uniforms = shader.uniforms + shader.bind() + if(oit) setOITUniforms(shader, oit) + uniforms.model = camera.model || IDENTITY + uniforms.view = camera.view || IDENTITY + uniforms.projection = camera.projection || IDENTITY + VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth + VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight + uniforms.screenSize = VIEW_SHAPE + uniforms.highlightId = points.highlightId + uniforms.highlightScale = points.highlightScale + uniforms.clipBounds = points.axes.bounds + uniforms.opacity = points.opacity + uniforms.pickGroup = points.pickId / 255.0 + uniforms.pixelRatio = pixelRatio + uniforms.unitA = points.discUnit.a + uniforms.unitB = points.discUnit.b + uniforms.unitCenter = [points.discUnit.cx, points.discUnit.cy] + uniforms.lineHalf = points._discLineHalf(pixelRatio) + // Opaque pass, soft edges, in order of preference: + // 1. Multisampled target and an opaque clear alpha: pure alpha-to-coverage. Full colour, blending off, alpha written as + // coverage only (the alpha channel is masked off, it stays 1). Every sample is either fully this disc (with depth) or + // untouched, so the result does not depend on draw order, exactly like MSAA of the glyph meshes. + // 2. Transparent canvas (the plotly default scene background) or an export: hard cores with depth write, then the + // antialiased rim blended over (premultiplied) with the depth test and no depth write. This doubles the draw cost, so + // interactive draws only use it when points.discRimScreen is set; otherwise they keep the hard alpha-1 edge. + var samples = hard && !pick ? gl.getParameter(gl.SAMPLES) : 0 + var clearAlpha = hard && !pick ? gl.getParameter(gl.COLOR_CLEAR_VALUE)[3] : 0 + var a2c = !!(hard && !pick && points.discA2C !== false && samples > 0 && clearAlpha >= 0.999) + var rimPass = !!(hard && !pick && !a2c && !points.discHardEdge && + (points.discExport || (points.discRimScreen === true && samples > 0))) + uniforms.hardEdge = (hard && !a2c && !rimPass || points.discHardEdge) ? 1 : 0 + points.discPath = pick ? 'pick' : a2c ? 'a2c' : rimPass ? 'rim' : (hard || points.discHardEdge) ? 'hard' : 'smooth' // last draw path, for diagnostics + uniforms.a2c = a2c ? 1 : 0 + uniforms.rim = rimPass ? 0 : -1 + if(a2c) { + gl.enable(gl.SAMPLE_ALPHA_TO_COVERAGE) + gl.disable(gl.BLEND) + gl.colorMask(true, true, true, false) + } + + // a preview draws every lodStride-th disc through an index buffer; the pick pass draws them all + var vao = set.vao + var count = points.vertexCount + var lod = !pick && points.lodStride > 1 ? points._discLod(set, points.lodStride) : null + if(lod) { + vao = lod.vao + count = lod.count + } + vao.bind() + points._discConstAttrs(gl) + vao.draw(gl.POINTS, count) + if(rimPass) { + uniforms.rim = 1 + gl.enable(gl.BLEND) + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + gl.depthMask(false) + vao.draw(gl.POINTS, count) + gl.depthMask(true) + gl.disable(gl.BLEND) + } + vao.unbind() + if(a2c) { + gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE) + gl.colorMask(true, true, true, true) + } +} + function drawFull(shader, pshader, points, camera, pixelRatio, transparent, forceDraw, oit) { var gl = points.gl @@ -21067,6 +21911,12 @@ function drawFull(shader, pshader, points, camera, pixelRatio, transparent, forc if(transparent === points.hasAlpha || forceDraw) { + if(points.discActive) { + var isPick = pshader === points.pickProjectShader + drawDisc(points, camera, pixelRatio, isPick, isPick || !transparent) + return + } + shader.bind() var uniforms = shader.uniforms if(oit) setOITUniforms(shader, oit) @@ -21131,7 +21981,34 @@ function setOITUniforms(shader, oit) { } } +// The disc shaders for the OIT passes: the disc vertex shader plus the view depth, and the OIT fragment shader +function getOITDiscShader(gl, o, outline) { + var entry = shaders.oitCacheEntry(gl) + var key = 'disc-' + (outline ? 'o-' : 'p-') + (o.pass === 0 ? '0' : [o.pass, o.K, o.anchored ? 1 : 0, o.mrt ? 1 : 0].join('-')) + if(!entry.map[key]) { + var vert = discVert(outline) + var anchor = ' interpColor = color;' + if(vert.indexOf(anchor) < 0 || vert.indexOf('varying float vA;') < 0) throw new Error('oit: cannot patch disc vertex shader') + vert = vert.replace('varying float vA;', 'varying float vA;\nvarying float oitZ;') + .replace(anchor, anchor + '\n oitZ = (view * (model * vec4(position, 1.0))).z;') + var frag = shaders.oitFragSrc({pass: o.pass, K: o.K, anchored: o.anchored, mrt: o.mrt, disc: true, outline: outline}) + var shader = createShaderWrapper(gl, {vertex: vert, fragment: frag}) + var attr = shader.attributes + attr.position.location = 0 + attr.color.location = 1 + attr.size.location = 2 + attr.id.location = 3 + if(outline && attr.lineColor) attr.lineColor.location = 4 + entry.map[key] = shader + } + return entry.map[key] +} + proto.drawOIT = function(camera, oit) { + if(this.discActive) { + if(this.hasAlpha) drawDisc(this, camera, this.pixelRatio, false, false, getOITDiscShader(this.gl, oit, this.discOutline), oit) + return + } var sh = shaders.getOITShaders(this.gl, oit) var shader = this.useOrtho ? sh.ortho : sh.perspective drawFull(shader, sh.project, this, camera, this.pixelRatio, true, false, oit) @@ -21149,15 +22026,28 @@ proto.pick = function(selected) { if(selected.id !== this.pickId) { return null } + // A cloud that is never picked gives no hit. Nor does one with more points than the 24 bits of the point index + // in the pick buffer can tell apart (the last value means none): its ids would name other points + if(this.noPick || this.pointCount > 16777215) { + return null + } var x = selected.value[2] + (selected.value[1]<<8) + (selected.value[0]<<16) if(x >= this.pointCount || x < 0) { return null } + if(!this.points) return null + //Unpack result - var coord = this.points[x] var result = this._selectResult result.index = x + if(isFlatPositions(this.points)) { + for(var i=0; i<3; ++i) { + result.position[i] = result.dataCoordinate[i] = this.points[3 * x + i] + } + return result + } + var coord = this.points[x] for(var i=0; i<3; ++i) { result.position[i] = result.dataCoordinate[i] = coord[i] } @@ -21291,9 +22181,40 @@ proto.update = function(options) { //Set dirty flag this.dirty = true + // A cloud that is never picked (hoverinfo 'skip'). The scene draws no pick pass when no object can be picked. + if('pick' in options) this.noPick = options.pick === false + //Create new buffers var points = options.position + //Circle markers as 1 vertex discs + if('markerRender' in options) this.markerRender = options.markerRender + if('discHardEdge' in options) this.discHardEdge = !!options.discHardEdge + // With positionsKept the caller sends no positions; if the buffers of the last update cannot serve + // this one, positionsMissing asks for them + var kept = !!options.positionsKept + this.positionsMissing = false + if(!kept) this.flatState = null + else if(!this.flatState) { + this.positionsMissing = true + return + } + this.discBlocker = this._discBlocker(options) + this.discActive = false + if(!this.discBlocker && this._updateDisc(options)) { + this.discActive = true + return + } + if(kept) { + this.flatState = null + this.positionsMissing = true + return + } + if(this.sizeBuffer) this.sizeBuffer.update(1) // release the disc buffers while glyphs are in use + if(this.lineColorBuffer) this.lineColorBuffer.update(1) + this.discConst = null + if(isFlatPositions(points)) points = unflattenPositions(points) + //Text font var font = { family: options.font || 'normal', @@ -21359,7 +22280,7 @@ proto.update = function(options) { var glyphBounds = glyphData.bounds triVertexCount += glyphMesh.cells.length * 3 - lineVertexCount += glyphLines.edges.length * 2 + if(this.lineWidth > 0) lineVertexCount += glyphLines.edges.length * 2 } } @@ -21555,7 +22476,7 @@ proto.update = function(options) { } } - var cells = glyphLines.edges + var cells = this.lineWidth > 0 ? glyphLines.edges : [] var verts = glyphLines.positions for(var j=0; j Date: Fri, 4 Dec 2026 12:14:03 -0800 Subject: [PATCH 20/45] Regenerate the schema for the combined attributes --- src/types/generated/schema.d.ts | 10 ++++++++++ test/plot-schema.json | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/types/generated/schema.d.ts b/src/types/generated/schema.d.ts index 6056000dce8..d825927251b 100644 --- a/src/types/generated/schema.d.ts +++ b/src/types/generated/schema.d.ts @@ -13739,6 +13739,11 @@ export interface Scene { z?: number; }; }; + /** + * Determines which traces set the scale that the data of this scene is drawn at. With *visible*, hiding or showing a trace that changes the extent of the data changes the scale, and the positions of every trace are converted and uploaded again. With *all*, traces that are hidden with `visible: *legendonly*` count as well, so hiding and showing them leaves the positions of the other traces as they are. + * @default 'visible' + */ + datascale?: 'visible' | 'all'; domain?: Domain; /** Determines the mode of drag interactions for this scene. */ dragmode?: 'orbit' | 'turntable' | 'zoom' | 'pan' | false; @@ -13747,6 +13752,11 @@ export interface Scene { * @default 'closest' */ hovermode?: 'closest' | false; + /** + * Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph. *auto* is currently the same as *disc*. + * @default 'glyph' + */ + markerrender?: 'glyph' | 'disc' | 'auto'; /** * Determines how translucent `scatter3d` markers blend. With *off*, the markers blend in draw order. The picture then depends on the order of the traces and of the points. With *auto*, the markers blend by depth and the draw order has no effect. This uses extra render passes and float render targets. The targets need memory in proportion to the size of the plot. If the graphics hardware lacks a feature, plotly.js falls back to *off*. The scene reports the result in `getOITStatus()` and in the `plotly_oitstatus` event. * @default 'off' diff --git a/test/plot-schema.json b/test/plot-schema.json index c70d9443716..a580b14d439 100644 --- a/test/plot-schema.json +++ b/test/plot-schema.json @@ -6621,6 +6621,16 @@ } } }, + "datascale": { + "description": "Determines which traces set the scale that the data of this scene is drawn at. With *visible*, hiding or showing a trace that changes the extent of the data changes the scale, and the positions of every trace are converted and uploaded again. With *all*, traces that are hidden with `visible: *legendonly*` count as well, so hiding and showing them leaves the positions of the other traces as they are.", + "dflt": "visible", + "editType": "plot", + "valType": "enumerated", + "values": [ + "visible", + "all" + ] + }, "domain": { "column": { "description": "If there is a layout grid, use the domain for this column in the grid for this scene subplot.", @@ -6708,6 +6718,17 @@ false ] }, + "markerrender": { + "description": "Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph. *auto* is currently the same as *disc*.", + "dflt": "glyph", + "editType": "plot", + "valType": "enumerated", + "values": [ + "glyph", + "disc", + "auto" + ] + }, "oit": { "description": "Determines how translucent `scatter3d` markers blend. With *off*, the markers blend in draw order. The picture then depends on the order of the traces and of the points. With *auto*, the markers blend by depth and the draw order has no effect. This uses extra render passes and float render targets. The targets need memory in proportion to the size of the plot. If the graphics hardware lacks a feature, plotly.js falls back to *off*. The scene reports the result in `getOITStatus()` and in the `plotly_oitstatus` event.", "dflt": "off", From 244133200f301e77326846a29176e97b633e06a4 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 12:17:44 -0800 Subject: [PATCH 21/45] Move the regl-scatter2d pin to a commit without build scripts npm prepares a git dependency that has a build script. It installs the devDependencies of regl-scatter2d, which include the native gl package, and a plain npm ci fails where gl has no binary. The new pinned commit holds the same bundle.js and no build script, so npm ci needs no build. --- package-lock.json | 6 +++--- package.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index 684d2505d3e..26db59660a9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,7 +44,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "github:settylab/regl-scatter2d#e2db766d5f8032210289a86a3bbef883e9f6ef10", + "regl-scatter2d": "github:settylab/regl-scatter2d#dd2fb74d0c2f964025a3054953723f2e533cbdd3", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", @@ -6231,8 +6231,8 @@ }, "node_modules/regl-scatter2d": { "version": "3.4.0", - "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#e2db766d5f8032210289a86a3bbef883e9f6ef10", - "integrity": "sha512-UuCLyCo03l/d0TxnXvlg+iYwad/IrtCk5cin9oIZXEM1xilGQHXLFz2InrGNyUryafwo2bSnTKShNbX/fEQE1A==", + "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#dd2fb74d0c2f964025a3054953723f2e533cbdd3", + "integrity": "sha512-2sQKxt3aSJiPCPbsSNKn32ExgLNp8VMOpiguaysC7A+4NwNh7rvm+YRS5ZmTzo8jJF63F+avkFAuyLl/v01Elw==", "license": "MIT", "dependencies": { "@plotly/point-cluster": "^3.1.9", diff --git a/package.json b/package.json index a0169cef81d..3c3f130e823 100644 --- a/package.json +++ b/package.json @@ -118,7 +118,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "github:settylab/regl-scatter2d#e2db766d5f8032210289a86a3bbef883e9f6ef10", + "regl-scatter2d": "github:settylab/regl-scatter2d#dd2fb74d0c2f964025a3054953723f2e533cbdd3", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", From 14d6c6a64d2e4a1509ced87f092abf86d8abf126 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 12:24:45 -0800 Subject: [PATCH 22/45] Pin regl-scatter2d to a fork commit with the level of detail draws The next commits call drawStride, drawRange and lodCount of regl-scatter2d. No release has these calls. The pinned commit holds them on top of the typed positions of the base branch, with a built bundle.js and no build script, so npm installs it without a build. A regl-scatter2d release replaces this pin. --- package-lock.json | 6 +++--- package.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index 26db59660a9..fff71681de6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,7 +44,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "github:settylab/regl-scatter2d#dd2fb74d0c2f964025a3054953723f2e533cbdd3", + "regl-scatter2d": "github:settylab/regl-scatter2d#ad3a8b53c2a8879b34545f714d4dd0fc7dd077fc", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", @@ -6231,8 +6231,8 @@ }, "node_modules/regl-scatter2d": { "version": "3.4.0", - "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#dd2fb74d0c2f964025a3054953723f2e533cbdd3", - "integrity": "sha512-2sQKxt3aSJiPCPbsSNKn32ExgLNp8VMOpiguaysC7A+4NwNh7rvm+YRS5ZmTzo8jJF63F+avkFAuyLl/v01Elw==", + "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#ad3a8b53c2a8879b34545f714d4dd0fc7dd077fc", + "integrity": "sha512-9wXCsMEDQvMmKeSmajd0NcQlXIB+Mlq380CzUNIoWwv9yDcvZimoZsUQadHjoPV3jtQKtovtaS0g2rAwM7LSZA==", "license": "MIT", "dependencies": { "@plotly/point-cluster": "^3.1.9", diff --git a/package.json b/package.json index 3c3f130e823..288dfba2446 100644 --- a/package.json +++ b/package.json @@ -118,7 +118,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "github:settylab/regl-scatter2d#dd2fb74d0c2f964025a3054953723f2e533cbdd3", + "regl-scatter2d": "github:settylab/regl-scatter2d#ad3a8b53c2a8879b34545f714d4dd0fc7dd077fc", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", From 6aa60d9623a85c344717eae4b2a380002a032a60 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:29:36 -0800 Subject: [PATCH 23/45] Add scene.hidden and scene.setHidden to the scattergl scene A restyle of visible does a calc of every trace and an upload of every point. An application that hides one group of a large plot needs a faster path. scene.hidden[i] removes the markers of trace i from each draw. scene.setHidden(map) sets entries and draws again, without a calc or an upload. scene.visibleCount[i] replaces the point count of a trace for a caller that counts visible points. Each calc empties the two arrays. --- src/traces/scattergl/scene_update.js | 20 +++- test/jasmine/tests/scattergl_lod_test.js | 120 +++++++++++++++++++++++ 2 files changed, 138 insertions(+), 2 deletions(-) create mode 100644 test/jasmine/tests/scattergl_lod_test.js diff --git a/src/traces/scattergl/scene_update.js b/src/traces/scattergl/scene_update.js index 080c524525c..c5be80bce7d 100644 --- a/src/traces/scattergl/scene_update.js +++ b/src/traces/scattergl/scene_update.js @@ -1,6 +1,7 @@ 'use strict'; var Lib = require('../../lib'); +const clearGlCanvases = require('../../lib/clear_gl_canvases'); // make sure scene exists on subplot, return it module.exports = function sceneUpdate(gd, subplot) { @@ -24,7 +25,11 @@ module.exports = function sceneUpdate(gd, subplot) { textUnselectedOptions: [], // selection batches selectBatch: [], - unselectBatch: [] + unselectBatch: [], + // Sparse arrays by scene index. If hidden[i] is true, no draw shows the markers of trace i. + // visibleCount[i] replaces the point count of trace i where a caller counts visible points. + hidden: [], + visibleCount: [] }; // regl- component stubs, initialized in dirty plot call @@ -85,7 +90,7 @@ module.exports = function sceneUpdate(gd, subplot) { if(scene.errorXOptions[i]) error2d.draw(i); if(scene.errorYOptions[i]) error2d.draw(i + count); } - if(scatter2d && scene.markerOptions[i]) { + if(scatter2d && scene.markerOptions[i] && !scene.hidden[i]) { if(unselectBatch[i].length) { var arg = Lib.repeat([], scene.count); arg[i] = unselectBatch[i]; @@ -106,6 +111,15 @@ module.exports = function sceneUpdate(gd, subplot) { scene.dirty = false; }; + // Hide or show the markers of traces by scene index, then draw again. + // A restyle of `visible` does a calc and an upload. setHidden does not. + scene.setHidden = (map) => { + for(const index in map) scene.hidden[index] = !!map[index]; + clearGlCanvases(gd); + // A require at the top makes a cycle, because plot_api/subroutines loads the trace modules. + require('../../plot_api/subroutines').redrawReglTraces(gd); + }; + // remove scene resources scene.destroy = function destroy() { if(scene.fill2d && scene.fill2d.destroy) scene.fill2d.destroy(); @@ -132,6 +146,8 @@ module.exports = function sceneUpdate(gd, subplot) { scene.selectBatch = null; scene.unselectBatch = null; + scene.hidden = null; + scene.visibleCount = null; // we can't just delete _scene, because `destroy` is called in the // middle of supplyDefaults, before relinkPrivateKeys which will put it back. diff --git a/test/jasmine/tests/scattergl_lod_test.js b/test/jasmine/tests/scattergl_lod_test.js new file mode 100644 index 00000000000..3181c52c3fe --- /dev/null +++ b/test/jasmine/tests/scattergl_lod_test.js @@ -0,0 +1,120 @@ +const Plotly = require('../../../lib/index'); +const createGraphDiv = require('../assets/create_graph_div'); +const destroyGraphDiv = require('../assets/destroy_graph_div'); + +// level of detail at draw time: layout.lod, scene.lod, scene.hidden + +function f32(n, seed) { + const a = new Float32Array(n); + let s = seed; + for (let i = 0; i < n; i++) { + s = (s * 1664525 + 1013904223) >>> 0; + a[i] = s / 4294967296; + } + return a; +} + +function trace(n, seed, extra) { + const t = { type: 'scattergl', mode: 'markers', x: f32(n, seed), y: f32(n, seed + 1), marker: { size: 6 } }; + for (let k in extra) t[k] = extra[k]; + return t; +} + +// what the regl context of the graph is asked to draw +function watch(gd) { + let gl = gd._fullLayout._glcanvas.data()[0].regl._gl; + let log = { elements: [], arrays: [], indexUploads: 0 }; + const de = gl.drawElements; + const da = gl.drawArrays; + let bd = gl.bufferData; + gl.drawElements = function (mode, count, type) { + log.elements.push([mode, count, type]); + return de.apply(gl, arguments); + }; + gl.drawArrays = function (mode, first, count) { + log.arrays.push([mode, first, count]); + return da.apply(gl, arguments); + }; + gl.bufferData = function (target) { + if (target === gl.ELEMENT_ARRAY_BUFFER) log.indexUploads++; + return bd.apply(gl, arguments); + }; + log.gl = gl; + log.reset = () => { + log.elements = []; + log.arrays = []; + log.indexUploads = 0; + }; + log.restore = () => { + gl.drawElements = de; + gl.drawArrays = da; + gl.bufferData = bd; + }; + return log; +} + +describe('scattergl scene.hidden', () => { + let gd; + + beforeEach(() => { + gd = createGraphDiv(); + }); + afterEach(() => { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function scene() { + return gd._fullLayout._plots.xy._scene; + } + function counts(log) { + return log.arrays.map((a) => { + return a[2]; + }); + } + + it('@gl leaves hidden traces out of the draw, in place, until the next calc', (done) => { + let log; + let uploads = 0; + Plotly.newPlot(gd, [trace(1000, 1), trace(501, 3), trace(250, 5)]) + .then(() => { + log = watch(gd); + const bd = log.gl.bufferData; + log.gl.bufferData = function (target) { + if (target === log.gl.ARRAY_BUFFER) uploads++; + return bd.apply(log.gl, arguments); + }; + expect(scene().hidden).toEqual([]); + expect(scene().visibleCount).toEqual([]); + + scene().setHidden({ 1: true }); + expect(counts(log)).toEqual([1000, 250]); + expect(uploads).toBe(0); + expect(scene().hidden[1]).toBe(true); + expect(gd.calcdata.length).toBe(3); + + // a pan draws the same two + log.reset(); + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.5] }); + }) + .then(() => { + expect(counts(log)).toEqual([1000, 250]); + + log.reset(); + uploads = 0; + scene().setHidden({ 1: false, 2: true }); + expect(counts(log)).toEqual([1000, 501]); + expect(uploads).toBe(0); + + // a calc starts again with nothing hidden + log.reset(); + return Plotly.restyle(gd, 'marker.size', 7); + }) + .then(() => { + expect(scene().hidden).toEqual([]); + expect(counts(log)).toEqual([1000, 501, 250]); + log.restore(); + }) + .then(done, done.fail); + }); +}); From 6292b4c7a85e121b09122ef285bf8d351245b554 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:29:37 -0800 Subject: [PATCH 24/45] Add an opt-in level of detail to scattergl (layout.lod, plotly_lod) One full draw of tens of millions of points takes the GPU 0.3 s to 0.7 s. Each open, edit and pan frame waits for that draw. With layout.lod.minpoints set, a draw shows every k-th point first. The full picture follows layout.lod.settle ms after the last draw request, in parts of layout.lod.slice points. A timer query paces the parts, so a new draw request waits for one part only. A copy of the preview covers the canvas until the last part. An edit of a fully drawn plot keeps the old full picture on screen until the new one is ready, in state stale. layout.lod.edits: 'preview' gives edits the preview. The graph emits plotly_lod on each change of state. Without layout.lod the draw calls and _fullLayout do not change. --- src/lib/clear_gl_canvases.js | 6 + src/traces/scattergl/base_index.js | 2 + src/traces/scattergl/layout_attributes.ts | 77 ++ src/traces/scattergl/layout_defaults.ts | 23 + src/traces/scattergl/lod.ts | 358 ++++++++ src/traces/scattergl/scene_update.js | 6 +- src/types/core/events.d.ts | 23 + test/jasmine/tests/scattergl_lod_test.js | 980 ++++++++++++++++++++++ 8 files changed, 1474 insertions(+), 1 deletion(-) create mode 100644 src/traces/scattergl/layout_attributes.ts create mode 100644 src/traces/scattergl/layout_defaults.ts create mode 100644 src/traces/scattergl/lod.ts diff --git a/src/lib/clear_gl_canvases.js b/src/lib/clear_gl_canvases.js index 234ed82a9f7..5298db9f73e 100644 --- a/src/lib/clear_gl_canvases.js +++ b/src/lib/clear_gl_canvases.js @@ -11,6 +11,12 @@ module.exports = function clearGlCanvases(gd) { var fullLayout = gd._fullLayout; if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { + // A scattergl scene with a level of detail can keep a copy of the full picture on screen. + for(const id in fullLayout._plots) { + const scene = fullLayout._plots[id]._scene; + if(scene?.lod?.beforeClear) scene.lod.beforeClear(); + } + fullLayout._glcanvas.each(function(d) { if(d.regl) d.regl.clear({color: true, depth: true}); }); diff --git a/src/traces/scattergl/base_index.js b/src/traces/scattergl/base_index.js index 2339e07acb7..32a0339fc6e 100644 --- a/src/traces/scattergl/base_index.js +++ b/src/traces/scattergl/base_index.js @@ -9,7 +9,9 @@ module.exports = { categories: ['gl', 'regl', 'cartesian', 'symbols', 'errorBarsOK', 'showLegend', 'scatter-like'], attributes: require('./attributes'), + layoutAttributes: require('./layout_attributes').default, supplyDefaults: require('./defaults'), + supplyLayoutDefaults: require('./layout_defaults').default, crossTraceDefaults: require('../scatter/cross_trace_defaults'), colorbar: require('../scatter/marker_colorbar'), formatLabels: require('./format_labels'), diff --git a/src/traces/scattergl/layout_attributes.ts b/src/traces/scattergl/layout_attributes.ts new file mode 100644 index 00000000000..ae206726a34 --- /dev/null +++ b/src/traces/scattergl/layout_attributes.ts @@ -0,0 +1,77 @@ +import type { AttributeMap } from '../../types/lib/attributes'; + +/** + * Layout attributes of the scattergl level of detail. + * Consumer-facing types are generated from the schema by generate_schema_types.mjs. + */ +const attributes = { + lod: { + minpoints: { + valType: 'number', + min: 0, + dflt: 0, + editType: 'none', + description: [ + 'Sets the number of visible scattergl points from which a draw shows a preview first.', + 'A preview draws every k-th point of every trace.', + 'The full picture follows when no draw request came for `settle` milliseconds.', + '0 turns the preview off.', + 'Applies to a graph where the scattergl markers of one subplot are the only WebGL traces.', + 'The graph emits `plotly_lod` when the state changes.' + ].join(' ') + }, + budget: { + valType: 'number', + min: 1, + dflt: 2500000, + editType: 'none', + description: [ + 'Sets the largest number of points in a preview.', + 'The stride k is the smallest power of two, from 2 to `maxstride`,', + 'that brings the visible points within this number.' + ].join(' ') + }, + maxstride: { + valType: 'integer', + min: 2, + dflt: 64, + editType: 'none', + description: 'Sets the largest stride of a preview.' + }, + settle: { + valType: 'number', + min: 0, + dflt: 150, + editType: 'none', + description: 'Sets the time in milliseconds between the last draw request and the full picture.' + }, + slice: { + valType: 'number', + min: 0, + dflt: 5000000, + editType: 'none', + description: [ + 'Sets the number of points in one part of the full picture.', + 'The plot draws the next part when the GPU finished the part before.', + 'Thus a draw request between two parts does not wait for the full picture.', + '0 draws the full picture in one part.' + ].join(' ') + }, + edits: { + valType: 'enumerated', + values: ['hold', 'preview'] as const, + dflt: 'hold', + editType: 'none', + description: [ + 'Determines the picture during an edit of a fully drawn plot', + 'that keeps the axis ranges, the plot area and the size.', + '*hold* keeps the previous full picture until the new full picture is ready.', + '*preview* shows a preview first, as a pan does.', + 'Use *preview* for edits in quick succession, for example from a slider.' + ].join(' ') + }, + editType: 'none' + } +} as const satisfies AttributeMap; + +export default attributes; diff --git a/src/traces/scattergl/layout_defaults.ts b/src/traces/scattergl/layout_defaults.ts new file mode 100644 index 00000000000..7805bef03e9 --- /dev/null +++ b/src/traces/scattergl/layout_defaults.ts @@ -0,0 +1,23 @@ +import Lib from '../../lib'; +import layoutAttributes from './layout_attributes'; + +/** + * Supply the `lod` container of the layout. + * A layout without `lod` gets no `lod` container. + * + * @param layoutIn - the user-supplied layout + * @param layoutOut - the full layout to write into + */ +export default function supplyLayoutDefaults(layoutIn: any, layoutOut: any) { + if (!Lib.isPlainObject(layoutIn.lod)) return; + + const coerce = (attr: string) => Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr); + + if (coerce('lod.minpoints')) { + coerce('lod.budget'); + coerce('lod.maxstride'); + coerce('lod.settle'); + coerce('lod.slice'); + coerce('lod.edits'); + } +} diff --git a/src/traces/scattergl/lod.ts b/src/traces/scattergl/lod.ts new file mode 100644 index 00000000000..ba2339b0d35 --- /dev/null +++ b/src/traces/scattergl/lod.ts @@ -0,0 +1,358 @@ +/** The `layout.lod` container after defaults. */ +interface LodOptions { + minpoints: number; + budget: number; + maxstride: number; + settle: number; + slice: number; + edits: 'hold' | 'preview'; +} + +type LodState = 'off' | 'preview' | 'stale' | 'full'; +type LodReason = 'plot' | 'range' | 'settle'; + +/** The work that waits for the GPU: the parts of a full picture, or the one draw of a held edit. */ +interface LodRun { + /** Index of the next group for `drawRange`. */ + g: number; + /** Offset of the next point in that group. */ + off: number; + slice: number; + gl: WebGLRenderingContext; + /** `EXT_disjoint_timer_query`, or null. */ + ext: any; + query: unknown; + /** Time of the last query, from `Date.now()`. */ + asked: number; +} + +const TIMER_QUERY = 'EXT_disjoint_timer_query'; +// A timer query that never returns must not stop the plot. +const PART_TIMEOUT = 2000; +const HOLD_TIMEOUT = 5000; + +/** + * Attach the level of detail to the scene of a scattergl subplot. + * + * With `layout.lod.minpoints` set, `scene.draw` draws a preview of every k-th point. + * The full picture follows `layout.lod.settle` ms after the last draw request, in parts. + * The function replaces `scene.draw` and `scene.update` and adds `scene.lod`: + * `{state, stride, shown, total, settle(), beforeClear(), cancel()}`. + * The graph emits `plotly_lod` when `state`, `stride` or `total` changes. + * Without `layout.lod`, `scene.draw` draws as before. + * + * @param gd - the graph div + * @param subplot - the cartesian subplot (`plotinfo`) that owns the scene + * @param scene - the scattergl scene of the subplot + */ +export function attachLod(gd: any, subplot: any, scene: any) { + const fullDraw = scene.draw; + const update = scene.update; + const S = (scene.lod = { state: 'off' as LodState, stride: 0, shown: 0, total: 0 } as any); + let timer: ReturnType | null = null; + let frame: number | null = null; + let run: LodRun | null = null; + let cover: HTMLCanvasElement | null = null; + let covered: HTMLCanvasElement | null = null; + // A drag or a wheel changed the range since the last draw. + let ranged = false; + // The view of the full picture that the cover shows, between a clear and the next draw. + let held: string | null = null; + let heldTimer: ReturnType | null = null; + let view = ''; + + const strideFor = (n: number, opts: LodOptions) => { + if (n < opts.minpoints) return 0; + let k = 2; + while (k < opts.maxstride && n / k > opts.budget) k *= 2; + return k; + }; + + /** The visible points of the scene, or 0 if the scene cannot show a preview. */ + const points = (opts: LodOptions | undefined) => { + const fullLayout = gd._fullLayout; + const scatter = scene.scatter2d; + if (!opts || !(opts.minpoints > 0) || gd._context.staticPlot || !scatter || !scatter.lodCount) return 0; + // The regl components stay after their traces go, so the options of this calc tell what the scene draws. + for (let i = 0; i < scene.count; i++) { + if ( + scene.lineOptions[i] || + scene.fillOptions[i] || + scene.errorXOptions[i] || + scene.errorYOptions[i] || + scene.textOptions[i] || + scene.selectBatch[i].length || + scene.unselectBatch[i].length + ) + return 0; + } + // All regl scenes share one canvas, and the full picture needs a clear of that canvas. + if (fullLayout._has('splom') || fullLayout._has('polar')) return 0; + for (const id in fullLayout._plots) { + const other = fullLayout._plots[id]._scene; + if (other && other !== scene) return 0; + } + const n = scatter.lodCount(scene.hidden, scene.visibleCount); + return n > 0 ? n : 0; + }; + + const clearCanvases = () => { + gd._fullLayout._glcanvas.each((d: any) => { + if (d.regl) d.regl.clear({ color: true, depth: true }); + }); + }; + + /** The ranges and the geometry that fix the position of each point on the canvas. */ + const viewOf = () => { + const { width, height } = gd._fullLayout; + const xa = subplot.xaxis; + const ya = subplot.yaxis; + return [...xa.range, ...ya.range, xa._offset, xa._length, ya._offset, ya._length, width, height].join(); + }; + + const set = (state: LodState, stride: number, total: number, reason: LodReason) => { + if (S.state === state && S.stride === stride && S.total === total) return; + const shown = state === 'preview' ? Math.round(total / stride) : total; + S.state = state; + S.stride = stride; + S.total = total; + S.shown = shown; + if (gd.emit) gd.emit('plotly_lod', { subplot: subplot.id, state, stride, shown, total, reason }); + }; + + const glCanvas = (): HTMLCanvasElement => gd._fullLayout._glcanvas.node(); + + /** Show a copy of the canvas in place of the canvas, so that the scene can draw on the canvas in parts. */ + const coverCanvas = () => { + const canvas = glCanvas(); + if (!cover) { + cover = document.createElement('canvas'); + cover.className = 'gl-lod-cover'; + cover.style.cssText = 'position:absolute;top:0;left:0;pointer-events:none'; + } + if (cover.parentNode !== canvas.parentNode) canvas.parentNode!.appendChild(cover); + cover.width = canvas.width; + cover.height = canvas.height; + cover.style.width = canvas.style.width; + cover.style.height = canvas.style.height; + cover.style.display = ''; + cover.getContext('2d')!.drawImage(canvas, 0, 0); + canvas.style.visibility = 'hidden'; + covered = canvas; + }; + + const uncover = () => { + if (!covered || !cover) return; + covered.style.visibility = ''; + covered = null; + cover.style.display = 'none'; + // Release the pixels of the copy. + cover.width = cover.height = 0; + }; + + /** Stop all work that waits. The cover stays. */ + const stop = () => { + if (timer !== null) { + clearTimeout(timer); + timer = null; + } + if (heldTimer !== null) { + clearTimeout(heldTimer); + heldTimer = null; + } + held = null; + if (frame !== null) { + window.cancelAnimationFrame(frame); + frame = null; + } + if (run) { + if (run.query) run.ext.deleteQueryEXT(run.query); + run = null; + } + }; + + const cancel = () => { + stop(); + uncover(); + }; + + /** Tell if the GPU still works on the draws of the last query of `me`, for `ms` at most. */ + const pending = (me: LodRun, ms: number) => { + if (!me.query) return false; + const available = me.ext.getQueryObjectEXT(me.query, me.ext.QUERY_RESULT_AVAILABLE_EXT); + if (!available && Date.now() - me.asked < ms) return true; + me.ext.deleteQueryEXT(me.query); + me.query = null; + return false; + }; + + /** Do `draw` and start a timer query on `me` for the draw. Without the extension, wait for the GPU. */ + const timed = (me: LodRun, draw: () => boolean, wait: (done: boolean) => boolean) => { + const { gl, ext } = me; + if (ext) { + me.query = ext.createQueryEXT(); + ext.beginQueryEXT(ext.TIME_ELAPSED_EXT, me.query); + } + const done = draw(); + if (ext) { + ext.endQueryEXT(ext.TIME_ELAPSED_EXT); + gl.flush(); + me.asked = Date.now(); + } else if (wait(done)) { + gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)); + } + return done; + }; + + const newRun = (slice: number): LodRun => { + const gl = scene.scatter2d.gl; + return { g: 0, off: 0, slice, gl, ext: gl.getExtension(TIMER_QUERY), query: null, asked: 0 }; + }; + + /** Draw one part of the full picture. Draw the next part when the GPU finished this part. */ + const step = () => { + const me = run!; + frame = null; + if (pending(me, PART_TIMEOUT)) { + frame = window.requestAnimationFrame(step); + return; + } + const done = timed( + me, + () => scene.scatter2d.drawRange(me, me.slice, scene.hidden), + (last) => !last + ); + if (done) { + cancel(); + scene.dirty = false; + set('full', S.stride, S.total, 'settle'); + } else { + frame = window.requestAnimationFrame(step); + } + }; + + const refine = () => { + const opts: LodOptions = gd._fullLayout.lod; + timer = null; + if (!scene.scatter2d) return; + if (!(opts.slice > 0)) { + clearCanvases(); + fullDraw.call(scene); + set('full', S.stride, S.total, 'settle'); + return; + } + run = newRun(opts.slice); + coverCanvas(); + clearCanvases(); + step(); + }; + + /** + * Draw the new full picture of an edit in one draw, below the copy of the old full picture. + * A settle time or parts only delay the new picture, because the old picture stays on screen. + */ + const holdDraw = (stride: number, total: number, reason: LodReason) => { + const me = (run = newRun(0)); + timed( + me, + () => { + fullDraw.call(scene); + return true; + }, + () => true + ); + set('stale', stride, total, reason); + const wait = () => { + frame = null; + if (pending(me, HOLD_TIMEOUT)) { + frame = window.requestAnimationFrame(wait); + return; + } + cancel(); + set('full', stride, total, 'settle'); + }; + wait(); + }; + + // The browser reports the loss of a released canvas one task later, on the same graph div. + // A new plot can then own the graph div, so only a canvas of this plot counts. + const contextLost = (d: any) => { + const target = d?.event?.target; + const glcanvas = gd._fullLayout?._glcanvas; + if (!target || !glcanvas) return; + let own = false; + glcanvas.each(function (this: Element) { + if (this === target) own = true; + }); + if (own) cancel(); + }; + if (gd.on) gd.on('plotly_webglcontextlost', contextLost); + + scene.update = function (opt: any) { + if (opt && opt.range) ranged = true; + return update.apply(scene, arguments); + }; + + scene.draw = () => { + const opts: LodOptions | undefined = gd._fullLayout.lod; + const reason: LodReason = ranged ? 'range' : 'plot'; + const was = held; + const now = viewOf(); + ranged = false; + stop(); + const total = points(opts); + const stride = total ? strideFor(total, opts!) : 0; + view = now; + if (stride && was === now && reason === 'plot') { + holdDraw(stride, total, reason); + return; + } + uncover(); + if (!stride) { + fullDraw.call(scene); + set('off', 0, total, reason); + return; + } + scene.scatter2d.drawStride(stride, scene.hidden); + scene.dirty = false; + set('preview', stride, total, reason); + timer = setTimeout(refine, opts!.settle); + }; + + /** + * Prepare for a clear of the canvas. `clearGlCanvases` calls this function. + * If the canvas shows the full picture, a copy takes the place of the canvas. + * The next `scene.draw` keeps the copy for an edit and removes the copy for a new view. + */ + S.beforeClear = () => { + const opts: LodOptions | undefined = gd._fullLayout.lod; + if (ranged || !opts || opts.edits === 'preview' || !glCanvas()) return; + if (S.state === 'full' && !covered) coverCanvas(); + else if (S.state !== 'stale' || !covered) return; + held = view; + if (heldTimer !== null) return; + // If no draw follows the clear, remove the copy. + heldTimer = setTimeout(() => { + heldTimer = null; + if (held === null) return; + held = null; + if (!run) uncover(); + }, 0); + }; + + /** Draw the full picture now, in one draw. */ + S.settle = () => { + if (S.state !== 'preview' && S.state !== 'stale') return; + cancel(); + clearCanvases(); + fullDraw.call(scene); + set('full', S.stride, S.total, 'settle'); + }; + + /** Stop all work and remove the cover. `scene.destroy` calls this function. */ + S.cancel = () => { + cancel(); + if (cover && cover.parentNode) cover.parentNode.removeChild(cover); + if (gd.removeListener) gd.removeListener('plotly_webglcontextlost', contextLost); + }; +} diff --git a/src/traces/scattergl/scene_update.js b/src/traces/scattergl/scene_update.js index c5be80bce7d..d6542c05ce7 100644 --- a/src/traces/scattergl/scene_update.js +++ b/src/traces/scattergl/scene_update.js @@ -2,6 +2,7 @@ var Lib = require('../../lib'); const clearGlCanvases = require('../../lib/clear_gl_canvases'); +const { attachLod } = require('./lod'); // make sure scene exists on subplot, return it module.exports = function sceneUpdate(gd, subplot) { @@ -27,7 +28,7 @@ module.exports = function sceneUpdate(gd, subplot) { selectBatch: [], unselectBatch: [], // Sparse arrays by scene index. If hidden[i] is true, no draw shows the markers of trace i. - // visibleCount[i] replaces the point count of trace i where a caller counts visible points. + // visibleCount[i] replaces the point count of trace i for the level of detail. hidden: [], visibleCount: [] }; @@ -120,8 +121,11 @@ module.exports = function sceneUpdate(gd, subplot) { require('../../plot_api/subroutines').redrawReglTraces(gd); }; + attachLod(gd, subplot, scene); + // remove scene resources scene.destroy = function destroy() { + scene.lod.cancel(); if(scene.fill2d && scene.fill2d.destroy) scene.fill2d.destroy(); if(scene.scatter2d && scene.scatter2d.destroy) scene.scatter2d.destroy(); if(scene.error2d && scene.error2d.destroy) scene.error2d.destroy(); diff --git a/src/types/core/events.d.ts b/src/types/core/events.d.ts index fb42ba475ad..c96b2942d67 100644 --- a/src/types/core/events.d.ts +++ b/src/types/core/events.d.ts @@ -321,6 +321,26 @@ export interface SliderEndEvent { step: SliderStep; } +// --------------------------------------------------------------------------- +// Level of detail events +// --------------------------------------------------------------------------- + +/** Payload for `plotly_lod`, emitted when the level of detail of a subplot changes. */ +export interface LodEvent { + /** The id of the cartesian subplot or of the gl3d scene, for example 'xy' or 'scene'. */ + subplot: string; + /** 'preview': a part of the points is on screen. 'stale': the picture before an edit is on screen. */ + state: 'off' | 'preview' | 'stale' | 'full'; + /** The preview draws every `stride`-th point. 0 in state 'off'. */ + stride: number; + /** The number of points on screen. */ + shown: number; + /** The number of visible points. */ + total: number; + /** The cause of the change. */ + reason: 'plot' | 'range' | 'camera' | 'settle'; +} + // --------------------------------------------------------------------------- // WebGL context events // --------------------------------------------------------------------------- @@ -428,6 +448,8 @@ export interface PlotlyHTMLElement extends HTMLElement { on(event: 'plotly_relayout' | 'plotly_relayouting', callback: (event: PlotRelayoutEvent) => void): void; /** Subscribe to update events (`Plotly.update` calls). */ on(event: 'plotly_update', callback: (event: PlotUpdateEvent) => void): void; + /** Subscribe to level of detail events (`layout.lod`, `scene.lod`). */ + on(event: 'plotly_lod', callback: (event: LodEvent) => void): void; /** Subscribe to WebGL context loss events. */ on(event: 'plotly_webglcontextlost', callback: (event: WebGLContextLostEvent) => void): void; /** Subscribe to annotation click events. */ @@ -523,6 +545,7 @@ export type PlotlyEventName = | 'plotly_legenddoubleclick' | 'plotly_legendtitleclick' | 'plotly_legendtitledoubleclick' + | 'plotly_lod' | 'plotly_react' | 'plotly_redraw' | 'plotly_relayout' diff --git a/test/jasmine/tests/scattergl_lod_test.js b/test/jasmine/tests/scattergl_lod_test.js index 3181c52c3fe..5aa545db364 100644 --- a/test/jasmine/tests/scattergl_lod_test.js +++ b/test/jasmine/tests/scattergl_lod_test.js @@ -53,6 +53,237 @@ function watch(gd) { return log; } +describe('regl-scatter2d level of detail draws', () => { + let gd; + + beforeEach(() => { + gd = createGraphDiv(); + }); + afterEach(() => { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function scatter() { + return gd._fullLayout._plots.xy._scene.scatter2d; + } + + it('@gl counts the points of the groups, with groups left out and counts replaced', (done) => { + Plotly.newPlot(gd, [trace(1000, 1), trace(501, 3), trace(250, 5)]) + .then(() => { + let sc = scatter(); + expect(sc.lodCount()).toBe(1751); + expect(sc.lodCount([false, true])).toBe(1250); + expect(sc.lodCount(null, [100])).toBe(851); + expect(sc.lodCount([true], [100, 1])).toBe(251); + }) + .then(done, done.fail); + }); + + it('@gl draws every k-th point of every group through one shared index buffer', (done) => { + let log; + Plotly.newPlot(gd, [trace(1000, 1), trace(501, 3), trace(250, 5)]) + .then(() => { + let sc = scatter(); + log = watch(gd); + sc.drawStride(4); + expect(log.elements).toEqual([ + [log.gl.POINTS, 250, log.gl.UNSIGNED_INT], + [log.gl.POINTS, 126, log.gl.UNSIGNED_INT], + [log.gl.POINTS, 63, log.gl.UNSIGNED_INT] + ]); + expect(log.arrays.length).toBe(0); + expect(log.indexUploads).toBe(1); + + // the same stride again: the index buffer is kept; a group left out is not drawn + log.reset(); + sc.drawStride(4, [false, true]); + expect( + log.elements.map((e) => { + return e[1]; + }) + ).toEqual([250, 63]); + expect(log.indexUploads).toBe(0); + + // another stride: a new index buffer + log.reset(); + sc.drawStride(8); + expect( + log.elements.map((e) => { + return e[1]; + }) + ).toEqual([125, 63, 32]); + expect(log.indexUploads).toBe(1); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl draws the full picture in parts, in order, cutting inside a group', (done) => { + let log; + Plotly.newPlot(gd, [trace(1000, 1), trace(501, 3), trace(250, 5)]) + .then(() => { + let sc = scatter(); + log = watch(gd); + let at = { g: 0, off: 0 }; + expect(sc.drawRange(at, 700)).toBe(false); + expect(at).toEqual({ g: 0, off: 700 }); + expect(sc.drawRange(at, 700)).toBe(false); + expect(at).toEqual({ g: 1, off: 400 }); + expect(sc.drawRange(at, 700)).toBe(true); + expect(log.arrays).toEqual([ + [log.gl.POINTS, 0, 700], + [log.gl.POINTS, 700, 300], + [log.gl.POINTS, 0, 400], + [log.gl.POINTS, 400, 101], + [log.gl.POINTS, 0, 250] + ]); + expect(log.elements.length).toBe(0); + + // a group left out, and the whole picture in one part + log.reset(); + expect(sc.drawRange({ g: 0, off: 0 }, Infinity, [false, true])).toBe(true); + expect(log.arrays).toEqual([ + [log.gl.POINTS, 0, 1000], + [log.gl.POINTS, 0, 250] + ]); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl draws a group that lies in several GPU segments piece by piece, with the pixels of the plain draws', (done) => { + const createScatter = require('regl-scatter2d'); + const segment = createScatter.xySegment; + let gl, sc, plain, strided, log; + function read() { + let px = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, px); + return px; + } + function clear() { + gd._fullLayout._glcanvas.each((d) => { + if (d.regl) d.regl.clear({ color: true, depth: true }); + }); + } + function every(n, k) { + const out = []; + for (let i = 0; i < n; i += k) out.push(i); + return out; + } + // 1,024 points per segment: 3 pieces and 2 pieces + createScatter.xySegment = 4096; + Plotly.newPlot( + gd, + [ + trace(3000, 1, { marker: { size: 9, opacity: 0.6, color: 'red' } }), + trace(1500, 3, { marker: { size: 9, opacity: 0.6, color: 'blue' } }) + ], + { width: 400, height: 300, xaxis: { range: [0, 1] }, yaxis: { range: [0, 1] } } + ) + .then(() => { + sc = scatter(); + gl = gd._fullLayout._glcanvas.data()[0].regl._gl; + plain = read(); + + // in parts of 700 points + clear(); + log = watch(gd); + let at = { g: 0, off: 0 }; + while (!sc.drawRange(at, 700)); + expect( + log.arrays.map((a) => { + return [a[1], a[2]]; + }) + ).toEqual([ + [0, 700], + [700, 324], + [0, 376], + [376, 648], + [0, 52], + [52, 700], + [752, 200], + [0, 500], + [500, 524], + [0, 176], + [176, 300] + ]); + log.restore(); + expect(read()).toEqual(plain); + + // every 5th point: the plain draw of those elements, and drawStride + clear(); + sc.draw(every(3000, 5), every(1500, 5)); + strided = read(); + clear(); + log = watch(gd); + sc.drawStride(5); + // pieces of 1024, 1024, 952 and 1024, 476 points; the second starts at its point 1 (1025 in the group) + expect( + log.elements.map((e) => { + return e[1]; + }) + ).toEqual([205, 205, 190, 205, 95]); + expect(log.indexUploads).toBe(1); + log.restore(); + expect(read()).toEqual(strided); + }) + .then( + () => { + createScatter.xySegment = segment; + }, + (e) => { + createScatter.xySegment = segment; + throw e; + } + ) + .then(done, done.fail); + }); + + it('@gl draws the same pixels in parts as the plain draw does', (done) => { + let gl, full, parts; + function read() { + let px = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, px); + return px; + } + function clear() { + gd._fullLayout._glcanvas.each((d) => { + if (d.regl) d.regl.clear({ color: true, depth: true }); + }); + } + Plotly.newPlot( + gd, + [ + trace(3000, 1, { marker: { size: 9, opacity: 0.6, color: 'red' } }), + trace(3000, 3, { marker: { size: 9, opacity: 0.6, color: 'blue' } }), + trace(3000, 5, { marker: { size: 12, symbol: 'square', color: 'green' } }) + ], + { width: 400, height: 300 } + ) + .then(() => { + const sc = scatter(); + gl = gd._fullLayout._glcanvas.data()[0].regl._gl; + full = read(); + clear(); + const at = { g: 0, off: 0 }; + let n = 0; + while (!sc.drawRange(at, 1234)) n++; + expect(n).toBe(7); + parts = read(); + let diff = 0; + let drawn = 0; + for (let i = 0; i < full.length; i++) { + if (full[i] !== parts[i]) diff++; + if (full[i]) drawn++; + } + expect(drawn).toBeGreaterThan(10000); + expect(diff).toBe(0); + }) + .then(done, done.fail); + }); +}); + describe('scattergl scene.hidden', () => { let gd; @@ -118,3 +349,752 @@ describe('scattergl scene.hidden', () => { .then(done, done.fail); }); }); + +describe('scattergl layout.lod', () => { + let gd; + let events; + + beforeEach(() => { + gd = createGraphDiv(); + events = []; + }); + afterEach(() => { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + const LOD = { minpoints: 1000, budget: 500, maxstride: 64, settle: 30 }; + function data() { + return [trace(1000, 1), trace(501, 3), trace(250, 5)]; + } + function layout(lod, extra) { + const l = { width: 400, height: 300, lod: JSON.parse(JSON.stringify(lod)) }; + for (let k in extra) l[k] = extra[k]; + return l; + } + function scene() { + return gd._fullLayout._plots.xy._scene; + } + function listen() { + gd.on('plotly_lod', (e) => { + events.push(e); + }); + } + function plot(d, l, config) { + return Plotly.newPlot(gd, d, l, config).then(listen); + } + function states() { + return events.map((e) => { + return e.state + ':' + e.reason; + }); + } + // resolves when the scene reaches `state` + function when(state) { + return new Promise((resolve, reject) => { + const t0 = Date.now(); + (function poll() { + if (scene().lod.state === state) resolve(); + else if (Date.now() - t0 > 3000) reject(new Error('never ' + state + ', still ' + scene().lod.state)); + else setTimeout(poll, 5); + })(); + }); + } + function clear() { + gd._fullLayout._glcanvas.each((d) => { + if (d.regl) d.regl.clear({ color: true, depth: true }); + }); + } + function pixels() { + let gl = gd._fullLayout._glcanvas.data()[0].regl._gl; + const px = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, px); + return px; + } + function differ(a, b) { + let n = 0; + for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) n++; + return n; + } + + it('@gl is off without layout.lod: the draws of before, no event, no layout key', (done) => { + let log; + Plotly.newPlot(gd, data(), { width: 400, height: 300 }) + .then(() => { + listen(); + expect(gd._fullLayout.lod).toBeUndefined(); + expect(scene().lod.state).toBe('off'); + log = watch(gd); + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.5] }); + }) + .then(() => { + expect( + log.arrays.map((a) => { + return a[2]; + }) + ).toEqual([1000, 501, 250]); + expect(log.elements.length).toBe(0); + expect(events.length).toBe(0); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl previews every k-th point, then draws the full picture, and says so', (done) => { + let log, full; + plot(data(), layout(LOD)) + .then(() => { + // 1751 points, budget 500: every 4th + expect(gd._fullLayout.lod).toEqual({ + minpoints: 1000, + budget: 500, + maxstride: 64, + settle: 30, + slice: 5000000, + edits: 'hold' + }); + expect(scene().lod.state).toBe('preview'); + expect(scene().lod.stride).toBe(4); + expect(scene().lod.total).toBe(1751); + expect(scene().lod.shown).toBe(438); + log = watch(gd); + return when('full'); + }) + .then(() => { + expect( + log.arrays.map((a) => { + return a[2]; + }) + ).toEqual([1000, 501, 250]); + expect(states()).toEqual(['full:settle']); + expect(events[0]).toEqual({ + subplot: 'xy', + state: 'full', + stride: 4, + shown: 1751, + total: 1751, + reason: 'settle' + }); + full = pixels(); + + // an edit: a preview through the index buffer, then the same full picture + log.reset(); + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.5] }); + }) + .then(() => { + expect( + log.elements.map((e) => { + return e[1]; + }) + ).toEqual([250, 126, 63]); + expect(log.arrays.length).toBe(0); + expect(events[1]).toEqual({ + subplot: 'xy', + state: 'preview', + stride: 4, + shown: 438, + total: 1751, + reason: 'plot' + }); + return when('full'); + }) + .then(() => { + expect(states()).toEqual(['full:settle', 'preview:plot', 'full:settle']); + log.restore(); + full = pixels(); + // the picture without the level of detail + return Plotly.relayout(gd, { 'lod.minpoints': 0 }); + }) + .then(() => { + expect(scene().lod.state).toBe('full'); + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.5] }); + }) + .then(() => { + expect(scene().lod.state).toBe('off'); + expect(differ(full, pixels())).toBe(0); + }) + .then(done, done.fail); + }); + + it('@gl restarts the wait with each draw request and settles once; a drag gives reason range', (done) => { + function drag(i) { + scene().update({ range: [0.01 * i, 0.01 * i, 0.5, 0.5] }); + clear(); + scene().draw(); + } + plot(data(), layout(LOD)) + .then(() => { + return when('full'); + }) + .then(() => { + events.length = 0; + drag(1); + drag(2); + return new Promise((r) => { + setTimeout(r, 15); + }); + }) + .then(() => { + drag(3); + expect(scene().lod.state).toBe('preview'); + return when('full'); + }) + .then(() => { + expect(states()).toEqual(['preview:range', 'full:settle']); + }) + .then(done, done.fail); + }); + + it('@gl draws in full at once on settle()', (done) => { + let log; + plot(data(), layout({ minpoints: 1000, budget: 500, settle: 100000 })) + .then(() => { + expect(scene().lod.state).toBe('preview'); + log = watch(gd); + scene().lod.settle(); + expect(scene().lod.state).toBe('full'); + expect( + log.arrays.map((a) => { + return a[2]; + }) + ).toEqual([1000, 501, 250]); + expect(states()).toEqual(['full:settle']); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl counts visible points only: hidden traces and visibleCount', (done) => { + plot(data(), layout({ minpoints: 800, budget: 500, settle: 100000 })) + .then(() => { + expect(scene().lod.total).toBe(1751); + scene().visibleCount[0] = 100; + clear(); + scene().draw(); + // 851 visible points: every 2nd + expect(scene().lod.total).toBe(851); + expect(scene().lod.stride).toBe(2); + expect(events[events.length - 1]).toEqual({ + subplot: 'xy', + state: 'preview', + stride: 2, + shown: 426, + total: 851, + reason: 'plot' + }); + scene().setHidden({ 1: true }); + // 350 visible points: under minpoints, every point is drawn + expect(scene().lod.total).toBe(350); + expect(scene().lod.state).toBe('off'); + }) + .then(done, done.fail); + }); + + it('@gl stays off below minpoints, in a static plot, with lines, a selection or a second subplot', (done) => { + plot(data(), layout({ minpoints: 5000, budget: 500 })) + .then(() => { + expect(scene().lod.state).toBe('off'); + let d = data(); + d[1].mode = 'lines+markers'; + return plot(d, layout(LOD)); + }) + .then(() => { + expect(scene().lod.state).toBe('off'); + let d = data(); + d[0].selectedpoints = [1, 2, 3]; + return plot(d, layout(LOD)); + }) + .then(() => { + expect(scene().lod.state).toBe('off'); + const d = data(); + d[2].xaxis = 'x2'; + d[2].yaxis = 'y2'; + return plot(d, layout(LOD, { grid: { rows: 1, columns: 2, pattern: 'independent' } })); + }) + .then(() => { + expect(scene().lod.state).toBe('off'); + expect(gd._fullLayout._plots.x2y2._scene.lod.state).toBe('off'); + expect(events.length).toBe(0); + // a big single trace is drawn in a preview like any other + return plot([trace(120000, 7)], layout({ minpoints: 1000, budget: 50000, settle: 100000 })); + }) + .then(() => { + expect(scene().lod.state).toBe('preview'); + expect(scene().lod.stride).toBe(4); + return plot(data(), layout(LOD), { staticPlot: true }); + }) + .then(() => { + expect(scene().lod.state).toBe('off'); + }) + .then(done, done.fail); + }); + + it('@gl leaves nothing pending after a purge during a preview', (done) => { + plot(data(), layout(LOD)) + .then(() => { + expect(scene().lod.state).toBe('preview'); + Plotly.purge(gd); + return new Promise((r) => { + setTimeout(r, 80); + }); + }) + .then(() => { + expect(events.length).toBe(0); + }) + .then(done, done.fail); + }); + + it('@gl ignores the late context loss of a released canvas, and settles the new plot', (done) => { + let old; + plot(data(), layout(LOD)) + .then(() => { + old = gd.querySelector('.gl-canvas-context'); + Plotly.purge(gd); + return plot(data(), layout(LOD)); + }) + .then(() => { + expect(gd.querySelector('.gl-canvas-context')).not.toBe(old); + expect(scene().lod.state).toBe('preview'); + // the browser reports the loss of the old context a task later, through Plotly's listener on that canvas + old.dispatchEvent(new Event('webglcontextlost')); + return when('full'); + }) + .then(() => { + expect(states()).toEqual(['full:settle']); + }) + .then(done, done.fail); + }); + + // the full picture in parts + const PARTS = { minpoints: 1000, budget: 500, maxstride: 64, settle: 40, slice: 400 }; + function glOf() { + return gd._fullLayout._glcanvas.data()[0].regl._gl; + } + function canvas() { + return gd.querySelector('.gl-canvas-context'); + } + function cover() { + return gd.querySelector('.gl-lod-cover'); + } + function wait(ms) { + return new Promise((r) => { + setTimeout(r, ms); + }); + } + // a timer query whose result comes when the spec says so (null: the extension is missing) + function fakeTimer(missing) { + let gl = glOf(); + const orig = gl.getExtension; + const f = { + available: false, + begun: 0, + deleted: 0, + QUERY_RESULT_AVAILABLE_EXT: 1, + TIME_ELAPSED_EXT: 2, + createQueryEXT: () => { + return {}; + }, + deleteQueryEXT: () => { + f.deleted++; + }, + beginQueryEXT: () => { + f.begun++; + }, + endQueryEXT: () => {}, + getQueryObjectEXT: () => { + return f.available; + } + }; + gl.getExtension = (name) => { + return name === 'EXT_disjoint_timer_query' ? (missing ? null : f) : orig.call(gl, name); + }; + f.restore = () => { + gl.getExtension = orig; + }; + return f; + } + + it('@gl draws the full picture in parts under a copy of the preview, each part when the GPU has finished the last', (done) => { + let log, timer, full; + plot(data(), layout(PARTS)) + .then(() => { + timer = fakeTimer(); + log = watch(gd); + return wait(200); + }) + .then(() => { + // the first part is out and its query is pending: nothing more is issued + expect(timer.begun).toBe(1); + expect(log.arrays).toEqual([[log.gl.POINTS, 0, 400]]); + expect(scene().lod.state).toBe('preview'); + // the canvas is not shown while it holds a part; the copy of the preview is + expect(canvas().style.visibility).toBe('hidden'); + expect(cover().style.display).toBe(''); + expect(cover().width).toBe(canvas().width); + expect(cover().height).toBe(canvas().height); + expect(cover().style.width).toBe(canvas().style.width); + timer.available = true; + return when('full'); + }) + .then(() => { + expect(log.arrays).toEqual([ + [log.gl.POINTS, 0, 400], + [log.gl.POINTS, 400, 400], + [log.gl.POINTS, 800, 200], + [log.gl.POINTS, 0, 200], + [log.gl.POINTS, 200, 301], + [log.gl.POINTS, 0, 99], + [log.gl.POINTS, 99, 151] + ]); + expect(timer.begun).toBe(5); + expect(canvas().style.visibility).toBe(''); + expect(cover().style.display).toBe('none'); + expect(cover().width).toBe(0); + expect(states()).toEqual(['full:settle']); + timer.restore(); + log.restore(); + full = pixels(); + return Plotly.relayout(gd, { 'lod.minpoints': 0 }); + }) + .then(() => { + clear(); + scene().draw(); + expect(scene().lod.state).toBe('off'); + expect(differ(full, pixels())).toBe(0); + }) + .then(done, done.fail); + }); + + it('@gl waits for the GPU with readPixels when there is no timer query', (done) => { + let gl, rp; + let reads = 0; + plot(data(), layout(PARTS)) + .then(() => { + fakeTimer(true); + gl = glOf(); + rp = gl.readPixels; + gl.readPixels = function (x, y, w, h) { + if (w === 1 && h === 1) reads++; + return rp.apply(gl, arguments); + }; + return when('full'); + }) + .then(() => { + // five parts, a wait after each but the last + expect(reads).toBe(4); + expect(canvas().style.visibility).toBe(''); + gl.readPixels = rp; + }) + .then(done, done.fail); + }); + + it('@gl drops the parts that are left when a draw is asked for, and previews again', (done) => { + let log, timer; + plot(data(), layout(PARTS)) + .then(() => { + timer = fakeTimer(); + return wait(200); + }) + .then(() => { + expect(timer.begun).toBe(1); + log = watch(gd); + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.5] }); + }) + .then(() => { + // the preview is on the canvas, shown; the pending query is let go + expect( + log.elements.map((e) => { + return e[1]; + }) + ).toEqual([250, 126, 63]); + expect(log.arrays.length).toBe(0); + expect(canvas().style.visibility).toBe(''); + expect(cover().style.display).toBe('none'); + expect(timer.deleted).toBe(1); + expect(scene().lod.state).toBe('preview'); + timer.available = true; + return when('full'); + }) + .then(() => { + // one full picture, from its start + expect(log.arrays.length).toBe(7); + expect(log.arrays[0]).toEqual([log.gl.POINTS, 0, 400]); + expect(states()).toEqual(['full:settle']); + timer.restore(); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl settles, loses its context or is purged in the middle of the parts with nothing left pending', (done) => { + let log, timer; + plot(data(), layout(PARTS)) + .then(() => { + timer = fakeTimer(); + return wait(200); + }) + .then(() => { + log = watch(gd); + scene().lod.settle(); + expect(scene().lod.state).toBe('full'); + expect( + log.arrays.map((a) => { + return a[2]; + }) + ).toEqual([1000, 501, 250]); + expect(canvas().style.visibility).toBe(''); + timer.available = true; + return wait(100); + }) + .then(() => { + expect(log.arrays.length).toBe(3); + expect(timer.begun).toBe(1); + + // a context loss during the parts + timer.available = false; + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.6] }); + }) + .then(() => { + return wait(200); + }) + .then(function () { + expect(timer.begun).toBe(2); + expect(canvas().style.visibility).toBe('hidden'); + // the loss of a canvas that is not this plot's (a released one) changes nothing + gd.emit('plotly_webglcontextlost', { + event: { target: document.createElement('canvas') }, + layer: 'contextLayer' + }); + gd.emit('plotly_webglcontextlost', {}); + expect(canvas().style.visibility).toBe('hidden'); + gd.emit('plotly_webglcontextlost', { event: { target: canvas() }, layer: 'contextLayer' }); + expect(canvas().style.visibility).toBe(''); + timer.available = true; + return wait(100); + }) + .then(() => { + expect(timer.begun).toBe(2); + + // a purge during the parts + timer.available = false; + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.7] }); + }) + .then(() => { + return wait(200); + }) + .then(() => { + expect(timer.begun).toBe(3); + expect(cover().parentNode).not.toBe(null); + timer.restore(); + log.restore(); + Plotly.purge(gd); + expect(gd.querySelector('.gl-lod-cover')).toBe(null); + return wait(100); + }) + .then(() => { + expect(timer.begun).toBe(3); + }) + .then(done, done.fail); + }); + + // an edit of a fully drawn plot + it('@gl holds the full picture through an edit: stale, then full, never a preview', (done) => { + let log, timer, full; + plot(data(), layout(PARTS)) + .then(() => { + return when('full'); + }) + .then(() => { + events.length = 0; + timer = fakeTimer(); + log = watch(gd); + return Plotly.restyle(gd, { 'marker.color': 'black' }, [0]); + }) + .then(() => { + // the new full picture is drawn at once, in one draw, on the hidden canvas + expect(scene().lod.state).toBe('stale'); + expect( + log.arrays.map((a) => { + return a[2]; + }) + ).toEqual([1000, 501, 250]); + expect(log.elements.length).toBe(0); + expect(canvas().style.visibility).toBe('hidden'); + expect(cover().style.display).toBe(''); + expect(events[0]).toEqual({ + subplot: 'xy', + state: 'stale', + stride: 4, + shown: 1751, + total: 1751, + reason: 'plot' + }); + return wait(100); + }) + .then(() => { + expect(scene().lod.state).toBe('stale'); + // a second edit during the hold: still held, drawn again, no event + log.reset(); + return Plotly.moveTraces(gd, 2, 0); + }) + .then(() => { + expect(scene().lod.state).toBe('stale'); + expect( + log.arrays.map((a) => { + return a[2]; + }) + ).toEqual([250, 1000, 501]); + expect(canvas().style.visibility).toBe('hidden'); + expect(timer.deleted).toBe(1); + timer.available = true; + return when('full'); + }) + .then(() => { + expect(states()).toEqual(['stale:plot', 'full:settle']); + expect(canvas().style.visibility).toBe(''); + expect(cover().style.display).toBe('none'); + timer.restore(); + log.restore(); + full = pixels(); + return Plotly.relayout(gd, { 'lod.minpoints': 0 }); + }) + .then(() => { + clear(); + scene().draw(); + expect(differ(full, pixels())).toBe(0); + }) + .then(done, done.fail); + }); + + it('@gl holds for setHidden, previews for another view, and a view change ends a hold', (done) => { + let log, timer; + plot(data(), layout(PARTS)) + .then(() => { + return when('full'); + }) + .then(() => { + events.length = 0; + timer = fakeTimer(); + log = watch(gd); + // 1250 visible points: every 4th + scene().setHidden({ 1: true }); + expect(scene().lod.state).toBe('stale'); + expect( + log.arrays.map((a) => { + return a[2]; + }) + ).toEqual([1000, 250]); + expect(canvas().style.visibility).toBe('hidden'); + + // a zoom during the hold: the copy goes, a preview is drawn + log.reset(); + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.5] }); + }) + .then(() => { + expect(scene().lod.state).toBe('preview'); + expect( + log.elements.map((e) => { + return e[1]; + }) + ).toEqual([250, 63]); + expect(canvas().style.visibility).toBe(''); + expect(cover().style.display).toBe('none'); + timer.available = true; + return when('full'); + }) + .then(() => { + expect(states()).toEqual(['stale:plot', 'preview:plot', 'full:settle']); + // a drag of a fully drawn plot previews + events.length = 0; + scene().update({ range: [0.1, 0.1, 0.5, 0.5] }); + require('../../../src/lib/clear_gl_canvases')(gd); + scene().draw(); + expect(scene().lod.state).toBe('preview'); + expect(canvas().style.visibility).toBe(''); + expect(events[0].reason).toBe('range'); + return when('full'); + }) + .then(() => { + // a clear that no draw follows: the copy does not stay + require('../../../src/lib/clear_gl_canvases')(gd); + expect(canvas().style.visibility).toBe('hidden'); + return wait(30); + }) + .then(() => { + expect(canvas().style.visibility).toBe(''); + expect(cover().style.display).toBe('none'); + timer.restore(); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl previews an edit with edits: preview, and holds again with edits: hold', (done) => { + let log; + const lod = { minpoints: 1000, budget: 500, settle: 40, slice: 400, edits: 'preview' }; + plot(data(), layout(lod)) + .then(() => { + return when('full'); + }) + .then(() => { + events.length = 0; + log = watch(gd); + return Plotly.restyle(gd, { 'marker.color': 'black' }, [0]); + }) + .then(() => { + expect(scene().lod.state).toBe('preview'); + expect(log.elements.length).toBe(3); + expect(canvas().style.visibility).toBe(''); + return when('full'); + }) + .then(() => { + log.reset(); + return Plotly.relayout(gd, { 'lod.edits': 'hold' }); + }) + .then(() => { + // setting it draws nothing + expect(log.arrays.length + log.elements.length).toBe(0); + expect(gd._fullLayout.lod.edits).toBe('hold'); + return Plotly.restyle(gd, { 'marker.color': 'red' }, [0]); + }) + .then(() => { + expect(log.elements.length).toBe(0); + expect(log.arrays.length).toBe(3); + return when('full'); + }) + .then(() => { + expect(states()).toEqual(['preview:plot', 'full:settle', 'stale:plot', 'full:settle']); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl waits with readPixels for a held edit when there is no timer query', (done) => { + plot(data(), layout(PARTS)) + .then(() => { + return when('full'); + }) + .then(() => { + events.length = 0; + fakeTimer(true); + return Plotly.restyle(gd, { 'marker.color': 'black' }, [0]); + }) + .then(() => { + expect(scene().lod.state).toBe('full'); + expect(states()).toEqual(['stale:plot', 'full:settle']); + expect(canvas().style.visibility).toBe(''); + }) + .then(done, done.fail); + }); + + it('@gl draws every point for an image', (done) => { + plot(data(), layout({ minpoints: 1000, budget: 500, settle: 100000 })) + .then(() => { + return Plotly.toImage(gd, { format: 'png', width: 400, height: 300 }); + }) + .then((url) => { + expect(url.length).toBeGreaterThan(1000); + expect(scene().lod.state).toBe('preview'); + }) + .then(done, done.fail); + }); +}); From 8fff818f109429601770f889abbe0512dd999de2 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 12:14:37 -0800 Subject: [PATCH 25/45] Add an opt-in level of detail for camera moves to gl3d (scene.lod) Each frame of a rotation draws every scatter3d marker, and draws every marker again for the pick buffer. With scene.lod.minpoints set, a frame with a changed view draws every k-th disc marker and no pick pass. The scene draws every marker scene.lod.settle ms after the last change of the view, and the pick pass follows. scene.getLOD() returns the state, and the graph emits plotly_lod. stackgl_modules/package.json pins gl-plot3d and gl-scatter3d to the fork commits of the two package pull requests. stackgl_modules/index.js is the webpack output of that install. A static scene gets no level of detail. --- src/plots/gl3d/layout/defaults.js | 6 + src/plots/gl3d/layout/layout_attributes.js | 45 ++- src/plots/gl3d/scene.js | 19 + stackgl_modules/index.js | 138 ++++++- stackgl_modules/package-lock.json | 11 +- stackgl_modules/package.json | 4 +- test/jasmine/tests/gl3d_lod_test.js | 417 +++++++++++++++++++++ 7 files changed, 624 insertions(+), 16 deletions(-) create mode 100644 test/jasmine/tests/gl3d_lod_test.js diff --git a/src/plots/gl3d/layout/defaults.js b/src/plots/gl3d/layout/defaults.js index fc71c144408..4e0701f549b 100644 --- a/src/plots/gl3d/layout/defaults.js +++ b/src/plots/gl3d/layout/defaults.js @@ -51,6 +51,12 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { */ var bgcolor = coerce('bgcolor'); + // A scene without `lod` gets no `lod` container. + if(Lib.isPlainObject(sceneLayoutIn.lod) && coerce('lod.minpoints')) { + coerce('lod.budget'); + coerce('lod.maxstride'); + coerce('lod.settle'); + } var bgColorCombined = Color.combine(bgcolor, opts.paper_bgcolor); var cameraKeys = ['up', 'center', 'eye']; diff --git a/src/plots/gl3d/layout/layout_attributes.js b/src/plots/gl3d/layout/layout_attributes.js index 026f471bee2..87462a9e96e 100644 --- a/src/plots/gl3d/layout/layout_attributes.js +++ b/src/plots/gl3d/layout/layout_attributes.js @@ -144,8 +144,8 @@ module.exports = { '*glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default.', '*disc* draws each marker as one round point sprite. It needs far less memory and draws faster.', 'The edge of a disc differs from the edge of a glyph by about one pixel.', - 'A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph.', - '*auto* is currently the same as *disc*.' + '*auto* draws discs where it can.', + 'It draws glyphs for other symbols, for projections on the axes, and for markers that exceed the point size limit of the GPU.' ].join(' ') }, dragmode: { @@ -165,6 +165,47 @@ module.exports = { 'Determines the mode of hover interactions for this scene.' ].join(' ') }, + lod: { + minpoints: { + valType: 'number', + min: 0, + dflt: 0, + editType: 'plot', + description: [ + 'Sets the number of `scatter3d` disc markers from which a camera move shows a preview.', + 'A preview draws every k-th marker of every trace and no pick pass.', + 'The scene draws every marker again `settle` milliseconds after the last camera move.', + '0 turns the preview off.', + 'The graph emits `plotly_lod` when the state changes.' + ].join(' ') + }, + budget: { + valType: 'number', + min: 1, + dflt: 2500000, + editType: 'plot', + description: [ + 'Sets the largest number of markers in a preview.', + 'The stride k is the smallest power of two, from 2 to `maxstride`,', + 'that brings the markers within this number.' + ].join(' ') + }, + maxstride: { + valType: 'integer', + min: 2, + dflt: 64, + editType: 'plot', + description: 'Sets the largest stride of a preview.' + }, + settle: { + valType: 'number', + min: 0, + dflt: 150, + editType: 'plot', + description: 'Sets the time in milliseconds between the last camera move and the full picture.' + }, + editType: 'plot' + }, uirevision: { valType: 'any', editType: 'none', diff --git a/src/plots/gl3d/scene.js b/src/plots/gl3d/scene.js index b76514d335a..2fdb3e50685 100644 --- a/src/plots/gl3d/scene.js +++ b/src/plots/gl3d/scene.js @@ -293,9 +293,26 @@ proto.initializeGLPlot = function() { scene.render(); }; + // A static scene gets no level of detail, because an image must show every point. + scene.glplot.onlod = (state) => { + const gd = scene.graphDiv; + if(gd?.emit) gd.emit('plotly_lod', { subplot: scene.id, ...state }); + }; + scene.glplot.lod = scene.staticMode ? null : scene.fullSceneLayout.lod; + return true; }; +/** + * Get the level of detail of the scene. + * + * @returns `{state, stride, shown, total, settle}`. `state` is 'off', 'preview' or 'full'. `settle()` draws every point now. + */ +proto.getLOD = function() { + const { lodState, lodSettle } = this.glplot; + return { ...lodState, settle: lodSettle }; +}; + proto.render = function() { var scene = this; var gd = scene.graphDiv; @@ -580,6 +597,8 @@ proto.plot = function(sceneData, fullLayout, layout) { scene.updateFx(fullSceneLayout.dragmode, fullSceneLayout.hovermode); scene.camera.enableWheel = scene.graphDiv._context._scrollZoom.gl3d; + scene.glplot.lod = scene.staticMode ? null : fullSceneLayout.lod; + // Update scene background scene.glplot.setClearColor(str2RGBAarray(fullSceneLayout.bgcolor)); diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index 33c1ff2b948..ac9fea3e128 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -18881,6 +18881,16 @@ function createScene(options) { mouseListener: null, _stopped: false, + // Level of detail while the camera moves. lod = {minpoints, budget, maxstride, settle} (or null): + // with at least minpoints thinnable points in the scene (objects with lodPoints()), a frame in which + // the view changed draws every k-th point of every such object (k: the smallest power of two, at + // least 2 and at most maxstride, that brings them within budget) and no pick pass, and the first + // frame settle ms after the view last changed draws them all. + // lodState = {state: 'off', 'preview' or 'full', stride, shown, total}; onlod(state and reason) on a change. + lod: options.lod || null, + lodState: {state: 'off', stride: 0, shown: 0, total: 0}, + onlod: options.onlod || null, + getAspectratio: function() { return { x: this.aspect[0], @@ -19101,7 +19111,8 @@ function createScene(options) { } scene._mouseRotating = false - for(var i=0; i selection.distance) { @@ -19208,6 +19219,72 @@ function createScene(options) { var prevBounds = [nBounds[0].slice(), nBounds[1].slice()] + // Level of detail while the camera moves (scene.lod) + var lodMoved = 0 // when the camera last moved in a preview, ms + var lodOn = false // the frames are previews + var lodView = new Float64Array(16) // the view matrix of the last frame + var lodForce = false // lodSettle: this frame draws every disc + + function lodFrame(cameraMoved) { + var o = scene.lod + var n = 0 + var k = 0 + var i + // the camera can report a move after it has reached its place: only a view that changed is a move here. + // (After a plot the camera glides to its place for about 0.4 s: those frames are previews too.) + var view = scene.camera.matrix + var moved = false + for(i=0; i<16; ++i) { + if(lodView[i] !== view[i]) { + moved = true + lodView[i] = view[i] + } + } + cameraMoved = cameraMoved && moved + if(o && o.minpoints > 0) { + for(i=0; i= o.minpoints) { + k = 2 + while(k < o.maxstride && n / k > o.budget) k *= 2 + } + } + var now = Date.now() + if(k && cameraMoved) lodMoved = now + var preview = k > 0 && !lodForce && lodMoved > 0 && now - lodMoved < o.settle + lodForce = false + if(!preview) lodMoved = 0 + var toggled = preview !== lodOn + lodOn = preview + // the frame that draws every disc again + if(toggled && !preview) dirty = true + if(preview || toggled) { + for(i=0; i 1 draws every lodStride-th disc (a preview; never the pick pass) this.discOutline = false this.lineColorBuffer = null this.sizeBuffer = null @@ -20289,7 +20369,9 @@ proto._discSetup = function(kind, outline) { this.discSet[key] = { shader: createDiscShader(gl, outline, false), pickShader: createDiscShader(gl, outline, true), - vao: createVAO(gl, attrs) + vao: createVAO(gl, attrs), + attrs: attrs, + lod: null } } this.discCur = this.discSet[key] @@ -20465,6 +20547,36 @@ proto._discLineHalf = function(pixelRatio) { return 0.5 * this.lineWidth * pixelRatio } +// the discs a preview can thin out (0 when the markers are not discs) +proto.lodPoints = function() { + return this.discActive ? this.vertexCount : 0 +} + +// A second vertex array of the same buffers with the element indices 0, k, 2k, ... for a preview of every +// k-th disc; kept until k or the number of discs changes. Null when 32-bit element indices are missing. +proto._discLod = function(set, k) { + var gl = this.gl + var count = Math.ceil(this.vertexCount / k) + var lod = set.lod + if(lod && lod.k === k && lod.count === count) return lod + if(this.lodIndex32 === undefined) { + this.lodIndex32 = !!((typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext) || + gl.getExtension('OES_element_index_uint')) + } + if(!this.lodIndex32 || !count) return null + var index = new Uint32Array(count) + for(var i = 0; i < count; ++i) index[i] = i * k + if(lod) { + lod.elements.update(index) + } else { + lod = set.lod = {elements: createBuffer(gl, index, gl.ELEMENT_ARRAY_BUFFER)} + lod.vao = createVAO(gl, set.attrs, lod.elements, gl.UNSIGNED_INT) + } + lod.k = k + lod.count = count + return lod +} + function drawDisc(points, camera, pixelRatio, pick, hard) { var gl = points.gl var set = points.discCur @@ -20509,18 +20621,26 @@ function drawDisc(points, camera, pixelRatio, pick, hard) { gl.colorMask(true, true, true, false) } - set.vao.bind() - set.vao.draw(gl.POINTS, points.vertexCount) + // a preview draws every lodStride-th disc through an index buffer; the pick pass draws them all + var vao = set.vao + var count = points.vertexCount + var lod = !pick && points.lodStride > 1 ? points._discLod(set, points.lodStride) : null + if(lod) { + vao = lod.vao + count = lod.count + } + vao.bind() + vao.draw(gl.POINTS, count) if(rimPass) { uniforms.rim = 1 gl.enable(gl.BLEND) gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) gl.depthMask(false) - set.vao.draw(gl.POINTS, points.vertexCount) + vao.draw(gl.POINTS, count) gl.depthMask(true) gl.disable(gl.BLEND) } - set.vao.unbind() + vao.unbind() if(a2c) { gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE) gl.colorMask(true, true, true, true) @@ -21086,6 +21206,10 @@ proto.dispose = function() { this.discSet[k].shader.dispose() this.discSet[k].pickShader.dispose() this.discSet[k].vao.dispose() + if(this.discSet[k].lod) { + this.discSet[k].lod.vao.dispose() + this.discSet[k].lod.elements.dispose() + } } this.sizeBuffer.dispose() if(this.lineColorBuffer) this.lineColorBuffer.dispose() diff --git a/stackgl_modules/package-lock.json b/stackgl_modules/package-lock.json index 36e50d1169a..9b3c7722b46 100644 --- a/stackgl_modules/package-lock.json +++ b/stackgl_modules/package-lock.json @@ -16,8 +16,8 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "^2.4.7", - "gl-scatter3d": "github:settylab/gl-scatter3d#25590f6d72f6f98b91f283d4d5614933657bfb6a", + "gl-plot3d": "github:settylab/gl-plot3d#72fbc2ea6c558e7f4d6f71a347bb42ace5521dae", + "gl-scatter3d": "github:settylab/gl-scatter3d#d887305148a560f05fd5857ef18b06215e84f632", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", "gl-streamtube3d": "^1.4.2", @@ -1312,8 +1312,8 @@ }, "node_modules/gl-plot3d": { "version": "2.4.7", - "resolved": "https://registry.npmjs.org/gl-plot3d/-/gl-plot3d-2.4.7.tgz", - "integrity": "sha512-mLDVWrl4Dj0O0druWyHUK5l7cBQrRIJRn2oROEgrRuOgbbrLAzsREKefwMO0bA0YqkiZMFMnV5VvPA9j57X5Xg==", + "resolved": "git+ssh://git@github.com/settylab/gl-plot3d.git#72fbc2ea6c558e7f4d6f71a347bb42ace5521dae", + "integrity": "sha512-coi9DUI5ulJSAWpO7PCwZli6JdX/8gZRnHHwXhjSjy4BgIjecIfyoBUE/5OzU/VELg6BtDMo3yMIF8ehXob54g==", "license": "MIT", "dependencies": { "3d-view": "^2.0.0", @@ -1347,7 +1347,8 @@ }, "node_modules/gl-scatter3d": { "version": "1.4.1", - "resolved": "git+ssh://git@github.com/settylab/gl-scatter3d.git#25590f6d72f6f98b91f283d4d5614933657bfb6a", + "resolved": "git+ssh://git@github.com/settylab/gl-scatter3d.git#d887305148a560f05fd5857ef18b06215e84f632", + "integrity": "sha512-DC5oC6IsBstjO7E0s6G8hUnSBd0pGEyu4iBXNmB1c6LWCZCpV6DfHmNltkI/bbcdZ6aDi28LBILFCuAtaxIXUw==", "license": "MIT", "dependencies": { "gl-buffer": "^2.1.2", diff --git a/stackgl_modules/package.json b/stackgl_modules/package.json index f8ec311abc1..8e36f79398f 100644 --- a/stackgl_modules/package.json +++ b/stackgl_modules/package.json @@ -19,8 +19,8 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "^2.4.7", - "gl-scatter3d": "github:settylab/gl-scatter3d#25590f6d72f6f98b91f283d4d5614933657bfb6a", + "gl-plot3d": "github:settylab/gl-plot3d#72fbc2ea6c558e7f4d6f71a347bb42ace5521dae", + "gl-scatter3d": "github:settylab/gl-scatter3d#d887305148a560f05fd5857ef18b06215e84f632", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", "gl-streamtube3d": "^1.4.2", diff --git a/test/jasmine/tests/gl3d_lod_test.js b/test/jasmine/tests/gl3d_lod_test.js new file mode 100644 index 00000000000..f5b2d6693ce --- /dev/null +++ b/test/jasmine/tests/gl3d_lod_test.js @@ -0,0 +1,417 @@ +const Plotly = require('../../../lib/index'); +const createGraphDiv = require('../assets/create_graph_div'); +const destroyGraphDiv = require('../assets/destroy_graph_div'); + +// level of detail while the camera moves: scene.lod + +function f32(n, seed) { + const a = new Float32Array(n); + let s = seed; + for (let i = 0; i < n; i++) { + s = (s * 1664525 + 1013904223) >>> 0; + a[i] = s / 4294967296; + } + return a; +} + +describe('gl-scatter3d strided discs', () => { + let gd; + + beforeEach(() => { + gd = createGraphDiv(); + }); + afterEach(() => { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function trace3d(n, seed, extra) { + let t = { + type: 'scatter3d', + mode: 'markers', + x: f32(n, seed), + y: f32(n, seed + 1), + z: f32(n, seed + 2), + marker: { size: 4, color: 'red', line: { width: 0 } } + }; + for (let k in extra) t[k] = extra[k]; + return t; + } + function glplot() { + return gd._fullLayout.scene._scene.glplot; + } + function watch3d() { + let gl = glplot().gl; + let log = { elements: [], arrays: [] }; + let de = gl.drawElements; + let da = gl.drawArrays; + gl.drawElements = function (mode, count, type) { + if (mode === gl.POINTS) log.elements.push([count, type]); + return de.apply(gl, arguments); + }; + gl.drawArrays = function (mode, first, count) { + if (mode === gl.POINTS) log.arrays.push(count); + return da.apply(gl, arguments); + }; + log.reset = () => { + log.elements = []; + log.arrays = []; + }; + log.restore = () => { + gl.drawElements = de; + gl.drawArrays = da; + }; + return log; + } + function frame() { + glplot().dirty = true; + glplot().redraw(); + } + function differ3(a, b) { + let n = 0; + for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) n++; + return n; + } + function pixels() { + let gl = glplot().gl; + const px = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, px); + return px; + } + + it('@gl draws every k-th disc of a trace when asked, opaque and translucent, and all of them again after', (done) => { + let log, full, plain, objs; + Plotly.newPlot( + gd, + [ + trace3d(1000, 1), + trace3d(501, 4, { marker: { size: 4, color: 'blue', opacity: 0.5, line: { width: 0 } } }) + ], + { width: 400, height: 300, scene: { bgcolor: '#ffffff', markerrender: 'auto' } } + ) + .then(() => { + objs = glplot().objects; + expect( + objs.map((o) => { + return o.lodPoints(); + }) + ).toEqual([1000, 501]); + // no alpha to coverage: the thinned frame is compared with a full one + objs.forEach((o) => { + o.discA2C = false; + }); + log = watch3d(); + frame(); + plain = log.arrays.slice(); + expect(log.elements.length).toBe(0); + full = pixels(); + log.reset(); + objs.forEach((o) => { + o.lodStride = 8; + }); + frame(); + let gl = glplot().gl; + // every draw of the two traces for the picture is thinned (the pick pass, drawArrays, is not) + const counts = log.elements.map((e) => { + return e[0]; + }); + expect(counts.indexOf(125)).not.toBe(-1); + expect(counts.indexOf(63)).not.toBe(-1); + expect( + counts.filter((c) => { + return c !== 125 && c !== 63; + }) + ).toEqual([]); + expect(counts.length).toBeGreaterThan(2); + log.elements.forEach((e) => { + expect(e[1]).toBe(gl.UNSIGNED_INT); + }); + const thin = pixels(); + expect(differ3(full, thin)).toBeGreaterThan(1000); + + // the same stride again: no new index buffer + let uploads = 0; + const bd = gl.bufferData; + gl.bufferData = function (target) { + if (target === gl.ELEMENT_ARRAY_BUFFER) uploads++; + return bd.apply(gl, arguments); + }; + frame(); + expect(uploads).toBe(0); + gl.bufferData = bd; + + log.reset(); + objs.forEach((o) => { + o.lodStride = 0; + }); + frame(); + // the draws of before + expect(log.elements.length).toBe(0); + expect(log.arrays).toEqual(plain); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl never thins the pick pass, and has no discs to thin for glyph markers', (done) => { + let log; + Plotly.newPlot(gd, [trace3d(1000, 1), trace3d(300, 4, { marker: { size: 4, symbol: 'square' } })], { + width: 400, + height: 300, + scene: { markerrender: 'auto' } + }) + .then(() => { + const objs = glplot().objects; + expect( + objs.map((o) => { + return o.lodPoints(); + }) + ).toEqual([1000, 0]); + objs.forEach((o) => { + o.lodStride = 8; + }); + log = watch3d(); + objs[0].drawPick({ + model: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], + view: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], + projection: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] + }); + expect(log.elements.length).toBe(0); + expect(log.arrays).toEqual([1000]); + log.restore(); + }) + .then(done, done.fail); + }); +}); + +describe('gl3d scene.lod', () => { + let gd; + let events; + + beforeEach(() => { + gd = createGraphDiv(); + events = []; + }); + afterEach(() => { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function trace3d(n, seed, extra) { + const t = { + type: 'scatter3d', + mode: 'markers', + x: f32(n, seed), + y: f32(n, seed + 1), + z: f32(n, seed + 2), + marker: { size: 4, color: 'red', line: { width: 0 } } + }; + for (let k in extra) t[k] = extra[k]; + return t; + } + function data() { + return [ + trace3d(1000, 1), + trace3d(501, 4, { marker: { size: 4, color: 'blue', opacity: 0.5, line: { width: 0 } } }) + ]; + } + function layout(lod) { + const scene = { bgcolor: '#ffffff', markerrender: 'auto', camera: { eye: { x: 1.5, y: 1.5, z: 1.5 } } }; + if (lod) scene.lod = JSON.parse(JSON.stringify(lod)); + return { width: 400, height: 300, scene: scene }; + } + const LOD = { minpoints: 1000, budget: 200, maxstride: 64, settle: 80 }; + function scene() { + return gd._fullLayout.scene._scene; + } + function glplot() { + return scene().glplot; + } + function wait(ms) { + return new Promise((r) => { + setTimeout(r, ms); + }); + } + function when(state) { + return new Promise((resolve, reject) => { + const t0 = Date.now(); + (function poll() { + if (scene().getLOD().state === state) resolve(); + else if (Date.now() - t0 > 3000) + reject(new Error('never ' + state + ', still ' + scene().getLOD().state)); + else setTimeout(poll, 5); + })(); + }); + } + function watch3d() { + const gl = glplot().gl; + let log = { elements: [], arrays: [] }; + const de = gl.drawElements; + const da = gl.drawArrays; + gl.drawElements = function (mode, count) { + if (mode === gl.POINTS) log.elements.push(count); + return de.apply(gl, arguments); + }; + gl.drawArrays = function (mode, first, count) { + if (mode === gl.POINTS) log.arrays.push(count); + return da.apply(gl, arguments); + }; + log.reset = () => { + log.elements = []; + log.arrays = []; + }; + log.restore = () => { + gl.drawElements = de; + gl.drawArrays = da; + }; + return log; + } + function moveCamera(x) { + return Plotly.relayout(gd, { 'scene.camera.eye': { x: x, y: 1.5, z: 1.5 } }); + } + function plot(lod, config) { + return Plotly.newPlot(gd, data(), layout(lod), config).then(() => { + gd.on('plotly_lod', (e) => { + events.push(e); + }); + }); + } + + it('@gl thins the discs while the camera moves, with no pick pass, and draws them all at rest', (done) => { + let log; + plot(LOD) + .then(() => { + return wait(800); + }) + .then(() => { + // at rest after the open every disc is drawn: 1501 discs, budget 200, stride 8 + expect(gd._fullLayout.scene.lod).toEqual(LOD); + expect(scene().getLOD().state).toBe('full'); + expect(scene().getLOD().stride).toBe(8); + expect(scene().getLOD().total).toBe(1501); + events.length = 0; + log = watch3d(); + return moveCamera(1.7); + }) + .then(() => { + return when('preview'); + }) + .then(() => { + return wait(30); + }) + .then(() => { + expect(log.elements.length).toBeGreaterThan(1); + expect( + log.elements.filter((c) => { + return c !== 125 && c !== 63; + }) + ).toEqual([]); + expect(log.arrays.length).toBe(0); + expect(events[0]).toEqual({ + subplot: 'scene', + state: 'preview', + stride: 8, + shown: 188, + total: 1501, + reason: 'camera' + }); + // a second move restarts the wait + return moveCamera(1.9); + }) + .then(() => { + return wait(40); + }) + .then(() => { + expect(scene().getLOD().state).toBe('preview'); + // no pick pass in a preview: it would draw every disc with drawArrays + expect(log.arrays.length).toBe(0); + log.reset(); + return when('full'); + }) + .then(() => { + return wait(30); + }) + .then(() => { + expect(log.arrays.indexOf(1000)).not.toBe(-1); + expect(log.arrays.indexOf(501)).not.toBe(-1); + expect( + events.map((e) => { + return e.state + ':' + e.reason; + }) + ).toEqual(['preview:camera', 'full:settle']); + // the full frame draws the pick pass too: every disc once more + expect( + log.arrays.filter((c) => { + return c === 501; + }).length + ).toBeGreaterThan(1); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl draws every disc at once on settle()', (done) => { + let log; + plot({ minpoints: 1000, budget: 200, settle: 100000 }) + .then(() => { + return wait(800); + }) + .then(() => { + return moveCamera(1.7); + }) + .then(() => { + return when('preview'); + }) + .then(() => { + log = watch3d(); + scene().getLOD().settle(); + expect(scene().getLOD().state).toBe('full'); + expect(log.arrays.indexOf(1000)).not.toBe(-1); + expect(log.elements.length).toBe(0); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl is off without scene.lod, below minpoints and in a static plot', (done) => { + let log; + plot(null) + .then(() => { + return wait(800); + }) + .then(() => { + expect(gd._fullLayout.scene.lod).toBeUndefined(); + expect(scene().getLOD().state).toBe('off'); + log = watch3d(); + return moveCamera(1.7); + }) + .then(() => { + return wait(150); + }) + .then(() => { + expect(log.elements.length).toBe(0); + expect(log.arrays.indexOf(1000)).not.toBe(-1); + expect(events.length).toBe(0); + log.restore(); + return plot({ minpoints: 5000, budget: 200 }); + }) + .then(() => { + return wait(800); + }) + .then(() => { + return moveCamera(1.7); + }) + .then(() => { + return wait(150); + }) + .then(() => { + expect(scene().getLOD().state).toBe('off'); + expect(scene().getLOD().total).toBe(1501); + return plot(LOD, { staticPlot: true }); + }) + .then(() => { + expect(glplot().lod).toBe(null); + }) + .then(done, done.fail); + }); +}); From ea4ab99c63228838db433a7e2b4050477dd2612d Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:29:44 -0800 Subject: [PATCH 26/45] Add the schema and the draftlog of layout.lod and scene.lod npm run schema wrote test/plot-schema.json and src/types/generated/schema.d.ts. --- draftlogs/YYYY_add.md | 1 + src/types/generated/schema.d.ts | 65 ++++++++++++++++++++++++- test/plot-schema.json | 85 ++++++++++++++++++++++++++++++++- 3 files changed, 149 insertions(+), 2 deletions(-) create mode 100644 draftlogs/YYYY_add.md diff --git a/draftlogs/YYYY_add.md b/draftlogs/YYYY_add.md new file mode 100644 index 00000000000..ebae61ec3b6 --- /dev/null +++ b/draftlogs/YYYY_add.md @@ -0,0 +1 @@ + - Add `layout.lod` and `layout.scene.lod` to draw a preview of every k-th point first in `scattergl` plots and while the camera moves in `scatter3d` plots of many points, with the full picture drawn when the plot is at rest, the `plotly_lod` event, and `scene.hidden` / `scene.setHidden` to hide `scattergl` traces without a recalculation [[#YYYY](https://github.com/plotly/plotly.js/pull/YYYY)] diff --git a/src/types/generated/schema.d.ts b/src/types/generated/schema.d.ts index dd813ebf803..94dcad33f5c 100644 --- a/src/types/generated/schema.d.ts +++ b/src/types/generated/schema.d.ts @@ -13742,8 +13742,34 @@ export interface Scene { * @default 'closest' */ hovermode?: 'closest' | false; + lod?: { + /** + * Sets the largest number of markers in a preview. The stride k is the smallest power of two, from 2 to `maxstride`, that brings the markers within this number. + * @default 2500000 + * Minimum: 1 + */ + budget?: number; + /** + * Sets the largest stride of a preview. + * @default 64 + * Minimum: 2 + */ + maxstride?: number; + /** + * Sets the number of `scatter3d` disc markers from which a camera move shows a preview. A preview draws every k-th marker of every trace and no pick pass. The scene draws every marker again `settle` milliseconds after the last camera move. 0 turns the preview off. The graph emits `plotly_lod` when the state changes. + * @default 0 + * Minimum: 0 + */ + minpoints?: number; + /** + * Sets the time in milliseconds between the last camera move and the full picture. + * @default 150 + * Minimum: 0 + */ + settle?: number; + }; /** - * Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph. *auto* is currently the same as *disc*. + * Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. *auto* draws discs where it can. It draws glyphs for other symbols, for projections on the axes, and for markers that exceed the point size limit of the GPU. * @default 'glyph' */ markerrender?: 'glyph' | 'disc' | 'auto'; @@ -16338,6 +16364,43 @@ export interface Layout { iciclecolorway?: Color[]; images?: LayoutImage[]; legend?: Legend; + lod?: { + /** + * Sets the largest number of points in a preview. The stride k is the smallest power of two, from 2 to `maxstride`, that brings the visible points within this number. + * @default 2500000 + * Minimum: 1 + */ + budget?: number; + /** + * Determines the picture during an edit of a fully drawn plot that keeps the axis ranges, the plot area and the size. *hold* keeps the previous full picture until the new full picture is ready. *preview* shows a preview first, as a pan does. Use *preview* for edits in quick succession, for example from a slider. + * @default 'hold' + */ + edits?: 'hold' | 'preview'; + /** + * Sets the largest stride of a preview. + * @default 64 + * Minimum: 2 + */ + maxstride?: number; + /** + * Sets the number of visible scattergl points from which a draw shows a preview first. A preview draws every k-th point of every trace. The full picture follows when no draw request came for `settle` milliseconds. 0 turns the preview off. Applies to a graph where the scattergl markers of one subplot are the only WebGL traces. The graph emits `plotly_lod` when the state changes. + * @default 0 + * Minimum: 0 + */ + minpoints?: number; + /** + * Sets the time in milliseconds between the last draw request and the full picture. + * @default 150 + * Minimum: 0 + */ + settle?: number; + /** + * Sets the number of points in one part of the full picture. The plot draws the next part when the GPU finished the part before. Thus a draw request between two parts does not wait for the full picture. 0 draws the full picture in one part. + * @default 5000000 + * Minimum: 0 + */ + slice?: number; + }; map?: MapLayout; margin?: { /** diff --git a/test/plot-schema.json b/test/plot-schema.json index 6cd634d633d..1e5d1d54238 100644 --- a/test/plot-schema.json +++ b/test/plot-schema.json @@ -6708,8 +6708,40 @@ false ] }, + "lod": { + "budget": { + "description": "Sets the largest number of markers in a preview. The stride k is the smallest power of two, from 2 to `maxstride`, that brings the markers within this number.", + "dflt": 2500000, + "editType": "plot", + "min": 1, + "valType": "number" + }, + "editType": "plot", + "maxstride": { + "description": "Sets the largest stride of a preview.", + "dflt": 64, + "editType": "plot", + "min": 2, + "valType": "integer" + }, + "minpoints": { + "description": "Sets the number of `scatter3d` disc markers from which a camera move shows a preview. A preview draws every k-th marker of every trace and no pick pass. The scene draws every marker again `settle` milliseconds after the last camera move. 0 turns the preview off. The graph emits `plotly_lod` when the state changes.", + "dflt": 0, + "editType": "plot", + "min": 0, + "valType": "number" + }, + "role": "object", + "settle": { + "description": "Sets the time in milliseconds between the last camera move and the full picture.", + "dflt": 150, + "editType": "plot", + "min": 0, + "valType": "number" + } + }, "markerrender": { - "description": "Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph. *auto* is currently the same as *disc*.", + "description": "Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. *auto* draws discs where it can. It draws glyphs for other symbols, for projections on the axes, and for markers that exceed the point size limit of the GPU.", "dflt": "glyph", "editType": "plot", "valType": "enumerated", @@ -64003,6 +64035,57 @@ "showLegend", "scatter-like" ], + "layoutAttributes": { + "lod": { + "budget": { + "description": "Sets the largest number of points in a preview. The stride k is the smallest power of two, from 2 to `maxstride`, that brings the visible points within this number.", + "dflt": 2500000, + "editType": "none", + "min": 1, + "valType": "number" + }, + "edits": { + "description": "Determines the picture during an edit of a fully drawn plot that keeps the axis ranges, the plot area and the size. *hold* keeps the previous full picture until the new full picture is ready. *preview* shows a preview first, as a pan does. Use *preview* for edits in quick succession, for example from a slider.", + "dflt": "hold", + "editType": "none", + "valType": "enumerated", + "values": [ + "hold", + "preview" + ] + }, + "editType": "none", + "maxstride": { + "description": "Sets the largest stride of a preview.", + "dflt": 64, + "editType": "none", + "min": 2, + "valType": "integer" + }, + "minpoints": { + "description": "Sets the number of visible scattergl points from which a draw shows a preview first. A preview draws every k-th point of every trace. The full picture follows when no draw request came for `settle` milliseconds. 0 turns the preview off. Applies to a graph where the scattergl markers of one subplot are the only WebGL traces. The graph emits `plotly_lod` when the state changes.", + "dflt": 0, + "editType": "none", + "min": 0, + "valType": "number" + }, + "role": "object", + "settle": { + "description": "Sets the time in milliseconds between the last draw request and the full picture.", + "dflt": 150, + "editType": "none", + "min": 0, + "valType": "number" + }, + "slice": { + "description": "Sets the number of points in one part of the full picture. The plot draws the next part when the GPU finished the part before. Thus a draw request between two parts does not wait for the full picture. 0 draws the full picture in one part.", + "dflt": 5000000, + "editType": "none", + "min": 0, + "valType": "number" + } + } + }, "meta": { "description": "The data visualized as scatter point or lines is set in `x` and `y` using the WebGL plotting engine. Bubble charts are achieved by setting `marker.size` and/or `marker.color` to a numerical arrays.", "hrName": "scatter_gl" From 94f16c74626eeac940a45838417a5270fccedc34 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 12:42:20 -0800 Subject: [PATCH 27/45] Pin regl-scatter2d to the combined branch without build scripts A plain npm ci failed in the preparation of the git dependency. The new commit of the package holds the same code and no build script. --- package-lock.json | 6 +++--- package.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index d9072789cdb..15c4626356f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,7 +44,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "github:settylab/regl-scatter2d#f1147d82758075373f2719a081bd51f4ab69e62c", + "regl-scatter2d": "github:settylab/regl-scatter2d#e56fbc64db4f0c5e69d984a16a83ecb7a24602f1", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", @@ -6231,8 +6231,8 @@ }, "node_modules/regl-scatter2d": { "version": "3.4.0", - "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#f1147d82758075373f2719a081bd51f4ab69e62c", - "integrity": "sha512-XMR0qBcf1cWR+EmLECwGQF5KtuN66YeEGZ/FDra9q5EkZ5xtfGr/98NZZxPguucnTOeWof6csl4ibo1c0TAcTw==", + "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#e56fbc64db4f0c5e69d984a16a83ecb7a24602f1", + "integrity": "sha512-9wXCsMEDQvMmKeSmajd0NcQlXIB+Mlq380CzUNIoWwv9yDcvZimoZsUQadHjoPV3jtQKtovtaS0g2rAwM7LSZA==", "license": "MIT", "dependencies": { "@plotly/point-cluster": "^3.1.9", diff --git a/package.json b/package.json index 6a0fd0d8990..e18ff1dd09e 100644 --- a/package.json +++ b/package.json @@ -118,7 +118,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "github:settylab/regl-scatter2d#f1147d82758075373f2719a081bd51f4ab69e62c", + "regl-scatter2d": "github:settylab/regl-scatter2d#e56fbc64db4f0c5e69d984a16a83ecb7a24602f1", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", From 0ecd09e84f9bdee2c8b65ab7567f76f151e23bd2 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 12:43:33 -0800 Subject: [PATCH 28/45] Test scene.oit with disc markers The specs of scene.oit draw glyph markers, because scene.markerrender defaults to glyph. Only the combined branch holds the two features, so the spec lives here. --- test/jasmine/tests/scatter3d_test.js | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/test/jasmine/tests/scatter3d_test.js b/test/jasmine/tests/scatter3d_test.js index 17dbd2da3e9..ebd53bbbbdc 100644 --- a/test/jasmine/tests/scatter3d_test.js +++ b/test/jasmine/tests/scatter3d_test.js @@ -388,7 +388,7 @@ describe('Test scatter3d interactions:', function() { describe('order independent transparency', function() { // a red marker at z=+0.5 and a blue marker at z=-0.5 on the line of sight - function plot(eyez, opacity, oit) { + function plot(eyez, opacity, oit, markerrender) { const scene = { xaxis: { range: [-1, 1], visible: false }, yaxis: { range: [-1, 1], visible: false }, @@ -402,6 +402,7 @@ describe('Test scatter3d interactions:', function() { } }; if (oit) scene.oit = oit; + if (markerrender) scene.markerrender = markerrender; return Plotly.react( gd, [ @@ -468,6 +469,22 @@ describe('Test scatter3d interactions:', function() { .then(done, done.fail); }); + it('@gl scene.oit auto orders red over blue from either side for disc markers', function(done) { + const disc = () => gd._fullLayout.scene._scene.traces[gd._fullData[0].uid].scatterPlot.discActive; + plot(2.5, 0.5, 'auto', 'disc') + .then(function() { + expect(disc()).toBe(true); + expect(status().mode).toBe('D'); + expectNear(centre(), [192, 64, 128]); + return plot(-2.5, 0.5, 'auto', 'disc'); + }) + .then(function() { + expect(disc()).toBe(true); + expectNear(centre(), [128, 64, 192]); + }) + .then(done, done.fail); + }); + it('@gl scene.oit auto gives the exact over operator at opacity 0.3 and 0.8', function(done) { plot(2.5, 0.3, 'auto') .then(function() { From df038262e48b032e934fa2dd56c0164db4a3c2d1 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 12:44:49 -0800 Subject: [PATCH 29/45] Regenerate the schema with layout.lod and scene.lod --- src/types/generated/schema.d.ts | 65 ++++++++++++++++++++++++- test/plot-schema.json | 85 ++++++++++++++++++++++++++++++++- 2 files changed, 148 insertions(+), 2 deletions(-) diff --git a/src/types/generated/schema.d.ts b/src/types/generated/schema.d.ts index d825927251b..705b04fd985 100644 --- a/src/types/generated/schema.d.ts +++ b/src/types/generated/schema.d.ts @@ -13752,8 +13752,34 @@ export interface Scene { * @default 'closest' */ hovermode?: 'closest' | false; + lod?: { + /** + * Sets the largest number of markers in a preview. The stride k is the smallest power of two, from 2 to `maxstride`, that brings the markers within this number. + * @default 2500000 + * Minimum: 1 + */ + budget?: number; + /** + * Sets the largest stride of a preview. + * @default 64 + * Minimum: 2 + */ + maxstride?: number; + /** + * Sets the number of `scatter3d` disc markers from which a camera move shows a preview. A preview draws every k-th marker of every trace and no pick pass. The scene draws every marker again `settle` milliseconds after the last camera move. 0 turns the preview off. The graph emits `plotly_lod` when the state changes. + * @default 0 + * Minimum: 0 + */ + minpoints?: number; + /** + * Sets the time in milliseconds between the last camera move and the full picture. + * @default 150 + * Minimum: 0 + */ + settle?: number; + }; /** - * Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph. *auto* is currently the same as *disc*. + * Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. *auto* draws discs where it can. It draws glyphs for other symbols, for projections on the axes, and for markers that exceed the point size limit of the GPU. * @default 'glyph' */ markerrender?: 'glyph' | 'disc' | 'auto'; @@ -16353,6 +16379,43 @@ export interface Layout { iciclecolorway?: Color[]; images?: LayoutImage[]; legend?: Legend; + lod?: { + /** + * Sets the largest number of points in a preview. The stride k is the smallest power of two, from 2 to `maxstride`, that brings the visible points within this number. + * @default 2500000 + * Minimum: 1 + */ + budget?: number; + /** + * Determines the picture during an edit of a fully drawn plot that keeps the axis ranges, the plot area and the size. *hold* keeps the previous full picture until the new full picture is ready. *preview* shows a preview first, as a pan does. Use *preview* for edits in quick succession, for example from a slider. + * @default 'hold' + */ + edits?: 'hold' | 'preview'; + /** + * Sets the largest stride of a preview. + * @default 64 + * Minimum: 2 + */ + maxstride?: number; + /** + * Sets the number of visible scattergl points from which a draw shows a preview first. A preview draws every k-th point of every trace. The full picture follows when no draw request came for `settle` milliseconds. 0 turns the preview off. Applies to a graph where the scattergl markers of one subplot are the only WebGL traces. The graph emits `plotly_lod` when the state changes. + * @default 0 + * Minimum: 0 + */ + minpoints?: number; + /** + * Sets the time in milliseconds between the last draw request and the full picture. + * @default 150 + * Minimum: 0 + */ + settle?: number; + /** + * Sets the number of points in one part of the full picture. The plot draws the next part when the GPU finished the part before. Thus a draw request between two parts does not wait for the full picture. 0 draws the full picture in one part. + * @default 5000000 + * Minimum: 0 + */ + slice?: number; + }; map?: MapLayout; margin?: { /** diff --git a/test/plot-schema.json b/test/plot-schema.json index a580b14d439..d431e39de24 100644 --- a/test/plot-schema.json +++ b/test/plot-schema.json @@ -6718,8 +6718,40 @@ false ] }, + "lod": { + "budget": { + "description": "Sets the largest number of markers in a preview. The stride k is the smallest power of two, from 2 to `maxstride`, that brings the markers within this number.", + "dflt": 2500000, + "editType": "plot", + "min": 1, + "valType": "number" + }, + "editType": "plot", + "maxstride": { + "description": "Sets the largest stride of a preview.", + "dflt": 64, + "editType": "plot", + "min": 2, + "valType": "integer" + }, + "minpoints": { + "description": "Sets the number of `scatter3d` disc markers from which a camera move shows a preview. A preview draws every k-th marker of every trace and no pick pass. The scene draws every marker again `settle` milliseconds after the last camera move. 0 turns the preview off. The graph emits `plotly_lod` when the state changes.", + "dflt": 0, + "editType": "plot", + "min": 0, + "valType": "number" + }, + "role": "object", + "settle": { + "description": "Sets the time in milliseconds between the last camera move and the full picture.", + "dflt": 150, + "editType": "plot", + "min": 0, + "valType": "number" + } + }, "markerrender": { - "description": "Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph. *auto* is currently the same as *disc*.", + "description": "Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. *auto* draws discs where it can. It draws glyphs for other symbols, for projections on the axes, and for markers that exceed the point size limit of the GPU.", "dflt": "glyph", "editType": "plot", "valType": "enumerated", @@ -64029,6 +64061,57 @@ "showLegend", "scatter-like" ], + "layoutAttributes": { + "lod": { + "budget": { + "description": "Sets the largest number of points in a preview. The stride k is the smallest power of two, from 2 to `maxstride`, that brings the visible points within this number.", + "dflt": 2500000, + "editType": "none", + "min": 1, + "valType": "number" + }, + "edits": { + "description": "Determines the picture during an edit of a fully drawn plot that keeps the axis ranges, the plot area and the size. *hold* keeps the previous full picture until the new full picture is ready. *preview* shows a preview first, as a pan does. Use *preview* for edits in quick succession, for example from a slider.", + "dflt": "hold", + "editType": "none", + "valType": "enumerated", + "values": [ + "hold", + "preview" + ] + }, + "editType": "none", + "maxstride": { + "description": "Sets the largest stride of a preview.", + "dflt": 64, + "editType": "none", + "min": 2, + "valType": "integer" + }, + "minpoints": { + "description": "Sets the number of visible scattergl points from which a draw shows a preview first. A preview draws every k-th point of every trace. The full picture follows when no draw request came for `settle` milliseconds. 0 turns the preview off. Applies to a graph where the scattergl markers of one subplot are the only WebGL traces. The graph emits `plotly_lod` when the state changes.", + "dflt": 0, + "editType": "none", + "min": 0, + "valType": "number" + }, + "role": "object", + "settle": { + "description": "Sets the time in milliseconds between the last draw request and the full picture.", + "dflt": 150, + "editType": "none", + "min": 0, + "valType": "number" + }, + "slice": { + "description": "Sets the number of points in one part of the full picture. The plot draws the next part when the GPU finished the part before. Thus a draw request between two parts does not wait for the full picture. 0 draws the full picture in one part.", + "dflt": 5000000, + "editType": "none", + "min": 0, + "valType": "number" + } + } + }, "meta": { "description": "The data visualized as scatter point or lines is set in `x` and `y` using the WebGL plotting engine. Bubble charts are achieved by setting `marker.size` and/or `marker.color` to a numerical arrays.", "hrName": "scatter_gl" From c9d1df0457aaeea743c188032520d643cbe5cdb9 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 12:48:58 -0800 Subject: [PATCH 30/45] Test scene.lod with the pick pass on demand On the combined branch a frame at rest draws no pick pass. The spec now expects none in a preview, also for a pointer query, and one for the first query after the settle. --- test/jasmine/tests/gl3d_lod_test.js | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/test/jasmine/tests/gl3d_lod_test.js b/test/jasmine/tests/gl3d_lod_test.js index f5b2d6693ce..a63e4c7df95 100644 --- a/test/jasmine/tests/gl3d_lod_test.js +++ b/test/jasmine/tests/gl3d_lod_test.js @@ -1,6 +1,7 @@ const Plotly = require('../../../lib/index'); const createGraphDiv = require('../assets/create_graph_div'); const destroyGraphDiv = require('../assets/destroy_graph_div'); +const mouseEvent = require('../assets/mouse_event'); // level of detail while the camera moves: scene.lod @@ -279,6 +280,8 @@ describe('gl3d scene.lod', () => { it('@gl thins the discs while the camera moves, with no pick pass, and draws them all at rest', (done) => { let log; + let picks; + const pickDraws = () => glplot().pickStats.draws; plot(LOD) .then(() => { return wait(800); @@ -289,6 +292,10 @@ describe('gl3d scene.lod', () => { expect(scene().getLOD().state).toBe('full'); expect(scene().getLOD().stride).toBe(8); expect(scene().getLOD().total).toBe(1501); + // The pick pass is drawn only for a pointer query. + glplot().pickIdleDelay = 0; + mouseEvent('mousemove', 200, 150); + picks = pickDraws(); events.length = 0; log = watch3d(); return moveCamera(1.7); @@ -323,8 +330,10 @@ describe('gl3d scene.lod', () => { }) .then(() => { expect(scene().getLOD().state).toBe('preview'); - // no pick pass in a preview: it would draw every disc with drawArrays + // no pick pass in a preview, also for a pointer query: it would draw every disc with drawArrays + mouseEvent('mousemove', 210, 150); expect(log.arrays.length).toBe(0); + expect(pickDraws()).toBe(picks); log.reset(); return when('full'); }) @@ -339,12 +348,12 @@ describe('gl3d scene.lod', () => { return e.state + ':' + e.reason; }) ).toEqual(['preview:camera', 'full:settle']); - // the full frame draws the pick pass too: every disc once more - expect( - log.arrays.filter((c) => { - return c === 501; - }).length - ).toBeGreaterThan(1); + // the full frame draws no pick pass, and the next pointer query draws one: every disc once more + expect(pickDraws()).toBe(picks); + const before = log.arrays.filter((c) => c === 501).length; + mouseEvent('mousemove', 220, 155); + expect(pickDraws()).toBe(picks + 1); + expect(log.arrays.filter((c) => c === 501).length).toBe(before + 1); log.restore(); }) .then(done, done.fail); From 4bd6578992fbf14e4c6a157912df359fa2d3d2c7 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 13:16:09 -0800 Subject: [PATCH 31/45] Keep the scene.markerrender description of the base branch The level of detail commit carried an older wording of the scene.markerrender description. That text belongs to the disc marker change. This commit puts the description of the base branch back, with the schema output of npm run schema. --- src/plots/gl3d/layout/layout_attributes.js | 4 ++-- src/types/generated/schema.d.ts | 2 +- test/plot-schema.json | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/plots/gl3d/layout/layout_attributes.js b/src/plots/gl3d/layout/layout_attributes.js index 87462a9e96e..872dbe1eb57 100644 --- a/src/plots/gl3d/layout/layout_attributes.js +++ b/src/plots/gl3d/layout/layout_attributes.js @@ -144,8 +144,8 @@ module.exports = { '*glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default.', '*disc* draws each marker as one round point sprite. It needs far less memory and draws faster.', 'The edge of a disc differs from the edge of a glyph by about one pixel.', - '*auto* draws discs where it can.', - 'It draws glyphs for other symbols, for projections on the axes, and for markers that exceed the point size limit of the GPU.' + 'A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph.', + '*auto* is currently the same as *disc*.' ].join(' ') }, dragmode: { diff --git a/src/types/generated/schema.d.ts b/src/types/generated/schema.d.ts index 94dcad33f5c..9f5e75b0bf1 100644 --- a/src/types/generated/schema.d.ts +++ b/src/types/generated/schema.d.ts @@ -13769,7 +13769,7 @@ export interface Scene { settle?: number; }; /** - * Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. *auto* draws discs where it can. It draws glyphs for other symbols, for projections on the axes, and for markers that exceed the point size limit of the GPU. + * Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph. *auto* is currently the same as *disc*. * @default 'glyph' */ markerrender?: 'glyph' | 'disc' | 'auto'; diff --git a/test/plot-schema.json b/test/plot-schema.json index 1e5d1d54238..f9b873d43f0 100644 --- a/test/plot-schema.json +++ b/test/plot-schema.json @@ -6741,7 +6741,7 @@ } }, "markerrender": { - "description": "Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. *auto* draws discs where it can. It draws glyphs for other symbols, for projections on the axes, and for markers that exceed the point size limit of the GPU.", + "description": "Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph. *auto* is currently the same as *disc*.", "dflt": "glyph", "editType": "plot", "valType": "enumerated", From 06c56d7dbc7d4b077b00cb6a4fa7efb31072867c Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 13:16:09 -0800 Subject: [PATCH 32/45] Remove the leading space from the level of detail draftlog The other draftlog files start with the dash. --- draftlogs/YYYY_add.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/draftlogs/YYYY_add.md b/draftlogs/YYYY_add.md index ebae61ec3b6..4d6d3908590 100644 --- a/draftlogs/YYYY_add.md +++ b/draftlogs/YYYY_add.md @@ -1 +1 @@ - - Add `layout.lod` and `layout.scene.lod` to draw a preview of every k-th point first in `scattergl` plots and while the camera moves in `scatter3d` plots of many points, with the full picture drawn when the plot is at rest, the `plotly_lod` event, and `scene.hidden` / `scene.setHidden` to hide `scattergl` traces without a recalculation [[#YYYY](https://github.com/plotly/plotly.js/pull/YYYY)] +- Add `layout.lod` and `layout.scene.lod` to draw a preview of every k-th point first in `scattergl` plots and while the camera moves in `scatter3d` plots of many points, with the full picture drawn when the plot is at rest, the `plotly_lod` event, and `scene.hidden` / `scene.setHidden` to hide `scattergl` traces without a recalculation [[#YYYY](https://github.com/plotly/plotly.js/pull/YYYY)] From 624036a439d79d3b5dd43b9aa593bba60e828f71 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 13:16:26 -0800 Subject: [PATCH 33/45] Test that a typed disc trace above the pick id range keeps no hover positions Only the combined branch drops the stored positions of such a trace, because one call decides the pick option and the kept positions. --- test/jasmine/tests/gl3d_hover_click_test.js | 32 +++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/test/jasmine/tests/gl3d_hover_click_test.js b/test/jasmine/tests/gl3d_hover_click_test.js index 5b5d41d43e1..ad146f44f9d 100644 --- a/test/jasmine/tests/gl3d_hover_click_test.js +++ b/test/jasmine/tests/gl3d_hover_click_test.js @@ -1834,6 +1834,38 @@ describe('Test gl3d pick pass:', function() { .then(done, done.fail); }); + it('@gl a disc trace of typed positions above the pick id range keeps no hover positions', function(done) { + var convert = require('../../../src/traces/scatter3d/convert'); + var max = convert.maxPickPoints; + convert.maxPickPoints = 2000; + spyOn(Lib, 'warn'); + var trail; + var fig = layout(); + fig.scene.markerrender = 'disc'; + Plotly.newPlot(gd, [cloud(3000)], fig) + .then(delay(900)) + .then(function() { + var trace = gd._fullLayout.scene._scene.traces[gd._fullData[0].uid]; + var o = trace.scatterPlot; + expect(Lib.warn).toHaveBeenCalled(); + expect(o.discActive).toBe(true); + expect(o.vertexCount).toBe(3000, 'the cloud is drawn'); + expect(o.noPick).toBe(true); + expect(trace.dataPoints.length).toBe(0); + trail = hoverTrail(); + return moves(PATH); + }) + .then(function() { + expect(trail.length).toBe(0); + expect(draws()).toBe(0); + }) + .then(function() { convert.maxPickPoints = max; }, function(e) { + convert.maxPickPoints = max; + throw e; + }) + .then(done, done.fail); + }); + it('@gl a purge with a pending idle timer does not throw', function(done) { Plotly.newPlot(gd, [cloud(3000)], layout()) .then(delay(50)) From 4a5568d990de95abc50f3094b8d9e3318883493f Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 13:36:36 -0800 Subject: [PATCH 34/45] Draw a translucent level of detail preview as dense as the full picture A preview of every k-th marker had one k-th of the cover of the full picture, so faint markers all but vanished in it. A marker of alpha a that stands for k markers now gets the alpha 1 - (1 - a)^k. This is exact where the k markers cover the same pixels, and an estimate elsewhere. A marker of alpha 1 does not change. The change is in the two packages: this commit moves the pins of regl-scatter2d and gl-scatter3d, holds the webpack output for stackgl_modules, and adds one spec for scattergl and one for scatter3d. --- package-lock.json | 6 +-- package.json | 2 +- stackgl_modules/index.js | 24 ++++++++- stackgl_modules/package-lock.json | 6 +-- stackgl_modules/package.json | 2 +- test/jasmine/tests/gl3d_lod_test.js | 68 ++++++++++++++++++++++++ test/jasmine/tests/scattergl_lod_test.js | 62 ++++++++++++++++++++- 7 files changed, 159 insertions(+), 11 deletions(-) diff --git a/package-lock.json b/package-lock.json index fff71681de6..18fbbaa75d4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,7 +44,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "github:settylab/regl-scatter2d#ad3a8b53c2a8879b34545f714d4dd0fc7dd077fc", + "regl-scatter2d": "github:settylab/regl-scatter2d#55a33abbcc0b936b9fd68b72a86b3e6abebac512", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", @@ -6231,8 +6231,8 @@ }, "node_modules/regl-scatter2d": { "version": "3.4.0", - "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#ad3a8b53c2a8879b34545f714d4dd0fc7dd077fc", - "integrity": "sha512-9wXCsMEDQvMmKeSmajd0NcQlXIB+Mlq380CzUNIoWwv9yDcvZimoZsUQadHjoPV3jtQKtovtaS0g2rAwM7LSZA==", + "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#55a33abbcc0b936b9fd68b72a86b3e6abebac512", + "integrity": "sha512-FUoOWDV5xmYe4OaEje1K6LvDJLq5ZHgwh6cUicxa84p13tDvD/IGe7lFPJtj6PEC1FnecUX2yGjY9LycD71R3A==", "license": "MIT", "dependencies": { "@plotly/point-cluster": "^3.1.9", diff --git a/package.json b/package.json index 288dfba2446..89f5140f091 100644 --- a/package.json +++ b/package.json @@ -118,7 +118,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "github:settylab/regl-scatter2d#ad3a8b53c2a8879b34545f714d4dd0fc7dd077fc", + "regl-scatter2d": "github:settylab/regl-scatter2d#55a33abbcc0b936b9fd68b72a86b3e6abebac512", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index ac9fea3e128..0cf554184aa 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -20229,6 +20229,7 @@ function discVert(outline) { 'uniform vec2 screenSize;', 'uniform vec3 clipBounds[2];', 'uniform float highlightScale, pixelRatio, unitA, unitB, lineHalf;', + 'uniform float opacity, lodK;', 'uniform vec2 unitCenter;', 'uniform vec4 highlightId;', 'varying vec4 interpColor;', @@ -20236,11 +20237,22 @@ function discVert(outline) { 'varying float vA;', 'varying float vB;', 'varying float vHalf;', + 'varying vec2 vDense;', + // A preview draws every lodK-th disc. A translucent disc then stands for lodK discs: its alpha a becomes + // 1 - (1 - a)^lodK, the cover of lodK discs on one pixel. The factor is 1 for a disc of alpha 1 and for a full draw. + 'float lodDense(float alpha) {', + ' float a = alpha * opacity;', + ' if (lodK > 1.0 && a > 0.0 && a < 1.0) {', + ' return (1.0 - pow(1.0 - a, lodK)) / a;', + ' }', + ' return 1.0;', + '}', 'void main() {', ' if (outOfRange(clipBounds[0], clipBounds[1], position)) {', ' gl_Position = vec4(0, 0, 0, 0);', ' gl_PointSize = 1.0;', ' vA = -1.0; vB = 0.0; vHalf = 1.0;', + ' vDense = vec2(1.0);', ' } else {', ' float scale = pixelRatio;', ' if (distance(highlightId.bgr, id.bgr) < 0.001) {', @@ -20254,9 +20266,13 @@ function discVert(outline) { ' vHalf = vB + lineHalf + 1.0;', ' gl_PointSize = 2.0 * vHalf;', ' interpColor = color;', + ' vDense = vec2(lodDense(color.a), 1.0);', + ' interpColor.a *= vDense.x;', ' pickId = id;', '#ifdef OUTLINE', ' interpLine = lineColor;', + ' vDense.y = lodDense(lineColor.a);', + ' interpLine.a *= vDense.y;', '#endif', ' }', '}' @@ -20272,6 +20288,7 @@ function discFrag(outline) { 'varying float vA;', 'varying float vB;', 'varying float vHalf;', + 'varying vec2 vDense;', '#ifdef OUTLINE', 'varying vec4 interpLine;', '#endif', @@ -20280,11 +20297,12 @@ function discFrag(outline) { ' float cf = hardEdge > 0.5 ? step(d, vB) * step(vA, d)', ' : clamp(vB - d + 0.5, 0.0, 1.0) * clamp(d - vA + 0.5, 0.0, 1.0);', ' if (interpColor.a * opacity == 0.) cf = 0.;', - ' vec4 c = interpColor * (opacity * cf);', + // (the vertex shader made the alpha of a thinned translucent disc denser; the color takes the same factor) + ' vec4 c = vec4(interpColor.rgb * vDense.x, interpColor.a) * (opacity * cf);', '#ifdef OUTLINE', ' float e = min(abs(d - vB), vA < 0.0 ? 1e6 : abs(d - vA));', // outer edge, plus the inner edge of a ring ' float cl = hardEdge > 0.5 ? step(e, lineHalf) : clamp(lineHalf - e + 0.5, 0.0, 1.0);', - ' c = c * (1.0 - cl) + interpLine * (opacity * cl);', + ' c = c * (1.0 - cl) + vec4(interpLine.rgb * vDense.y, interpLine.a) * (opacity * cl);', ' if (cf + cl <= 0.0) discard;', '#else', ' if (cf <= 0.0) discard;', @@ -20629,6 +20647,8 @@ function drawDisc(points, camera, pixelRatio, pick, hard) { vao = lod.vao count = lod.count } + // the thinned discs are drawn denser, see lodDense in the vertex shader + uniforms.lodK = lod ? points.lodStride : 1 vao.bind() vao.draw(gl.POINTS, count) if(rimPass) { diff --git a/stackgl_modules/package-lock.json b/stackgl_modules/package-lock.json index 9b3c7722b46..de2bd48a467 100644 --- a/stackgl_modules/package-lock.json +++ b/stackgl_modules/package-lock.json @@ -17,7 +17,7 @@ "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", "gl-plot3d": "github:settylab/gl-plot3d#72fbc2ea6c558e7f4d6f71a347bb42ace5521dae", - "gl-scatter3d": "github:settylab/gl-scatter3d#d887305148a560f05fd5857ef18b06215e84f632", + "gl-scatter3d": "github:settylab/gl-scatter3d#f856212e37a9562dc66d727f363d5850e96e9949", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", "gl-streamtube3d": "^1.4.2", @@ -1347,8 +1347,8 @@ }, "node_modules/gl-scatter3d": { "version": "1.4.1", - "resolved": "git+ssh://git@github.com/settylab/gl-scatter3d.git#d887305148a560f05fd5857ef18b06215e84f632", - "integrity": "sha512-DC5oC6IsBstjO7E0s6G8hUnSBd0pGEyu4iBXNmB1c6LWCZCpV6DfHmNltkI/bbcdZ6aDi28LBILFCuAtaxIXUw==", + "resolved": "git+ssh://git@github.com/settylab/gl-scatter3d.git#f856212e37a9562dc66d727f363d5850e96e9949", + "integrity": "sha512-E5+AnlsvwXoBH850yUdBlOf8vwsC4kvm2newMxP6taGXgparj2CrylZepq4+iDBcTpk6uX/e1ZMU2RwOr4tShg==", "license": "MIT", "dependencies": { "gl-buffer": "^2.1.2", diff --git a/stackgl_modules/package.json b/stackgl_modules/package.json index 8e36f79398f..a8f7dd11fe9 100644 --- a/stackgl_modules/package.json +++ b/stackgl_modules/package.json @@ -20,7 +20,7 @@ "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", "gl-plot3d": "github:settylab/gl-plot3d#72fbc2ea6c558e7f4d6f71a347bb42ace5521dae", - "gl-scatter3d": "github:settylab/gl-scatter3d#d887305148a560f05fd5857ef18b06215e84f632", + "gl-scatter3d": "github:settylab/gl-scatter3d#f856212e37a9562dc66d727f363d5850e96e9949", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", "gl-streamtube3d": "^1.4.2", diff --git a/test/jasmine/tests/gl3d_lod_test.js b/test/jasmine/tests/gl3d_lod_test.js index f5b2d6693ce..64518a123e0 100644 --- a/test/jasmine/tests/gl3d_lod_test.js +++ b/test/jasmine/tests/gl3d_lod_test.js @@ -153,6 +153,74 @@ describe('gl-scatter3d strided discs', () => { .then(done, done.fail); }); + it('@gl draws thinned translucent discs as dense as all of them, and thinned opaque discs as before', (done) => { + // no axes: only the discs are compared + const axis = { range: [0, 1], autorange: false, visible: false }; + const layout = { + width: 400, + height: 300, + scene: { bgcolor: '#ffffff', markerrender: 'auto', xaxis: axis, yaxis: axis, zaxis: axis } + }; + // 64 discs of opacity 0.1 on one place: 8 of them with the opacity of 8 discs each cover the same + const pile = { + type: 'scatter3d', + mode: 'markers', + x: new Float32Array(64).fill(0.5), + y: new Float32Array(64).fill(0.5), + z: new Float32Array(64).fill(0.5), + marker: { size: 30, color: 'red', opacity: 0.1, line: { width: 0 } } + }; + const opaque = trace3d(1000, 1); + let at, full, thin; + // the camera glides to its place after a plot: wait until it rests + const rest = () => new Promise((r) => setTimeout(r, 700)); + Plotly.newPlot(gd, [pile], layout) + .then(rest) + .then(() => { + expect(glplot().objects[0].lodPoints()).toBe(64); + frame(); + full = pixels(); + // the pixel with the most red over the white ground: the lowest green + at = 1; + for (let i = 1; i < full.length; i += 4) if (full[i] < full[at]) at = i; + expect(full[at]).toBeLessThan(40); + + glplot().objects[0].lodStride = 8; + frame(); + thin = pixels(); + expect(Math.abs(thin[at] - full[at])).toBeLessThan(17); + // (without the denser alpha, 8 discs of opacity 0.1 leave the green at about 110) + + return Plotly.react(gd, [opaque], layout); + }) + .then(rest) + .then(() => { + const gl = glplot().gl; + glplot().objects.forEach((o) => { + o.discA2C = false; + o.lodStride = 16; + }); + frame(); + thin = pixels(); + // the same thinned draw with the stride of the shader set to 1, which turns the denser alpha off: + // opaque discs have the same pixels + const u1f = gl.uniform1f; + let replaced = 0; + gl.uniform1f = function (loc, v) { + if (v === 16) { + replaced++; + v = 1; + } + return u1f.call(gl, loc, v); + }; + frame(); + gl.uniform1f = u1f; + expect(replaced).toBeGreaterThan(0); + expect(differ3(pixels(), thin)).toBe(0); + }) + .then(done, done.fail); + }); + it('@gl never thins the pick pass, and has no discs to thin for glyph markers', (done) => { let log; Plotly.newPlot(gd, [trace3d(1000, 1), trace3d(300, 4, { marker: { size: 4, symbol: 'square' } })], { diff --git a/test/jasmine/tests/scattergl_lod_test.js b/test/jasmine/tests/scattergl_lod_test.js index 5aa545db364..0aacafc835f 100644 --- a/test/jasmine/tests/scattergl_lod_test.js +++ b/test/jasmine/tests/scattergl_lod_test.js @@ -217,7 +217,8 @@ describe('regl-scatter2d level of detail draws', () => { strided = read(); clear(); log = watch(gd); - sc.drawStride(5); + // (plain: the opacity of the every 5th point as it is, to compare with the plain draw) + sc.drawStride(5, null, true); // pieces of 1024, 1024, 952 and 1024, 476 points; the second starts at its point 1 (1025 in the group) expect( log.elements.map((e) => { @@ -240,6 +241,65 @@ describe('regl-scatter2d level of detail draws', () => { .then(done, done.fail); }); + it('@gl draws a thinned translucent group as dense as the full one, and a thinned opaque group as it is', (done) => { + let gl, sc; + function read() { + let px = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, px); + return px; + } + function clear() { + gd._fullLayout._glcanvas.each((d) => { + if (d.regl) d.regl.clear({ color: true, depth: true }); + }); + } + function every(n, k) { + const out = []; + for (let i = 0; i < n; i += k) out.push(i); + return out; + } + const layout = { width: 400, height: 300, xaxis: { range: [0, 1] }, yaxis: { range: [0, 1] } }; + // 16 markers of opacity 0.05 on one place: 4 of them with the opacity of 4 markers each cover the same + const pile = { + type: 'scattergl', + mode: 'markers', + x: new Float32Array(16).fill(0.5), + y: new Float32Array(16).fill(0.5), + marker: { size: 40, color: 'red', opacity: 0.05 } + }; + Plotly.newPlot(gd, [pile], layout) + .then(() => { + sc = scatter(); + gl = gd._fullLayout._glcanvas.data()[0].regl._gl; + const full = read(); + // the pixel with the most cover + let at = 3; + for (let i = 3; i < full.length; i += 4) if (full[i] > full[at]) at = i; + expect(full[at]).toBeGreaterThan(100); + + clear(); + sc.drawStride(4); + const dense = read()[at]; + expect(Math.abs(dense - full[at])).toBeLessThan(9); + + clear(); + sc.drawStride(4, null, true); + expect(read()[at]).toBeLessThan(full[at] / 2); + + return Plotly.react(gd, [trace(1000, 1, { marker: { size: 9, color: 'blue' } })], layout); + }) + .then(() => { + sc = scatter(); + clear(); + sc.draw(every(1000, 4)); + const plain = read(); + clear(); + sc.drawStride(4); + expect(read()).toEqual(plain); + }) + .then(done, done.fail); + }); + it('@gl draws the same pixels in parts as the plain draw does', (done) => { let gl, full, parts; function read() { From ac1c172b143dcff036db2ad5b2cb493ec43eede2 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 13:42:57 -0800 Subject: [PATCH 35/45] Pin the combined package branches with the denser thinned draws gl-scatter3d and regl-scatter2d gained the opacity compensation of a level of detail preview. The stackgl bundle is rebuilt from the new pin. --- package-lock.json | 6 +++--- package.json | 2 +- stackgl_modules/index.js | 24 ++++++++++++++++++++++-- stackgl_modules/package-lock.json | 6 +++--- stackgl_modules/package.json | 2 +- 5 files changed, 30 insertions(+), 10 deletions(-) diff --git a/package-lock.json b/package-lock.json index 15c4626356f..86fb3986b5e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,7 +44,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "github:settylab/regl-scatter2d#e56fbc64db4f0c5e69d984a16a83ecb7a24602f1", + "regl-scatter2d": "github:settylab/regl-scatter2d#37e65835d22ff96b1b4e759cf857549143f18ad8", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", @@ -6231,8 +6231,8 @@ }, "node_modules/regl-scatter2d": { "version": "3.4.0", - "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#e56fbc64db4f0c5e69d984a16a83ecb7a24602f1", - "integrity": "sha512-9wXCsMEDQvMmKeSmajd0NcQlXIB+Mlq380CzUNIoWwv9yDcvZimoZsUQadHjoPV3jtQKtovtaS0g2rAwM7LSZA==", + "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#37e65835d22ff96b1b4e759cf857549143f18ad8", + "integrity": "sha512-FUoOWDV5xmYe4OaEje1K6LvDJLq5ZHgwh6cUicxa84p13tDvD/IGe7lFPJtj6PEC1FnecUX2yGjY9LycD71R3A==", "license": "MIT", "dependencies": { "@plotly/point-cluster": "^3.1.9", diff --git a/package.json b/package.json index e18ff1dd09e..cd1a33344e1 100644 --- a/package.json +++ b/package.json @@ -118,7 +118,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "github:settylab/regl-scatter2d#e56fbc64db4f0c5e69d984a16a83ecb7a24602f1", + "regl-scatter2d": "github:settylab/regl-scatter2d#37e65835d22ff96b1b4e759cf857549143f18ad8", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index b9840c3e632..1a3eb2787ed 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -21324,6 +21324,7 @@ function discVert(outline) { 'uniform vec2 screenSize;', 'uniform vec3 clipBounds[2];', 'uniform float highlightScale, pixelRatio, unitA, unitB, lineHalf;', + 'uniform float opacity, lodK;', 'uniform vec2 unitCenter;', 'uniform vec4 highlightId;', 'varying vec4 interpColor;', @@ -21331,11 +21332,22 @@ function discVert(outline) { 'varying float vA;', 'varying float vB;', 'varying float vHalf;', + 'varying vec2 vDense;', + // A preview draws every lodK-th disc. A translucent disc then stands for lodK discs: its alpha a becomes + // 1 - (1 - a)^lodK, the cover of lodK discs on one pixel. The factor is 1 for a disc of alpha 1 and for a full draw. + 'float lodDense(float alpha) {', + ' float a = alpha * opacity;', + ' if (lodK > 1.0 && a > 0.0 && a < 1.0) {', + ' return (1.0 - pow(1.0 - a, lodK)) / a;', + ' }', + ' return 1.0;', + '}', 'void main() {', ' if (outOfRange(clipBounds[0], clipBounds[1], position)) {', ' gl_Position = vec4(0, 0, 0, 0);', ' gl_PointSize = 1.0;', ' vA = -1.0; vB = 0.0; vHalf = 1.0;', + ' vDense = vec2(1.0);', ' } else {', ' float scale = pixelRatio;', ' if (distance(highlightId.bgr, id.bgr) < 0.001) {', @@ -21349,9 +21361,13 @@ function discVert(outline) { ' vHalf = vB + lineHalf + 1.0;', ' gl_PointSize = 2.0 * vHalf;', ' interpColor = color;', + ' vDense = vec2(lodDense(color.a), 1.0);', + ' interpColor.a *= vDense.x;', ' pickId = id;', '#ifdef OUTLINE', ' interpLine = lineColor;', + ' vDense.y = lodDense(lineColor.a);', + ' interpLine.a *= vDense.y;', '#endif', ' }', '}' @@ -21367,6 +21383,7 @@ function discFrag(outline) { 'varying float vA;', 'varying float vB;', 'varying float vHalf;', + 'varying vec2 vDense;', '#ifdef OUTLINE', 'varying vec4 interpLine;', '#endif', @@ -21375,11 +21392,12 @@ function discFrag(outline) { ' float cf = hardEdge > 0.5 ? step(d, vB) * step(vA, d)', ' : clamp(vB - d + 0.5, 0.0, 1.0) * clamp(d - vA + 0.5, 0.0, 1.0);', ' if (interpColor.a * opacity == 0.) cf = 0.;', - ' vec4 c = interpColor * (opacity * cf);', + // (the vertex shader made the alpha of a thinned translucent disc denser; the color takes the same factor) + ' vec4 c = vec4(interpColor.rgb * vDense.x, interpColor.a) * (opacity * cf);', '#ifdef OUTLINE', ' float e = min(abs(d - vB), vA < 0.0 ? 1e6 : abs(d - vA));', // outer edge, plus the inner edge of a ring ' float cl = hardEdge > 0.5 ? step(e, lineHalf) : clamp(lineHalf - e + 0.5, 0.0, 1.0);', - ' c = c * (1.0 - cl) + interpLine * (opacity * cl);', + ' c = c * (1.0 - cl) + vec4(interpLine.rgb * vDense.y, interpLine.a) * (opacity * cl);', ' if (cf + cl <= 0.0) discard;', '#else', ' if (cf <= 0.0) discard;', @@ -21883,6 +21901,8 @@ function drawDisc(points, camera, pixelRatio, pick, hard, oitShader, oit) { vao = lod.vao count = lod.count } + // the thinned discs are drawn denser, see lodDense in the vertex shader + uniforms.lodK = lod ? points.lodStride : 1 vao.bind() points._discConstAttrs(gl) vao.draw(gl.POINTS, count) diff --git a/stackgl_modules/package-lock.json b/stackgl_modules/package-lock.json index b47286849ad..b0cf7824597 100644 --- a/stackgl_modules/package-lock.json +++ b/stackgl_modules/package-lock.json @@ -17,7 +17,7 @@ "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", "gl-plot3d": "github:settylab/gl-plot3d#147b9928ba1863b4fdfe561bd295c1560c5b9fc0", - "gl-scatter3d": "github:settylab/gl-scatter3d#f27d7687ffcc347ae33a16342a8fb0a4d9ad767e", + "gl-scatter3d": "github:settylab/gl-scatter3d#213d696815416d3dc22acc35d0e7712ca737d6e3", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", "gl-streamtube3d": "^1.4.2", @@ -1347,8 +1347,8 @@ }, "node_modules/gl-scatter3d": { "version": "1.4.1", - "resolved": "git+ssh://git@github.com/settylab/gl-scatter3d.git#f27d7687ffcc347ae33a16342a8fb0a4d9ad767e", - "integrity": "sha512-1CsC+Z5WqDj59/lz1x2kq/UQkQL7PR0Whk61r/D6CjP/D0YfYoQbY2B3b7MX+4sEb7vRTgFt77ihzdftGwe6EQ==", + "resolved": "git+ssh://git@github.com/settylab/gl-scatter3d.git#213d696815416d3dc22acc35d0e7712ca737d6e3", + "integrity": "sha512-tCAynQDsbYBE1CGWMZpFniTjD4vgR/aJPogocfjYV/etAvraNelGDXkGWr9/KWIqMpow/OwDy0DTCbLNJrUHHg==", "license": "MIT", "dependencies": { "gl-buffer": "^2.1.2", diff --git a/stackgl_modules/package.json b/stackgl_modules/package.json index d6d4037f877..1f26f0a0506 100644 --- a/stackgl_modules/package.json +++ b/stackgl_modules/package.json @@ -20,7 +20,7 @@ "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", "gl-plot3d": "github:settylab/gl-plot3d#147b9928ba1863b4fdfe561bd295c1560c5b9fc0", - "gl-scatter3d": "github:settylab/gl-scatter3d#f27d7687ffcc347ae33a16342a8fb0a4d9ad767e", + "gl-scatter3d": "github:settylab/gl-scatter3d#213d696815416d3dc22acc35d0e7712ca737d6e3", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", "gl-streamtube3d": "^1.4.2", From fd8cfbb564f42e4ad348d08e06dac3ab5bcbe25e Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 13:43:30 -0800 Subject: [PATCH 36/45] Test a thinned translucent disc cloud with scene.oit auto The order independent passes use their own disc fragment shader. The spec shows that it links with the denser thinned draw and gives about the density of the full picture. --- test/jasmine/tests/gl3d_lod_test.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/test/jasmine/tests/gl3d_lod_test.js b/test/jasmine/tests/gl3d_lod_test.js index 505073ed4a9..912bdfff141 100644 --- a/test/jasmine/tests/gl3d_lod_test.js +++ b/test/jasmine/tests/gl3d_lod_test.js @@ -222,6 +222,34 @@ describe('gl-scatter3d strided discs', () => { .then(done, done.fail); }); + it('@gl draws a thinned translucent cloud about as dense as the full one with scene.oit auto', (done) => { + const mean = (px) => { + let sum = 0; + for (let i = 0; i < px.length; i += 4) sum += px[i + 1]; + return sum / (px.length / 4); + }; + Plotly.newPlot( + gd, + [trace3d(40000, 1, { marker: { size: 6, color: 'red', opacity: 0.2, line: { width: 0 } } })], + { width: 400, height: 300, scene: { bgcolor: '#ffffff', markerrender: 'disc', oit: 'auto' } } + ) + .then(() => { + const objs = glplot().objects; + expect(gd._fullLayout.scene._scene.getOITStatus().mode).toBe('D'); + expect(objs[0].lodPoints()).toBe(40000); + frame(); + // green is 255 on the background and 0 under an opaque red cover + const full = mean(pixels()); + objs[0].lodStride = 8; + frame(); + const thin = mean(pixels()); + // an eighth of the discs at the same alpha would leave most of the cover out + expect(full).toBeLessThan(235); + expect(Math.abs(thin - full)).toBeLessThan(6); + }) + .then(done, done.fail); + }); + it('@gl never thins the pick pass, and has no discs to thin for glyph markers', (done) => { let log; Plotly.newPlot(gd, [trace3d(1000, 1), trace3d(300, 4, { marker: { size: 4, symbol: 'square' } })], { From dae4331851fb444920ba41c00057a1531b5982e1 Mon Sep 17 00:00:00 2001 From: Dominik Date: Sat, 5 Dec 2026 01:03:19 -0800 Subject: [PATCH 37/45] Count the uploads on the context that regl uses With virtual-webgl, regl gets a virtual context. That context calls functions that virtual-webgl copied from WebGLRenderingContext.prototype at load, so a later spy on that prototype records nothing, and four upload specs failed in the virtual-webgl job. The specs now spy on the prototype of the context itself. Without virtual-webgl, that prototype is WebGLRenderingContext.prototype as before. --- test/jasmine/tests/scattergl_test.js | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/test/jasmine/tests/scattergl_test.js b/test/jasmine/tests/scattergl_test.js index d10a94c22bf..d1e1b415610 100644 --- a/test/jasmine/tests/scattergl_test.js +++ b/test/jasmine/tests/scattergl_test.js @@ -1005,12 +1005,19 @@ describe('scattergl Float32Array positions', () => { function groups() { return gd._fullLayout._plots.xy._scene.scatter2d.groups; } function options(i) { return gd._fullLayout._plots.xy._scene.markerOptions[i]; } + // The prototype of the contexts that regl gets. With virtual-webgl, it is not WebGLRenderingContext.prototype. + let glProto; + function contextPrototype() { + if (!glProto) glProto = Object.getPrototypeOf(document.createElement('canvas').getContext('webgl')); + return glProto; + } // Record the byte length of each Float32Array that goes to the GPU function countUploads() { let uploads = []; + let proto = contextPrototype(); ['bufferData', 'bufferSubData'].forEach((name) => { - let orig = WebGLRenderingContext.prototype[name]; - spyOn(WebGLRenderingContext.prototype, name).and.callFake(function () { + let orig = proto[name]; + spyOn(proto, name).and.callFake(function () { let d = arguments[name === 'bufferData' ? 1 : 2]; if (d instanceof Float32Array && d.byteLength) uploads.push(d.byteLength); return orig.apply(this, arguments); @@ -1277,9 +1284,11 @@ describe('regl-scatter2d {x, y} positions', () => { Plotly.newPlot(gd, [{type: 'scattergl', mode: 'markers', x: [0, 1], y: [0, 1]}]).then(() => { regl = gd._fullLayout._glcanvas.data()[0].regl; sc = createScatter(regl); + // With virtual-webgl, the context of regl does not use WebGLRenderingContext.prototype + let proto = Object.getPrototypeOf(regl._gl); ['bufferData', 'bufferSubData'].forEach((name) => { - let orig = WebGLRenderingContext.prototype[name]; - spyOn(WebGLRenderingContext.prototype, name).and.callFake(function () { + let orig = proto[name]; + spyOn(proto, name).and.callFake(function () { let d = arguments[name === 'bufferData' ? 1 : 2]; if (d instanceof Float32Array && d.byteLength) uploads.push(d.byteLength); return orig.apply(this, arguments); From 6d0689fec7b604f6cfc5bd19680a72b720464eb2 Mon Sep 17 00:00:00 2001 From: Dominik Date: Sat, 5 Dec 2026 01:04:26 -0800 Subject: [PATCH 38/45] Wait with readPixels when the timer query extension has no functions virtual-webgl returns an object with constants and no functions for an extension that it does not wrap, also when the context has no such extension. The level of detail tested only that the object exists, and then threw in the timer that draws the full picture in parts. The full picture never came. The extension now counts as missing unless createQueryEXT and getQueryObjectEXT are functions, and the plot waits with readPixels after each part. One spec passes such an object to the scene. The spec was not run on this machine before the commit. --- src/traces/scattergl/lod.ts | 6 +++++- test/jasmine/tests/scattergl_lod_test.js | 27 +++++++++++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/traces/scattergl/lod.ts b/src/traces/scattergl/lod.ts index ba2339b0d35..fd3d2470562 100644 --- a/src/traces/scattergl/lod.ts +++ b/src/traces/scattergl/lod.ts @@ -206,7 +206,11 @@ export function attachLod(gd: any, subplot: any, scene: any) { const newRun = (slice: number): LodRun => { const gl = scene.scatter2d.gl; - return { g: 0, off: 0, slice, gl, ext: gl.getExtension(TIMER_QUERY), query: null, asked: 0 }; + // A context wrapper can return an object without functions for an extension that the wrapper does not + // know, as virtual-webgl does. Such an extension counts as missing. + let ext = gl.getExtension(TIMER_QUERY); + if (!ext || typeof ext.createQueryEXT !== 'function' || typeof ext.getQueryObjectEXT !== 'function') ext = null; + return { g: 0, off: 0, slice, gl, ext, query: null, asked: 0 }; }; /** Draw one part of the full picture. Draw the next part when the GPU finished this part. */ diff --git a/test/jasmine/tests/scattergl_lod_test.js b/test/jasmine/tests/scattergl_lod_test.js index 0aacafc835f..92fcc7525e3 100644 --- a/test/jasmine/tests/scattergl_lod_test.js +++ b/test/jasmine/tests/scattergl_lod_test.js @@ -764,8 +764,11 @@ describe('scattergl layout.lod', () => { return f.available; } }; + // 'hollow': an object with the constants and no functions, as virtual-webgl gives for this extension + const hollow = { QUERY_RESULT_AVAILABLE_EXT: 1, TIME_ELAPSED_EXT: 2, createQueryEXT: undefined }; gl.getExtension = (name) => { - return name === 'EXT_disjoint_timer_query' ? (missing ? null : f) : orig.call(gl, name); + if (name !== 'EXT_disjoint_timer_query') return orig.call(gl, name); + return missing === 'hollow' ? hollow : missing ? null : f; }; f.restore = () => { gl.getExtension = orig; @@ -847,6 +850,28 @@ describe('scattergl layout.lod', () => { .then(done, done.fail); }); + it('@gl waits with readPixels when the timer query extension has no functions', (done) => { + let gl, rp; + let reads = 0; + plot(data(), layout(PARTS)) + .then(() => { + fakeTimer('hollow'); + gl = glOf(); + rp = gl.readPixels; + gl.readPixels = function (x, y, w, h) { + if (w === 1 && h === 1) reads++; + return rp.apply(gl, arguments); + }; + return when('full'); + }) + .then(() => { + expect(reads).toBe(4); + expect(canvas().style.visibility).toBe(''); + gl.readPixels = rp; + }) + .then(done, done.fail); + }); + it('@gl drops the parts that are left when a draw is asked for, and previews again', (done) => { let log, timer; plot(data(), layout(PARTS)) From 85178c4d7fde3f27ab7b86d0e382898a8a78628e Mon Sep 17 00:00:00 2001 From: Dominik Date: Sat, 5 Dec 2026 01:08:42 -0800 Subject: [PATCH 39/45] Wait for the scene frame in the pick specs, and test a pointer event before the first frame of a trace Two specs compare a run whose hover events come from the frame with a run whose events come from the pointer handler. They waited 60 ms after each pointer event, and on a slow runner the frame came later, so the frame run lost its last events. They now wait for the frame. The new spec sends a pointer event in the task in which newPlot resolves. It needs the gl-plot3d commit that draws no pick pass on demand before the frame that draws a change. The pin of that commit follows. --- test/jasmine/tests/gl3d_hover_click_test.js | 40 ++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/test/jasmine/tests/gl3d_hover_click_test.js b/test/jasmine/tests/gl3d_hover_click_test.js index 5b5d41d43e1..7311610305c 100644 --- a/test/jasmine/tests/gl3d_hover_click_test.js +++ b/test/jasmine/tests/gl3d_hover_click_test.js @@ -1548,10 +1548,21 @@ describe('Test gl3d pick pass:', function() { }); return out; } + // Wait for the frame of the scene that follows a pointer event. With the pick pass in each frame, or with + // the axis spikes on, the hover events come from that frame, and a frame can take longer than a fixed delay. + const frame = () => + new Promise((resolve) => { + requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(resolve, 0))); + }); function moves(list) { var p = Promise.resolve(); list.forEach(function(xy) { - p = p.then(function() { mouseEvent('mousemove', xy[0], xy[1]); }).then(delay(60)); + p = p + .then(() => { + mouseEvent('mousemove', xy[0], xy[1]); + }) + .then(delay(60)) + .then(frame); }); return p; } @@ -1741,6 +1752,31 @@ describe('Test gl3d pick pass:', function() { .then(done, done.fail); }); + it('@gl gives no hover for a trace before the frame that draws it', function(done) { + // A pointer that rests on a scene sends an event when the canvas appears, before the first frame with the trace. + // The pick pass on demand must find nothing then, as the pick pass in the frame did. + const labels = () => document.querySelectorAll('g.hovertext').length; + Plotly.newPlot(gd, Lib.extendDeep({}, mesh3dcoloringMock)) + .then(() => { + mouseEvent('mousemove', 600, 200); + }) + .then(frame) + .then(() => { + expect(labels()).toBe(0, 'no label for a mesh that no frame drew'); + }) + .then(delay(300)) + .then(() => { + expect(labels()).toBe(0, 'and none later without a pointer event'); + mouseEvent('mousemove', 601, 201); + }) + .then(delay(20)) + .then(frame) + .then(() => { + expect(labels()).toBe(1, 'the mesh is under that pointer: a move at rest finds it'); + }) + .then(done, done.fail); + }); + it('@gl a hover move draws no frame when the axis spikes are off, and gives the same events', function(done) { function run(spikes) { var L = layout(); @@ -1763,8 +1799,10 @@ describe('Test gl3d pick pass:', function() { }) .then(function() { mouseEvent('mousedown', 305, 230, {buttons: 1}); }) .then(delay(60)) + .then(frame) .then(function() { mouseEvent('mouseup', 305, 230); }) .then(delay(60)) + .then(frame) .then(function() { return moves([[5, 5]]); }) .then(function() { expect(document.querySelectorAll('g.hovertext').length).toBe(0); From 4bd6f7d013ce81394790e613084287b090417a3f Mon Sep 17 00:00:00 2001 From: Dominik Date: Sat, 5 Dec 2026 01:48:44 -0800 Subject: [PATCH 40/45] Pin gl-plot3d to the pick pass that waits for the frame of a change The pinned commit draws no pick pass on demand while a change waits for its frame, and queries no pick buffer before a pass has drawn it. Without it, a pointer event between scene.add and the next frame gave a hover label for a trace that no frame had drawn. The stackgl bundle is the webpack output for the pin. --- stackgl_modules/index.js | 13 ++++++++++--- stackgl_modules/package-lock.json | 5 ++--- stackgl_modules/package.json | 2 +- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index 45cc7a132f3..62c04a24940 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -18990,6 +18990,7 @@ function createScene(options) { } //Create new pick buffer var nbuffer = createSelect(gl, viewShape) + pickDrawn = false pickBufferIds[i] = numPick pickBuffers.push(nbuffer) pickBufferCount.push(pickCount) @@ -19118,7 +19119,7 @@ function createScene(options) { ensurePick() } - for(var i=0; i selection.distance) { @@ -19200,6 +19201,9 @@ function createScene(options) { var pickTimer = null var pickFrameSeen = false var pickEmpty = false + // False until a pick pass has drawn every pick buffer. A new buffer holds memory from the pool, not a picture, + // so no query reads the buffers before that. + var pickDrawn = false // True if some object that is drawn into a pick buffer can be picked function anyPickable() { @@ -19211,13 +19215,15 @@ function createScene(options) { return false } - // Draw the pick buffers and read them back now, if they are out of date + // Draw the pick buffers and read them back now, if they are out of date. + // Not while a change waits for its frame (an object added, removed or updated, a new size): a pass on demand + // shows what the last frame drew, as the pass in the frame did. That frame starts the idle timer again. function ensurePick() { if(pickTimer) { clearTimeout(pickTimer) pickTimer = null } - if(!pickDirty || !pickFrameSeen || scene._stopped || scene.contextLost) { + if(!pickDirty || !pickFrameSeen || dirty || scene._stopped || scene.contextLost) { return } pickDirty = false @@ -19293,6 +19299,7 @@ function createScene(options) { } buf.end() } + pickDrawn = true } var nBounds = [ diff --git a/stackgl_modules/package-lock.json b/stackgl_modules/package-lock.json index e250c874603..33eeb460df9 100644 --- a/stackgl_modules/package-lock.json +++ b/stackgl_modules/package-lock.json @@ -16,7 +16,7 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "github:settylab/gl-plot3d#af538fec50f8e212bde2cdfbfcf733bad5d7c771", + "gl-plot3d": "github:settylab/gl-plot3d#d054d4cfc56c35df9fd603344b48d5a5e0877422", "gl-scatter3d": "github:settylab/gl-scatter3d#370d619a7ec1351f87989c9963a37cd4ccb06e5b", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", @@ -1312,8 +1312,7 @@ }, "node_modules/gl-plot3d": { "version": "2.4.7", - "resolved": "git+ssh://git@github.com/settylab/gl-plot3d.git#af538fec50f8e212bde2cdfbfcf733bad5d7c771", - "integrity": "sha512-ilgUga590Ge94vR4MMFtq/NWjoTB99XrXnuyNCXFLPcLixAM3gHNMlN2ktcF19dlYKXtQNMA19xCLpkB/BSJXA==", + "resolved": "git+ssh://git@github.com/settylab/gl-plot3d.git#d054d4cfc56c35df9fd603344b48d5a5e0877422", "license": "MIT", "dependencies": { "3d-view": "^2.0.0", diff --git a/stackgl_modules/package.json b/stackgl_modules/package.json index 0acffbece66..848bfcfcf30 100644 --- a/stackgl_modules/package.json +++ b/stackgl_modules/package.json @@ -19,7 +19,7 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "github:settylab/gl-plot3d#af538fec50f8e212bde2cdfbfcf733bad5d7c771", + "gl-plot3d": "github:settylab/gl-plot3d#d054d4cfc56c35df9fd603344b48d5a5e0877422", "gl-scatter3d": "github:settylab/gl-scatter3d#370d619a7ec1351f87989c9963a37cd4ccb06e5b", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", From 5e45f30bd23a37c908042c34220cb7d3b3692081 Mon Sep 17 00:00:00 2001 From: Dominik Date: Sat, 5 Dec 2026 01:49:48 -0800 Subject: [PATCH 41/45] Pin gl-plot3d to the combined branch with the pick pass that waits for the frame of a change The pick pass on demand no longer runs before the frame that draws a change, and no query reads a pick buffer before a pass has drawn it. The stackgl bundle is rebuilt from the new pin. --- stackgl_modules/index.js | 13 ++++++++++--- stackgl_modules/package-lock.json | 6 +++--- stackgl_modules/package.json | 2 +- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index 1a3eb2787ed..fbaa9fcfb26 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -19484,6 +19484,7 @@ function createScene(options) { } //Create new pick buffer var nbuffer = createSelect(gl, viewShape) + pickDrawn = false pickBufferIds[i] = numPick pickBuffers.push(nbuffer) pickBufferCount.push(pickCount) @@ -19615,7 +19616,7 @@ function createScene(options) { ensurePick() } - for(var i=0; i selection.distance) { @@ -19697,6 +19698,9 @@ function createScene(options) { var pickTimer = null var pickFrameSeen = false var pickEmpty = false + // False until a pick pass has drawn every pick buffer. A new buffer holds memory from the pool, not a picture, + // so no query reads the buffers before that. + var pickDrawn = false // True if some object that is drawn into a pick buffer can be picked function anyPickable() { @@ -19708,13 +19712,15 @@ function createScene(options) { return false } - // Draw the pick buffers and read them back now, if they are out of date + // Draw the pick buffers and read them back now, if they are out of date. + // Not while a change waits for its frame (an object added, removed or updated, a new size): a pass on demand + // shows what the last frame drew, as the pass in the frame did. That frame starts the idle timer again. function ensurePick() { if(pickTimer) { clearTimeout(pickTimer) pickTimer = null } - if(!pickDirty || !pickFrameSeen || lodOn || scene._stopped || scene.contextLost) { + if(!pickDirty || !pickFrameSeen || dirty || lodOn || scene._stopped || scene.contextLost) { return } pickDirty = false @@ -19790,6 +19796,7 @@ function createScene(options) { } buf.end() } + pickDrawn = true } var nBounds = [ diff --git a/stackgl_modules/package-lock.json b/stackgl_modules/package-lock.json index b0cf7824597..e757a0e9062 100644 --- a/stackgl_modules/package-lock.json +++ b/stackgl_modules/package-lock.json @@ -16,7 +16,7 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "github:settylab/gl-plot3d#147b9928ba1863b4fdfe561bd295c1560c5b9fc0", + "gl-plot3d": "github:settylab/gl-plot3d#40d1edd48a2a0dca7a65fa4b1c850c65270a132e", "gl-scatter3d": "github:settylab/gl-scatter3d#213d696815416d3dc22acc35d0e7712ca737d6e3", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", @@ -1312,8 +1312,8 @@ }, "node_modules/gl-plot3d": { "version": "2.4.7", - "resolved": "git+ssh://git@github.com/settylab/gl-plot3d.git#147b9928ba1863b4fdfe561bd295c1560c5b9fc0", - "integrity": "sha512-8sspIeTJSVHgOSHTzovc6TXrSYgUSC6Xm/26xI3drny4RAjqktzqvbP2AA+Vnpbc7GzmbKVYT/aMqyZFSFZmLA==", + "resolved": "git+ssh://git@github.com/settylab/gl-plot3d.git#40d1edd48a2a0dca7a65fa4b1c850c65270a132e", + "integrity": "sha512-lj8JO5XOf6OrpN/ulYFGEF689b0lt1JRhzZxLiXRNk4GerpJBcewKk9SW2GZnwkcxi+g/EBJd9OGownDlGenjQ==", "license": "MIT", "dependencies": { "3d-view": "^2.0.0", diff --git a/stackgl_modules/package.json b/stackgl_modules/package.json index 1f26f0a0506..c1037d7fdfb 100644 --- a/stackgl_modules/package.json +++ b/stackgl_modules/package.json @@ -19,7 +19,7 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "github:settylab/gl-plot3d#147b9928ba1863b4fdfe561bd295c1560c5b9fc0", + "gl-plot3d": "github:settylab/gl-plot3d#40d1edd48a2a0dca7a65fa4b1c850c65270a132e", "gl-scatter3d": "github:settylab/gl-scatter3d#213d696815416d3dc22acc35d0e7712ca737d6e3", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", From 66cec41bad7501a8e4005b15e2ca21d8e68ac2ac Mon Sep 17 00:00:00 2001 From: Dominik Date: Sat, 5 Dec 2026 01:53:20 -0800 Subject: [PATCH 42/45] Name the early pointer spec after what it tests plotly draws the first frame of a scene inside newPlot, so the event of the spec comes right after that frame, not before it. The spec text said otherwise. --- test/jasmine/tests/gl3d_hover_click_test.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/test/jasmine/tests/gl3d_hover_click_test.js b/test/jasmine/tests/gl3d_hover_click_test.js index 7311610305c..e177d77a028 100644 --- a/test/jasmine/tests/gl3d_hover_click_test.js +++ b/test/jasmine/tests/gl3d_hover_click_test.js @@ -1752,9 +1752,10 @@ describe('Test gl3d pick pass:', function() { .then(done, done.fail); }); - it('@gl gives no hover for a trace before the frame that draws it', function(done) { - // A pointer that rests on a scene sends an event when the canvas appears, before the first frame with the trace. - // The pick pass on demand must find nothing then, as the pick pass in the frame did. + it('@gl gives no hover for a pointer event right after the first frame of a scene', function(done) { + // A pointer that rests on a scene sends an event when the canvas appears, right after the first frame. + // The pick pass in the frame was read back 1 ms later, so that event found nothing, and the pointer got no label + // until it moved. The pick pass on demand must answer the same way. const labels = () => document.querySelectorAll('g.hovertext').length; Plotly.newPlot(gd, Lib.extendDeep({}, mesh3dcoloringMock)) .then(() => { @@ -1762,7 +1763,7 @@ describe('Test gl3d pick pass:', function() { }) .then(frame) .then(() => { - expect(labels()).toBe(0, 'no label for a mesh that no frame drew'); + expect(labels()).toBe(0, 'no label for the event right after the first frame'); }) .then(delay(300)) .then(() => { From 53971c44a3420334a7d5f02c23e9d9bfd07cae0c Mon Sep 17 00:00:00 2001 From: Dominik Date: Sat, 5 Dec 2026 01:59:36 -0800 Subject: [PATCH 43/45] Pin gl-plot3d to the pick pass that waits 1 ms after a frame The pinned commit gives a pick pass on demand 1 ms after a frame that changed the scene, as the read-back of the frame pass did. A pointer event right after the first frame of a scene finds nothing again, so a pointer that rests on a scene gets no hover label until it moves. The stackgl bundle is the webpack output for the pin. --- stackgl_modules/index.js | 15 ++++++++++++++- stackgl_modules/package-lock.json | 4 ++-- stackgl_modules/package.json | 2 +- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index 62c04a24940..3b45b9dc891 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -19050,6 +19050,10 @@ function createScene(options) { clearTimeout(pickTimer) pickTimer = null } + if(pickWait) { + clearTimeout(pickWait) + pickWait = null + } window.removeEventListener('resize', resizeListener) canvas.removeEventListener('webglcontextlost', checkContextLoss) @@ -19204,6 +19208,9 @@ function createScene(options) { // False until a pick pass has drawn every pick buffer. A new buffer holds memory from the pool, not a picture, // so no query reads the buffers before that. var pickDrawn = false + // The pick pass of a frame was read back 1 ms after the frame, so a pointer event right after a frame saw the + // picture of the frame before. A pass on demand waits as long: pickWait is set for 1 ms after a frame that changed it. + var pickWait = null // True if some object that is drawn into a pick buffer can be picked function anyPickable() { @@ -19223,7 +19230,7 @@ function createScene(options) { clearTimeout(pickTimer) pickTimer = null } - if(!pickDirty || !pickFrameSeen || dirty || scene._stopped || scene.contextLost) { + if(!pickDirty || !pickFrameSeen || dirty || pickWait || scene._stopped || scene.contextLost) { return } pickDirty = false @@ -19445,6 +19452,12 @@ function createScene(options) { if(scene.pickMode === 'lazy') { // Not in this frame: a pointer event that queries the buffer draws it, or the idle timer does schedulePick() + // (one timer at a time: a scene that draws frame after frame must not hold the wait for good) + if(!pickWait) { + pickWait = setTimeout(function() { + pickWait = null + }, 1) + } } else { pickDirty = false renderPick() diff --git a/stackgl_modules/package-lock.json b/stackgl_modules/package-lock.json index 33eeb460df9..758d09f1d07 100644 --- a/stackgl_modules/package-lock.json +++ b/stackgl_modules/package-lock.json @@ -16,7 +16,7 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "github:settylab/gl-plot3d#d054d4cfc56c35df9fd603344b48d5a5e0877422", + "gl-plot3d": "github:settylab/gl-plot3d#e68f3db7da0e319755d8df6aec1c0b6a0e83385b", "gl-scatter3d": "github:settylab/gl-scatter3d#370d619a7ec1351f87989c9963a37cd4ccb06e5b", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", @@ -1312,7 +1312,7 @@ }, "node_modules/gl-plot3d": { "version": "2.4.7", - "resolved": "git+ssh://git@github.com/settylab/gl-plot3d.git#d054d4cfc56c35df9fd603344b48d5a5e0877422", + "resolved": "git+ssh://git@github.com/settylab/gl-plot3d.git#e68f3db7da0e319755d8df6aec1c0b6a0e83385b", "license": "MIT", "dependencies": { "3d-view": "^2.0.0", diff --git a/stackgl_modules/package.json b/stackgl_modules/package.json index 848bfcfcf30..ccd671d851d 100644 --- a/stackgl_modules/package.json +++ b/stackgl_modules/package.json @@ -19,7 +19,7 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "github:settylab/gl-plot3d#d054d4cfc56c35df9fd603344b48d5a5e0877422", + "gl-plot3d": "github:settylab/gl-plot3d#e68f3db7da0e319755d8df6aec1c0b6a0e83385b", "gl-scatter3d": "github:settylab/gl-scatter3d#370d619a7ec1351f87989c9963a37cd4ccb06e5b", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", From a2509b54f62bf0cc438c70ab02e0bf493aa48230 Mon Sep 17 00:00:00 2001 From: Dominik Date: Sat, 5 Dec 2026 02:03:43 -0800 Subject: [PATCH 44/45] Pin gl-plot3d to the pick pass that waits 1 ms after a change of the objects The pinned commit gives no pick pass on demand for 1 ms after the first frame that follows scene.add or scene.remove, as the read-back of the frame pass did. A pointer that rests on a scene when it appears gets no hover label until it moves, as before. The pins of the two commits before this one made the wait too wide: it also ran after each frame of a moving camera, and hover specs failed at random. The stackgl bundle is the webpack output for the pin. --- stackgl_modules/index.js | 12 ++++++++++-- stackgl_modules/package-lock.json | 4 ++-- stackgl_modules/package.json | 2 +- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index 3b45b9dc891..d3475467f60 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -19022,6 +19022,7 @@ function createScene(options) { pickBufferIds.push(-1) dirty = true pickDirty = true + pickNew = true reallocPickIds() } @@ -19037,6 +19038,7 @@ function createScene(options) { pickBufferIds.pop() dirty = true pickDirty = true + pickNew = true reallocPickIds() } @@ -19211,6 +19213,9 @@ function createScene(options) { // The pick pass of a frame was read back 1 ms after the frame, so a pointer event right after a frame saw the // picture of the frame before. A pass on demand waits as long: pickWait is set for 1 ms after a frame that changed it. var pickWait = null + // True from a change of the objects (add, remove) to the next frame. Only that frame starts the wait: after a frame + // that moves the camera, the pass on demand answers at once, where the frame pass gave the picture of the frame before. + var pickNew = true // True if some object that is drawn into a pick buffer can be picked function anyPickable() { @@ -19452,12 +19457,15 @@ function createScene(options) { if(scene.pickMode === 'lazy') { // Not in this frame: a pointer event that queries the buffer draws it, or the idle timer does schedulePick() - // (one timer at a time: a scene that draws frame after frame must not hold the wait for good) - if(!pickWait) { + if(pickNew) { + if(pickWait) { + clearTimeout(pickWait) + } pickWait = setTimeout(function() { pickWait = null }, 1) } + pickNew = false } else { pickDirty = false renderPick() diff --git a/stackgl_modules/package-lock.json b/stackgl_modules/package-lock.json index 758d09f1d07..2927e14cd37 100644 --- a/stackgl_modules/package-lock.json +++ b/stackgl_modules/package-lock.json @@ -16,7 +16,7 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "github:settylab/gl-plot3d#e68f3db7da0e319755d8df6aec1c0b6a0e83385b", + "gl-plot3d": "github:settylab/gl-plot3d#03ca2f651f73835f17e9643480301054c2f4c26e", "gl-scatter3d": "github:settylab/gl-scatter3d#370d619a7ec1351f87989c9963a37cd4ccb06e5b", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", @@ -1312,7 +1312,7 @@ }, "node_modules/gl-plot3d": { "version": "2.4.7", - "resolved": "git+ssh://git@github.com/settylab/gl-plot3d.git#e68f3db7da0e319755d8df6aec1c0b6a0e83385b", + "resolved": "git+ssh://git@github.com/settylab/gl-plot3d.git#03ca2f651f73835f17e9643480301054c2f4c26e", "license": "MIT", "dependencies": { "3d-view": "^2.0.0", diff --git a/stackgl_modules/package.json b/stackgl_modules/package.json index ccd671d851d..ac97e922a08 100644 --- a/stackgl_modules/package.json +++ b/stackgl_modules/package.json @@ -19,7 +19,7 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "github:settylab/gl-plot3d#e68f3db7da0e319755d8df6aec1c0b6a0e83385b", + "gl-plot3d": "github:settylab/gl-plot3d#03ca2f651f73835f17e9643480301054c2f4c26e", "gl-scatter3d": "github:settylab/gl-scatter3d#370d619a7ec1351f87989c9963a37cd4ccb06e5b", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", From 6366e4737d3876cb790df63d5c6a7fc097751a38 Mon Sep 17 00:00:00 2001 From: Dominik Date: Sat, 5 Dec 2026 02:28:17 -0800 Subject: [PATCH 45/45] Pin gl-plot3d to the combined branch with the 1 ms wait of the pick pass A pick pass on demand waits 1 ms after the first frame that follows a change of the objects. The frame at the end of scene.plot no longer lets a pointer event pick before that. --- stackgl_modules/index.js | 23 ++++++++++++++++++++++- stackgl_modules/package-lock.json | 6 +++--- stackgl_modules/package.json | 2 +- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index fbaa9fcfb26..68d7423b205 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -19516,6 +19516,7 @@ function createScene(options) { pickBufferIds.push(-1) dirty = true pickDirty = true + pickNew = true reallocPickIds() } @@ -19531,6 +19532,7 @@ function createScene(options) { pickBufferIds.pop() dirty = true pickDirty = true + pickNew = true reallocPickIds() } @@ -19544,6 +19546,10 @@ function createScene(options) { clearTimeout(pickTimer) pickTimer = null } + if(pickWait) { + clearTimeout(pickWait) + pickWait = null + } window.removeEventListener('resize', resizeListener) canvas.removeEventListener('webglcontextlost', checkContextLoss) @@ -19701,6 +19707,12 @@ function createScene(options) { // False until a pick pass has drawn every pick buffer. A new buffer holds memory from the pool, not a picture, // so no query reads the buffers before that. var pickDrawn = false + // The pick pass of a frame was read back 1 ms after the frame, so a pointer event right after a frame saw the + // picture of the frame before. A pass on demand waits as long: pickWait is set for 1 ms after a frame that changed it. + var pickWait = null + // True from a change of the objects (add, remove) to the next frame. Only that frame starts the wait: after a frame + // that moves the camera, the pass on demand answers at once, where the frame pass gave the picture of the frame before. + var pickNew = true // True if some object that is drawn into a pick buffer can be picked function anyPickable() { @@ -19720,7 +19732,7 @@ function createScene(options) { clearTimeout(pickTimer) pickTimer = null } - if(!pickDirty || !pickFrameSeen || dirty || lodOn || scene._stopped || scene.contextLost) { + if(!pickDirty || !pickFrameSeen || dirty || pickWait || lodOn || scene._stopped || scene.contextLost) { return } pickDirty = false @@ -20307,6 +20319,15 @@ function createScene(options) { if(scene.pickMode === 'lazy') { // Not in this frame: a pointer event that queries the buffer draws it, or the idle timer does schedulePick() + if(pickNew) { + if(pickWait) { + clearTimeout(pickWait) + } + pickWait = setTimeout(function() { + pickWait = null + }, 1) + } + pickNew = false } else if(!lodOn) { //(not in a preview frame: the pick pass follows the frame that draws every point) pickDirty = false diff --git a/stackgl_modules/package-lock.json b/stackgl_modules/package-lock.json index e757a0e9062..93d5b589ad1 100644 --- a/stackgl_modules/package-lock.json +++ b/stackgl_modules/package-lock.json @@ -16,7 +16,7 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "github:settylab/gl-plot3d#40d1edd48a2a0dca7a65fa4b1c850c65270a132e", + "gl-plot3d": "github:settylab/gl-plot3d#70ff6bddf0199d4201a4aabed2cd505b30c5aff6", "gl-scatter3d": "github:settylab/gl-scatter3d#213d696815416d3dc22acc35d0e7712ca737d6e3", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11", @@ -1312,8 +1312,8 @@ }, "node_modules/gl-plot3d": { "version": "2.4.7", - "resolved": "git+ssh://git@github.com/settylab/gl-plot3d.git#40d1edd48a2a0dca7a65fa4b1c850c65270a132e", - "integrity": "sha512-lj8JO5XOf6OrpN/ulYFGEF689b0lt1JRhzZxLiXRNk4GerpJBcewKk9SW2GZnwkcxi+g/EBJd9OGownDlGenjQ==", + "resolved": "git+ssh://git@github.com/settylab/gl-plot3d.git#70ff6bddf0199d4201a4aabed2cd505b30c5aff6", + "integrity": "sha512-dSxXOqevkW+KF5XxXS1c+6OkmqtTFLhfMR9U0kZpDvLueoYoj6vG6VWPbCVANLY6SNN9903BAe6hMZwmyj7YjQ==", "license": "MIT", "dependencies": { "3d-view": "^2.0.0", diff --git a/stackgl_modules/package.json b/stackgl_modules/package.json index c1037d7fdfb..eaabf099bc9 100644 --- a/stackgl_modules/package.json +++ b/stackgl_modules/package.json @@ -19,7 +19,7 @@ "gl-error3d": "^1.0.17", "gl-line3d": "^1.2.2", "gl-mesh3d": "^2.3.2", - "gl-plot3d": "github:settylab/gl-plot3d#40d1edd48a2a0dca7a65fa4b1c850c65270a132e", + "gl-plot3d": "github:settylab/gl-plot3d#70ff6bddf0199d4201a4aabed2cd505b30c5aff6", "gl-scatter3d": "github:settylab/gl-scatter3d#213d696815416d3dc22acc35d0e7712ca737d6e3", "gl-shader": "4.3.1", "gl-spikes3d": "^1.0.11",