3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Add a pixel outline to splat pixel-art output (#1744)
Nguyen Xuan Andf9f040693bf
diff --git a/changes/1744-outline.md b/changes/1744-outline.mdnew file mode 100644index 00000000..844d2c96--- /dev/null+++ b/changes/1744-outline.md@@ -0,0 +1 @@+- `createGaussianSplats` takes `outline: { color, width }` (width 1 to 4 pixels, needs `alphaCut`) to draw a dark pixel outline round the silhouette of hard-disc splats, for the pixel-art look (#1744)diff --git a/changes/1744-outline.size.md b/changes/1744-outline.size.mdnew file mode 100644index 00000000..c2d37f41--- /dev/null+++ b/changes/1744-outline.size.md@@ -0,0 +1 @@+- entry:gaussian-splats: about 510 bytes gzip for the outline option (width and colour checks, the grown-quad vertex shader and the outline fragment shader), the dark silhouette line pixel-art users otherwise draw in a separate image pass after every frame (#1744). Measured by minifying the entry with and without the outline module.diff --git a/docs/gaussian-splats.md b/docs/gaussian-splats.mdindex 76a051ef..ed55af55 100644--- a/docs/gaussian-splats.md+++ b/docs/gaussian-splats.md@@ -35,7 +35,9 @@ A Z-up file (Blender, CAD) loads upright with `parseGaussianSplatPly(bytes, { up`createGaussianSplats(data, { alphaCut: 0.5 })` (and the async version) draws the scene as hard discs instead of soft blobs. A pixel whose gaussian alpha (the falloff times the splat's opacity) is below `alphaCut`, a number from 0 to 1, is dropped; every other pixel is written opaque with depth, with no blending, so neighbouring splats stay their own colour and the result does not depend on the sort. Leave it out for the soft look, which is unchanged. Opaque scenes draw before soft ones on the same renderer, and a splat whose opacity is under the cut never shows.-For a pixel-art look add a palette: `createGaussianSplats(data, { alphaCut: 0.5, palette: ['#1b1b2f', '#c8553d', '#ffd166', [0.9, 0.9, 0.85]], dither: 'bayer4' })`. `palette` is 2 to 256 colours, each a hex string (`'#rgb'` or `'#rrggbb'`) or an `[r, g, b]` array of numbers from 0 to 1, and it needs `alphaCut`, because a blended pixel has no single colour to snap. Every opaque splat pixel takes the nearest palette colour by squared RGB distance (the first one on a tie), judged on the splat's display colour before any HDR exposure. `dither` is `'none'` (default), `'bayer4'` or `'bayer8'`: before the nearest colour is picked, each pixel moves by an ordered-dither threshold from its screen position (the canvas pixel, so a frame at the same size always gives the same pixels), up to 0.125 either way in each channel. The sky, parts and other splat scenes in the frame are not snapped. With no `palette` nothing changes. The outline, the upscale and baking a surface into splats are not part of this.+For a pixel-art look add a palette: `createGaussianSplats(data, { alphaCut: 0.5, palette: ['#1b1b2f', '#c8553d', '#ffd166', [0.9, 0.9, 0.85]], dither: 'bayer4' })`. `palette` is 2 to 256 colours, each a hex string (`'#rgb'` or `'#rrggbb'`) or an `[r, g, b]` array of numbers from 0 to 1, and it needs `alphaCut`, because a blended pixel has no single colour to snap. Every opaque splat pixel takes the nearest palette colour by squared RGB distance (the first one on a tie), judged on the splat's display colour before any HDR exposure. `dither` is `'none'` (default), `'bayer4'` or `'bayer8'`: before the nearest colour is picked, each pixel moves by an ordered-dither threshold from its screen position (the canvas pixel, so a frame at the same size always gives the same pixels), up to 0.125 either way in each channel. The sky, parts and other splat scenes in the frame are not snapped. With no `palette` nothing changes. The upscale and baking a surface into splats are not part of this.++For a one-pixel dark outline round the silhouette add `outline`: `createGaussianSplats(data, { alphaCut: 0.5, palette, dither: 'bayer4', outline: { color: '#101018', width: 1 } })`. `width` is a whole number of pixels from 1 to 4 (default 1), `color` is a hex string or an `[r, g, b]` array from 0 to 1 (default a near black, `[0.04, 0.04, 0.06]`), and it needs `alphaCut`, because a soft edge has no silhouette. The scene draws a second time first, before the fills, from the same splats grown by `width` plus one pixel; a pixel takes the outline colour when its distance to the edge of the cut disc is within `width`. That distance is the disc's edge function divided by its screen-space gradient, so it is exact on a straight edge and slightly off on a tight curve, and it is measured to the pixel centre. The outline writes no depth, so any fill covers it: you get a line round the outer silhouette and round holes in it, not round every disc inside. The outline colour is not snapped to the palette and not dithered. A splat whose opacity is under the cut has no outline, as it has no disc. Parts and other splat scenes drawn before it stay in front where they are nearer. With no `outline` nothing changes, and the shaders are the same text as before. Costs one more draw of the scene.## Loading without freezing the pagediff --git a/src/gaussian-splats.js b/src/gaussian-splats.jsindex ee086025..083e7dde 100644--- a/src/gaussian-splats.js+++ b/src/gaussian-splats.js@@ -5,6 +5,7 @@ import { runInChunks } from './gaussian-splat-chunks.js';import { GAUSSIAN_SPLAT_HARD_COUNT_LIMIT, GAUSSIAN_SPLAT_LIMITS, parseGaussianSplatPly, parseGaussianSplatPlyAsync } from './gaussian-splat-ply.js';import { parseGaussianSplatSpz, parseGaussianSplatSpzAsync } from './gaussian-splat-spz.js';import { buildPaletteFragmentSource, resolveSplatPalette } from './splat-palette.js';+import { buildOutlineVertexSource, OUTLINE_FRAGMENT_SOURCE, resolveSplatOutline } from './splat-outline.js';export { GAUSSIAN_SPLAT_HARD_COUNT_LIMIT, GAUSSIAN_SPLAT_LIMITS, parseGaussianSplatPly, parseGaussianSplatPlyAsync, parseGaussianSplatSpz, parseGaussianSplatSpzAsync };@@ -182,7 +183,7 @@ function checkSplatArray(data, { field, stride, types, meaning }, caller) {function resolveSplatOptions(options, caller) {if (options === undefined) return {};if (options === null || typeof options !== 'object') {- throw new TypeError(`${caller} options must be an object such as { matrix, maximumCount, alphaCut, palette, dither } or left out, got ${options === null ? 'null' : typeof options}`);+ throw new TypeError(`${caller} options must be an object such as { matrix, maximumCount, alphaCut, palette, dither, outline } or left out, got ${options === null ? 'null' : typeof options}`);}return options;}@@ -216,13 +217,13 @@ function resolveAlphaCut(alphaCut, caller) {function resolveSplatLook(options, caller) {const alphaCut = resolveAlphaCut(options.alphaCut, caller);- return { alphaCut, palette: resolveSplatPalette(options.palette, options.dither, alphaCut, caller) };+ return { alphaCut, palette: resolveSplatPalette(options.palette, options.dither, alphaCut, caller), outline: resolveSplatOutline(options.outline, alphaCut, caller) };}-function buildSplats(data, matrix, packed, { alphaCut, palette }) {+function buildSplats(data, matrix, packed, { alphaCut, palette, outline }) {const sorter = createSplatSorter(data.positions, data.count, data.bounds);const statistics = { count: data.count, visibleCount: 0, sortMilliseconds: 0, gpuBytes: 0, cpuBytes: data.positions.byteLength + data.count * 8 };- return { count: data.count, matrix: mat4.clone(matrix), bounds: data.bounds, statistics, packed, sorter, alphaCut, palette };+ return { count: data.count, matrix: mat4.clone(matrix), bounds: data.bounds, statistics, packed, sorter, alphaCut, palette, outline };}/**@@ -234,6 +235,8 @@ function buildSplats(data, matrix, packed, { alphaCut, palette }) {* neighbouring splats no longer mix their colours. These splats draw before the soft ones.* `palette` (2 to 256 colours, hex strings or [r, g, b] from 0 to 1; needs `alphaCut`) snaps every opaque pixel to its nearest* palette colour, and `dither` (`'none'` default, `'bayer4'`, `'bayer8'`) adds an ordered dither first. Both are off by default.+ * `outline` (`{ color, width }`, width 1 to 4 pixels, color a hex string or [r, g, b], default near black; needs `alphaCut`)+ * draws a dark outline round the outer silhouette of the hard discs. Off by default.* The returned object has `count`, `matrix`, `bounds` and `statistics` (`count`, `visibleCount`, `sortMilliseconds`,* `gpuBytes`, `cpuBytes`).*/@@ -288,15 +291,15 @@ function createGpuResources(context, splats) {const attachments = new WeakMap();-function createProgramInfo(context, fragmentSource, extraUniformNames = []) {- const program = compileProgram(context, VERTEX_SOURCE, fragmentSource);+function createProgramInfo(context, fragmentSource, extraUniformNames = [], vertexSource = VERTEX_SOURCE) {+ const program = compileProgram(context, vertexSource, fragmentSource);const uniforms = Object.fromEntries([...UNIFORM_NAMES, ...extraUniformNames].map(name => [name, context.getUniformLocation(program, name)]));return { program, uniforms };}function createAttachment(renderer) {const context = renderer.context;- const attachment = { blended: createProgramInfo(context, FRAGMENT_SOURCE), opaque: null, palettePrograms: new Map(), entries: new Set(), modelView: mat4.create(), original: null, disposeOriginal: null };+ const attachment = { blended: createProgramInfo(context, FRAGMENT_SOURCE), opaque: null, palettePrograms: new Map(), outline: null, entries: new Set(), modelView: mat4.create(), original: null, disposeOriginal: null };attachment.original = renderer.drawBlendBatches;attachment.disposeOriginal = renderer.dispose;renderer.drawBlendBatches = function drawBlendBatchesAndSplats(frame) {@@ -321,6 +324,7 @@ function releaseAttachment(renderer, attachment) {attachment.entries.clear();renderer.context.deleteProgram(attachment.blended.program);if (attachment.opaque) renderer.context.deleteProgram(attachment.opaque.program);+ if (attachment.outline) renderer.context.deleteProgram(attachment.outline.program);for (const programInfo of attachment.palettePrograms.values()) renderer.context.deleteProgram(programInfo.program);renderer.drawBlendBatches = attachment.original;renderer.dispose = attachment.disposeOriginal;@@ -373,6 +377,20 @@ function paletteProgramFor(renderer, attachment, palette) {return attachment.palettePrograms.get(key);}+function drawOutlines(renderer, attachment, outlineEntries, frame) {+ const context = renderer.context;+ attachment.outline ??= createProgramInfo(context, OUTLINE_FRAGMENT_SOURCE, ['outlineWidth', 'outlineColor'], buildOutlineVertexSource(VERTEX_SOURCE));+ context.depthMask(false);+ context.disable(context.BLEND);+ for (const entry of outlineEntries) {+ const { color, width } = entry.splats.outline;+ useProgram(renderer, attachment.outline, frame);+ context.uniform1f(attachment.outline.uniforms.outlineWidth, width);+ context.uniform3fv(attachment.outline.uniforms.outlineColor, color);+ drawEntry(renderer, attachment, entry, attachment.outline);+ }+}+function restoreState(renderer) {const context = renderer.context;context.depthMask(true);@@ -397,7 +415,7 @@ function drawEntry(renderer, attachment, entry, programInfo) {if (visibleCount === 0) return;context.uniformMatrix4fv(programInfo.uniforms.modelView, false, attachment.modelView);if (splats.alphaCut !== null) context.uniform1f(programInfo.uniforms.alphaCut, splats.alphaCut);- if (splats.palette) context.uniform3fv(programInfo.uniforms.paletteColors, splats.palette.colors);+ if (splats.palette && programInfo.uniforms.paletteColors !== undefined) context.uniform3fv(programInfo.uniforms.paletteColors, splats.palette.colors);context.activeTexture(context.TEXTURE0 + DATA_TEXTURE_UNIT);context.bindTexture(context.TEXTURE_2D, entry.texture);context.bindVertexArray(entry.vertexArray);@@ -412,6 +430,8 @@ function drawEntries(renderer, attachment, frame) {const opaqueEntries = entries.filter(entry => entry.splats.alphaCut !== null && !entry.splats.palette);const paletteEntries = entries.filter(entry => entry.splats.palette);const blendedEntries = entries.filter(entry => entry.splats.alphaCut === null);+ const outlineEntries = entries.filter(entry => entry.splats.outline);+ if (outlineEntries.length > 0) drawOutlines(renderer, attachment, outlineEntries, frame);if (opaqueEntries.length > 0) {prepareOpaqueState(renderer, attachment, frame);for (const entry of opaqueEntries) drawEntry(renderer, attachment, entry, attachment.opaque);diff --git a/src/splat-outline.js b/src/splat-outline.jsnew file mode 100644index 00000000..38f693b8--- /dev/null+++ b/src/splat-outline.js@@ -0,0 +1,90 @@+// A pixel outline round the silhouette of a gaussian splat scene drawn with `alphaCut`. The outline is drawn before the fills,+// without writing depth, from the same splats grown by the outline width: a pixel takes the outline colour when its distance to+// the edge of the cut disc is within the width. Any fill then covers the outline, so only the outer silhouette keeps it.+// `dilateSplatMask` below is the discrete reference of that rule, so a unit test on it pins what the shader should draw.++import { parseSplatColor } from './splat-palette.js';++export const SPLAT_OUTLINE_LIMITS = Object.freeze({ minimumWidth: 1, maximumWidth: 4 });+export const SPLAT_OUTLINE_DEFAULT_COLOR = Object.freeze([0.04, 0.04, 0.06]);++function describe(value) {+ return value === null ? 'null' : Array.isArray(value) ? 'an array' : typeof value;+}++/**+ * Checks the `outline` option of createGaussianSplats and returns `{ color, width }` (color is three numbers from 0 to 1),+ * or null when no outline is asked for.+ */+export function resolveSplatOutline(outline, alphaCut, caller) {+ if (outline === undefined || outline === null) return null;+ if (typeof outline !== 'object' || Array.isArray(outline)) {+ throw new TypeError(`${caller} outline must be an object such as { color: '#101018', width: 1 }, got ${describe(outline)}`);+ }+ const { minimumWidth, maximumWidth } = SPLAT_OUTLINE_LIMITS;+ const { color, width = minimumWidth } = outline;+ if (!Number.isInteger(width) || width < minimumWidth || width > maximumWidth) {+ throw new RangeError(`${caller} outline.width must be a whole number of pixels from ${minimumWidth} to ${maximumWidth}, got ${JSON.stringify(width)}`);+ }+ const resolvedColor = color === undefined ? [...SPLAT_OUTLINE_DEFAULT_COLOR] : parseSplatColor(color, 'outline.color');+ if (alphaCut === null) {+ throw new TypeError(`${caller} outline needs alphaCut (a number from 0 to 1): a soft blended edge has no silhouette to outline. Pass alphaCut: 0.5, or leave outline out`);+ }+ return { color: resolvedColor, width };+}++/**+ * The outline pixels of a silhouette. `rows` is an array of equal-length strings where '#' is inside the silhouette; the+ * result has 'o' on every outside pixel whose centre is within `width` pixels (straight-line distance) of an inside pixel+ * centre, '#' unchanged and '.' elsewhere.+ */+export function dilateSplatMask(rows, width) {+ return rows.map((row, y) => [...row].map((cell, x) => {+ if (cell === '#') return '#';+ for (let offsetY = -width; offsetY <= width; offsetY++) {+ for (let offsetX = -width; offsetX <= width; offsetX++) {+ const inside = rows[y + offsetY]?.[x + offsetX] === '#';+ if (inside && offsetX * offsetX + offsetY * offsetY <= width * width) return 'o';+ }+ }+ return '.';+ }).join(''));+}++const VIEWPORT_LINE = 'uniform vec2 viewport;';+const CORNER_LINE = 'vec2 corner = vec2(float(gl_VertexID & 1), float(gl_VertexID >> 1)) * 4.0 - 2.0;';++function replaceOnce(source, line, replacement) {+ if (!source.includes(line)) throw new Error(`The splat vertex shader no longer contains "${line}"; update buildOutlineVertexSource`);+ return source.replace(line, replacement);+}++/** The splat vertex shader with each quad grown by the outline width plus one pixel, so the outline has room to draw. */+export function buildOutlineVertexSource(vertexSource) {+ const withUniform = replaceOnce(vertexSource, VIEWPORT_LINE, `${VIEWPORT_LINE}\nuniform float outlineWidth;`);+ return replaceOnce(withUniform, CORNER_LINE, `${CORNER_LINE}+ corner *= 1.0 + (outlineWidth + 1.0) / (2.0 * vec2(length(majorAxis), length(minorAxis)));`);+}++// The edge of the cut disc is where `edgeSquared - dot(offset, offset)` is zero; dividing that by its screen-space gradient+// gives the distance to the edge in pixels, exact for a straight edge and close for a curved one.+export const OUTLINE_FRAGMENT_SOURCE = `#version 300 es+precision highp float;+uniform float hdrEnabled;+uniform float exposure;+uniform float alphaCut;+uniform float outlineWidth;+uniform vec3 outlineColor;+in vec4 vertexColor;+in vec2 vertexOffset;+out vec4 outputColor;+void main() {+ float cut = max(alphaCut, 1.0 / 255.0);+ if (vertexColor.a < cut) discard;+ float edgeSquared = min(4.0, log(vertexColor.a / cut));+ float inside = edgeSquared - dot(vertexOffset, vertexOffset);+ float gradient = max(length(vec2(dFdx(inside), dFdy(inside))), 1e-6);+ if (-inside / gradient > outlineWidth) discard;+ vec3 color = hdrEnabled > 0.5 ? pow(outlineColor, vec3(2.2)) * exposure : outlineColor;+ outputColor = vec4(color, 1.0);+}`;diff --git a/src/splat-palette.js b/src/splat-palette.jsindex 71e230b1..4d454979 100644--- a/src/splat-palette.js+++ b/src/splat-palette.js@@ -27,27 +27,28 @@ export function buildBayerMatrix(size) {return matrix;}-function parseHexColor(text, position) {+function parseHexColor(text, label) {const match = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(text);if (!match) {- throw new RangeError(`palette[${position}] must be a hex colour such as '#a1b2c3' or '#abc', or an [r, g, b] array of numbers from 0 to 1, got ${JSON.stringify(text)}`);+ throw new RangeError(`${label} must be a hex colour such as '#a1b2c3' or '#abc', or an [r, g, b] array of numbers from 0 to 1, got ${JSON.stringify(text)}`);}const digits = match[1].length === 3 ? [...match[1]].map(digit => digit + digit).join('') : match[1];return [0, 2, 4].map(offset => parseInt(digits.slice(offset, offset + 2), 16) / 255);}-function parseArrayColor(color, position) {+function parseArrayColor(color, label) {const valid = color.length === 3 && color.every(value => typeof value === 'number' && value >= 0 && value <= 1);if (!valid) {- throw new RangeError(`palette[${position}] must be a hex colour such as '#a1b2c3' or an [r, g, b] array of three numbers from 0 to 1, got ${JSON.stringify(color)}`);+ throw new RangeError(`${label} must be a hex colour such as '#a1b2c3' or an [r, g, b] array of three numbers from 0 to 1, got ${JSON.stringify(color)}`);}return color;}-function parsePaletteColor(color, position) {- if (typeof color === 'string') return parseHexColor(color, position);- if (Array.isArray(color)) return parseArrayColor(color, position);- throw new RangeError(`palette[${position}] must be a hex colour such as '#a1b2c3' or an [r, g, b] array of numbers from 0 to 1, got ${String(color)}`);+/** A colour option as three numbers from 0 to 1: a hex string or an [r, g, b] array. `label` names the field in errors. */+export function parseSplatColor(color, label) {+ if (typeof color === 'string') return parseHexColor(color, label);+ if (Array.isArray(color)) return parseArrayColor(color, label);+ throw new RangeError(`${label} must be a hex colour such as '#a1b2c3' or an [r, g, b] array of numbers from 0 to 1, got ${String(color)}`);}/**@@ -73,7 +74,7 @@ export function resolveSplatPalette(palette, dither, alphaCut, caller) {throw new TypeError(`${caller} palette needs alphaCut (a number from 0 to 1) so the splats draw as opaque discs; blended pixels cannot be snapped to a palette. Pass alphaCut: 0.5, or leave palette out`);}const colors = new Float32Array(palette.length * 3);- palette.forEach((color, position) => colors.set(parsePaletteColor(color, position), position * 3));+ palette.forEach((color, position) => colors.set(parseSplatColor(color, `palette[${position}]`), position * 3));return { colors, count: palette.length, dither: resolvedDither };}diff --git a/tests/gaussian-splat-outline.test.js b/tests/gaussian-splat-outline.test.jsnew file mode 100644index 00000000..e88dd775--- /dev/null+++ b/tests/gaussian-splat-outline.test.js@@ -0,0 +1,135 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import test from 'node:test';+import { mat4 } from 'gl-matrix';+import { attachGaussianSplats, createGaussianSplats, createGaussianSplatsAsync, GAUSSIAN_SPLAT_SHADER_SOURCES } from '../src/gaussian-splats.js';+import { buildOutlineVertexSource, dilateSplatMask, OUTLINE_FRAGMENT_SOURCE, resolveSplatOutline } from '../src/splat-outline.js';++function resolve(outline, alphaCut = 0.5) {+ return resolveSplatOutline(outline, alphaCut, 'createGaussianSplats');+}++test('width 1 outlines the four neighbours of a block, not its diagonals', () => {+ const mask = ['.......', '.......', '..###..', '..###..', '..###..', '.......', '.......'];+ assert.deepEqual(dilateSplatMask(mask, 1), [+ '.......',+ '..ooo..',+ '.o###o.',+ '.o###o.',+ '.o###o.',+ '..ooo..',+ '.......',+ ]);+});++test('width 2 reaches two pixels out along the axes and one diagonal step, and is clipped at the image edge', () => {+ const mask = ['.....', '.....', '..#..', '.....', '.....'];+ assert.deepEqual(dilateSplatMask(mask, 2), [+ '..o..',+ '.ooo.',+ 'oo#oo',+ '.ooo.',+ '..o..',+ ]);+ assert.deepEqual(dilateSplatMask(['#..'], 2), ['#oo']);+ assert.deepEqual(dilateSplatMask(['...', '...'], 1), ['...', '...']);+});++test('the outline needs alphaCut, whole pixels from 1 to 4, a real colour and says what to pass otherwise', () => {+ assert.equal(resolve(undefined, null), null);+ assert.equal(resolve(null, null), null);+ assert.deepEqual(resolve({}), { color: [0.04, 0.04, 0.06], width: 1 });+ assert.deepEqual(resolve({ color: '#fff', width: 4 }), { color: [1, 1, 1], width: 4 });+ assert.deepEqual(resolve({ color: [0, 0.5, 1], width: 2 }).color, [0, 0.5, 1]);+ assert.throws(() => resolve(3), /outline must be an object such as \{ color.*got number/);+ assert.throws(() => resolve([1]), /outline must be an object.*got an array/);+ assert.throws(() => resolve({ width: 0 }), /outline\.width must be a whole number of pixels from 1 to 4, got 0/);+ assert.throws(() => resolve({ width: 5 }), /outline\.width.*got 5/);+ assert.throws(() => resolve({ width: 1.5 }), /outline\.width.*got 1\.5/);+ assert.throws(() => resolve({ color: 'red' }), /outline\.color must be a hex colour.*"red"/);+ assert.throws(() => resolve({ color: [0, 2, 0] }), /outline\.color must be a hex colour/);+ assert.throws(() => resolve({ width: 1 }, null), /outline needs alphaCut/);+});++function oneSplat() {+ return {+ count: 1,+ positions: new Float32Array([0, 0, -3]),+ scales: new Float32Array([0.1, 0.1, 0.1]),+ rotations: new Float32Array([1, 0, 0, 0]),+ colors: new Uint8Array([200, 100, 50, 255]),+ bounds: { minimum: [-1, -1, -4], maximum: [1, 1, -2] },+ };+}++test('createGaussianSplats and its async twin validate the outline at the boundary', async () => {+ const data = oneSplat();+ assert.equal(createGaussianSplats(data, { alphaCut: 0.5 }).outline, null);+ assert.equal(createGaussianSplats(data, { alphaCut: 0.5, outline: { width: 2 } }).outline.width, 2);+ assert.throws(() => createGaussianSplats(data, { outline: { width: 1 } }), /createGaussianSplats outline needs alphaCut/);+ await assert.rejects(createGaussianSplatsAsync(data, { alphaCut: 0.5, outline: { width: 9 } }), /createGaussianSplatsAsync outline\.width/);+});++function createRecordingRenderer() {+ const calls = [];+ const context = new Proxy({}, {+ get(target, name) {+ if (typeof name !== 'string') return undefined;+ if (name === 'getShaderParameter' || name === 'getProgramParameter') return () => true;+ if (/^[A-Z_0-9]+$/.test(name)) return name;+ return (...parameters) => {+ calls.push([name, ...parameters]);+ return { created: name };+ };+ },+ });+ const renderer = {+ context,+ canvas: { width: 64, height: 64 },+ multisampleFramebuffer: {},+ projection: mat4.perspective(mat4.create(), 1, 1, 0.1, 50),+ view: mat4.create(),+ hdr: false,+ drawBlendBatches() {},+ dispose() {},+ };+ return { renderer, calls };+}++function drawWith(options) {+ const { renderer, calls } = createRecordingRenderer();+ attachGaussianSplats(renderer, createGaussianSplats(oneSplat(), options));+ calls.length = 0;+ renderer.drawBlendBatches({ eye: [0, 0, 0], exposure: 1 });+ return calls;+}++const shaderSources = calls => calls.filter(([name]) => name === 'shaderSource').map(call => String(call[2]));+const sha256 = text => createHash('sha256').update(text).digest('hex');++test('without an outline the shaders and draw calls are as before', () => {+ const plain = drawWith({ alphaCut: 0.5 });+ assert.ok(!shaderSources(plain).some(source => source.includes('outline')));+ assert.equal(plain.filter(([name]) => name === 'drawArraysInstanced').length, 1);+ assert.equal(sha256(GAUSSIAN_SPLAT_SHADER_SOURCES.opaqueFragment), 'd86baccbe36073ee22f6df8c9a2687bb6a9c1d2e9f3046b951139e5ae536cb61');+ assert.equal(sha256(GAUSSIAN_SPLAT_SHADER_SOURCES.vertex), 'c9557318769fb7d25c8f7b69089a23f0c95a4885fc1c23337d56dd4783ec75d8');+});++test('an outline scene draws the grown quads first, without depth write, then the fill', () => {+ const calls = drawWith({ alphaCut: 0.5, outline: { color: '#ff0000', width: 3 } });+ const sources = shaderSources(calls);+ assert.ok(sources.includes(OUTLINE_FRAGMENT_SOURCE));+ assert.ok(sources.includes(buildOutlineVertexSource(GAUSSIAN_SPLAT_SHADER_SOURCES.vertex)));+ assert.ok(!GAUSSIAN_SPLAT_SHADER_SOURCES.vertex.includes('outlineWidth'));+ assert.deepEqual(Array.from(calls.find(([name]) => name === 'uniform3fv')[2]), [1, 0, 0]);+ assert.ok(calls.some(([name, , value]) => name === 'uniform1f' && value === 3));+ const draws = calls.map(([name], index) => (name === 'drawArraysInstanced' ? index : -1)).filter(index => index >= 0);+ assert.equal(draws.length, 2);+ const depthMaskBefore = (start, end) => calls.slice(start, end).filter(([name]) => name === 'depthMask').map(call => call[1]).at(-1);+ assert.equal(depthMaskBefore(0, draws[0]), false);+ assert.equal(depthMaskBefore(draws[0], draws[1]), true);+});++test('the outline vertex shader refuses a vertex shader it cannot grow', () => {+ assert.throws(() => buildOutlineVertexSource('void main() {}'), /no longer contains/);+});