@react-three/tsl 10.0.0-canary.d46ab63 → 10.0.0-canary.d8aec34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -278,6 +278,103 @@ function configureTSL(next) {
278
278
  for (const store of primaries) applyConfig(store, config);
279
279
  }
280
280
 
281
+ const owners = /* @__PURE__ */ new WeakMap();
282
+ const warned$1 = /* @__PURE__ */ new WeakSet();
283
+ const sweeps = /* @__PURE__ */ new WeakMap();
284
+ function createOwner(store, rebuild) {
285
+ return { store, pipeline: null, scenePass: null, passes: {}, mounted: false, releaseTimer: null, rebuild };
286
+ }
287
+ function disposeOwnerResources(owner) {
288
+ owner.scenePass?.node.dispose();
289
+ owner.pipeline?.dispose();
290
+ owner.scenePass = null;
291
+ owner.pipeline = null;
292
+ owner.passes = {};
293
+ }
294
+ function activeOwner(store) {
295
+ return owners.get(store)?.at(-1);
296
+ }
297
+ function renderThroughPipeline(store) {
298
+ return () => {
299
+ const pipeline = store.getState().renderPipeline;
300
+ if (pipeline?.render) pipeline.render();
301
+ };
302
+ }
303
+ function claimOwnership(owner) {
304
+ if (owner.releaseTimer !== null) clearTimeout(owner.releaseTimer);
305
+ owner.releaseTimer = null;
306
+ owner.mounted = true;
307
+ let list = owners.get(owner.store);
308
+ if (!list) owners.set(owner.store, list = []);
309
+ if (list.includes(owner)) return;
310
+ if (list.some((other) => other.mounted) && !warned$1.has(owner.store)) {
311
+ warned$1.add(owner.store);
312
+ if (typeof process === "undefined" || process.env.NODE_ENV !== "production") {
313
+ console.warn(
314
+ "[useRenderPipeline] More than one mounted component configures this canvas's render pipeline. The most recently mounted one renders; the others take over again when it unmounts."
315
+ );
316
+ }
317
+ }
318
+ list.push(owner);
319
+ scheduleSweep(owner.store);
320
+ }
321
+ function scheduleSweep(store) {
322
+ if (sweeps.has(store)) return;
323
+ sweeps.set(
324
+ store,
325
+ setTimeout(() => {
326
+ sweeps.delete(store);
327
+ const active = activeOwner(store);
328
+ for (const owner of [...owners.get(store) ?? []]) {
329
+ if (owner !== active && !owner.mounted && owner.releaseTimer === null) releaseOwner(owner);
330
+ }
331
+ })
332
+ );
333
+ }
334
+ function publishOwner(owner) {
335
+ if (activeOwner(owner.store) !== owner || !owner.pipeline) return;
336
+ owner.store.setState({ renderPipeline: owner.pipeline, passes: owner.passes });
337
+ extension.setRenderOverride(owner.store, renderThroughPipeline(owner.store));
338
+ }
339
+ function scheduleRelease(owner) {
340
+ owner.mounted = false;
341
+ if (owner.releaseTimer !== null) return;
342
+ owner.releaseTimer = setTimeout(() => releaseOwner(owner));
343
+ }
344
+ function releaseOwner(owner) {
345
+ if (owner.releaseTimer !== null) clearTimeout(owner.releaseTimer);
346
+ owner.releaseTimer = null;
347
+ const { store } = owner;
348
+ const list = owners.get(store);
349
+ const index = list?.indexOf(owner) ?? -1;
350
+ if (list && index !== -1) {
351
+ const wasActive = index === list.length - 1;
352
+ list.splice(index, 1);
353
+ if (wasActive) {
354
+ const next = activeOwner(store);
355
+ if (next) {
356
+ publishOwner(next);
357
+ } else {
358
+ store.setState({ renderPipeline: null, passes: {} });
359
+ extension.setRenderOverride(store, null);
360
+ }
361
+ }
362
+ }
363
+ disposeOwnerResources(owner);
364
+ }
365
+ function releaseAllOwners(store) {
366
+ clearTimeout(sweeps.get(store));
367
+ sweeps.delete(store);
368
+ const list = owners.get(store);
369
+ if (!list) return;
370
+ owners.delete(store);
371
+ for (const owner of list) {
372
+ if (owner.releaseTimer !== null) clearTimeout(owner.releaseTimer);
373
+ owner.releaseTimer = null;
374
+ disposeOwnerResources(owner);
375
+ }
376
+ }
377
+
281
378
  const SHARED_KEYS = ["uniforms", "nodes", "buffers", "gpuStorage", "_hmrVersion"];
282
379
  const following = /* @__PURE__ */ new WeakMap();
