Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/utils/shaderPatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,19 @@
*/
export function patchOnBeforeCompile(material, fn) {
const previous = material.onBeforeCompile;
const previousKey = material.customProgramCacheKey?.bind(material);
const injectionKey = Function.prototype.toString.call(fn);
material.onBeforeCompile = function (shader, renderer) {
if (previous) previous.call(this, shader, renderer);
fn.call(this, shader, renderer);
};
// three.js keys the program cache on onBeforeCompile.toString() by default.
// Nested wrappers are identically worded, so the closed-over injection never
// appears in that string and every patched material would share one program.
material.customProgramCacheKey = function () {
const prior = previousKey ? previousKey.call(this) : '';
return `${prior}\n${injectionKey}`;
};
return material;
}

Expand Down
15 changes: 15 additions & 0 deletions src/utils/shaderPatch.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { patchOnBeforeCompile } from './shaderPatch.js';

test('composed patches get distinct program cache keys', () => {
const material = {};
patchOnBeforeCompile(material, function icePatch() {});
const iceKey = material.customProgramCacheKey();
patchOnBeforeCompile(material, function firePatch() {});
const fireKey = material.customProgramCacheKey();
assert.notEqual(iceKey, fireKey);
assert.match(iceKey, /icePatch/);
assert.match(fireKey, /firePatch/);
assert.match(fireKey, /icePatch/);
});