From 1913ab98a9ad0a69033353d816f4a2b1ef592e5f Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:22:38 +0000 Subject: [PATCH 1/3] Cut the renderer's cost per sprite move, costume switch and pen line A skin kept the drawables using it in a Set, so every costume switch paid for a hash delete and a hash add. It is now an array with each drawable remembering its slot. Pen lines grew the dirty box with eight Math.min and Math.max calls per line. They are now plain comparisons. Fencing recomputed the drawable's transform and bounds on every move. The bounds are now remembered until the sprite changes shape, and a move that stays clearly inside the stage returns without recomputing them. Moves near the edge still take the exact path. --- package-lock.json | 4 +- package.json | 2 +- src/Drawable.js | 33 ++++- src/PenSkin.js | 20 +-- src/RenderWebGL.js | 21 ++- src/Skin.js | 23 +++- test/unit/FencingTests.js | 229 +++++++++++++++++++++++++++++++ test/unit/PenDirtyRegionTests.js | 97 +++++++++++++ test/unit/SkinLifecycleTests.js | 59 ++++++++ 9 files changed, 468 insertions(+), 20 deletions(-) create mode 100644 test/unit/FencingTests.js create mode 100644 test/unit/PenDirtyRegionTests.js diff --git a/package-lock.json b/package-lock.json index fafa8ce21..0836af840 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "scratch-render", - "version": "0.1.1", + "version": "0.1.2", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "scratch-render", - "version": "0.1.1", + "version": "0.1.2", "license": "MPL-2.0", "dependencies": { "@turbowarp/ancient-hull.js": "^0.2.13", diff --git a/package.json b/package.json index 98b4288cf..504551d58 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "scratch-render", - "version": "0.1.1", + "version": "0.1.2", "description": "WebGL Renderer for Scratch 3.0", "author": "Massachusetts Institute of Technology", "license": "MPL-2.0", diff --git a/src/Drawable.js b/src/Drawable.js index 4f636ee8e..f58793312 100644 --- a/src/Drawable.js +++ b/src/Drawable.js @@ -17,6 +17,7 @@ const __isTouchingPosition = twgl.v3.create(); const __hullProjection = twgl.m4.ortho(-1, 1, -1, 1, -1, 1); const __hullTransform = twgl.m4.identity(); const FLOATING_POINT_ERROR_ALLOWANCE = 1e-6; +const MAX_REMEMBERED_FENCE_COORDINATE = 1e6; const SHAPE_EFFECTS_MASK = ShaderManager.EFFECT_INFO.fisheye.mask | ShaderManager.EFFECT_INFO.whirl.mask | ShaderManager.EFFECT_INFO.pixelate.mask | @@ -130,10 +131,18 @@ class Drawable { this._rotationCenterDirty = true; this._skinScale = twgl.v3.create(0, 0, 0); this._skinScaleDirty = true; + this._skinSlot = -1; this._inverseMatrix = twgl.m4.identity(); this._inverseTransformDirty = true; this._snappedFastBounds = new Rectangle(); this._snappedFastBoundsDirty = true; + this._fenceBoundsKnown = false; + this._fenceLeft = 0; + this._fenceRight = 0; + this._fenceBottom = 0; + this._fenceTop = 0; + this._fenceX = 0; + this._fenceY = 0; this._visible = true; /** A bitmask identifying which effects are currently in use. @@ -185,6 +194,24 @@ class Drawable { this._inverseTransformDirty = true; this._transformedHullDirty = true; this._snappedFastBoundsDirty = true; + this._fenceBoundsKnown = false; + } + + rememberFenceBounds (bounds) { + const x = this._position[0]; + const y = this._position[1]; + this._fenceBoundsKnown = Math.abs(x) < MAX_REMEMBERED_FENCE_COORDINATE && + Math.abs(y) < MAX_REMEMBERED_FENCE_COORDINATE && + Math.abs(bounds.left) < MAX_REMEMBERED_FENCE_COORDINATE && + Math.abs(bounds.right) < MAX_REMEMBERED_FENCE_COORDINATE && + Math.abs(bounds.bottom) < MAX_REMEMBERED_FENCE_COORDINATE && + Math.abs(bounds.top) < MAX_REMEMBERED_FENCE_COORDINATE; + this._fenceLeft = bounds.left; + this._fenceRight = bounds.right; + this._fenceBottom = bounds.bottom; + this._fenceTop = bounds.top; + this._fenceX = x; + this._fenceY = y; } /** @@ -207,11 +234,11 @@ class Drawable { set skin (newSkin) { if (this._skin !== newSkin) { if (this._skin) { - this._skin.attachedDrawables.delete(this); + this._skin.detachDrawable(this); } this._skin = newSkin; if (newSkin) { - newSkin.attachedDrawables.add(this); + newSkin.attachDrawable(this); } this._skinWasAltered(); } @@ -256,7 +283,9 @@ class Drawable { this._position[1] = Math.round(position[1]); } this._renderer.dirty = true; + const fenceBoundsKnown = this._fenceBoundsKnown; this.setTransformDirty(); + this._fenceBoundsKnown = fenceBoundsKnown; } } diff --git a/src/PenSkin.js b/src/PenSkin.js index 0ee4d4f5d..7c5fdf535 100644 --- a/src/PenSkin.js +++ b/src/PenSkin.js @@ -258,10 +258,10 @@ class PenSkin extends Skin { _markSilhouetteDirty (left, right, bottom, top) { if (this._silhouetteDirty) { - this._dirtyLeft = Math.min(this._dirtyLeft, left); - this._dirtyRight = Math.max(this._dirtyRight, right); - this._dirtyBottom = Math.min(this._dirtyBottom, bottom); - this._dirtyTop = Math.max(this._dirtyTop, top); + if (left < this._dirtyLeft) this._dirtyLeft = left; + if (right > this._dirtyRight) this._dirtyRight = right; + if (bottom < this._dirtyBottom) this._dirtyBottom = bottom; + if (top > this._dirtyTop) this._dirtyTop = top; } else { this._silhouetteDirty = true; this._dirtyLeft = left; @@ -463,11 +463,15 @@ class PenSkin extends Skin { const dirtyRadius = (lineThickness * 0.5) + 2; const halfWidth = this._size[0] * 0.5; const halfHeight = this._size[1] * 0.5; + const lowX = x0 < x1 ? x0 : x1; + const highX = x0 < x1 ? x1 : x0; + const lowY = y0 < y1 ? y0 : y1; + const highY = y0 < y1 ? y1 : y0; this._markSilhouetteDirty( - halfWidth + Math.min(x0, x1) - dirtyRadius, - halfWidth + Math.max(x0, x1) + dirtyRadius, - halfHeight - Math.max(y0, y1) - dirtyRadius, - halfHeight - Math.min(y0, y1) + dirtyRadius + halfWidth + lowX - dirtyRadius, + halfWidth + highX + dirtyRadius, + halfHeight - highY - dirtyRadius, + halfHeight - lowY + dirtyRadius ); for (let i = 0; i < iters; i++) { diff --git a/src/RenderWebGL.js b/src/RenderWebGL.js index 96995da76..ab7d3f2dd 100644 --- a/src/RenderWebGL.js +++ b/src/RenderWebGL.js @@ -95,6 +95,7 @@ const colorMatches = (a, b, offset) => ( * @type {number} */ const FENCE_WIDTH = 15; +const FENCE_SLACK = 0.01; // Loading text wrapper takes a while because of some of its dependencies, so only do so when needed. let _TextWrapper; @@ -959,8 +960,9 @@ class RenderWebGL extends EventEmitter { } skinWasAltered(skin) { - for (const drawable of skin.attachedDrawables) { - drawable._skinWasAltered(); + const attached = skin.attachedDrawables; + for (let i = 0; i < attached.length; i++) { + attached[i]._skinWasAltered(); } } @@ -1989,9 +1991,24 @@ class RenderWebGL extends EventEmitter { return [x, y]; } + if (drawable._fenceBoundsKnown) { + const shiftX = x - drawable._fenceX; + const shiftY = y - drawable._fenceY; + const limitX = this._xRight - FENCE_WIDTH - FENCE_SLACK; + const limitY = this._yTop - FENCE_WIDTH - FENCE_SLACK; + if (drawable._fenceRight + shiftX >= -limitX && drawable._fenceLeft + shiftX <= limitX && + drawable._fenceTop + shiftY >= -limitY && drawable._fenceBottom + shiftY <= limitY) { + return [x, y]; + } + } + const dx = x - drawable._position[0]; const dy = y - drawable._position[1]; const aabb = skin.getFenceBounds(drawable, __fenceBounds); + if (skin.getFenceBounds === Skin.prototype.getFenceBounds && + drawable.getAABB === Drawable.prototype.getAABB) { + drawable.rememberFenceBounds(aabb); + } const inset = Math.floor(Math.min(aabb.width, aabb.height) / 2); const sx = this._xRight - Math.min(FENCE_WIDTH, inset); diff --git a/src/Skin.js b/src/Skin.js index f8fc7cd6a..61871df3f 100644 --- a/src/Skin.js +++ b/src/Skin.js @@ -54,11 +54,24 @@ class Skin { */ this.private = false; - /** - * Drawables currently using this skin, maintained by the Drawable skin setter. - * @type {Set} - */ - this.attachedDrawables = new Set(); + this.attachedDrawables = []; + } + + attachDrawable (drawable) { + drawable._skinSlot = this.attachedDrawables.length; + this.attachedDrawables.push(drawable); + } + + detachDrawable (drawable) { + const attached = this.attachedDrawables; + const slot = drawable._skinSlot; + if (attached[slot] !== drawable) return; + const last = attached.pop(); + if (last !== drawable) { + attached[slot] = last; + last._skinSlot = slot; + } + drawable._skinSlot = -1; } /** diff --git a/test/unit/FencingTests.js b/test/unit/FencingTests.js new file mode 100644 index 000000000..1320266fd --- /dev/null +++ b/test/unit/FencingTests.js @@ -0,0 +1,229 @@ +const test = require('tap').test; +global.window = {}; +global.document = {createElement: () => ({getContext: () => ({})})}; +const RenderWebGL = require('../../src/RenderWebGL'); +const Drawable = require('../../src/Drawable'); +const Rectangle = require('../../src/Rectangle'); +const Skin = require('../../src/Skin'); + +const FENCE_WIDTH = 15; + +class SizedSkin extends Skin { + constructor (id, renderer, size) { + super(id, renderer); + this._size = size; + this.fenceBoundsCalls = 0; + } + get size () { + return this._size; + } + moveRotationCenter (x, y) { + this._rotationCenter[0] = x; + this._rotationCenter[1] = y; + this.emitWasAltered(); + } +} + +class CountingSkin extends SizedSkin { + getFenceBounds (drawable, result) { + this.fenceBoundsCalls++; + return drawable.getAABB(result); + } +} + +const fakeRenderer = () => { + const renderer = Object.create(RenderWebGL.prototype); + renderer._allSkins = {}; + renderer._allDrawables = []; + renderer._xRight = 240; + renderer._yTop = 180; + return renderer; +}; + +const fenceWithoutMemory = (renderer, drawable, position) => { + let x = position[0]; + let y = position[1]; + const dx = x - drawable._position[0]; + const dy = y - drawable._position[1]; + const aabb = drawable.getAABB(new Rectangle()); + const inset = Math.floor(Math.min(aabb.width, aabb.height) / 2); + const sx = renderer._xRight - Math.min(FENCE_WIDTH, inset); + if (aabb.right + dx < -sx) { + x = Math.ceil(drawable._position[0] - (sx + aabb.right)); + } else if (aabb.left + dx > sx) { + x = Math.floor(drawable._position[0] + (sx - aabb.left)); + } + const sy = renderer._yTop - Math.min(FENCE_WIDTH, inset); + if (aabb.top + dy < -sy) { + y = Math.ceil(drawable._position[1] - (sy + aabb.top)); + } else if (aabb.bottom + dy > sy) { + y = Math.floor(drawable._position[1] + (sy - aabb.bottom)); + } + return [x, y]; +}; + +const makeRandom = seed => () => { + seed = ((seed * 1103515245) + 12345) % 2147483648; + return seed / 2147483648; +}; + +const makeWorld = SkinClass => { + const renderer = fakeRenderer(); + const skins = [ + new SkinClass(1, renderer, [40, 30]), + new SkinClass(2, renderer, [3, 200]), + new SkinClass(3, renderer, [600, 500]) + ]; + skins[1].moveRotationCenter(1, 10); + const drawable = new Drawable(0, renderer); + renderer._allDrawables[0] = drawable; + drawable.skin = skins[0]; + return {renderer, skins, drawable}; +}; + +const runSequence = (t, seed, steps) => { + const random = makeRandom(seed); + const remembered = makeWorld(SizedSkin); + const plain = makeWorld(SizedSkin); + const special = [NaN, Infinity, -Infinity, 1e300, -1e300, 1e7, -1e7, 0, -0, 239.995, -239.995, 179.995]; + let fullPathCalls = 0; + const getAABB = Drawable.prototype.getAABB; + Drawable.prototype.getAABB = function (result) { + if (this === remembered.drawable) fullPathCalls++; + return getAABB.call(this, result); + }; + let mismatch = null; + try { + for (let step = 0; step < steps && mismatch === null; step++) { + const choice = random(); + const both = change => { + change(remembered); + change(plain); + }; + if (choice < 0.03) { + const scale = [5 + (random() * 400), 5 + (random() * 400)]; + both(world => world.drawable.updateScale(scale)); + } else if (choice < 0.06) { + const direction = Math.floor(random() * 360) - 180; + both(world => world.drawable.updateDirection(direction)); + } else if (choice < 0.08) { + const index = Math.floor(random() * 3); + both(world => { + world.drawable.skin = world.skins[index]; + }); + } else if (choice < 0.09) { + const center = [random() * 50, random() * 50]; + both(world => world.drawable.skin.moveRotationCenter(center[0], center[1])); + } else if (choice < 0.1) { + const highQuality = random() < 0.5; + both(world => world.drawable.setHighQuality(highQuality)); + } else { + let x; + let y; + if (choice < 0.12) { + x = special[Math.floor(random() * special.length)]; + y = special[Math.floor(random() * special.length)]; + } else if (choice < 0.5) { + x = remembered.drawable._position[0] + ((random() * 6) - 3); + y = remembered.drawable._position[1] + ((random() * 6) - 3); + } else if (choice < 0.8) { + x = (random() * 480) - 240; + y = (random() * 360) - 180; + } else { + x = (random() * 1200) - 600; + y = (random() * 900) - 450; + } + const expected = fenceWithoutMemory(plain.renderer, plain.drawable, [x, y]); + const actual = remembered.renderer.getFencedPositionOfDrawable(0, [x, y]); + if (!Object.is(actual[0], expected[0]) || !Object.is(actual[1], expected[1])) { + mismatch = `step ${step}: went to ${x}, ${y}, got ${actual} instead of ${expected}`; + } + both(world => world.drawable.updatePosition(expected)); + } + } + } finally { + Drawable.prototype.getAABB = getAABB; + } + t.equal(mismatch, null, `seed ${seed}`); + return fullPathCalls; +}; + +test('fencing gives the same position with and without remembered bounds', t => { + let fullPathCalls = 0; + const steps = 20000; + for (const seed of [1, 2, 3, 4, 5]) { + fullPathCalls += runSequence(t, seed, steps); + } + t.ok(fullPathCalls < steps * 5 * 0.6, `bounds were recomputed ${fullPathCalls} times in ${steps * 5} steps`); + t.end(); +}); + +test('a sprite moving well inside the stage does not recompute its bounds', t => { + const {renderer, drawable} = makeWorld(SizedSkin); + let transforms = 0; + const calculateTransform = drawable._calculateTransform; + drawable._calculateTransform = function () { + transforms++; + return calculateTransform.call(this); + }; + for (let i = 0; i < 100; i++) { + const position = renderer.getFencedPositionOfDrawable(0, [i - 50, 50 - i]); + t.same(position, [i - 50, 50 - i]); + drawable.updatePosition(position); + } + t.equal(transforms, 1); + t.end(); +}); + +test('a skin with its own fence bounds is asked on every move', t => { + const {renderer, skins, drawable} = makeWorld(CountingSkin); + for (let i = 0; i < 50; i++) { + drawable.updatePosition(renderer.getFencedPositionOfDrawable(0, [i, i])); + } + t.equal(skins[0].fenceBoundsCalls, 50); + t.end(); +}); + +test('remembered bounds are dropped when the sprite changes shape', t => { + const {renderer, drawable, skins} = makeWorld(SizedSkin); + const results = []; + const moveTo = (x, y) => { + const expected = fenceWithoutMemory(renderer, drawable, [x, y]); + const position = renderer.getFencedPositionOfDrawable(0, [x, y]); + t.same(position, expected, `moving to ${x}, ${y}`); + results.push(position[0] === x && position[1] === y ? 'free' : 'fenced'); + drawable.updatePosition(position); + }; + moveTo(0, 0); + moveTo(200, 0); + moveTo(300, 0); + drawable.updateScale([1000, 1000]); + moveTo(300, 0); + drawable.updateScale([100, 100]); + moveTo(300, 0); + drawable.skin = skins[2]; + moveTo(500, 0); + drawable.skin = skins[0]; + moveTo(500, 0); + drawable.updateDirection(0); + moveTo(0, 185); + drawable.updateDirection(90); + moveTo(0, 185); + skins[0].moveRotationCenter(-200, 15); + moveTo(100, 0); + t.same(results, ['free', 'free', 'fenced', 'fenced', 'fenced', 'fenced', 'fenced', 'fenced', 'free', 'fenced']); + t.end(); +}); + +test('bounds measured very far away are not reused near the fence', t => { + const {renderer, drawable} = makeWorld(SizedSkin); + drawable.setHighQuality(true); + drawable.updatePosition([3e16, 0]); + for (const [x, y] of [[0, 0], [245.9, 0], [10, 0], [-245.9, 0]]) { + const expected = fenceWithoutMemory(renderer, drawable, [x, y]); + const position = renderer.getFencedPositionOfDrawable(0, [x, y]); + t.same(position, expected, `moving to ${x}, ${y}`); + drawable.updatePosition(position); + } + t.end(); +}); diff --git a/test/unit/PenDirtyRegionTests.js b/test/unit/PenDirtyRegionTests.js new file mode 100644 index 000000000..20cb346f8 --- /dev/null +++ b/test/unit/PenDirtyRegionTests.js @@ -0,0 +1,97 @@ +const test = require('tap').test; +global.window = {}; +global.document = {createElement: () => ({getContext: () => ({})})}; +const PenSkin = require('../../src/PenSkin'); + +const fakePenSkin = (width, height, quality) => { + const skin = Object.create(PenSkin.prototype); + skin._renderer = {enterDrawRegion: () => {}}; + skin.instancedRendering = true; + skin.attribute_data = new Float32Array(4096); + skin.attribute_index = 0; + skin.renderQuality = quality; + skin._size = [width * quality, height * quality]; + skin._silhouetteDirty = false; + return skin; +}; + +const region = skin => [skin._dirtyLeft, skin._dirtyRight, skin._dirtyBottom, skin._dirtyTop]; + +const expectedRegion = (skin, lines) => { + let left = Infinity; + let right = -Infinity; + let bottom = Infinity; + let top = -Infinity; + for (const [diameter, x0, y0, x1, y1] of lines) { + const quality = skin.renderQuality; + const radius = (diameter * quality * 0.5) + 2; + const halfWidth = skin._size[0] * 0.5; + const halfHeight = skin._size[1] * 0.5; + left = Math.min(left, halfWidth + (Math.min(x0, x1) * quality) - radius); + right = Math.max(right, halfWidth + (Math.max(x0, x1) * quality) + radius); + bottom = Math.min(bottom, halfHeight - (Math.max(y0, y1) * quality) - radius); + top = Math.max(top, halfHeight - (Math.min(y0, y1) * quality) + radius); + } + return [left, right, bottom, top]; +}; + +const draw = (skin, lines) => { + for (const [diameter, x0, y0, x1, y1] of lines) { + skin._drawLineOnBuffer({diameter, color4f: [1, 0, 0, 1]}, x0, y0, x1, y1); + } +}; + +test('a pen line dirties the box around it whichever way it points', t => { + const directions = [ + [3, -10, -20, 30, 40], + [3, 30, 40, -10, -20], + [3, -10, 40, 30, -20], + [3, 30, -20, -10, 40], + [7, 5, 5, 5, 5], + [1, -240, 180, 240, -180] + ]; + for (const quality of [1, 2]) { + for (const line of directions) { + const skin = fakePenSkin(480, 360, quality); + draw(skin, [line]); + t.equal(skin._silhouetteDirty, true); + t.same(region(skin), expectedRegion(skin, [line]), `quality ${quality}, line ${line.join(' ')}`); + } + } + t.end(); +}); + +test('several pen lines dirty the box around all of them', t => { + const lines = []; + let seed = 12345; + const random = () => { + seed = ((seed * 1103515245) + 12345) % 2147483648; + return seed / 2147483648; + }; + for (let i = 0; i < 200; i++) { + lines.push([ + 1 + Math.floor(random() * 20), + (random() * 600) - 300, (random() * 500) - 250, + (random() * 600) - 300, (random() * 500) - 250 + ]); + } + const skin = fakePenSkin(480, 360, 1); + for (let count = 1; count <= lines.length; count++) { + draw(skin, [lines[count - 1]]); + if (count % 20 === 0 || count < 5) { + t.same(region(skin), expectedRegion(skin, lines.slice(0, count)), `after ${count} lines`); + } + } + t.end(); +}); + +test('a clean pen layer starts its dirty box from the next mark', t => { + const skin = fakePenSkin(480, 360, 1); + skin._markSilhouetteDirty(10, 20, 30, 40); + skin._markSilhouetteDirty(15, 18, 5, 35); + t.same(region(skin), [10, 20, 5, 40]); + skin._silhouetteDirty = false; + skin._markSilhouetteDirty(100, 110, 120, 130); + t.same(region(skin), [100, 110, 120, 130]); + t.end(); +}); diff --git a/test/unit/SkinLifecycleTests.js b/test/unit/SkinLifecycleTests.js index 95cf3a52d..4e92233b3 100644 --- a/test/unit/SkinLifecycleTests.js +++ b/test/unit/SkinLifecycleTests.js @@ -3,6 +3,7 @@ global.window = {}; global.document = {createElement: () => ({getContext: () => ({})})}; const RenderWebGL = require('../../src/RenderWebGL'); const Drawable = require('../../src/Drawable'); +const Skin = require('../../src/Skin'); const fakeRenderer = () => { const renderer = Object.create(RenderWebGL.prototype); @@ -52,3 +53,61 @@ test('convex hull of a drawable with no skin is empty, not a crash', t => { t.doesNotThrow(() => drawable.getFastBounds()); t.end(); }); + +test('a skin tracks exactly the drawables that use it', t => { + const renderer = fakeRenderer(); + const first = new Skin(1, renderer); + const second = new Skin(2, renderer); + const drawables = [0, 1, 2, 3, 4].map(id => new Drawable(id, renderer)); + const attachedTo = skin => skin.attachedDrawables.map(drawable => drawable.id).sort(); + + for (const drawable of drawables) drawable.skin = first; + t.same(attachedTo(first), [0, 1, 2, 3, 4]); + + drawables[1].skin = second; + drawables[4].skin = second; + drawables[0].skin = null; + t.same(attachedTo(first), [2, 3]); + t.same(attachedTo(second), [1, 4]); + + drawables[1].skin = second; + t.same(attachedTo(second), [1, 4], 'setting the same skin again changes nothing'); + + for (let round = 0; round < 50; round++) { + for (const drawable of drawables) { + drawable.skin = (drawable.id + round) % 3 === 0 ? first : second; + } + } + const expectedFirst = drawables.filter(drawable => drawable.skin === first).map(drawable => drawable.id); + const expectedSecond = drawables.filter(drawable => drawable.skin === second).map(drawable => drawable.id); + t.same(attachedTo(first), expectedFirst); + t.same(attachedTo(second), expectedSecond); + + for (const drawable of drawables) drawable.dispose(); + t.same(first.attachedDrawables, []); + t.same(second.attachedDrawables, []); + t.end(); +}); + +test('altering a skin only reaches the drawables that use it', t => { + const renderer = fakeRenderer(); + const first = new Skin(1, renderer); + const second = new Skin(2, renderer); + const drawables = [0, 1, 2, 3].map(id => new Drawable(id, renderer)); + drawables[0].skin = first; + drawables[1].skin = second; + drawables[2].skin = first; + drawables[3].skin = first; + drawables[2].skin = second; + + const reached = []; + for (const drawable of drawables) { + drawable._skinWasAltered = () => reached.push(drawable.id); + } + renderer.skinWasAltered(first); + t.same(reached.sort(), [0, 3]); + reached.length = 0; + renderer.skinWasAltered(second); + t.same(reached.sort(), [1, 2]); + t.end(); +}); From 6e96338133063e120b4bff968b8b26b02d926c6e Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:04:26 +0000 Subject: [PATCH 2/3] Remember which moves need no fencing instead of the bounds The remembered state is now the box of positions that are free of the fence, so the check on a move is four comparisons. A sprite whose bounds cannot be measured, such as one with an infinite size, is never fenced and is remembered as free everywhere. The margin is sized for the 32-bit model matrix, positions beyond 10000 drop the memory, and a change of stage size is noticed. --- src/Drawable.js | 42 ++++-------- src/RenderWebGL.js | 55 ++++++++++++--- test/unit/FencingTests.js | 137 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 196 insertions(+), 38 deletions(-) diff --git a/src/Drawable.js b/src/Drawable.js index f58793312..81107f691 100644 --- a/src/Drawable.js +++ b/src/Drawable.js @@ -17,7 +17,7 @@ const __isTouchingPosition = twgl.v3.create(); const __hullProjection = twgl.m4.ortho(-1, 1, -1, 1, -1, 1); const __hullTransform = twgl.m4.identity(); const FLOATING_POINT_ERROR_ALLOWANCE = 1e-6; -const MAX_REMEMBERED_FENCE_COORDINATE = 1e6; +const FREE_MOVES_RANGE = 1e4; const SHAPE_EFFECTS_MASK = ShaderManager.EFFECT_INFO.fisheye.mask | ShaderManager.EFFECT_INFO.whirl.mask | ShaderManager.EFFECT_INFO.pixelate.mask | @@ -136,13 +136,12 @@ class Drawable { this._inverseTransformDirty = true; this._snappedFastBounds = new Rectangle(); this._snappedFastBoundsDirty = true; - this._fenceBoundsKnown = false; - this._fenceLeft = 0; - this._fenceRight = 0; - this._fenceBottom = 0; - this._fenceTop = 0; - this._fenceX = 0; - this._fenceY = 0; + this._freeMovesLeft = NaN; + this._freeMovesRight = 0; + this._freeMovesBottom = 0; + this._freeMovesTop = 0; + this._freeMovesStageRight = 0; + this._freeMovesStageTop = 0; this._visible = true; /** A bitmask identifying which effects are currently in use. @@ -194,24 +193,7 @@ class Drawable { this._inverseTransformDirty = true; this._transformedHullDirty = true; this._snappedFastBoundsDirty = true; - this._fenceBoundsKnown = false; - } - - rememberFenceBounds (bounds) { - const x = this._position[0]; - const y = this._position[1]; - this._fenceBoundsKnown = Math.abs(x) < MAX_REMEMBERED_FENCE_COORDINATE && - Math.abs(y) < MAX_REMEMBERED_FENCE_COORDINATE && - Math.abs(bounds.left) < MAX_REMEMBERED_FENCE_COORDINATE && - Math.abs(bounds.right) < MAX_REMEMBERED_FENCE_COORDINATE && - Math.abs(bounds.bottom) < MAX_REMEMBERED_FENCE_COORDINATE && - Math.abs(bounds.top) < MAX_REMEMBERED_FENCE_COORDINATE; - this._fenceLeft = bounds.left; - this._fenceRight = bounds.right; - this._fenceBottom = bounds.bottom; - this._fenceTop = bounds.top; - this._fenceX = x; - this._fenceY = y; + this._freeMovesLeft = NaN; } /** @@ -283,9 +265,11 @@ class Drawable { this._position[1] = Math.round(position[1]); } this._renderer.dirty = true; - const fenceBoundsKnown = this._fenceBoundsKnown; + const freeMovesLeft = this._freeMovesLeft; this.setTransformDirty(); - this._fenceBoundsKnown = fenceBoundsKnown; + if (Math.abs(this._position[0]) <= FREE_MOVES_RANGE && Math.abs(this._position[1]) <= FREE_MOVES_RANGE) { + this._freeMovesLeft = freeMovesLeft; + } } } @@ -969,4 +953,6 @@ class Drawable { } } +Drawable.FREE_MOVES_RANGE = FREE_MOVES_RANGE; + module.exports = Drawable; diff --git a/src/RenderWebGL.js b/src/RenderWebGL.js index ab7d3f2dd..46e2a566e 100644 --- a/src/RenderWebGL.js +++ b/src/RenderWebGL.js @@ -96,6 +96,8 @@ const colorMatches = (a, b, offset) => ( */ const FENCE_WIDTH = 15; const FENCE_SLACK = 0.01; +const FENCE_ROUNDING = 1e-6; +const FREE_MOVES_RANGE = Drawable.FREE_MOVES_RANGE; // Loading text wrapper takes a while because of some of its dependencies, so only do so when needed. let _TextWrapper; @@ -1991,15 +1993,10 @@ class RenderWebGL extends EventEmitter { return [x, y]; } - if (drawable._fenceBoundsKnown) { - const shiftX = x - drawable._fenceX; - const shiftY = y - drawable._fenceY; - const limitX = this._xRight - FENCE_WIDTH - FENCE_SLACK; - const limitY = this._yTop - FENCE_WIDTH - FENCE_SLACK; - if (drawable._fenceRight + shiftX >= -limitX && drawable._fenceLeft + shiftX <= limitX && - drawable._fenceTop + shiftY >= -limitY && drawable._fenceBottom + shiftY <= limitY) { - return [x, y]; - } + if (x >= drawable._freeMovesLeft && x <= drawable._freeMovesRight && + y >= drawable._freeMovesBottom && y <= drawable._freeMovesTop && + drawable._freeMovesStageRight === this._xRight && drawable._freeMovesStageTop === this._yTop) { + return [x, y]; } const dx = x - drawable._position[0]; @@ -2007,7 +2004,7 @@ class RenderWebGL extends EventEmitter { const aabb = skin.getFenceBounds(drawable, __fenceBounds); if (skin.getFenceBounds === Skin.prototype.getFenceBounds && drawable.getAABB === Drawable.prototype.getAABB) { - drawable.rememberFenceBounds(aabb); + this._rememberFreeMoves(drawable, aabb); } const inset = Math.floor(Math.min(aabb.width, aabb.height) / 2); @@ -2026,6 +2023,44 @@ class RenderWebGL extends EventEmitter { return [x, y]; } + _rememberFreeMoves(drawable, aabb) { + drawable._freeMovesStageRight = this._xRight; + drawable._freeMovesStageTop = this._yTop; + const positionX = drawable._position[0]; + const positionY = drawable._position[1]; + if (!(Math.abs(positionX) <= FREE_MOVES_RANGE && Math.abs(positionY) <= FREE_MOVES_RANGE)) { + drawable._freeMovesLeft = NaN; + return; + } + const halfShortSide = Math.min(aabb.width, aabb.height) / 2; + if (Number.isNaN(halfShortSide)) { + drawable._freeMovesLeft = -Infinity; + drawable._freeMovesRight = Infinity; + drawable._freeMovesBottom = -Infinity; + drawable._freeMovesTop = Infinity; + return; + } + const inset = Math.min(FENCE_WIDTH, Math.floor(halfShortSide + FENCE_SLACK)); + const reachX = this._xRight - inset; + const reachY = this._yTop - inset; + const marginX = FENCE_SLACK + + ((FREE_MOVES_RANGE + Math.abs(aabb.left) + Math.abs(aabb.right)) * FENCE_ROUNDING); + const marginY = FENCE_SLACK + + ((FREE_MOVES_RANGE + Math.abs(aabb.bottom) + Math.abs(aabb.top)) * FENCE_ROUNDING); + let left = positionX - reachX - aabb.right; + if (left > -Infinity) left += marginX; + let right = positionX + reachX - aabb.left; + if (right < Infinity) right -= marginX; + let bottom = positionY - reachY - aabb.top; + if (bottom > -Infinity) bottom += marginY; + let top = positionY + reachY - aabb.bottom; + if (top < Infinity) top -= marginY; + drawable._freeMovesLeft = left; + drawable._freeMovesRight = right; + drawable._freeMovesBottom = bottom; + drawable._freeMovesTop = top; + } + /** * Clear a pen layer. * @param {int} penSkinID - the unique ID of a Pen Skin. diff --git a/test/unit/FencingTests.js b/test/unit/FencingTests.js index 1320266fd..f5ea12949 100644 --- a/test/unit/FencingTests.js +++ b/test/unit/FencingTests.js @@ -227,3 +227,140 @@ test('bounds measured very far away are not reused near the fence', t => { } t.end(); }); + +test('a sprite with no measurable bounds is never fenced and stops recomputing them', t => { + const {renderer, drawable} = makeWorld(SizedSkin); + const plain = makeWorld(SizedSkin); + drawable.updateScale([Infinity, Infinity]); + plain.drawable.updateScale([Infinity, Infinity]); + let transforms = 0; + const calculateTransform = drawable._calculateTransform; + drawable._calculateTransform = function () { + transforms++; + return calculateTransform.call(this); + }; + const moves = [[0, 0], [9000, -9000], [239, 400], [12.5, 7.25], [-Infinity, 5], [3, 4], [1e9, -1e9], [1, 2]]; + const recomputed = []; + for (const [x, y] of moves) { + const before = transforms; + const expected = fenceWithoutMemory(plain.renderer, plain.drawable, [x, y]); + const position = renderer.getFencedPositionOfDrawable(0, [x, y]); + t.same(position, expected, `moving to ${x}, ${y}`); + t.same(position, [x, y]); + recomputed.push(transforms > before); + drawable.updatePosition(position); + plain.drawable.updatePosition(position); + } + t.same(recomputed, [true, false, false, false, false, true, true, true], + 'only the first move and the moves around far or endless positions recompute'); + drawable.updateScale([100, 100]); + plain.drawable.updateScale([100, 100]); + const expected = fenceWithoutMemory(plain.renderer, plain.drawable, [900, 0]); + t.same(renderer.getFencedPositionOfDrawable(0, [900, 0]), expected); + t.not(expected[0], 900); + t.end(); +}); + +test('remembered free moves are dropped when the stage changes size', t => { + const {renderer, drawable} = makeWorld(SizedSkin); + drawable.updatePosition(renderer.getFencedPositionOfDrawable(0, [0, 0])); + t.same(renderer.getFencedPositionOfDrawable(0, [200, 150]), [200, 150]); + renderer._xRight = 100; + renderer._yTop = 80; + const expected = fenceWithoutMemory(renderer, drawable, [200, 150]); + t.same(renderer.getFencedPositionOfDrawable(0, [200, 150]), expected); + t.not(expected[0], 200); + t.not(expected[1], 150); + renderer._xRight = 240; + renderer._yTop = 180; + t.same(renderer.getFencedPositionOfDrawable(0, [200, 150]), [200, 150]); + t.end(); +}); + +test('moves right at the fence are decided the same way from any starting point', t => { + const random = makeRandom(99); + let checked = 0; + let mismatch = null; + for (let shape = 0; shape < 40 && mismatch === null; shape++) { + const remembered = makeWorld(SizedSkin); + const plain = makeWorld(SizedSkin); + const scale = [20 + (random() * 300), 20 + (random() * 300)]; + const direction = Math.floor(random() * 360) - 180; + const skinIndex = Math.floor(random() * 3); + for (const world of [remembered, plain]) { + world.drawable.setHighQuality(true); + world.drawable.skin = world.skins[skinIndex]; + world.drawable.updateScale(scale); + world.drawable.updateDirection(direction); + } + const isFree = (x, y) => { + const result = fenceWithoutMemory(plain.renderer, plain.drawable, [x, y]); + return result[0] === x && result[1] === y; + }; + for (let round = 0; round < 30 && mismatch === null; round++) { + const start = [(random() * 400) - 200, (random() * 300) - 150]; + const startPosition = fenceWithoutMemory(plain.renderer, plain.drawable, start); + remembered.renderer.getFencedPositionOfDrawable(0, start); + remembered.drawable.updatePosition(startPosition); + plain.drawable.updatePosition(startPosition); + const horizontal = random() < 0.5; + const other = (random() * 100) - 50; + const at = value => (horizontal ? [value, other] : [other, value]); + if (!isFree(...at(0))) continue; + let inside = 0; + let outside = random() < 0.5 ? 3000 : -3000; + if (isFree(...at(outside))) continue; + for (let i = 0; i < 60; i++) { + const middle = (inside + outside) / 2; + if (isFree(...at(middle))) inside = middle; else outside = middle; + } + const offsets = [0.5, 0.02, 0.0101, 0.0099, 1e-3, 1e-5, 1e-7]; + for (const offset of [0, ...offsets, ...offsets.map(value => -value)]) { + const target = at(inside + offset); + const expected = fenceWithoutMemory(plain.renderer, plain.drawable, target); + const actual = remembered.renderer.getFencedPositionOfDrawable(0, target); + checked++; + if (!Object.is(actual[0], expected[0]) || !Object.is(actual[1], expected[1])) { + mismatch = `shape ${shape} round ${round}: ${target} gave ${actual} instead of ${expected}`; + } + } + } + } + t.equal(mismatch, null); + t.ok(checked > 5000, `${checked} moves checked`); + t.end(); +}); + +test('moves that stop just short of the fence still skip the bounds', t => { + for (const skinIndex of [0, 1, 2]) { + const {renderer, drawable, skins} = makeWorld(SizedSkin); + const plain = makeWorld(SizedSkin); + drawable.skin = skins[skinIndex]; + plain.drawable.skin = plain.skins[skinIndex]; + drawable.updatePosition(renderer.getFencedPositionOfDrawable(0, [0, 0])); + const isFree = (x, y) => { + const result = fenceWithoutMemory(plain.renderer, plain.drawable, [x, y]); + return result[0] === x && result[1] === y; + }; + let transforms = 0; + const calculateTransform = drawable._calculateTransform; + drawable._calculateTransform = function () { + transforms++; + return calculateTransform.call(this); + }; + for (const [stepX, stepY] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { + let inside = 0; + let outside = 5000; + for (let i = 0; i < 40; i++) { + const middle = (inside + outside) / 2; + if (isFree(stepX * middle, stepY * middle)) inside = middle; else outside = middle; + } + const move = [stepX * (inside - 0.5), stepY * (inside - 0.5)]; + t.same(renderer.getFencedPositionOfDrawable(0, move), move, `skin ${skinIndex} to ${move}`); + drawable.updatePosition(move); + plain.drawable.updatePosition(move); + } + t.equal(transforms, 0, `skin ${skinIndex}`); + } + t.end(); +}); From ff3356cc00fc0abeab37b58876a00cfc35ff2706 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:20:24 +0000 Subject: [PATCH 3/3] Mark the whole pen layer dirty for a line with a coordinate that is not a number --- src/PenSkin.js | 6 +++++ test/unit/PenDirtyRegionTests.js | 38 ++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/PenSkin.js b/src/PenSkin.js index 7c5fdf535..c5b43fdc4 100644 --- a/src/PenSkin.js +++ b/src/PenSkin.js @@ -257,6 +257,12 @@ class PenSkin extends Skin { } _markSilhouetteDirty (left, right, bottom, top) { + if (!(left <= right && bottom <= top)) { + left = 0; + right = this._size[0]; + bottom = 0; + top = this._size[1]; + } if (this._silhouetteDirty) { if (left < this._dirtyLeft) this._dirtyLeft = left; if (right > this._dirtyRight) this._dirtyRight = right; diff --git a/test/unit/PenDirtyRegionTests.js b/test/unit/PenDirtyRegionTests.js index 20cb346f8..0514e1e1f 100644 --- a/test/unit/PenDirtyRegionTests.js +++ b/test/unit/PenDirtyRegionTests.js @@ -95,3 +95,41 @@ test('a clean pen layer starts its dirty box from the next mark', t => { t.same(region(skin), [100, 110, 120, 130]); t.end(); }); + +const readBack = skin => { + const reads = []; + skin._renderer.gl = { + RGBA: 1, + UNSIGNED_BYTE: 2, + readPixels: (x, y, width, height) => reads.push([x, y, width, height]) + }; + skin._usePenBufferDrawRegionId = {}; + skin._silhouettePixels = new Uint8Array(skin._size[0] * skin._size[1] * 4); + skin._silhouetteImageData = {}; + skin._silhouette = {update: () => {}}; + skin.updateSilhouette(); + return reads; +}; + +test('only the dirty box is read back for the silhouette', t => { + const skin = fakePenSkin(480, 360, 1); + draw(skin, [[2, 0, 0, 10, 10]]); + t.same(readBack(skin), [[237, 167, 16, 16]]); + t.equal(skin._silhouetteDirty, false); + t.same(readBack(skin), [], 'nothing is read while the layer is clean'); + t.end(); +}); + +test('a line with a coordinate that is not a number makes the whole layer read back', t => { + for (const lines of [ + [[2, 0, 0, 10, 10], [2, NaN, 0, 5, 5]], + [[2, NaN, 0, 5, 5], [2, 0, 0, 10, 10]], + [[2, 0, 0, 10, NaN]], + [[2, 3, NaN, 4, 5], [2, 0, 0, 10, 10], [2, 1, 1, NaN, 1]] + ]) { + const skin = fakePenSkin(480, 360, 1); + draw(skin, lines); + t.same(readBack(skin), [[0, 0, 480, 360]], JSON.stringify(lines)); + } + t.end(); +});