283
380
  function createResourceState() {
@@ -306,6 +403,7 @@ function followPrimary(store, primary) {
306
403
  following.set(store, primary.subscribe(sync));
307
404
  }
308
405
  function dispose(store) {
406
+ releaseAllOwners(store);
309
407
  untrackPrimary(store);
310
408
  following.get(store)?.();
311
409
  following.delete(store);
@@ -1081,120 +1179,164 @@ function rebuildAllStorage(store, scope) {
1081
1179
  }
1082
1180
 
1083
1181
  const NO_PASSES = Object.freeze({});
1084
- function renderThroughPipeline(store) {
1085
- return () => {
1086
- const pipeline = store.getState().renderPipeline;
1087
- if (pipeline?.render) pipeline.render();
1088
- };
1089
- }
1090
- function useRenderPipeline(mainCB, setupCB) {
1182
+ function useRenderPipeline(mainCB, setupCB, options) {
1091
1183
  const store = extension.useStore();
1184
+ const primary = usePrimaryStore();
1185
+ const view = React.useMemo(() => createResourceView(primary, store), [primary, store]);
1092
1186
  const { scene, camera, renderer, isLegacy } = extension.useThree();
1187
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
1188
+ const isOwner = mainCB !== void 0 || setupCB !== void 0;
1093
1189
  const callbacksRanRef = React.useRef(false);
1094
- const scenePassCacheRef = React.useRef(null);
1095
1190
  const forceScenePassRebuildRef = React.useRef(false);
1096
1191
  const mainCBRef = React.useRef(mainCB);
1097
1192
  const setupCBRef = React.useRef(setupCB);
1193
+ const persistRef = React.useRef(options?.persist ?? false);
1098
1194
  mainCBRef.current = mainCB;
1099
1195
  setupCBRef.current = setupCB;
1196
+ persistRef.current = options?.persist ?? false;
1100
1197
  const [rebuildVersion, setRebuildVersion] = React.useState(0);
1101
- React.useEffect(() => {
1198
+ const rerun = React.useCallback((freshScenePass) => {
1102
1199
  callbacksRanRef.current = false;
1103
- forceScenePassRebuildRef.current = true;
1200
+ if (freshScenePass) forceScenePassRebuildRef.current = true;
1201
+ setRebuildVersion((v) => v + 1);
1104
1202
  }, []);
1203
+ const ownerRef = React.useRef(null);
1204
+ const target = React.useCallback(() => (isOwner ? ownerRef.current : activeOwner(store)) ?? null, [isOwner, store]);
1105
1205
  const clearPasses = React.useCallback(() => {
1106
- store.setState({ passes: {} });
1107
- }, [store]);
1206
+ const owner = target();
1207
+ if (!owner) return;
1208
+ owner.passes = {};
1209
+ if (activeOwner(store) === owner) store.setState({ passes: {} });
1210
+ }, [store, target]);
1108
1211
  const reset = React.useCallback(() => {
1109
- store.setState({
1110
- renderPipeline: null,
1111
- passes: {}
1112
- });
1113
- extension.setRenderOverride(store, null);
1114
- scenePassCacheRef.current?.scenePass.dispose();
1115
- callbacksRanRef.current = false;
1116
- scenePassCacheRef.current = null;
1117
- forceScenePassRebuildRef.current = false;
1118
- }, [store]);
1212
+ const owner = target();
1213
+ if (!owner) return;
1214
+ releaseOwner(owner);
1215
+ if (owner === ownerRef.current) committedReads.current = null;
1216
+ }, [target]);
1119
1217
  const rebuild = React.useCallback(() => {
1120
- callbacksRanRef.current = false;
1121
- forceScenePassRebuildRef.current = true;
1122
- setRebuildVersion((v) => v + 1);
1123
- }, []);
1218
+ if (isOwner) rerun(true);
1219
+ else activeOwner(store)?.rebuild();
1220
+ }, [isOwner, rerun, store]);
1221
+ const hmrVersionRef = React.useRef(hmrVersion);
1222
+ React.useEffect(() => {
1223
+ if (hmrVersionRef.current === hmrVersion) return;
1224
+ hmrVersionRef.current = hmrVersion;
1225
+ if (isOwner) rerun(false);
1226
+ }, [hmrVersion, isOwner, rerun]);
1227
+ const committedReads = React.useRef(null);
1228
+ const readsVersion = React.useRef(0);
1229
+ const getReadsVersion = () => {
1230
+ const tracker = committedReads.current;
1231
+ if (tracker && !tracker.stale && isTrackerStale(tracker, view)) readsVersion.current++;
1232
+ return readsVersion.current;
1233
+ };
1234
+ const subscribe = React.useCallback(
1235
+ (onChange) => {
1236
+ const unsubscribe = primary.subscribe(onChange);
1237
+ if (store === primary) return unsubscribe;
1238
+ const unsubscribeLocal = store.subscribe(onChange);
1239
+ return () => {
1240
+ unsubscribe();
1241
+ unsubscribeLocal();
1242
+ };
1243
+ },
1244
+ [primary, store]
1245
+ );
1246
+ const resourceVersion = React.useSyncExternalStore(subscribe, getReadsVersion, getReadsVersion);
1247
+ const lastResourceVersion = React.useRef(resourceVersion);
1124
1248
  React.useLayoutEffect(() => {
1125
1249
  if (isLegacy) {
1126
- throw new Error("useRenderPipeline is only available with WebGPU renderer. Set renderer prop on Canvas.");
1250
+ throw new Error(
1251
+ "useRenderPipeline needs WebGPU: import Canvas from @react-three/fiber, not @react-three/fiber/legacy."
1252
+ );
1127
1253
  }
1254
+ if (!isOwner) return;
1128
1255
  if (!renderer || !scene || !camera) return;
1129
1256
  if (!("isWebGPURenderer" in renderer)) {
1130
1257
  throw new Error("useRenderPipeline: renderer is not a WebGPURenderer but isLegacy is false.");
1131
1258
  }
1132
- const state = store.getState();
1133
- const set = store.setState;
1259
+ let owner = ownerRef.current;
1260
+ if (owner && owner.store !== store) {
1261
+ releaseOwner(owner);
1262
+ owner = null;
1263
+ }
1264
+ if (!owner) owner = ownerRef.current = createOwner(store, () => rerun(true));
1265
+ claimOwnership(owner);
1266
+ const currentOwner = owner;
1134
1267
  try {
1135
- let pipeline = state.renderPipeline ?? null;
1136
- let currentPasses = { ...state.passes };
1137
1268
  let justCreatedPipeline = false;
1138
- if (!pipeline) {
1139
- pipeline = new THREE__namespace.RenderPipeline(renderer);
1269
+ if (!owner.pipeline || owner.pipeline.renderer !== renderer) {
1270
+ disposeOwnerResources(owner);
1271
+ owner.pipeline = new THREE__namespace.RenderPipeline(renderer);
1140
1272
  justCreatedPipeline = true;
1141
1273
  }
1142
- const cacheValid = !forceScenePassRebuildRef.current && scenePassCacheRef.current && scenePassCacheRef.current.sceneUuid === scene.uuid && scenePassCacheRef.current.cameraUuid === camera.uuid;
1274
+ const pipeline = owner.pipeline;
1275
+ const cached = owner.scenePass;
1276
+ const cacheValid = !forceScenePassRebuildRef.current && cached !== null && cached.sceneUuid === scene.uuid && cached.cameraUuid === camera.uuid;
1143
1277
  let outgoingScenePass = null;
1144
1278
  let scenePass;
1145
- if (cacheValid) {
1146
- scenePass = scenePassCacheRef.current.scenePass;
1279
+ if (cacheValid && cached) {
1280
+ scenePass = cached.node;
1147
1281
  } else {
1148
- outgoingScenePass = scenePassCacheRef.current?.scenePass ?? null;
1282
+ outgoingScenePass = cached?.node ?? null;
1149
1283
  scenePass = tsl.pass(scene, camera);
1150
- scenePassCacheRef.current = { sceneUuid: scene.uuid, cameraUuid: camera.uuid, scenePass };
1284
+ owner.scenePass = { sceneUuid: scene.uuid, cameraUuid: camera.uuid, node: scenePass };
1151
1285
  forceScenePassRebuildRef.current = false;
1152
1286
  }
1153
- currentPasses.scenePass = scenePass;
1154
1287
  let outputNodeChanged = false;
1155
1288
  if (!pipeline.outputNode || justCreatedPipeline || pipeline.outputNode === outgoingScenePass) {
1156
1289
  pipeline.outputNode = scenePass;
1157
1290
  outputNodeChanged = true;
1158
1291
  }
1159
- set({ renderPipeline: pipeline, passes: currentPasses });
1160
- extension.setRenderOverride(store, renderThroughPipeline(store));
1161
- const shouldRunCallbacks = justCreatedPipeline || !callbacksRanRef.current || !cacheValid;
1292
+ const readsChanged = lastResourceVersion.current !== resourceVersion;
1293
+ lastResourceVersion.current = resourceVersion;
1294
+ const shouldRunCallbacks = justCreatedPipeline || !callbacksRanRef.current || !cacheValid || readsChanged;
1162
1295
  if (shouldRunCallbacks) {
1163
- if (setupCBRef.current) {
1164
- const freshState = Object.assign({}, store.getState(), {
1165
- renderPipeline: pipeline,
1166
- passes: { ...currentPasses, scenePass },
1167
- renderer,
1168
- isLegacy: false
1169
- });
1170
- const setupResult = setupCBRef.current(freshState);
1171
- if (setupResult && typeof setupResult === "object") {
1172
- currentPasses = { ...currentPasses, ...setupResult };
1173
- set({ passes: currentPasses });
1296
+ let currentPasses = { scenePass };
1297
+ owner.passes = currentPasses;
1298
+ const tracker = createReadTracker("useRenderPipeline");
1299
+ const callbackState = () => Object.assign(
1300
+ createLazyCreatorState(store.getState(), primary, {
1301
+ reads: { observe: tracker.observe, nested: true },
1302
+ view
1303
+ }),
1304
+ { renderPipeline: pipeline, passes: { ...currentPasses, scenePass }, renderer, isLegacy: false }
1305
+ );
1306
+ try {
1307
+ if (setupCBRef.current) {
1308
+ const setupResult = setupCBRef.current(callbackState());
1309
+ if (setupResult && typeof setupResult === "object") {
1310
+ currentPasses = { ...currentPasses, ...setupResult };
1311
+ owner.passes = currentPasses;
1312
+ }
1174
1313
  }
1175
- }
1176
- if (mainCBRef.current) {
1177
- const freshState = Object.assign({}, store.getState(), {
1178
- renderPipeline: pipeline,
1179
- passes: { ...currentPasses, scenePass },
1180
- renderer,
1181
- isLegacy: false
1182
- });
1183
- const mainResult = mainCBRef.current(freshState);
1184
- if (mainResult && typeof mainResult === "object") {
1185
- currentPasses = { ...currentPasses, ...mainResult };
1186
- set({ passes: currentPasses });
1314
+ if (mainCBRef.current) {
1315
+ const mainResult = mainCBRef.current(callbackState());
1316
+ if (mainResult && typeof mainResult === "object") {
1317
+ currentPasses = { ...currentPasses, ...mainResult };
1318
+ owner.passes = currentPasses;
1319
+ }
1187
1320
  }
1321
+ } finally {
1322
+ tracker.closed = true;
1323
+ committedReads.current = tracker;
1188
1324
  }
1189
1325
  outputNodeChanged = true;
1190
1326
  callbacksRanRef.current = true;
1191
1327
  }
1192
1328
  if (outputNodeChanged) pipeline.needsUpdate = true;
1329
+ publishOwner(owner);
1193
1330
  if (outgoingScenePass && outgoingScenePass !== scenePass) outgoingScenePass.dispose();
1194
1331
  } catch (error) {
1332
+ publishOwner(owner);
1195
1333
  console.warn("[useRenderPipeline] Setup failed; the render pipeline was not configured:", error);
1196
1334
  }
1197
- }, [store, renderer, scene, camera, isLegacy, rebuildVersion]);
1335
+ return () => {
1336
+ if (persistRef.current) currentOwner.mounted = false;
1337
+ else scheduleRelease(currentOwner);
1338
+ };
1339
+ }, [store, primary, view, renderer, scene, camera, isLegacy, isOwner, rebuildVersion, resourceVersion, rerun]);
1198
1340
  const passes = extension.useThree((s) => s.passes) ?? NO_PASSES;
1199
1341
  const renderPipeline = extension.useThree((s) => s.renderPipeline) ?? null;
1200
1342
  const actions = { passes, clearPasses, reset, rebuild };
package/dist/index.d.cts CHANGED
@@ -154,17 +154,11 @@ interface TSLRootState {
154
154
  }
155
155
 
156
156
  // Every fiber entry shares one core, and so one RootState: augmenting it through the root entry
157
- // reaches /legacy, /webgpu and /extension as well.
157
+ // reaches /legacy and /extension as well.
158
158
  declare module '@react-three/fiber' {
159
159
  interface RootState extends TSLRootState {}
160
160
  }
161
161
 
162
- // /webgpu exports WebGPURootState as RootState. Augmenting the base state it extends reaches both,
163
- // and also the stores (useStore(), get(), primaryStore) typed with the base.
164
- declare module '@react-three/fiber/webgpu' {
165
- interface BaseRootState extends TSLRootState {}
166
- }
167
-
168
162
  declare module '@react-three/fiber/extension' {
169
163
  interface RootState extends TSLRootState {}
170
164
  }
@@ -418,13 +412,18 @@ declare global {
418
412
  /**
419
413
  * State passed to pipeline callbacks after the active pipeline has been created.
420
414
  *
415
+ * The same state `useNodes` / `useLocalNodes` creators get: `uniforms`, `nodes`, `buffers`,
416
+ * `gpuStorage` and `textures` are the wrapped views, entries staged earlier in the render
417
+ * included. Reads through them are tracked, so a read resource that appears, is replaced or is
418
+ * removed re-runs the callbacks.
419
+ *
421
420
  * `passes.scenePass` is required here: the hook installs the default scene pass before either
422
421
  * callback runs, so callbacks can use it without a guard or a cast.
423
422
  *
424
423
  * `renderer` is narrowed to `WebGPURenderer` and `isLegacy` to `false`: the hook throws under
425
424
  * the legacy renderer before either callback can run, so a callback never sees WebGL.
426
425
  */
427
- type RenderPipelineCallbackState = RootState & {
426
+ type RenderPipelineCallbackState = CreatorState & {
428
427
  renderPipeline: ThreeRenderPipeline
429
428
  passes: PassRecord & { scenePass: ScenePassNode }
430
429
  renderer: three_webgpu.WebGPURenderer
@@ -435,7 +434,7 @@ declare global {
435
434
  * What a callback may return to register entries into `state.passes`.
436
435
  *
437
436
  * `scenePass` is reserved. The hook owns that entry and its lifecycle: it caches the pass it
438
- * created, and `rebuild()` / `reset()` dispose that cached pass. A callback overwriting the
437
+ * created, and `rebuild()`, `reset()` and unmount dispose that cached pass. A callback overwriting the
439
438
  * store entry would leave the store pointing at a node the hook never disposes, and the hook
440
439
  * disposing a pass nothing references. So returning it is a type error.
441
440
  */
@@ -447,15 +446,31 @@ declare global {
447
446
  /** Main callback - runs second to configure outputNode, create effect passes */
448
447
  type RenderPipelineMainCallback = (state: RenderPipelineCallbackState) => RegisteredPasses | void
449
448
 
449
+ /** Options for a configuring useRenderPipeline call */
450
+ interface RenderPipelineOptions {
451
+ /**
452
+ * Keep the pipeline rendering after the component unmounts, until another component configures
453
+ * the canvas's pipeline, `reset()`, or the canvas unmounts. Off by default: an owner frees its
454
+ * pipeline and scene pass when it unmounts. A remount is a new owner with a new pipeline either way.
455
+ */
456
+ persist?: boolean
457
+ }
458
+
450
459
  /** The imperative half of useRenderPipeline's return value, present in every state */
451
460
  interface UseRenderPipelineActions {
452
461
  /** Current passes from state */
453
462
  passes: PassRecord
454
- /** Clear all passes from state */
463
+ /** Clear the passes record. From a reader, acts on the pipeline that is rendering. */
455
464
  clearPasses: () => void
456
- /** Reset RenderPipeline entirely (clears PP + passes) */
465
+ /**
466
+ * Free the pipeline and its scene pass now. The previous owner takes over, or the canvas
467
+ * goes back to plain rendering. From a reader, acts on the pipeline that is rendering.
468
+ */
457
469
  reset: () => void
458
- /** Re-run setup/main callbacks with current closure values */
470
+ /**
471
+ * Re-run setup/main callbacks with current closure values, against a fresh scene pass. From
472
+ * a reader, rebuilds the pipeline that is rendering.
473
+ */
459
474
  rebuild: () => void
460
475
  }
461
476
 
@@ -475,9 +490,9 @@ declare global {
475
490
  renderPipeline: ThreeRenderPipeline
476
491
  }
477
492
  | {
478
- /** False until the pipeline has been created */
493
+ /** False until a configuring call has created the pipeline */
479
494
  isReady: false
480
- /** Not initialized yet, or torn down by reset() */
495
+ /** No owner yet, or torn down by reset() or the owner unmounting */
481
496
  renderPipeline: null
482
497
  }
483
498
  )
@@ -1019,11 +1034,15 @@ declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: s
1019
1034
  * Hook for managing WebGPU RenderPipeline with automatic scenePass setup.
1020
1035
  *
1021
1036
  * Features:
1022
- * - Creates RenderPipeline instance if not exists
1023
- * - Creates default scenePass (no MRT) automatically
1024
- * - Callbacks receive full RootState for flexibility
1025
- * - No auto-cleanup on unmount - use reset() for explicit cleanup
1026
- * - Scene/camera changes trigger scenePass recreation
1037
+ * - A call with a callback owns the canvas's pipeline: it creates the pipeline and a default
1038
+ * scenePass (no MRT), and frees both when it unmounts (opt out with `persist`)
1039
+ * - A call without callbacks only reads: it never creates, keeps alive or frees the pipeline
1040
+ * - The most recently mounted owner renders; when it unmounts, the previous owner takes over again
1041
+ * - StrictMode and Fast Refresh remounts reuse the graph instead of rebuilding it
1042
+ * - Callbacks receive the same state as creators (`uniforms`, `nodes`, ... wrapped, including
1043
+ * entries staged earlier in the render), and their reads are tracked as in useLocalNodes: a read
1044
+ * resource that appears, is replaced or is removed re-runs them
1045
+ * - Callbacks re-run on a hot update (`_hmrVersion`), on scene/camera change and on rebuild()
1027
1046
  * - A replaced scenePass is disposed once the new graph is installed, so rebuild() does not
1028
1047
  * strand its render target (and MRT attachments) on the GPU
1029
1048
  * - Any run that changes the output node sets RenderPipeline.needsUpdate, so rebuild() actually
@@ -1031,6 +1050,7 @@ declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: s
1031
1050
  *
1032
1051
  * @param mainCB - Main callback to configure outputNode and create effect passes
1033
1052
  * @param setupCB - Optional setup callback to configure MRT on scenePass
1053
+ * @param options - `persist: true` keeps the pipeline after the component unmounts
1034
1054
  * @returns { passes, renderPipeline, clearPasses, reset, rebuild }
1035
1055
  *
1036
1056
  * @example
@@ -1056,7 +1076,7 @@ declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: s
1056
1076
  * const { renderPipeline, passes } = useRenderPipeline()
1057
1077
  * ```
1058
1078
  */
1059
- declare function useRenderPipeline(mainCB?: RenderPipelineMainCallback, setupCB?: RenderPipelineSetupCallback): UseRenderPipelineReturn;
1079
+ declare function useRenderPipeline(mainCB?: RenderPipelineMainCallback, setupCB?: RenderPipelineSetupCallback, options?: RenderPipelineOptions): UseRenderPipelineReturn;
1060
1080
 
1061
1081
  export { configureTSL, createScopedStore, rebuildAllBuffers, rebuildAllNodes, rebuildAllStorage, rebuildAllUniforms, useBuffers, useGPUStorage, useLocalNodes, useNodes, useRenderPipeline, useUniform, useUniforms };
1062
1082
  export type { AppBuffers, AppGPUStorage, AppNodes, AppUniforms, BufferCreator, BufferLike, BufferRecord, BufferStore, BuffersWithUtils, ClearBuffersFn, ClearNodesFn, ClearStorageFn, ClearUniformsFn, CreatorState, DisposeBuffersFn, DisposeStorageFn, FnNodeLike, LocalNodeCreator, LocalNodeInstall, LocalNodeInstaller, LooseNode, LooseNodeEntry, LooseNodeStore, NodeCreator, NodeLike, NodeRecord, NodeStore, NodesWithUtils, RebuildBuffersFn, RebuildNodesFn, RebuildStorageFn, RebuildUniformsFn, Register, RegisteredBufferScopes, RegisteredBuffers, RegisteredGPUStorage, RegisteredGPUStorageScopes, RegisteredNodeScopes, RegisteredNodes, RegisteredScopeUniforms, RegisteredScopes, RegisteredUniform, RegisteredUniforms, RemoveBuffersFn, RemoveNodesFn, RemoveStorageFn, RemoveUniformsFn, RootBufferInput, RootGPUStorageInput, RootNodeInput, RootUniformInput, ScopeBufferInput, ScopeGPUStorageInput, ScopeNodeInput, ScopeUniformInput, ScopedStoreType, StorageCreator, StorageLike, StorageRecord, StorageStore, StorageWithUtils, TSLConfig, TSLNode, TSLNodeLike, TSLRootState, UniformCreator, UniformValue, UniformsWithUtils };
package/dist/index.d.mts CHANGED
@@ -154,17 +154,11 @@ interface TSLRootState {
154
154
  }
155
155
 
156
156
  // Every fiber entry shares one core, and so one RootState: augmenting it through the root entry
157
- // reaches /legacy, /webgpu and /extension as well.
157
+ // reaches /legacy and /extension as well.
158
158
  declare module '@react-three/fiber' {
159
159
  interface RootState extends TSLRootState {}
160
160
  }
161
161
 
162
- // /webgpu exports WebGPURootState as RootState. Augmenting the base state it extends reaches both,
163
- // and also the stores (useStore(), get(), primaryStore) typed with the base.
164
- declare module '@react-three/fiber/webgpu' {
165
- interface BaseRootState extends TSLRootState {}
166
- }
167
-
168
162
  declare module '@react-three/fiber/extension' {
169
163
  interface RootState extends TSLRootState {}
170
164
  }
@@ -418,13 +412,18 @@ declare global {
418
412
  /**
419
413
  * State passed to pipeline callbacks after the active pipeline has been created.
420
414
  *
415
+ * The same state `useNodes` / `useLocalNodes` creators get: `uniforms`, `nodes`, `buffers`,
416
+ * `gpuStorage` and `textures` are the wrapped views, entries staged earlier in the render
417
+ * included. Reads through them are tracked, so a read resource that appears, is replaced or is
418
+ * removed re-runs the callbacks.
419
+ *
421
420
  * `passes.scenePass` is required here: the hook installs the default scene pass before either
422
421
  * callback runs, so callbacks can use it without a guard or a cast.
423
422
  *
424
423
  * `renderer` is narrowed to `WebGPURenderer` and `isLegacy` to `false`: the hook throws under
425
424
  * the legacy renderer before either callback can run, so a callback never sees WebGL.
426
425
  */
427
- type RenderPipelineCallbackState = RootState & {
426
+ type RenderPipelineCallbackState = CreatorState & {
428
427
  renderPipeline: ThreeRenderPipeline
429
428
  passes: PassRecord & { scenePass: ScenePassNode }
430
429
  renderer: three_webgpu.WebGPURenderer
@@ -435,7 +434,7 @@ declare global {
435
434
  * What a callback may return to register entries into `state.passes`.
436
435
  *
437
436
  * `scenePass` is reserved. The hook owns that entry and its lifecycle: it caches the pass it
438
- * created, and `rebuild()` / `reset()` dispose that cached pass. A callback overwriting the
437
+ * created, and `rebuild()`, `reset()` and unmount dispose that cached pass. A callback overwriting the
439
438
  * store entry would leave the store pointing at a node the hook never disposes, and the hook
440
439
  * disposing a pass nothing references. So returning it is a type error.
441
440
  */
@@ -447,15 +446,31 @@ declare global {
447
446
  /** Main callback - runs second to configure outputNode, create effect passes */
448
447
  type RenderPipelineMainCallback = (state: RenderPipelineCallbackState) => RegisteredPasses | void
449
448
 
449
+ /** Options for a configuring useRenderPipeline call */
450
+ interface RenderPipelineOptions {
451
+ /**
452
+ * Keep the pipeline rendering after the component unmounts, until another component configures
453
+ * the canvas's pipeline, `reset()`, or the canvas unmounts. Off by default: an owner frees its
454
+ * pipeline and scene pass when it unmounts. A remount is a new owner with a new pipeline either way.
455
+ */
456
+ persist?: boolean
457
+ }
458
+
450
459
  /** The imperative half of useRenderPipeline's return value, present in every state */
451
460
  interface UseRenderPipelineActions {
452
461
  /** Current passes from state */
453
462
  passes: PassRecord
454
- /** Clear all passes from state */
463
+ /** Clear the passes record. From a reader, acts on the pipeline that is rendering. */
455
464
  clearPasses: () => void
456
- /** Reset RenderPipeline entirely (clears PP + passes) */
465
+ /**
466
+ * Free the pipeline and its scene pass now. The previous owner takes over, or the canvas
467
+ * goes back to plain rendering. From a reader, acts on the pipeline that is rendering.
468
+ */
457
469
  reset: () => void
458
- /** Re-run setup/main callbacks with current closure values */
470
+ /**
471
+ * Re-run setup/main callbacks with current closure values, against a fresh scene pass. From
472
+ * a reader, rebuilds the pipeline that is rendering.
473
+ */
459
474
  rebuild: () => void
460
475
  }
461
476
 
@@ -475,9 +490,9 @@ declare global {
475
490
  renderPipeline: ThreeRenderPipeline
476
491
  }
477
492
  | {
478
- /** False until the pipeline has been created */
493
+ /** False until a configuring call has created the pipeline */
479
494
  isReady: false
480
- /** Not initialized yet, or torn down by reset() */
495
+ /** No owner yet, or torn down by reset() or the owner unmounting */
481
496
  renderPipeline: null
482
497
  }
483
498
  )
@@ -1019,11 +1034,15 @@ declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: s
1019
1034
  * Hook for managing WebGPU RenderPipeline with automatic scenePass setup.
1020
1035
  *
1021
1036
  * Features:
1022
- * - Creates RenderPipeline instance if not exists
1023
- * - Creates default scenePass (no MRT) automatically
1024
- * - Callbacks receive full RootState for flexibility
1025
- * - No auto-cleanup on unmount - use reset() for explicit cleanup
1026
- * - Scene/camera changes trigger scenePass recreation
1037
+ * - A call with a callback owns the canvas's pipeline: it creates the pipeline and a default
1038
+ * scenePass (no MRT), and frees both when it unmounts (opt out with `persist`)
1039
+ * - A call without callbacks only reads: it never creates, keeps alive or frees the pipeline
1040
+ * - The most recently mounted owner renders; when it unmounts, the previous owner takes over again
1041
+ * - StrictMode and Fast Refresh remounts reuse the graph instead of rebuilding it
1042
+ * - Callbacks receive the same state as creators (`uniforms`, `nodes`, ... wrapped, including
1043
+ * entries staged earlier in the render), and their reads are tracked as in useLocalNodes: a read
1044
+ * resource that appears, is replaced or is removed re-runs them
1045
+ * - Callbacks re-run on a hot update (`_hmrVersion`), on scene/camera change and on rebuild()
1027
1046
  * - A replaced scenePass is disposed once the new graph is installed, so rebuild() does not
1028
1047
  * strand its render target (and MRT attachments) on the GPU
1029
1048
  * - Any run that changes the output node sets RenderPipeline.needsUpdate, so rebuild() actually
@@ -1031,6 +1050,7 @@ declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: s
1031
1050
  *
1032
1051
  * @param mainCB - Main callback to configure outputNode and create effect passes
1033
1052
  * @param setupCB - Optional setup callback to configure MRT on scenePass
1053
+ * @param options - `persist: true` keeps the pipeline after the component unmounts
1034
1054
  * @returns { passes, renderPipeline, clearPasses, reset, rebuild }
1035
1055
  *
1036
1056
  * @example
@@ -1056,7 +1076,7 @@ declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: s
1056
1076
  * const { renderPipeline, passes } = useRenderPipeline()
1057
1077
  * ```
1058
1078
  */
1059
- declare function useRenderPipeline(mainCB?: RenderPipelineMainCallback, setupCB?: RenderPipelineSetupCallback): UseRenderPipelineReturn;
1079
+ declare function useRenderPipeline(mainCB?: RenderPipelineMainCallback, setupCB?: RenderPipelineSetupCallback, options?: RenderPipelineOptions): UseRenderPipelineReturn;
1060
1080
 
1061
1081
  export { configureTSL, createScopedStore, rebuildAllBuffers, rebuildAllNodes, rebuildAllStorage, rebuildAllUniforms, useBuffers, useGPUStorage, useLocalNodes, useNodes, useRenderPipeline, useUniform, useUniforms };
1062
1082
  export type { AppBuffers, AppGPUStorage, AppNodes, AppUniforms, BufferCreator, BufferLike, BufferRecord, BufferStore, BuffersWithUtils, ClearBuffersFn, ClearNodesFn, ClearStorageFn, ClearUniformsFn, CreatorState, DisposeBuffersFn, DisposeStorageFn, FnNodeLike, LocalNodeCreator, LocalNodeInstall, LocalNodeInstaller, LooseNode, LooseNodeEntry, LooseNodeStore, NodeCreator, NodeLike, NodeRecord, NodeStore, NodesWithUtils, RebuildBuffersFn, RebuildNodesFn, RebuildStorageFn, RebuildUniformsFn, Register, RegisteredBufferScopes, RegisteredBuffers, RegisteredGPUStorage, RegisteredGPUStorageScopes, RegisteredNodeScopes, RegisteredNodes, RegisteredScopeUniforms, RegisteredScopes, RegisteredUniform, RegisteredUniforms, RemoveBuffersFn, RemoveNodesFn, RemoveStorageFn, RemoveUniformsFn, RootBufferInput, RootGPUStorageInput, RootNodeInput, RootUniformInput, ScopeBufferInput, ScopeGPUStorageInput, ScopeNodeInput, ScopeUniformInput, ScopedStoreType, StorageCreator, StorageLike, StorageRecord, StorageStore, StorageWithUtils, TSLConfig, TSLNode, TSLNodeLike, TSLRootState, UniformCreator, UniformValue, UniformsWithUtils };
package/dist/index.d.ts CHANGED
@@ -154,17 +154,11 @@ interface TSLRootState {
154
154
  }
155
155
 
156
156
  // Every fiber entry shares one core, and so one RootState: augmenting it through the root entry
157
- // reaches /legacy, /webgpu and /extension as well.
157
+ // reaches /legacy and /extension as well.
158
158
  declare module '@react-three/fiber' {
159
159
  interface RootState extends TSLRootState {}
160
160
  }
161
161
 
162
- // /webgpu exports WebGPURootState as RootState. Augmenting the base state it extends reaches both,
163
- // and also the stores (useStore(), get(), primaryStore) typed with the base.
164
- declare module '@react-three/fiber/webgpu' {
165
- interface BaseRootState extends TSLRootState {}
166
- }
167
-
168
162
  declare module '@react-three/fiber/extension' {
169
163
  interface RootState extends TSLRootState {}
170
164
  }
@@ -418,13 +412,18 @@ declare global {
418
412
  /**
419
413
  * State passed to pipeline callbacks after the active pipeline has been created.
420
414
  *
415
+ * The same state `useNodes` / `useLocalNodes` creators get: `uniforms`, `nodes`, `buffers`,
416
+ * `gpuStorage` and `textures` are the wrapped views, entries staged earlier in the render
417
+ * included. Reads through them are tracked, so a read resource that appears, is replaced or is
418
+ * removed re-runs the callbacks.
419
+ *
421
420
  * `passes.scenePass` is required here: the hook installs the default scene pass before either
422
421
  * callback runs, so callbacks can use it without a guard or a cast.
423
422
  *
424
423
  * `renderer` is narrowed to `WebGPURenderer` and `isLegacy` to `false`: the hook throws under
425
424
  * the legacy renderer before either callback can run, so a callback never sees WebGL.
426
425
  */
427
- type RenderPipelineCallbackState = RootState & {
426
+ type RenderPipelineCallbackState = CreatorState & {
428
427
  renderPipeline: ThreeRenderPipeline
429
428
  passes: PassRecord & { scenePass: ScenePassNode }
430
429
  renderer: three_webgpu.WebGPURenderer
@@ -435,7 +434,7 @@ declare global {
435
434
  * What a callback may return to register entries into `state.passes`.
436
435
  *
437
436
  * `scenePass` is reserved. The hook owns that entry and its lifecycle: it caches the pass it
438
- * created, and `rebuild()` / `reset()` dispose that cached pass. A callback overwriting the
437
+ * created, and `rebuild()`, `reset()` and unmount dispose that cached pass. A callback overwriting the
439
438
  * store entry would leave the store pointing at a node the hook never disposes, and the hook
440
439
  * disposing a pass nothing references. So returning it is a type error.
441
440
  */
@@ -447,15 +446,31 @@ declare global {
447
446
  /** Main callback - runs second to configure outputNode, create effect passes */
448
447
  type RenderPipelineMainCallback = (state: RenderPipelineCallbackState) => RegisteredPasses | void
449
448
 
449
+ /** Options for a configuring useRenderPipeline call */
450
+ interface RenderPipelineOptions {
451
+ /**
452
+ * Keep the pipeline rendering after the component unmounts, until another component configures
453
+ * the canvas's pipeline, `reset()`, or the canvas unmounts. Off by default: an owner frees its
454
+ * pipeline and scene pass when it unmounts. A remount is a new owner with a new pipeline either way.
455
+ */
456
+ persist?: boolean
457
+ }
458
+
450
459
  /** The imperative half of useRenderPipeline's return value, present in every state */
451
460
  interface UseRenderPipelineActions {
452
461
  /** Current passes from state */
453
462
  passes: PassRecord
454
- /** Clear all passes from state */
463
+ /** Clear the passes record. From a reader, acts on the pipeline that is rendering. */
455
464
  clearPasses: () => void
456
- /** Reset RenderPipeline entirely (clears PP + passes) */
465
+ /**
466
+ * Free the pipeline and its scene pass now. The previous owner takes over, or the canvas
467
+ * goes back to plain rendering. From a reader, acts on the pipeline that is rendering.
468
+ */
457
469
  reset: () => void
458
- /** Re-run setup/main callbacks with current closure values */
470
+ /**
471
+ * Re-run setup/main callbacks with current closure values, against a fresh scene pass. From
472
+ * a reader, rebuilds the pipeline that is rendering.
473
+ */
459
474
  rebuild: () => void
460
475
  }
461
476
 
@@ -475,9 +490,9 @@ declare global {
475
490
  renderPipeline: ThreeRenderPipeline
476
491
  }
477
492
  | {
478
- /** False until the pipeline has been created */
493
+ /** False until a configuring call has created the pipeline */
479
494
  isReady: false
480
- /** Not initialized yet, or torn down by reset() */
495
+ /** No owner yet, or torn down by reset() or the owner unmounting */
481
496
  renderPipeline: null
482
497
  }
483
498
  )
@@ -1019,11 +1034,15 @@ declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: s
1019
1034
  * Hook for managing WebGPU RenderPipeline with automatic scenePass setup.
1020
1035
  *
1021
1036
  * Features:
1022
- * - Creates RenderPipeline instance if not exists
1023
- * - Creates default scenePass (no MRT) automatically
1024
- * - Callbacks receive full RootState for flexibility
1025
- * - No auto-cleanup on unmount - use reset() for explicit cleanup
1026
- * - Scene/camera changes trigger scenePass recreation
1037
+ * - A call with a callback owns the canvas's pipeline: it creates the pipeline and a default
1038
+ * scenePass (no MRT), and frees both when it unmounts (opt out with `persist`)
1039
+ * - A call without callbacks only reads: it never creates, keeps alive or frees the pipeline
1040
+ * - The most recently mounted owner renders; when it unmounts, the previous owner takes over again
1041
+ * - StrictMode and Fast Refresh remounts reuse the graph instead of rebuilding it
1042
+ * - Callbacks receive the same state as creators (`uniforms`, `nodes`, ... wrapped, including
1043
+ * entries staged earlier in the render), and their reads are tracked as in useLocalNodes: a read
1044
+ * resource that appears, is replaced or is removed re-runs them
1045
+ * - Callbacks re-run on a hot update (`_hmrVersion`), on scene/camera change and on rebuild()
1027
1046
  * - A replaced scenePass is disposed once the new graph is installed, so rebuild() does not
1028
1047
  * strand its render target (and MRT attachments) on the GPU
1029
1048
  * - Any run that changes the output node sets RenderPipeline.needsUpdate, so rebuild() actually
@@ -1031,6 +1050,7 @@ declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: s
1031
1050
  *
1032
1051
  * @param mainCB - Main callback to configure outputNode and create effect passes
1033
1052
  * @param setupCB - Optional setup callback to configure MRT on scenePass
1053
+ * @param options - `persist: true` keeps the pipeline after the component unmounts
1034
1054
  * @returns { passes, renderPipeline, clearPasses, reset, rebuild }
1035
1055
  *
1036
1056
  * @example
@@ -1056,7 +1076,7 @@ declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: s
1056
1076
  * const { renderPipeline, passes } = useRenderPipeline()
1057
1077
  * ```
1058
1078
  */
1059
- declare function useRenderPipeline(mainCB?: RenderPipelineMainCallback, setupCB?: RenderPipelineSetupCallback): UseRenderPipelineReturn;
1079
+ declare function useRenderPipeline(mainCB?: RenderPipelineMainCallback, setupCB?: RenderPipelineSetupCallback, options?: RenderPipelineOptions): UseRenderPipelineReturn;
1060
1080
 
1061
1081
  export { configureTSL, createScopedStore, rebuildAllBuffers, rebuildAllNodes, rebuildAllStorage, rebuildAllUniforms, useBuffers, useGPUStorage, useLocalNodes, useNodes, useRenderPipeline, useUniform, useUniforms };
1062
1082
  export type { AppBuffers, AppGPUStorage, AppNodes, AppUniforms, BufferCreator, BufferLike, BufferRecord, BufferStore, BuffersWithUtils, ClearBuffersFn, ClearNodesFn, ClearStorageFn, ClearUniformsFn, CreatorState, DisposeBuffersFn, DisposeStorageFn, FnNodeLike, LocalNodeCreator, LocalNodeInstall, LocalNodeInstaller, LooseNode, LooseNodeEntry, LooseNodeStore, NodeCreator, NodeLike, NodeRecord, NodeStore, NodesWithUtils, RebuildBuffersFn, RebuildNodesFn, RebuildStorageFn, RebuildUniformsFn, Register, RegisteredBufferScopes, RegisteredBuffers, RegisteredGPUStorage, RegisteredGPUStorageScopes, RegisteredNodeScopes, RegisteredNodes, RegisteredScopeUniforms, RegisteredScopes, RegisteredUniform, RegisteredUniforms, RemoveBuffersFn, RemoveNodesFn, RemoveStorageFn, RemoveUniformsFn, RootBufferInput, RootGPUStorageInput, RootNodeInput, RootUniformInput, ScopeBufferInput, ScopeGPUStorageInput, ScopeNodeInput, ScopeUniformInput, ScopedStoreType, StorageCreator, StorageLike, StorageRecord, StorageStore, StorageWithUtils, TSLConfig, TSLNode, TSLNodeLike, TSLRootState, UniformCreator, UniformValue, UniformsWithUtils };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { registerRootExtension, getTextureView, useStore, useThree, setRenderOverride } from '@react-three/fiber/extension';
1
+ import { setRenderOverride, registerRootExtension, getTextureView, useStore, useThree } from '@react-three/fiber/extension';
2
2
  import { uniform, pass } from 'three/tsl';
3
3
  import * as THREE from 'three/webgpu';
4
4
  import { Color } from 'three/webgpu';
@@ -263,6 +263,103 @@ function configureTSL(next) {
263
263
  for (const store of primaries) applyConfig(store, config);
264
264
  }
265
265
 
266
+ const owners = /* @__PURE__ */ new WeakMap();
267
+ const warned$1 = /* @__PURE__ */ new WeakSet();
268
+ const sweeps = /* @__PURE__ */ new WeakMap();
269
+ function createOwner(store, rebuild) {
270
+ return { store, pipeline: null, scenePass: null, passes: {}, mounted: false, releaseTimer: null, rebuild };
271
+ }
272
+ function disposeOwnerResources(owner) {
273
+ owner.scenePass?.node.dispose();
274
+ owner.pipeline?.dispose();
275
+ owner.scenePass = null;
276
+ owner.pipeline = null;
277
+ owner.passes = {};
278
+ }
279
+ function activeOwner(store) {
280
+ return owners.get(store)?.at(-1);
281
+ }
282
+ function renderThroughPipeline(store) {
283
+ return () => {
284
+ const pipeline = store.getState().renderPipeline;
285
+ if (pipeline?.render) pipeline.render();
286
+ };
287
+ }
288
+ function claimOwnership(owner) {
289
+ if (owner.releaseTimer !== null) clearTimeout(owner.releaseTimer);
290
+ owner.releaseTimer = null;
291
+ owner.mounted = true;
292
+ let list = owners.get(owner.store);
293
+ if (!list) owners.set(owner.store, list = []);
294
+ if (list.includes(owner)) return;
295
+ if (list.some((other) => other.mounted) && !warned$1.has(owner.store)) {
296
+ warned$1.add(owner.store);
297
+ if (typeof process === "undefined" || process.env.NODE_ENV !== "production") {
298
+ console.warn(
299
+ "[useRenderPipeline] More than one mounted component configures this canvas's render pipeline. The most recently mounted one renders; the others take over again when it unmounts."
300
+ );
301
+ }
302
+ }
303
+ list.push(owner);
304
+ scheduleSweep(owner.store);
305
+ }
306
+ function scheduleSweep(store) {
307
+ if (sweeps.has(store)) return;
308
+ sweeps.set(
309
+ store,
310
+ setTimeout(() => {
311
+ sweeps.delete(store);
312
+ const active = activeOwner(store);
313
+ for (const owner of [...owners.get(store) ?? []]) {
314
+ if (owner !== active && !owner.mounted && owner.releaseTimer === null) releaseOwner(owner);
315
+ }
316
+ })
317
+ );
318
+ }
319
+ function publishOwner(owner) {
320
+ if (activeOwner(owner.store) !== owner || !owner.pipeline) return;
321
+ owner.store.setState({ renderPipeline: owner.pipeline, passes: owner.passes });
322
+ setRenderOverride(owner.store, renderThroughPipeline(owner.store));
323
+ }
324
+ function scheduleRelease(owner) {
325
+ owner.mounted = false;
326
+ if (owner.releaseTimer !== null) return;
327
+ owner.releaseTimer = setTimeout(() => releaseOwner(owner));
328
+ }
329
+ function releaseOwner(owner) {
330
+ if (owner.releaseTimer !== null) clearTimeout(owner.releaseTimer);
331
+ owner.releaseTimer = null;
332
+ const { store } = owner;
333
+ const list = owners.get(store);
334
+ const index = list?.indexOf(owner) ?? -1;
335
+ if (list && index !== -1) {
336
+ const wasActive = index === list.length - 1;
337
+ list.splice(index, 1);
338
+ if (wasActive) {
339
+ const next = activeOwner(store);
340
+ if (next) {
341
+ publishOwner(next);
342
+ } else {
343
+ store.setState({ renderPipeline: null, passes: {} });
344
+ setRenderOverride(store, null);
345
+ }
346
+ }
347
+ }
348
+ disposeOwnerResources(owner);
349
+ }
350
+ function releaseAllOwners(store) {
351
+ clearTimeout(sweeps.get(store));
352
+ sweeps.delete(store);
353
+ const list = owners.get(store);
354
+ if (!list) return;
355
+ owners.delete(store);
356
+ for (const owner of list) {
357
+ if (owner.releaseTimer !== null) clearTimeout(owner.releaseTimer);
358
+ owner.releaseTimer = null;
359
+ disposeOwnerResources(owner);
360
+ }
361
+ }
362
+
266
363
  const SHARED_KEYS = ["uniforms", "nodes", "buffers", "gpuStorage", "_hmrVersion"];
267
364
  const following = /* @__PURE__ */ new WeakMap();
268
365
  function createResourceState() {
@@ -291,6 +388,7 @@ function followPrimary(store, primary) {
291
388
  following.set(store, primary.subscribe(sync));
292
389
  }
293
390
  function dispose(store) {
391
+ releaseAllOwners(store);
294
392
  untrackPrimary(store);
295
393
  following.get(store)?.();
296
394
  following.delete(store);
@@ -1066,120 +1164,164 @@ function rebuildAllStorage(store, scope) {
1066
1164
  }
1067
1165
 
1068
1166
  const NO_PASSES = Object.freeze({});
1069
- function renderThroughPipeline(store) {
1070
- return () => {
1071
- const pipeline = store.getState().renderPipeline;
1072
- if (pipeline?.render) pipeline.render();
1073
- };
1074
- }
1075
- function useRenderPipeline(mainCB, setupCB) {
1167
+ function useRenderPipeline(mainCB, setupCB, options) {
1076
1168
  const store = useStore();
1169
+ const primary = usePrimaryStore();
1170
+ const view = useMemo(() => createResourceView(primary, store), [primary, store]);
1077
1171
  const { scene, camera, renderer, isLegacy } = useThree();
1172
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
1173
+ const isOwner = mainCB !== void 0 || setupCB !== void 0;
1078
1174
  const callbacksRanRef = useRef(false);
1079
- const scenePassCacheRef = useRef(null);
1080
1175
  const forceScenePassRebuildRef = useRef(false);
1081
1176
  const mainCBRef = useRef(mainCB);
1082
1177
  const setupCBRef = useRef(setupCB);
1178
+ const persistRef = useRef(options?.persist ?? false);
1083
1179
  mainCBRef.current = mainCB;
1084
1180
  setupCBRef.current = setupCB;
1181
+ persistRef.current = options?.persist ?? false;
1085
1182
  const [rebuildVersion, setRebuildVersion] = useState(0);
1086
- useEffect(() => {
1183
+ const rerun = useCallback((freshScenePass) => {
1087
1184
  callbacksRanRef.current = false;
1088
- forceScenePassRebuildRef.current = true;
1185
+ if (freshScenePass) forceScenePassRebuildRef.current = true;
1186
+ setRebuildVersion((v) => v + 1);
1089
1187
  }, []);
1188
+ const ownerRef = useRef(null);
1189
+ const target = useCallback(() => (isOwner ? ownerRef.current : activeOwner(store)) ?? null, [isOwner, store]);
1090
1190
  const clearPasses = useCallback(() => {
1091
- store.setState({ passes: {} });
1092
- }, [store]);
1191
+ const owner = target();
1192
+ if (!owner) return;
1193
+ owner.passes = {};
1194
+ if (activeOwner(store) === owner) store.setState({ passes: {} });
1195
+ }, [store, target]);
1093
1196
  const reset = useCallback(() => {
1094
- store.setState({
1095
- renderPipeline: null,
1096
- passes: {}
1097
- });
1098
- setRenderOverride(store, null);
1099
- scenePassCacheRef.current?.scenePass.dispose();
1100
- callbacksRanRef.current = false;
1101
- scenePassCacheRef.current = null;
1102
- forceScenePassRebuildRef.current = false;
1103
- }, [store]);
1197
+ const owner = target();
1198
+ if (!owner) return;
1199
+ releaseOwner(owner);
1200
+ if (owner === ownerRef.current) committedReads.current = null;
1201
+ }, [target]);
1104
1202
  const rebuild = useCallback(() => {
1105
- callbacksRanRef.current = false;
1106
- forceScenePassRebuildRef.current = true;
1107
- setRebuildVersion((v) => v + 1);
1108
- }, []);
1203
+ if (isOwner) rerun(true);
1204
+ else activeOwner(store)?.rebuild();
1205
+ }, [isOwner, rerun, store]);
1206
+ const hmrVersionRef = useRef(hmrVersion);
1207
+ useEffect(() => {
1208
+ if (hmrVersionRef.current === hmrVersion) return;
1209
+ hmrVersionRef.current = hmrVersion;
1210
+ if (isOwner) rerun(false);
1211
+ }, [hmrVersion, isOwner, rerun]);
1212
+ const committedReads = useRef(null);
1213
+ const readsVersion = useRef(0);
1214
+ const getReadsVersion = () => {
1215
+ const tracker = committedReads.current;
1216
+ if (tracker && !tracker.stale && isTrackerStale(tracker, view)) readsVersion.current++;
1217
+ return readsVersion.current;
1218
+ };
1219
+ const subscribe = useCallback(
1220
+ (onChange) => {
1221
+ const unsubscribe = primary.subscribe(onChange);
1222
+ if (store === primary) return unsubscribe;
1223
+ const unsubscribeLocal = store.subscribe(onChange);
1224
+ return () => {
1225
+ unsubscribe();
1226
+ unsubscribeLocal();
1227
+ };
1228
+ },
1229
+ [primary, store]
1230
+ );
1231
+ const resourceVersion = useSyncExternalStore(subscribe, getReadsVersion, getReadsVersion);
1232
+ const lastResourceVersion = useRef(resourceVersion);
1109
1233
  useLayoutEffect(() => {
1110
1234
  if (isLegacy) {
1111
- throw new Error("useRenderPipeline is only available with WebGPU renderer. Set renderer prop on Canvas.");
1235
+ throw new Error(
1236
+ "useRenderPipeline needs WebGPU: import Canvas from @react-three/fiber, not @react-three/fiber/legacy."
1237
+ );
1112
1238
  }
1239
+ if (!isOwner) return;
1113
1240
  if (!renderer || !scene || !camera) return;
1114
1241
  if (!("isWebGPURenderer" in renderer)) {
1115
1242
  throw new Error("useRenderPipeline: renderer is not a WebGPURenderer but isLegacy is false.");
1116
1243
  }
1117
- const state = store.getState();
1118
- const set = store.setState;
1244
+ let owner = ownerRef.current;
1245
+ if (owner && owner.store !== store) {
1246
+ releaseOwner(owner);
1247
+ owner = null;
1248
+ }
1249
+ if (!owner) owner = ownerRef.current = createOwner(store, () => rerun(true));
1250
+ claimOwnership(owner);
1251
+ const currentOwner = owner;
1119
1252
  try {
1120
- let pipeline = state.renderPipeline ?? null;
1121
- let currentPasses = { ...state.passes };
1122
1253
  let justCreatedPipeline = false;
1123
- if (!pipeline) {
1124
- pipeline = new THREE.RenderPipeline(renderer);
1254
+ if (!owner.pipeline || owner.pipeline.renderer !== renderer) {
1255
+ disposeOwnerResources(owner);
1256
+ owner.pipeline = new THREE.RenderPipeline(renderer);
1125
1257
  justCreatedPipeline = true;
1126
1258
  }
1127
- const cacheValid = !forceScenePassRebuildRef.current && scenePassCacheRef.current && scenePassCacheRef.current.sceneUuid === scene.uuid && scenePassCacheRef.current.cameraUuid === camera.uuid;
1259
+ const pipeline = owner.pipeline;
1260
+ const cached = owner.scenePass;
1261
+ const cacheValid = !forceScenePassRebuildRef.current && cached !== null && cached.sceneUuid === scene.uuid && cached.cameraUuid === camera.uuid;
1128
1262
  let outgoingScenePass = null;
1129
1263
  let scenePass;
1130
- if (cacheValid) {
1131
- scenePass = scenePassCacheRef.current.scenePass;
1264
+ if (cacheValid && cached) {
1265
+ scenePass = cached.node;
1132
1266
  } else {
1133
- outgoingScenePass = scenePassCacheRef.current?.scenePass ?? null;
1267
+ outgoingScenePass = cached?.node ?? null;
1134
1268
  scenePass = pass(scene, camera);
1135
- scenePassCacheRef.current = { sceneUuid: scene.uuid, cameraUuid: camera.uuid, scenePass };
1269
+ owner.scenePass = { sceneUuid: scene.uuid, cameraUuid: camera.uuid, node: scenePass };
1136
1270
  forceScenePassRebuildRef.current = false;
1137
1271
  }
1138
- currentPasses.scenePass = scenePass;
1139
1272
  let outputNodeChanged = false;
1140
1273
  if (!pipeline.outputNode || justCreatedPipeline || pipeline.outputNode === outgoingScenePass) {
1141
1274
  pipeline.outputNode = scenePass;
1142
1275
  outputNodeChanged = true;
1143
1276
  }
1144
- set({ renderPipeline: pipeline, passes: currentPasses });
1145
- setRenderOverride(store, renderThroughPipeline(store));
1146
- const shouldRunCallbacks = justCreatedPipeline || !callbacksRanRef.current || !cacheValid;
1277
+ const readsChanged = lastResourceVersion.current !== resourceVersion;
1278
+ lastResourceVersion.current = resourceVersion;
1279
+ const shouldRunCallbacks = justCreatedPipeline || !callbacksRanRef.current || !cacheValid || readsChanged;
1147
1280
  if (shouldRunCallbacks) {
1148
- if (setupCBRef.current) {
1149
- const freshState = Object.assign({}, store.getState(), {
1150
- renderPipeline: pipeline,
1151
- passes: { ...currentPasses, scenePass },
1152
- renderer,
1153
- isLegacy: false
1154
- });
1155
- const setupResult = setupCBRef.current(freshState);
1156
- if (setupResult && typeof setupResult === "object") {
1157
- currentPasses = { ...currentPasses, ...setupResult };
1158
- set({ passes: currentPasses });
1281
+ let currentPasses = { scenePass };
1282
+ owner.passes = currentPasses;
1283
+ const tracker = createReadTracker("useRenderPipeline");
1284
+ const callbackState = () => Object.assign(
1285
+ createLazyCreatorState(store.getState(), primary, {
1286
+ reads: { observe: tracker.observe, nested: true },
1287
+ view
1288
+ }),
1289
+ { renderPipeline: pipeline, passes: { ...currentPasses, scenePass }, renderer, isLegacy: false }
1290
+ );
1291
+ try {
1292
+ if (setupCBRef.current) {
1293
+ const setupResult = setupCBRef.current(callbackState());
1294
+ if (setupResult && typeof setupResult === "object") {
1295
+ currentPasses = { ...currentPasses, ...setupResult };
1296
+ owner.passes = currentPasses;
1297
+ }
1159
1298
  }
1160
- }
1161
- if (mainCBRef.current) {
1162
- const freshState = Object.assign({}, store.getState(), {
1163
- renderPipeline: pipeline,
1164
- passes: { ...currentPasses, scenePass },
1165
- renderer,
1166
- isLegacy: false
1167
- });
1168
- const mainResult = mainCBRef.current(freshState);
1169
- if (mainResult && typeof mainResult === "object") {
1170
- currentPasses = { ...currentPasses, ...mainResult };
1171
- set({ passes: currentPasses });
1299
+ if (mainCBRef.current) {
1300
+ const mainResult = mainCBRef.current(callbackState());
1301
+ if (mainResult && typeof mainResult === "object") {
1302
+ currentPasses = { ...currentPasses, ...mainResult };
1303
+ owner.passes = currentPasses;
1304
+ }
1172
1305
  }
1306
+ } finally {
1307
+ tracker.closed = true;
1308
+ committedReads.current = tracker;
1173
1309
  }
1174
1310
  outputNodeChanged = true;
1175
1311
  callbacksRanRef.current = true;
1176
1312
  }
1177
1313
  if (outputNodeChanged) pipeline.needsUpdate = true;
1314
+ publishOwner(owner);
1178
1315
  if (outgoingScenePass && outgoingScenePass !== scenePass) outgoingScenePass.dispose();
1179
1316
  } catch (error) {
1317
+ publishOwner(owner);
1180
1318
  console.warn("[useRenderPipeline] Setup failed; the render pipeline was not configured:", error);
1181
1319
  }
1182
- }, [store, renderer, scene, camera, isLegacy, rebuildVersion]);
1320
+ return () => {
1321
+ if (persistRef.current) currentOwner.mounted = false;
1322
+ else scheduleRelease(currentOwner);
1323
+ };
1324
+ }, [store, primary, view, renderer, scene, camera, isLegacy, isOwner, rebuildVersion, resourceVersion, rerun]);
1183
1325
  const passes = useThree((s) => s.passes) ?? NO_PASSES;
1184
1326
  const renderPipeline = useThree((s) => s.renderPipeline) ?? null;
1185
1327
  const actions = { passes, clearPasses, reset, rebuild };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@react-three/tsl",
3
- "version": "10.0.0-canary.d46ab63",
3
+ "version": "10.0.0-canary.d8aec34",
4
4
  "description": "TSL resource hooks for react-three-fiber: uniforms, nodes, buffers, GPU storage and render pipelines on WebGPU",
5
5
  "keywords": [
6
6
  "react",
@@ -56,7 +56,7 @@
56
56
  "@types/three": "^0.185.0",
57
57
  "@webgpu/types": "^0.1.64",
58
58
  "three": ">=0.185.0",
59
- "@react-three/fiber": "10.0.0-canary.d46ab63"
59
+ "@react-three/fiber": "10.0.0-canary.d8aec34"
60
60
  },
61
61
  "scripts": {
62
62
  "build": "unbuild",
package/readme.md CHANGED
@@ -3,7 +3,7 @@
3
3
  TSL resource hooks for [react-three-fiber](https://github.com/pmndrs/react-three-fiber) on WebGPU: shared uniforms, nodes, buffers, GPU storage and render pipelines.
4
4
 
5
5
  ```bash
6
- npm install @react-three/tsl
6
+ npm install @react-three/tsl@alpha
7
7
  ```
8
8
 
9
9
  ```tsx
@@ -32,7 +32,7 @@ function Driver() {
32
32
  }
33
33
 
34
34
  export const App = () => (
35
- <Canvas renderer>
35
+ <Canvas>
36
36
  <Wobble />
37
37
  <Driver />
38
38
  </Canvas>
@@ -48,6 +48,6 @@ export const App = () => (
48
48
 
49
49
  Resources belong to the renderer: a `<Canvas primary>`, the canvases sharing its renderer (every other WebGPU canvas, or `share="id"`) and every portal inside them share one set. They live on the primary canvas's `RootState` (`state.uniforms`, `state.nodes`, `state.buffers`, `state.gpuStorage`); secondaries hold the same objects and portals inherit them from their parent (a portal's scene and camera stay its own), so `state.uniforms` reads the same everywhere.
50
50
 
51
- Works under any Canvas that runs the WebGPU renderer: `@react-three/fiber` with the `renderer` prop, or `@react-three/fiber/webgpu`. It reaches fiber only through the three-free `@react-three/fiber/extension` entry, so it adds no renderer and no second copy of fiber to your bundle.
51
+ Works under any Canvas that runs the WebGPU renderer: `@react-three/fiber` (not `/legacy`). It reaches fiber only through the three-free `@react-three/fiber/extension` entry, so it adds no renderer and no second copy of fiber to your bundle.
52
52
 
53
53
  Full documentation: [WebGPU & TSL](https://github.com/pmndrs/react-three-fiber/tree/v10/docs/webgpu).