From 60fa4a1d84d84c01a2aa19d07b94d11aa3091bf3 Mon Sep 17 00:00:00 2001 From: Dominik Date: Thu, 3 Dec 2026 23:13:40 -0800 Subject: [PATCH 01/11] 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 6cec460a3440c2c15599b9e53b55431bf6efea17 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:26:04 -0800 Subject: [PATCH 02/11] 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 14d6c6a64d2e4a1509ced87f092abf86d8abf126 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 12:24:45 -0800 Subject: [PATCH 03/11] 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 04/11] 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 05/11] 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 06/11] 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 07/11] 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 4bd6578992fbf14e4c6a157912df359fa2d3d2c7 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 13:16:09 -0800 Subject: [PATCH 08/11] 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 09/11] 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 4a5568d990de95abc50f3094b8d9e3318883493f Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 13:36:36 -0800 Subject: [PATCH 10/11] 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 6d0689fec7b604f6cfc5bd19680a72b720464eb2 Mon Sep 17 00:00:00 2001 From: Dominik Date: Sat, 5 Dec 2026 01:04:26 -0800 Subject: [PATCH 11/11] 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))