@react-three/fiber 10.0.0-canary.5c62eb9 → 10.0.0-canary.6d6e5ab

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.
@@ -63,13 +63,16 @@ const WebGLRenderer = class WebGLRenderer2 {
63
63
  }
64
64
  };
65
65
  const WebGLRenderTarget = null;
66
+ const WebGLCubeRenderTarget = null;
66
67
 
67
68
  const THREE = /*#__PURE__*/_mergeNamespaces({
68
69
  __proto__: null,
70
+ CubeRenderTargetCompat: webgpu.CubeRenderTarget,
69
71
  Inspector: Inspector_js.Inspector,
70
72
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
71
73
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
72
74
  RenderTargetCompat: webgpu.RenderTarget,
75
+ WebGLCubeRenderTarget: WebGLCubeRenderTarget,
73
76
  WebGLRenderTarget: WebGLRenderTarget,
74
77
  WebGLRenderer: WebGLRenderer
75
78
  }, [webgpu__namespace]);
@@ -343,15 +346,16 @@ function EnvironmentPortal({
343
346
  preset = void 0,
344
347
  extensions
345
348
  }) {
346
- const gl = fiber.useThree((state) => state.gl);
349
+ const renderer = fiber.useThree((state) => state.renderer);
350
+ const isLegacy = fiber.useThree((state) => state.isLegacy);
347
351
  const defaultScene = fiber.useThree((state) => state.scene);
348
352
  const camera = React__namespace.useRef(null);
349
353
  const [virtualScene] = React__namespace.useState(() => new webgpu.Scene());
350
354
  const fbo = React__namespace.useMemo(() => {
351
- const fbo2 = new webgpu.WebGLCubeRenderTarget(resolution);
355
+ const fbo2 = isLegacy ? new WebGLCubeRenderTarget(resolution) : new webgpu.CubeRenderTarget(resolution);
352
356
  fbo2.texture.type = webgpu.HalfFloatType;
353
357
  return fbo2;
354
- }, [resolution]);
358
+ }, [resolution, isLegacy]);
355
359
  React__namespace.useEffect(() => {
356
360
  return () => {
357
361
  fbo.dispose();
@@ -359,10 +363,10 @@ function EnvironmentPortal({
359
363
  }, [fbo]);
360
364
  React__namespace.useLayoutEffect(() => {
361
365
  if (frames === 1) {
362
- const autoClear = gl.autoClear;
363
- gl.autoClear = true;
364
- camera.current.update(gl, virtualScene);
365
- gl.autoClear = autoClear;
366
+ const autoClear = renderer.autoClear;
367
+ renderer.autoClear = true;
368
+ camera.current.update(renderer, virtualScene);
369
+ renderer.autoClear = autoClear;
366
370
  }
367
371
  return setEnvProps(background, scene, defaultScene, fbo.texture, {
368
372
  backgroundBlurriness: blur ?? backgroundBlurriness,
@@ -379,7 +383,7 @@ function EnvironmentPortal({
379
383
  defaultScene,
380
384
  background,
381
385
  frames,
382
- gl,
386
+ renderer,
383
387
  blur,
384
388
  backgroundBlurriness,
385
389
  backgroundIntensity,
@@ -390,10 +394,10 @@ function EnvironmentPortal({
390
394
  let count = 1;
391
395
  fiber.useFrame(() => {
392
396
  if (frames === Infinity || count < frames) {
393
- const autoClear = gl.autoClear;
394
- gl.autoClear = true;
395
- camera.current.update(gl, virtualScene);
396
- gl.autoClear = autoClear;
397
+ const autoClear = renderer.autoClear;
398
+ renderer.autoClear = true;
399
+ camera.current.update(renderer, virtualScene);
400
+ renderer.autoClear = autoClear;
397
401
  count++;
398
402
  }
399
403
  });
@@ -460,7 +464,6 @@ function Environment(props) {
460
464
  var __defProp$1 = Object.defineProperty;
461
465
  var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
462
466
  var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
463
- const act = React__namespace["act"];
464
467
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
465
468
  function useMutableCallback(fn) {
466
469
  const ref = React__namespace.useRef(fn);
@@ -636,8 +639,7 @@ function prepare(target, root, type, props) {
636
639
  object,
637
640
  eventCount: 0,
638
641
  handlers: {},
639
- isHidden: false,
640
- deferredRefs: []
642
+ isHidden: false
641
643
  };
642
644
  if (object) object.__r3f = instance;
643
645
  }
@@ -794,6 +796,17 @@ function unregisterVisibility(store, object) {
794
796
  internal.visibilityRegistry.delete(object.uuid);
795
797
  internal.occlusionCache.delete(object);
796
798
  }
799
+ function updateVisibilityHandlers(store, object, handlers) {
800
+ const { internal } = store.getState();
801
+ const entry = internal.visibilityRegistry.get(object.uuid);
802
+ if (!entry) return false;
803
+ entry.handlers = handlers;
804
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
805
+ object.occlusionTest = true;
806
+ enableOcclusion(store);
807
+ }
808
+ return true;
809
+ }
797
810
  function checkVisibility(state) {
798
811
  const { internal, camera } = state;
799
812
  const registry = internal.visibilityRegistry;
@@ -954,9 +967,9 @@ function diffProps(instance, newProps) {
954
967
  const { root, key } = resolve(instance.object, prop);
955
968
  if (root.constructor && root.constructor.length === 0) {
956
969
  const ctor = getMemoizedPrototype(root);
957
- if (!is.und(ctor)) changedProps[key] = ctor[key];
970
+ if (!is.und(ctor)) changedProps[prop] = ctor[key];
958
971
  } else {
959
- changedProps[key] = 0;
972
+ changedProps[prop] = 0;
960
973
  }
961
974
  }
962
975
  return changedProps;
@@ -981,10 +994,7 @@ function applyProps(object, props) {
981
994
  continue;
982
995
  }
983
996
  if (value === void 0) continue;
984
- if (isFromRef(value)) {
985
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
986
- continue;
987
- }
997
+ if (isFromRef(value)) continue;
988
998
  if (isOnce(value)) {
989
999
  if (instance?.appliedOnce?.has(prop)) continue;
990
1000
  if (instance) {
@@ -1020,6 +1030,19 @@ function applyProps(object, props) {
1020
1030
  } else if (isVectorLike(target) && is.num(value)) {
1021
1031
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
1022
1032
  else target.set(value);
1033
+ } else if (root instanceof webgpu.ShaderMaterial && key === "uniforms" && is.obj(value)) {
1034
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1035
+ const uniforms = root.uniforms;
1036
+ const nextUniforms = value;
1037
+ for (const name in nextUniforms) {
1038
+ const uniform = nextUniforms[name];
1039
+ const targetUniform = uniforms[name];
1040
+ if (targetUniform) Object.assign(targetUniform, uniform);
1041
+ else {
1042
+ const nextUniform = uniform instanceof webgpu.Uniform ? uniform.clone() : new webgpu.Uniform(uniform.value);
1043
+ uniforms[name] = nextUniform;
1044
+ }
1045
+ }
1023
1046
  } else {
1024
1047
  root[key] = value;
1025
1048
  if (key.endsWith("Node") && root.isMaterial) {
@@ -1038,6 +1061,9 @@ function applyProps(object, props) {
1038
1061
  if (instance.eventCount && object2.raycast !== null) {
1039
1062
  rootState.internal.interaction.push(object2);
1040
1063
  }
1064
+ }
1065
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1066
+ const object2 = instance.object;
1041
1067
  const root = findInitialRoot(instance);
1042
1068
  const visibilityHandlers = {
1043
1069
  onFramed: instance.handlers.onFramed,
@@ -1045,7 +1071,9 @@ function applyProps(object, props) {
1045
1071
  onVisible: instance.handlers.onVisible
1046
1072
  };
1047
1073
  if (hasVisibilityHandlers(visibilityHandlers)) {
1048
- registerVisibility(root, object2, visibilityHandlers);
1074
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1075
+ registerVisibility(root, object2, visibilityHandlers);
1076
+ }
1049
1077
  } else {
1050
1078
  unregisterVisibility(root, object2);
1051
1079
  }
@@ -1573,6 +1601,7 @@ function createPointerEvents(store) {
1573
1601
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1574
1602
  }
1575
1603
  },
1604
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1576
1605
  registerPointer: (config) => {
1577
1606
  const pointerId = nextXRPointerId++;
1578
1607
  xrPointers.set(pointerId, config);
@@ -1660,11 +1689,10 @@ function notifyAlpha({ message, link }) {
1660
1689
  }
1661
1690
 
1662
1691
  const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1663
- const INTERNAL_FIBER_MARKERS = ["packages/fiber/src", "packages/fiber/dist", "@react-three/fiber", "@react-three_fiber"];
1664
1692
  function isInternalRendererAccess(stack, callerDepth = 2) {
1665
1693
  if (!stack) return false;
1666
1694
  const caller = stack.split("\n")[callerDepth] ?? "";
1667
- return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m)) || INTERNAL_FIBER_MARKERS.some((m) => caller.includes(m));
1695
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
1668
1696
  }
1669
1697
 
1670
1698
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
@@ -1799,6 +1827,7 @@ const createStore = (invalidate, advance) => {
1799
1827
  }),
1800
1828
  setFrameloop: (frameloop = "always") => {
1801
1829
  set(() => ({ frameloop }));
1830
+ scheduler.getScheduler().frameloop = frameloop;
1802
1831
  },
1803
1832
  setError: (error) => set(() => ({ error })),
1804
1833
  error: null,
@@ -1979,19 +2008,25 @@ function loadingFn(extensions, onProgress) {
1979
2008
  );
1980
2009
  };
1981
2010
  }
1982
- function useLoader(loader, input, extensions, onProgress) {
1983
- const keys = Array.isArray(input) ? input : [input];
2011
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
2012
+ const inputs = Array.isArray(input) ? input : [input];
2013
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
1984
2014
  const fn = loadingFn(extensions, onProgress);
1985
- const results = keys.map((key) => suspendReact.suspend(fn, [loader, key], { equal: is.equ }));
2015
+ const results = cacheKeys.map(
2016
+ (key, index) => suspendReact.suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
2017
+ );
1986
2018
  return Array.isArray(input) ? results : results[0];
1987
2019
  }
1988
- useLoader.preload = function(loader, input, extensions, onProgress) {
1989
- const keys = Array.isArray(input) ? input : [input];
1990
- keys.forEach((key) => suspendReact.preload(loadingFn(extensions, onProgress), [loader, key]));
2020
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2021
+ const inputs = Array.isArray(input) ? input : [input];
2022
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2023
+ cacheKeys.forEach(
2024
+ (key, index) => suspendReact.preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2025
+ );
1991
2026
  };
1992
- useLoader.clear = function(loader, input) {
1993
- const keys = Array.isArray(input) ? input : [input];
1994
- keys.forEach((key) => suspendReact.clear([loader, key]));
2027
+ useLoader.clear = function(loader, input, cacheKey) {
2028
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2029
+ cacheKeys.forEach((key) => suspendReact.clear([loader, key]));
1995
2030
  };
1996
2031
  useLoader.loader = getLoader;
1997
2032
 
@@ -2411,7 +2446,7 @@ function advance(timestamp) {
2411
2446
  scheduler.getScheduler().step(timestamp);
2412
2447
  }
2413
2448
 
2414
- const version = "10.0.0-alpha.2";
2449
+ const version = "10.0.0-alpha.3";
2415
2450
  const packageData = {
2416
2451
  version: version};
2417
2452
 
@@ -13667,7 +13702,7 @@ function n0() {
13667
13702
  var t0 = n0();
13668
13703
  const r0 = Xb(t0);
13669
13704
 
13670
- const t = 1, o = 8, r = 32, e = 2;
13705
+ const t = 1, o = 8, r = 32, e = 2, i$1 = 268435456;
13671
13706
 
13672
13707
  function createReconciler(config) {
13673
13708
  const reconciler2 = r0(config);
@@ -13832,7 +13867,15 @@ function setFiberRef(fiber, publicInstance) {
13832
13867
  }
13833
13868
  }
13834
13869
  const reconstructed = [];
13835
- function swapInstances() {
13870
+ function flushReconstructedInstances() {
13871
+ if (reconstructed.length === 0) return;
13872
+ try {
13873
+ swapReconstructedInstances();
13874
+ } finally {
13875
+ reconstructed.length = 0;
13876
+ }
13877
+ }
13878
+ function swapReconstructedInstances() {
13836
13879
  for (const [instance] of reconstructed) {
13837
13880
  const parent = instance.parent;
13838
13881
  if (parent) {
@@ -13850,6 +13893,7 @@ function swapInstances() {
13850
13893
  }
13851
13894
  }
13852
13895
  if (instance.isHidden) unhideInstance(instance);
13896
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
13853
13897
  if (instance.object.__r3f) delete instance.object.__r3f;
13854
13898
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
13855
13899
  }
@@ -13862,6 +13906,8 @@ function swapInstances() {
13862
13906
  instance.object.__r3f = instance;
13863
13907
  setFiberRef(fiber, instance.object);
13864
13908
  delete instance.appliedOnce;
13909
+ instance.eventCount = 0;
13910
+ instance.handlers = {};
13865
13911
  applyProps(instance.object, instance.props);
13866
13912
  if (instance.props.attach) {
13867
13913
  attach(parent, instance);
@@ -13878,14 +13924,114 @@ function swapInstances() {
13878
13924
  invalidateInstance(instance);
13879
13925
  }
13880
13926
  }
13881
- reconstructed.length = 0;
13882
13927
  }
13883
13928
  const handleTextInstance = () => {
13884
13929
  };
13885
13930
  const NO_CONTEXT = {};
13886
13931
  let currentUpdatePriority = NoEventPriority;
13887
- const NoFlags = 0;
13888
- const Update = 4;
13932
+ function getEventPriority(type) {
13933
+ switch (type) {
13934
+ case "beforetoggle":
13935
+ case "cancel":
13936
+ case "click":
13937
+ case "close":
13938
+ case "contextmenu":
13939
+ case "copy":
13940
+ case "cut":
13941
+ case "auxclick":
13942
+ case "dblclick":
13943
+ case "dragend":
13944
+ case "dragstart":
13945
+ case "drop":
13946
+ case "focusin":
13947
+ case "focusout":
13948
+ case "input":
13949
+ case "invalid":
13950
+ case "keydown":
13951
+ case "keypress":
13952
+ case "keyup":
13953
+ case "mousedown":
13954
+ case "mouseup":
13955
+ case "paste":
13956
+ case "pause":
13957
+ case "play":
13958
+ case "pointercancel":
13959
+ case "pointerdown":
13960
+ case "pointerup":
13961
+ case "ratechange":
13962
+ case "reset":
13963
+ case "resize":
13964
+ case "seeked":
13965
+ case "submit":
13966
+ case "touchcancel":
13967
+ case "touchend":
13968
+ case "touchstart":
13969
+ case "volumechange":
13970
+ case "change":
13971
+ case "selectionchange":
13972
+ case "compositionstart":
13973
+ case "compositionend":
13974
+ case "compositionupdate":
13975
+ case "beforeinput":
13976
+ case "blur":
13977
+ case "fullscreenchange":
13978
+ case "focus":
13979
+ case "hashchange":
13980
+ case "popstate":
13981
+ case "select":
13982
+ case "selectstart":
13983
+ return e;
13984
+ case "drag":
13985
+ case "dragenter":
13986
+ case "dragexit":
13987
+ case "dragleave":
13988
+ case "dragover":
13989
+ case "mousemove":
13990
+ case "mouseout":
13991
+ case "mouseover":
13992
+ case "pointermove":
13993
+ case "pointerout":
13994
+ case "pointerover":
13995
+ case "scroll":
13996
+ case "touchmove":
13997
+ case "wheel":
13998
+ case "mouseenter":
13999
+ case "mouseleave":
14000
+ case "pointerenter":
14001
+ case "pointerleave":
14002
+ return o;
14003
+ case "message": {
14004
+ switch (Tb.unstable_getCurrentPriorityLevel()) {
14005
+ case Tb.unstable_ImmediatePriority:
14006
+ return e;
14007
+ case Tb.unstable_UserBlockingPriority:
14008
+ return o;
14009
+ case Tb.unstable_NormalPriority:
14010
+ case Tb.unstable_LowPriority:
14011
+ return r;
14012
+ case Tb.unstable_IdlePriority:
14013
+ return i$1;
14014
+ default:
14015
+ return r;
14016
+ }
14017
+ }
14018
+ default:
14019
+ return r;
14020
+ }
14021
+ }
14022
+ function scheduleMicrotask(callback) {
14023
+ if (typeof queueMicrotask === "function") {
14024
+ queueMicrotask(callback);
14025
+ } else if (typeof Promise !== "undefined") {
14026
+ Promise.resolve().then(callback).catch((error) => {
14027
+ setTimeout(() => {
14028
+ throw error;
14029
+ });
14030
+ });
14031
+ } else {
14032
+ setTimeout(callback);
14033
+ }
14034
+ }
13889
14035
  const reconciler = /* @__PURE__ */ createReconciler({
13890
14036
  isPrimaryRenderer: false,
13891
14037
  warnsIfNotActing: false,
@@ -13924,16 +14070,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
13924
14070
  else if (newProps.args?.length !== oldProps.args?.length) reconstruct = true;
13925
14071
  else if (newProps.args?.some((value, index) => value !== oldProps.args?.[index])) reconstruct = true;
13926
14072
  if (reconstruct) {
13927
- reconstructed.push([instance, { ...newProps }, fiber]);
14073
+ reconstructed.push([instance, getInstanceProps(newProps), fiber]);
13928
14074
  } else {
13929
14075
  const changedProps = diffProps(instance, newProps);
13930
- if (Object.keys(changedProps).length) {
13931
- Object.assign(instance.props, changedProps);
13932
- applyProps(instance.object, changedProps);
13933
- }
14076
+ const attach2 = instance.props.attach;
14077
+ instance.props = getInstanceProps(newProps);
14078
+ if (attach2 !== void 0) instance.props.attach = attach2;
14079
+ else delete instance.props.attach;
14080
+ if (Object.keys(changedProps).length) applyProps(instance.object, changedProps);
13934
14081
  }
13935
- const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
13936
- if (isTailSibling) swapInstances();
13937
14082
  },
13938
14083
  finalizeInitialChildren: (instance) => {
13939
14084
  for (const prop in instance.props) {
@@ -13958,8 +14103,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
13958
14103
  const target = container.getState().internal.container ?? container.getState().scene;
13959
14104
  return prepare(target, container, "", {});
13960
14105
  },
13961
- resetAfterCommit: () => {
13962
- },
14106
+ // Reconstructed instances are swapped once all mutations are committed,
14107
+ // before layout effects run so refs point to the new objects
14108
+ resetAfterCommit: flushReconstructedInstances,
13963
14109
  shouldSetTextContent: () => false,
13964
14110
  clearContainer: () => false,
13965
14111
  hideInstance,
@@ -13967,6 +14113,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
13967
14113
  createTextInstance: handleTextInstance,
13968
14114
  hideTextInstance: handleTextInstance,
13969
14115
  unhideTextInstance: handleTextInstance,
14116
+ // Mirrors react-dom, which flushes discrete work in microtasks
14117
+ supportsMicrotasks: true,
14118
+ scheduleMicrotask,
13970
14119
  scheduleTimeout: typeof setTimeout === "function" ? setTimeout : void 0,
13971
14120
  cancelTimeout: typeof clearTimeout === "function" ? clearTimeout : void 0,
13972
14121
  noTimeout: -1,
@@ -14007,28 +14156,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
14007
14156
  },
14008
14157
  resolveUpdatePriority() {
14009
14158
  if (currentUpdatePriority !== NoEventPriority) return currentUpdatePriority;
14010
- switch (typeof window !== "undefined" && window.event?.type) {
14011
- case "click":
14012
- case "contextmenu":
14013
- case "dblclick":
14014
- case "dragenter":
14015
- case "dragleave":
14016
- case "drop":
14017
- case "pointercancel":
14018
- case "pointerdown":
14019
- case "pointerup":
14020
- return e;
14021
- case "dragover":
14022
- case "pointermove":
14023
- case "pointerout":
14024
- case "pointerover":
14025
- case "pointerenter":
14026
- case "pointerleave":
14027
- case "wheel":
14028
- return o;
14029
- default:
14030
- return r;
14031
- }
14159
+ const eventType = typeof window !== "undefined" ? window.event?.type : void 0;
14160
+ if (eventType === void 0) return r;
14161
+ return getEventPriority(eventType);
14032
14162
  },
14033
14163
  resetFormInstance() {
14034
14164
  },
@@ -14077,11 +14207,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14077
14207
  cloneMutableTextInstance(textInstance) {
14078
14208
  return textInstance;
14079
14209
  },
14210
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14211
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14212
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14213
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14214
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14215
+ // Guarded by a test asserting a full render + unmount never reaches them.
14080
14216
  cloneRootViewTransitionContainer(_rootContainer) {
14081
- throw new Error("Not implemented.");
14082
14217
  },
14083
14218
  removeRootViewTransitionClone(_rootContainer, _clone) {
14084
- throw new Error("Not implemented.");
14085
14219
  },
14086
14220
  // https://github.com/facebook/react/pull/32465
14087
14221
  createFragmentInstance: (_fiber) => null,
@@ -14166,6 +14300,7 @@ function createRoot(canvas) {
14166
14300
  const lastConfiguredProps = {};
14167
14301
  let configured = false;
14168
14302
  let pending = null;
14303
+ let rendererSetup = null;
14169
14304
  return {
14170
14305
  async configure(props = {}) {
14171
14306
  let resolve;
@@ -14196,7 +14331,7 @@ function createRoot(canvas) {
14196
14331
  forceEven
14197
14332
  } = props;
14198
14333
  const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || webgpu.SRGBColorSpace;
14199
- const state = store.getState();
14334
+ let state = store.getState();
14200
14335
  const defaultGPUProps = {
14201
14336
  canvas,
14202
14337
  antialias: true
@@ -14210,52 +14345,64 @@ function createRoot(canvas) {
14210
14345
  throw new Error("Cannot use both gl and renderer props at the same time");
14211
14346
  }
14212
14347
  let renderer = state.internal.actualRenderer;
14213
- if (primaryCanvas && !state.internal.actualRenderer) {
14214
- const primary = await waitForPrimary(primaryCanvas);
14215
- renderer = primary.renderer;
14216
- state.internal.actualRenderer = renderer;
14217
- const canvasTarget = new webgpu.CanvasTarget(canvas);
14218
- primary.store.setState((prev) => ({
14219
- internal: { ...prev.internal, isMultiCanvas: true }
14220
- }));
14221
- state.set((prev) => ({
14222
- webGPUSupported: primary.store.getState().webGPUSupported,
14223
- renderer,
14224
- primaryStore: primary.store,
14225
- internal: {
14226
- ...prev.internal,
14227
- canvasTarget,
14228
- isMultiCanvas: true,
14229
- isSecondary: true,
14230
- targetId: primaryCanvas
14231
- }
14232
- }));
14233
- } else if (!state.internal.actualRenderer) {
14234
- renderer = await resolveRenderer(rendererConfig, defaultGPUProps, webgpu.WebGPURenderer);
14235
- if (!renderer.hasInitialized?.()) {
14236
- const size2 = computeInitialSize(canvas, propsSize);
14237
- if (size2.width > 0 && size2.height > 0) {
14238
- const pixelRatio = calculateDpr(dpr);
14239
- canvas.width = size2.width * pixelRatio;
14240
- canvas.height = size2.height * pixelRatio;
14241
- }
14242
- await renderer.init();
14243
- }
14244
- const backend = renderer.backend;
14245
- const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14246
- state.internal.actualRenderer = renderer;
14247
- state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14248
- if (canvasId && !state.internal.isSecondary) {
14249
- const canvasTarget = new webgpu.CanvasTarget(canvas);
14250
- const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14251
- state.set((prev) => ({
14252
- internal: {
14253
- ...prev.internal,
14254
- canvasTarget,
14255
- unregisterPrimary
14348
+ if (!state.internal.actualRenderer) {
14349
+ if (!rendererSetup) {
14350
+ rendererSetup = (async () => {
14351
+ if (primaryCanvas) {
14352
+ const primary = await waitForPrimary(primaryCanvas);
14353
+ renderer = primary.renderer;
14354
+ state.internal.actualRenderer = renderer;
14355
+ const canvasTarget = new webgpu.CanvasTarget(canvas);
14356
+ primary.store.setState((prev) => ({
14357
+ internal: { ...prev.internal, isMultiCanvas: true }
14358
+ }));
14359
+ state.set((prev) => ({
14360
+ webGPUSupported: primary.store.getState().webGPUSupported,
14361
+ renderer,
14362
+ primaryStore: primary.store,
14363
+ internal: {
14364
+ ...prev.internal,
14365
+ canvasTarget,
14366
+ isMultiCanvas: true,
14367
+ isSecondary: true,
14368
+ targetId: primaryCanvas
14369
+ }
14370
+ }));
14371
+ } else {
14372
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, webgpu.WebGPURenderer);
14373
+ if (!renderer.hasInitialized?.()) {
14374
+ const size2 = computeInitialSize(canvas, propsSize);
14375
+ if (size2.width > 0 && size2.height > 0) {
14376
+ const pixelRatio = calculateDpr(dpr);
14377
+ canvas.width = size2.width * pixelRatio;
14378
+ canvas.height = size2.height * pixelRatio;
14379
+ }
14380
+ await renderer.init();
14381
+ }
14382
+ const backend = renderer.backend;
14383
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14384
+ state.internal.actualRenderer = renderer;
14385
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14386
+ if (canvasId && !state.internal.isSecondary) {
14387
+ const canvasTarget = new webgpu.CanvasTarget(canvas);
14388
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14389
+ state.set((prev) => ({
14390
+ internal: {
14391
+ ...prev.internal,
14392
+ canvasTarget,
14393
+ unregisterPrimary
14394
+ }
14395
+ }));
14396
+ }
14256
14397
  }
14257
- }));
14398
+ })().catch((err) => {
14399
+ rendererSetup = null;
14400
+ throw err;
14401
+ });
14258
14402
  }
14403
+ await rendererSetup;
14404
+ state = store.getState();
14405
+ renderer = state.internal.actualRenderer;
14259
14406
  }
14260
14407
  let raycaster = state.raycaster;
14261
14408
  if (!raycaster) state.set({ raycaster: raycaster = new webgpu.Raycaster() });
@@ -14605,7 +14752,8 @@ function unmountComponentAtNode(canvas, callback) {
14605
14752
  dispose(state.scene);
14606
14753
  _roots.delete(canvas);
14607
14754
  if (callback) callback(canvas);
14608
- } catch {
14755
+ } catch (error) {
14756
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
14609
14757
  }
14610
14758
  }, 500);
14611
14759
  }
@@ -14668,6 +14816,7 @@ function PortalInner({ state = {}, children, container }) {
14668
14816
  viewport = rootState.viewport.getCurrentViewport(camera, new webgpu.Vector3(), resolvedSize);
14669
14817
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
14670
14818
  }
14819
+ const set = injectState.set;
14671
14820
  return {
14672
14821
  // The intersect consists of the previous root state
14673
14822
  ...rootState,
@@ -14686,7 +14835,7 @@ function PortalInner({ state = {}, children, container }) {
14686
14835
  size: resolvedSize,
14687
14836
  viewport: { ...rootState.viewport, ...viewport },
14688
14837
  // Layers are allowed to override events
14689
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14838
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14690
14839
  // Container for child attachment - the portalScene (injected or container itself)
14691
14840
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
14692
14841
  };
@@ -14758,14 +14907,133 @@ function parseRendererConfig(rendererProp) {
14758
14907
  return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14759
14908
  }
14760
14909
 
14910
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14911
+ const ROOT_SCOPE = "";
14912
+ const registries = /* @__PURE__ */ new WeakMap();
14913
+ function getKindRegistry(store, kind) {
14914
+ let registry = registries.get(store);
14915
+ if (!registry) {
14916
+ registry = {
14917
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14918
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14919
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14920
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14921
+ };
14922
+ registries.set(store, registry);
14923
+ }
14924
+ return registry[kind];
14925
+ }
14926
+ function resolvePrimary$1(store) {
14927
+ return store.getState().primaryStore ?? store;
14928
+ }
14929
+ function isScopeValid(store, kind, scopeKey) {
14930
+ return getKindRegistry(store, kind).valid.has(scopeKey);
14931
+ }
14932
+ function peekStaged(store, kind, scopeKey) {
14933
+ return getKindRegistry(store, kind).staged.get(scopeKey);
14934
+ }
14935
+ function stageEntries(store, kind, scopeKey, entries) {
14936
+ const { staged } = getKindRegistry(store, kind);
14937
+ const current = staged.get(scopeKey);
14938
+ if (current) Object.assign(current, entries);
14939
+ else staged.set(scopeKey, { ...entries });
14940
+ }
14941
+ function readCommittedScope(map, scopeKey, isLeaf) {
14942
+ if (scopeKey === ROOT_SCOPE) {
14943
+ const leaves = {};
14944
+ for (const [key, value] of Object.entries(map)) if (isLeaf(value)) leaves[key] = value;
14945
+ return leaves;
14946
+ }
14947
+ const scopeData = map[scopeKey];
14948
+ if (scopeData && typeof scopeData === "object" && !isLeaf(scopeData)) return scopeData;
14949
+ return {};
14950
+ }
14951
+ function withStagedOverlay(store, kind, committed) {
14952
+ const { staged } = getKindRegistry(store, kind);
14953
+ if (staged.size === 0) return committed;
14954
+ const view = { ...committed };
14955
+ for (const [scopeKey, entries] of staged) {
14956
+ if (scopeKey === ROOT_SCOPE) Object.assign(view, entries);
14957
+ else view[scopeKey] = { ...view[scopeKey], ...entries };
14958
+ }
14959
+ return view;
14960
+ }
14961
+ function flushStagedScope(store, kind, scopeKey, isLeaf) {
14962
+ const registry = getKindRegistry(store, kind);
14963
+ const staged = registry.staged.get(scopeKey);
14964
+ if (!staged) return;
14965
+ registry.staged.delete(scopeKey);
14966
+ const replace = !registry.valid.has(scopeKey);
14967
+ store.setState((state) => {
14968
+ const map = state[kind];
14969
+ if (scopeKey === ROOT_SCOPE) {
14970
+ if (!replace) return { [kind]: { ...map, ...staged } };
14971
+ const next = {};
14972
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
14973
+ return { [kind]: { ...next, ...staged } };
14974
+ }
14975
+ const current = replace ? {} : map[scopeKey] ?? {};
14976
+ return { [kind]: { ...map, [scopeKey]: { ...current, ...staged } } };
14977
+ });
14978
+ registry.valid.add(scopeKey);
14979
+ }
14980
+ function invalidateResource(store, kind, scopeKey) {
14981
+ const registry = getKindRegistry(store, kind);
14982
+ if (scopeKey === void 0) {
14983
+ registry.valid.clear();
14984
+ registry.staged.clear();
14985
+ } else {
14986
+ registry.valid.delete(scopeKey);
14987
+ registry.staged.delete(scopeKey);
14988
+ }
14989
+ }
14990
+ function rebuildResource(store, kind, userScope) {
14991
+ const primary = resolvePrimary$1(store);
14992
+ invalidateResource(primary, kind, userScope === "root" ? ROOT_SCOPE : userScope);
14993
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14994
+ }
14995
+ function invalidateAllResources(store) {
14996
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
14997
+ }
14998
+ function removeResourceEntries(store, kind, names, scope, isLeaf) {
14999
+ const staged = peekStaged(store, kind, scope ?? ROOT_SCOPE);
15000
+ if (staged) for (const name of names) delete staged[name];
15001
+ store.setState((state) => {
15002
+ const map = state[kind];
15003
+ if (scope) {
15004
+ const currentScope = { ...map[scope] };
15005
+ for (const name of names) delete currentScope[name];
15006
+ return { [kind]: { ...map, [scope]: currentScope } };
15007
+ }
15008
+ const next = { ...map };
15009
+ for (const name of names) if (isLeaf(next[name])) delete next[name];
15010
+ return { [kind]: next };
15011
+ });
15012
+ }
15013
+ function clearResourceEntries(store, kind, scope, isLeaf) {
15014
+ const registry = getKindRegistry(store, kind);
15015
+ if (scope && scope !== "root") registry.staged.delete(scope);
15016
+ else if (scope === "root") registry.staged.delete(ROOT_SCOPE);
15017
+ else registry.staged.clear();
15018
+ store.setState((state) => {
15019
+ const map = state[kind];
15020
+ if (scope && scope !== "root") {
15021
+ const { [scope]: _, ...rest } = map;
15022
+ return { [kind]: rest };
15023
+ }
15024
+ if (scope === "root") {
15025
+ const next = {};
15026
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
15027
+ return { [kind]: next };
15028
+ }
15029
+ return { [kind]: {} };
15030
+ });
15031
+ }
15032
+
14761
15033
  function clearHmrCaches(store) {
14762
- store.setState((state) => ({
14763
- nodes: {},
14764
- uniforms: {},
14765
- buffers: {},
14766
- gpuStorage: {},
14767
- _hmrVersion: state._hmrVersion + 1
14768
- }));
15034
+ const primary = store.getState().primaryStore ?? store;
15035
+ invalidateAllResources(primary);
15036
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14769
15037
  }
14770
15038
 
14771
15039
  function CanvasImpl({
@@ -14846,6 +15114,7 @@ function CanvasImpl({
14846
15114
  const handleDropMissed = useMutableCallback(onDropMissed);
14847
15115
  const [block, setBlock] = React__namespace.useState(false);
14848
15116
  const [error, setError] = React__namespace.useState(false);
15117
+ const [fallbackVisible, setFallbackVisible] = React__namespace.useState(false);
14849
15118
  if (block) throw block;
14850
15119
  if (error) throw error;
14851
15120
  const root = React__namespace.useRef(null);
@@ -14853,6 +15122,7 @@ function CanvasImpl({
14853
15122
  const unsubscribeErrorRef = React__namespace.useRef(null);
14854
15123
  useIsomorphicLayoutEffect(() => {
14855
15124
  effectActiveRef.current = true;
15125
+ if (fallbackVisible) return;
14856
15126
  const canvas = canvasRef.current;
14857
15127
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
14858
15128
  if (!root.current) {
@@ -14873,7 +15143,7 @@ function CanvasImpl({
14873
15143
  }
14874
15144
  async function run() {
14875
15145
  if (!effectActiveRef.current || !root.current) return;
14876
- await root.current.configure({
15146
+ const configured = await root.current.configure({
14877
15147
  id,
14878
15148
  primaryCanvas,
14879
15149
  scheduler,
@@ -14914,8 +15184,20 @@ function CanvasImpl({
14914
15184
  }
14915
15185
  onCreated?.(state);
14916
15186
  }
14917
- });
14918
- if (!effectActiveRef.current || !root.current) return;
15187
+ }).then(
15188
+ () => true,
15189
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
15190
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
15191
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
15192
+ (setupError) => {
15193
+ if (effectActiveRef.current) {
15194
+ if (fallback != null) setFallbackVisible(true);
15195
+ else setError(setupError);
15196
+ }
15197
+ return false;
15198
+ }
15199
+ );
15200
+ if (!configured || !effectActiveRef.current || !root.current) return;
14919
15201
  root.current.render(
14920
15202
  /* @__PURE__ */ jsxRuntime.jsx(Bridge, { children: /* @__PURE__ */ jsxRuntime.jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxRuntime.jsxs(React__namespace.Suspense, { fallback: /* @__PURE__ */ jsxRuntime.jsx(Block, { set: setBlock }), children: [
14921
15203
  backgroundProps && /* @__PURE__ */ jsxRuntime.jsx(Environment, { ...backgroundProps }),
@@ -14978,7 +15260,11 @@ function CanvasImpl({
14978
15260
  ...style
14979
15261
  },
14980
15262
  ...props,
14981
- children: /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
15263
+ children: fallbackVisible ? (
15264
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15265
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15266
+ fallback
15267
+ ) : /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
14982
15268
  "canvas",
14983
15269
  {
14984
15270
  ref: canvasRef,
@@ -15060,30 +15346,31 @@ let ScopedStore = _ScopedStore;
15060
15346
  function createScopedStore(data) {
15061
15347
  return new ScopedStore(data);
15062
15348
  }
15063
- function createLazyCreatorState(state) {
15349
+ function createLazyCreatorState(state, store) {
15064
15350
  let _uniforms = null;
15065
15351
  let _nodes = null;
15066
15352
  let _buffers = null;
15067
15353
  let _gpuStorage = null;
15354
+ const view = (kind) => store ? withStagedOverlay(store, kind, state[kind]) : state[kind];
15068
15355
  return Object.create(state, {
15069
15356
  uniforms: {
15070
15357
  get() {
15071
- return _uniforms ?? (_uniforms = createScopedStore(state.uniforms));
15358
+ return _uniforms ?? (_uniforms = createScopedStore(view("uniforms")));
15072
15359
  }
15073
15360
  },
15074
15361
  nodes: {
15075
15362
  get() {
15076
- return _nodes ?? (_nodes = createScopedStore(state.nodes));
15363
+ return _nodes ?? (_nodes = createScopedStore(view("nodes")));
15077
15364
  }
15078
15365
  },
15079
15366
  buffers: {
15080
15367
  get() {
15081
- return _buffers ?? (_buffers = createScopedStore(state.buffers));
15368
+ return _buffers ?? (_buffers = createScopedStore(view("buffers")));
15082
15369
  }
15083
15370
  },
15084
15371
  gpuStorage: {
15085
15372
  get() {
15086
- return _gpuStorage ?? (_gpuStorage = createScopedStore(state.gpuStorage));
15373
+ return _gpuStorage ?? (_gpuStorage = createScopedStore(view("gpuStorage")));
15087
15374
  }
15088
15375
  }
15089
15376
  });
@@ -15206,65 +15493,56 @@ function useCompareMemoize(value, deep) {
15206
15493
  return ref.current;
15207
15494
  }
15208
15495
 
15496
+ function useScopedResource(options) {
15497
+ const { store, kind, scope, isLeaf, create, prepare, reconcile, input } = options;
15498
+ const scopeKey = scope ?? ROOT_SCOPE;
15499
+ const version = store((s) => s._hmrVersion);
15500
+ const entries = React.useMemo(() => {
15501
+ const staged = peekStaged(store, kind, scopeKey);
15502
+ const reusable = isScopeValid(store, kind, scopeKey);
15503
+ const map = store.getState()[kind];
15504
+ const committed = reusable ? readCommittedScope(map, scopeKey, isLeaf) : void 0;
15505
+ const result = {};
15506
+ let fresh = null;
15507
+ for (const [name, candidate] of Object.entries(create())) {
15508
+ const existing = staged?.[name] ?? committed?.[name];
15509
+ if (existing !== void 0) {
15510
+ result[name] = existing;
15511
+ reconcile?.(existing, candidate);
15512
+ } else {
15513
+ const value = prepare ? prepare(name, candidate) : candidate;
15514
+ result[name] = value;
15515
+ (fresh ?? (fresh = {}))[name] = value;
15516
+ }
15517
+ }
15518
+ if (fresh) stageEntries(store, kind, scopeKey, fresh);
15519
+ return result;
15520
+ }, [store, kind, scopeKey, version, input]);
15521
+ useIsomorphicLayoutEffect(() => {
15522
+ flushStagedScope(store, kind, scopeKey, isLeaf);
15523
+ });
15524
+ return entries;
15525
+ }
15526
+
15209
15527
  const isUniformNode$1 = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
15210
15528
  function useUniforms(creatorOrScope, scope) {
15211
15529
  const store = usePrimaryStore();
15212
15530
  const removeUniforms2 = React.useCallback(
15213
- (names, targetScope) => {
15214
- const nameArray = Array.isArray(names) ? names : [names];
15215
- store.setState((state) => {
15216
- if (targetScope) {
15217
- const currentScope = { ...state.uniforms[targetScope] };
15218
- for (const name of nameArray) delete currentScope[name];
15219
- return { uniforms: { ...state.uniforms, [targetScope]: currentScope } };
15220
- }
15221
- const uniforms2 = { ...state.uniforms };
15222
- for (const name of nameArray) if (isUniformNode$1(uniforms2[name])) delete uniforms2[name];
15223
- return { uniforms: uniforms2 };
15224
- });
15225
- },
15531
+ (names, targetScope) => removeResourceEntries(store, "uniforms", Array.isArray(names) ? names : [names], targetScope, isUniformNode$1),
15226
15532
  [store]
15227
15533
  );
15228
15534
  const clearUniforms = React.useCallback(
15229
- (targetScope) => {
15230
- store.setState((state) => {
15231
- if (targetScope && targetScope !== "root") {
15232
- const { [targetScope]: _, ...rest } = state.uniforms;
15233
- return { uniforms: rest };
15234
- }
15235
- if (targetScope === "root") {
15236
- const uniforms2 = {};
15237
- for (const [key, value] of Object.entries(state.uniforms)) {
15238
- if (!isUniformNode$1(value)) uniforms2[key] = value;
15239
- }
15240
- return { uniforms: uniforms2 };
15241
- }
15242
- return { uniforms: {} };
15243
- });
15244
- },
15535
+ (targetScope) => clearResourceEntries(store, "uniforms", targetScope, isUniformNode$1),
15245
15536
  [store]
15246
15537
  );
15247
15538
  const rebuildUniforms = React.useCallback(
15248
- (targetScope) => {
15249
- store.setState((state) => {
15250
- let newUniforms = {};
15251
- if (targetScope && targetScope !== "root") {
15252
- const { [targetScope]: _, ...rest } = state.uniforms;
15253
- newUniforms = rest;
15254
- } else if (targetScope === "root") {
15255
- for (const [key, value] of Object.entries(state.uniforms)) {
15256
- if (!isUniformNode$1(value)) newUniforms[key] = value;
15257
- }
15258
- }
15259
- return { uniforms: newUniforms, _hmrVersion: state._hmrVersion + 1 };
15260
- });
15261
- },
15539
+ (targetScope) => rebuildResource(store, "uniforms", targetScope),
15262
15540
  [store]
15263
15541
  );
15264
15542
  const inputForMemoization = React.useMemo(() => {
15265
15543
  let raw = creatorOrScope;
15266
15544
  if (is.fun(creatorOrScope)) {
15267
- const wrappedState = createLazyCreatorState(store.getState());
15545
+ const wrappedState = createLazyCreatorState(store.getState(), store);
15268
15546
  raw = creatorOrScope(wrappedState);
15269
15547
  }
15270
15548
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
@@ -15279,80 +15557,43 @@ function useUniforms(creatorOrScope, scope) {
15279
15557
  const memoizedInput = useCompareMemoize(inputForMemoization);
15280
15558
  const isReader = memoizedInput === void 0 || typeof memoizedInput === "string";
15281
15559
  const storeUniforms = usePrimaryThree((s) => s.uniforms);
15282
- const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
15283
- const readerDep = isReader ? storeUniforms : null;
15284
- const creatorDep = isReader ? null : hmrVersion;
15285
- const uniforms = React.useMemo(() => {
15286
- if (memoizedInput === void 0) {
15287
- return storeUniforms;
15288
- }
15289
- if (typeof memoizedInput === "string") {
15290
- const scopeData = storeUniforms[memoizedInput];
15291
- if (scopeData && !isUniformNode$1(scopeData)) return scopeData;
15292
- return {};
15293
- }
15294
- const state = store.getState();
15295
- const set = store.setState;
15296
- if (typeof memoizedInput !== "object" || memoizedInput === null) {
15297
- throw new Error("Invalid uniform input");
15298
- }
15299
- const created = memoizedInput;
15300
- const result = {};
15301
- let hasNewUniforms = false;
15302
- let targetRecord = state.uniforms;
15303
- if (scope) {
15304
- if (!state.uniforms[scope]) state.uniforms[scope] = {};
15305
- targetRecord = state.uniforms[scope];
15306
- }
15307
- for (const [name, node] of Object.entries(created)) {
15308
- if (targetRecord[name]) {
15309
- result[name] = targetRecord[name];
15310
- const existingVal = result[name].value;
15311
- const newVal = vectorize(node);
15312
- let equals = newVal === existingVal;
15313
- if (!equals && hasEqualsMethod(existingVal) && hasEqualsMethod(newVal)) {
15314
- if (isThreeVector(existingVal) && isThreeVector(newVal)) {
15315
- equals = vectorEquals(existingVal, newVal);
15316
- } else if (isSameThreeType(existingVal, newVal)) {
15317
- equals = existingVal.equals(newVal);
15318
- }
15319
- }
15320
- if (!equals) result[name].value = newVal;
15321
- } else {
15322
- result[name] = createUniform(name, node, scope);
15323
- hasNewUniforms = true;
15324
- }
15325
- }
15326
- if (hasNewUniforms) {
15327
- if (scope) {
15328
- set((s) => ({
15329
- uniforms: {
15330
- ...s.uniforms,
15331
- [scope]: { ...s.uniforms[scope], ...result }
15332
- }
15333
- }));
15334
- } else {
15335
- set((s) => ({ uniforms: { ...s.uniforms, ...result } }));
15560
+ const created = useScopedResource({
15561
+ store,
15562
+ kind: "uniforms",
15563
+ scope: isReader ? void 0 : scope,
15564
+ isLeaf: isUniformNode$1,
15565
+ input: memoizedInput,
15566
+ create: () => {
15567
+ if (isReader) return {};
15568
+ if (typeof memoizedInput !== "object" || memoizedInput === null) throw new Error("Invalid uniform input");
15569
+ return memoizedInput;
15570
+ },
15571
+ prepare: (name, candidate) => createUniform(name, candidate, scope),
15572
+ reconcile: (existing, candidate) => {
15573
+ const existingVal = existing.value;
15574
+ const newVal = vectorize(candidate);
15575
+ let equals = newVal === existingVal;
15576
+ if (!equals && hasEqualsMethod(existingVal) && hasEqualsMethod(newVal)) {
15577
+ if (isThreeVector(existingVal) && isThreeVector(newVal)) {
15578
+ equals = vectorEquals(existingVal, newVal);
15579
+ } else if (isSameThreeType(existingVal, newVal)) {
15580
+ equals = existingVal.equals(newVal);
15581
+ }
15336
15582
  }
15583
+ if (!equals) existing.value = newVal;
15337
15584
  }
15338
- return result;
15339
- }, [store, memoizedInput, scope, readerDep, creatorDep]);
15585
+ });
15586
+ let uniforms = created;
15587
+ if (memoizedInput === void 0) {
15588
+ uniforms = storeUniforms;
15589
+ } else if (typeof memoizedInput === "string") {
15590
+ const scopeData = storeUniforms[memoizedInput];
15591
+ uniforms = scopeData && !isUniformNode$1(scopeData) ? scopeData : {};
15592
+ }
15340
15593
  return { ...uniforms, removeUniforms: removeUniforms2, clearUniforms, rebuildUniforms };
15341
15594
  }
15342
15595
  function rebuildAllUniforms(store, scope) {
15343
- store = store.getState().primaryStore ?? store;
15344
- store.setState((state) => {
15345
- let newUniforms = {};
15346
- if (scope && scope !== "root") {
15347
- const { [scope]: _, ...rest } = state.uniforms;
15348
- newUniforms = rest;
15349
- } else if (scope === "root") {
15350
- for (const [key, value] of Object.entries(state.uniforms)) {
15351
- if (!isUniformNode$1(value)) newUniforms[key] = value;
15352
- }
15353
- }
15354
- return { uniforms: newUniforms, _hmrVersion: state._hmrVersion + 1 };
15355
- });
15596
+ rebuildResource(store, "uniforms", scope);
15356
15597
  }
15357
15598
  function removeUniforms(set, names, scope) {
15358
15599
  set((state) => {
@@ -15416,192 +15657,91 @@ function isSameThreeType(a, b) {
15416
15657
  return obj_a.isColor && obj_b.isColor || obj_a.isMatrix3 && obj_b.isMatrix3 || obj_a.isMatrix4 && obj_b.isMatrix4 || obj_a.isEuler && obj_b.isEuler || obj_a.isQuaternion && obj_b.isQuaternion;
15417
15658
  }
15418
15659
 
15660
+ const uniformOf = tsl.uniform;
15419
15661
  const isUniformNode = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
15420
15662
  const isTSLNode$1 = (value) => value !== null && typeof value === "object" && "uuid" in value && "nodeType" in value;
15421
15663
  function useUniform(name, value) {
15422
15664
  const store = useStore();
15423
- const hmrVersion = useThree((s) => s._hmrVersion);
15424
- return React.useMemo(() => {
15425
- const state = store.getState();
15426
- const set = store.setState;
15427
- const existing = state.uniforms[name];
15428
- if (existing && isUniformNode(existing)) {
15665
+ const registered = useScopedResource({
15666
+ store,
15667
+ kind: "uniforms",
15668
+ scope: void 0,
15669
+ isLeaf: isUniformNode,
15670
+ input: name,
15671
+ create: () => value === void 0 ? {} : { [name]: value },
15672
+ prepare: createNamedUniform,
15673
+ reconcile: (existing2) => {
15429
15674
  if (value !== void 0 && !isTSLNode$1(value) && !isUniformNode(value)) {
15430
- existing.value = typeof value === "string" ? new webgpu.Color(value) : value;
15675
+ existing2.value = typeof value === "string" ? new webgpu.Color(value) : value;
15431
15676
  }
15432
- return existing;
15433
15677
  }
15434
- if (value === void 0) {
15435
- throw new Error(
15436
- `[useUniform] Uniform "${name}" not found. Create it first with: useUniform('${name}', initialValue)`
15437
- );
15438
- }
15439
- if (isUniformNode(value)) {
15440
- const node2 = value;
15441
- if (typeof node2.setName === "function") {
15442
- node2.setName(name);
15443
- }
15444
- set((s) => ({
15445
- uniforms: { ...s.uniforms, [name]: node2 }
15446
- }));
15447
- return node2;
15448
- }
15449
- let node;
15450
- if (isTSLNode$1(value)) {
15451
- node = tsl.uniform(value);
15452
- } else if (typeof value === "string") {
15453
- node = tsl.uniform(new webgpu.Color(value));
15454
- } else {
15455
- node = tsl.uniform(value);
15456
- }
15457
- if (typeof node.setName === "function") {
15458
- node.setName(name);
15459
- }
15460
- set((s) => ({
15461
- uniforms: {
15462
- ...s.uniforms,
15463
- [name]: node
15464
- }
15465
- }));
15466
- return node;
15467
- }, [store, name, hmrVersion]);
15678
+ });
15679
+ if (registered[name]) return registered[name];
15680
+ const existing = peekStaged(store, "uniforms", ROOT_SCOPE)?.[name] ?? store.getState().uniforms[name];
15681
+ if (existing && isUniformNode(existing)) return existing;
15682
+ throw new Error(
15683
+ `[useUniform] Uniform "${name}" not found. Create it first with: useUniform('${name}', initialValue)`
15684
+ );
15685
+ }
15686
+ function createNamedUniform(name, value) {
15687
+ let node;
15688
+ if (isUniformNode(value)) {
15689
+ node = value;
15690
+ } else if (isTSLNode$1(value)) {
15691
+ node = uniformOf(value);
15692
+ } else if (typeof value === "string") {
15693
+ node = tsl.uniform(new webgpu.Color(value));
15694
+ } else {
15695
+ node = uniformOf(value);
15696
+ }
15697
+ if (typeof node.setName === "function") {
15698
+ node.setName(name);
15699
+ }
15700
+ return node;
15468
15701
  }
15469
15702
 
15470
15703
  const isTSLNode = (value) => value !== null && typeof value === "object" && ("uuid" in value || "nodeType" in value);
15471
15704
  function useNodes(creatorOrScope, scope) {
15472
15705
  const store = usePrimaryStore();
15473
15706
  const removeNodes2 = React.useCallback(
15474
- (names, targetScope) => {
15475
- const nameArray = Array.isArray(names) ? names : [names];
15476
- store.setState((state) => {
15477
- if (targetScope) {
15478
- const currentScope = { ...state.nodes[targetScope] };
15479
- for (const name of nameArray) delete currentScope[name];
15480
- return { nodes: { ...state.nodes, [targetScope]: currentScope } };
15481
- }
15482
- const nodes2 = { ...state.nodes };
15483
- for (const name of nameArray) if (isTSLNode(nodes2[name])) delete nodes2[name];
15484
- return { nodes: nodes2 };
15485
- });
15486
- },
15707
+ (names, targetScope) => removeResourceEntries(store, "nodes", Array.isArray(names) ? names : [names], targetScope, isTSLNode),
15487
15708
  [store]
15488
15709
  );
15489
15710
  const clearNodes = React.useCallback(
15490
- (targetScope) => {
15491
- store.setState((state) => {
15492
- if (targetScope && targetScope !== "root") {
15493
- const { [targetScope]: _, ...rest } = state.nodes;
15494
- return { nodes: rest };
15495
- }
15496
- if (targetScope === "root") {
15497
- const nodes2 = {};
15498
- for (const [key, value] of Object.entries(state.nodes)) {
15499
- if (!isTSLNode(value)) nodes2[key] = value;
15500
- }
15501
- return { nodes: nodes2 };
15502
- }
15503
- return { nodes: {} };
15504
- });
15505
- },
15711
+ (targetScope) => clearResourceEntries(store, "nodes", targetScope, isTSLNode),
15506
15712
  [store]
15507
15713
  );
15508
15714
  const rebuildNodes = React.useCallback(
15509
- (targetScope) => {
15510
- store.setState((state) => {
15511
- let newNodes = state.nodes;
15512
- if (targetScope && targetScope !== "root") {
15513
- const { [targetScope]: _, ...rest } = state.nodes;
15514
- newNodes = rest;
15515
- } else if (targetScope === "root") {
15516
- newNodes = {};
15517
- for (const [key, value] of Object.entries(state.nodes)) {
15518
- if (!isTSLNode(value)) newNodes[key] = value;
15519
- }
15520
- } else {
15521
- newNodes = {};
15522
- }
15523
- return { nodes: newNodes, _hmrVersion: state._hmrVersion + 1 };
15524
- });
15525
- },
15715
+ (targetScope) => rebuildResource(store, "nodes", targetScope),
15526
15716
  [store]
15527
15717
  );
15528
15718
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
15529
15719
  const storeNodes = usePrimaryThree((s) => s.nodes);
15530
- const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
15531
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
15532
- const readerDep = isReader ? storeNodes : null;
15533
- const creatorDep = isReader ? null : hmrVersion;
15534
- const nodes = React.useMemo(() => {
15535
- if (creatorOrScope === void 0) {
15536
- return storeNodes;
15537
- }
15538
- if (typeof creatorOrScope === "string") {
15539
- const scopeData = storeNodes[creatorOrScope];
15540
- if (scopeData && !isTSLNode(scopeData)) return scopeData;
15541
- return {};
15542
- }
15543
- const state = store.getState();
15544
- const set = store.setState;
15545
- const creator = creatorOrScope;
15546
- const wrappedState = createLazyCreatorState(state);
15547
- const created = creator(wrappedState);
15548
- const result = {};
15549
- let hasNewNodes = false;
15550
- if (scope) {
15551
- const currentScope = state.nodes[scope] ?? {};
15552
- for (const [name, node] of Object.entries(created)) {
15553
- if (currentScope[name]) {
15554
- result[name] = currentScope[name];
15555
- } else {
15556
- node.setName?.(`${scope}.${name}`);
15557
- result[name] = node;
15558
- hasNewNodes = true;
15559
- }
15560
- }
15561
- if (hasNewNodes) {
15562
- set((s) => ({
15563
- nodes: {
15564
- ...s.nodes,
15565
- [scope]: { ...s.nodes[scope], ...result }
15566
- }
15567
- }));
15568
- }
15569
- return result;
15570
- }
15571
- for (const [name, node] of Object.entries(created)) {
15572
- const existing = state.nodes[name];
15573
- if (existing && isTSLNode(existing)) {
15574
- result[name] = existing;
15575
- } else {
15576
- node.setName?.(name);
15577
- result[name] = node;
15578
- hasNewNodes = true;
15579
- }
15580
- }
15581
- if (hasNewNodes) {
15582
- set((s) => ({ nodes: { ...s.nodes, ...result } }));
15720
+ const created = useScopedResource({
15721
+ store,
15722
+ kind: "nodes",
15723
+ scope: isReader ? void 0 : scope,
15724
+ isLeaf: isTSLNode,
15725
+ create: () => {
15726
+ if (isReader) return {};
15727
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15728
+ },
15729
+ prepare: (name, node) => {
15730
+ node.setName?.(scope ? `${scope}.${name}` : name);
15731
+ return node;
15583
15732
  }
15584
- return result;
15585
- }, [store, scopeDep, readerDep, creatorDep]);
15733
+ });
15734
+ let nodes = created;
15735
+ if (creatorOrScope === void 0) {
15736
+ nodes = storeNodes;
15737
+ } else if (typeof creatorOrScope === "string") {
15738
+ const scopeData = storeNodes[creatorOrScope];
15739
+ nodes = scopeData && !isTSLNode(scopeData) ? scopeData : {};
15740
+ }
15586
15741
  return { ...nodes, removeNodes: removeNodes2, clearNodes, rebuildNodes };
15587
15742
  }
15588
15743
  function rebuildAllNodes(store, scope) {
15589
- store = store.getState().primaryStore ?? store;
15590
- store.setState((state) => {
15591
- let newNodes = state.nodes;
15592
- if (scope && scope !== "root") {
15593
- const { [scope]: _, ...rest } = state.nodes;
15594
- newNodes = rest;
15595
- } else if (scope === "root") {
15596
- newNodes = {};
15597
- for (const [key, value] of Object.entries(state.nodes)) {
15598
- if (!isTSLNode(value)) newNodes[key] = value;
15599
- }
15600
- } else {
15601
- newNodes = {};
15602
- }
15603
- return { nodes: newNodes, _hmrVersion: state._hmrVersion + 1 };
15604
- });
15744
+ rebuildResource(store, "nodes", scope);
15605
15745
  }
15606
15746
  function removeNodes(set, names, scope) {
15607
15747
  set((state) => {
@@ -15637,7 +15777,7 @@ function useLocalNodes(creator) {
15637
15777
  const textures = usePrimaryThree((s) => s.textures);
15638
15778
  const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
15639
15779
  return React.useMemo(() => {
15640
- const wrappedState = createLazyCreatorState(store.getState());
15780
+ const wrappedState = createLazyCreatorState(store.getState(), store);
15641
15781
  return creator(wrappedState);
15642
15782
  }, [store, creator, uniforms, nodes, textures, hmrVersion]);
15643
15783
  }
@@ -15658,58 +15798,15 @@ const disposeBuffer = (buffer) => {
15658
15798
  function useBuffers(creatorOrScope, scope) {
15659
15799
  const store = usePrimaryStore();
15660
15800
  const removeBuffers = React.useCallback(
15661
- (names, targetScope) => {
15662
- const nameArray = Array.isArray(names) ? names : [names];
15663
- store.setState((state) => {
15664
- if (targetScope) {
15665
- const currentScope = { ...state.buffers[targetScope] };
15666
- for (const name of nameArray) delete currentScope[name];
15667
- return { buffers: { ...state.buffers, [targetScope]: currentScope } };
15668
- }
15669
- const buffers2 = { ...state.buffers };
15670
- for (const name of nameArray) if (isBufferLike(buffers2[name])) delete buffers2[name];
15671
- return { buffers: buffers2 };
15672
- });
15673
- },
15801
+ (names, targetScope) => removeResourceEntries(store, "buffers", Array.isArray(names) ? names : [names], targetScope, isBufferLike),
15674
15802
  [store]
15675
15803
  );
15676
15804
  const clearBuffers = React.useCallback(
15677
- (targetScope) => {
15678
- store.setState((state) => {
15679
- if (targetScope && targetScope !== "root") {
15680
- const { [targetScope]: _, ...rest } = state.buffers;
15681
- return { buffers: rest };
15682
- }
15683
- if (targetScope === "root") {
15684
- const buffers2 = {};
15685
- for (const [key, value] of Object.entries(state.buffers)) {
15686
- if (!isBufferLike(value)) buffers2[key] = value;
15687
- }
15688
- return { buffers: buffers2 };
15689
- }
15690
- return { buffers: {} };
15691
- });
15692
- },
15805
+ (targetScope) => clearResourceEntries(store, "buffers", targetScope, isBufferLike),
15693
15806
  [store]
15694
15807
  );
15695
15808
  const rebuildBuffers = React.useCallback(
15696
- (targetScope) => {
15697
- store.setState((state) => {
15698
- let newBuffers = state.buffers;
15699
- if (targetScope && targetScope !== "root") {
15700
- const { [targetScope]: _, ...rest } = state.buffers;
15701
- newBuffers = rest;
15702
- } else if (targetScope === "root") {
15703
- newBuffers = {};
15704
- for (const [key, value] of Object.entries(state.buffers)) {
15705
- if (!isBufferLike(value)) newBuffers[key] = value;
15706
- }
15707
- } else {
15708
- newBuffers = {};
15709
- }
15710
- return { buffers: newBuffers, _hmrVersion: state._hmrVersion + 1 };
15711
- });
15712
- },
15809
+ (targetScope) => rebuildResource(store, "buffers", targetScope),
15713
15810
  [store]
15714
15811
  );
15715
15812
  const disposeBuffers = React.useCallback(
@@ -15728,85 +15825,33 @@ function useBuffers(creatorOrScope, scope) {
15728
15825
  );
15729
15826
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
15730
15827
  const storeBuffers = usePrimaryThree((s) => s.buffers);
15731
- const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
15732
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
15733
- const readerDep = isReader ? storeBuffers : null;
15734
- const creatorDep = isReader ? null : hmrVersion;
15735
- const buffers = React.useMemo(() => {
15736
- if (creatorOrScope === void 0) {
15737
- return storeBuffers;
15738
- }
15739
- if (typeof creatorOrScope === "string") {
15740
- const scopeData = storeBuffers[creatorOrScope];
15741
- if (scopeData && !isBufferLike(scopeData)) return scopeData;
15742
- return {};
15743
- }
15744
- const state = store.getState();
15745
- const set = store.setState;
15746
- const creator = creatorOrScope;
15747
- const wrappedState = createLazyCreatorState(state);
15748
- const created = creator(wrappedState);
15749
- const result = {};
15750
- let hasNewBuffers = false;
15751
- if (scope) {
15752
- const currentScope = state.buffers[scope] ?? {};
15753
- for (const [name, buffer] of Object.entries(created)) {
15754
- if (currentScope[name]) {
15755
- result[name] = currentScope[name];
15756
- } else {
15757
- if ("setName" in buffer && typeof buffer.setName === "function") {
15758
- buffer.setName(`${scope}.${name}`);
15759
- }
15760
- result[name] = buffer;
15761
- hasNewBuffers = true;
15762
- }
15763
- }
15764
- if (hasNewBuffers) {
15765
- set((s) => ({
15766
- buffers: {
15767
- ...s.buffers,
15768
- [scope]: { ...s.buffers[scope], ...result }
15769
- }
15770
- }));
15771
- }
15772
- return result;
15773
- }
15774
- for (const [name, buffer] of Object.entries(created)) {
15775
- const existing = state.buffers[name];
15776
- if (existing && isBufferLike(existing)) {
15777
- result[name] = existing;
15778
- } else {
15779
- if ("setName" in buffer && typeof buffer.setName === "function") {
15780
- buffer.setName(name);
15781
- }
15782
- result[name] = buffer;
15783
- hasNewBuffers = true;
15828
+ const created = useScopedResource({
15829
+ store,
15830
+ kind: "buffers",
15831
+ scope: isReader ? void 0 : scope,
15832
+ isLeaf: isBufferLike,
15833
+ create: () => {
15834
+ if (isReader) return {};
15835
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15836
+ },
15837
+ prepare: (name, buffer) => {
15838
+ if ("setName" in buffer && typeof buffer.setName === "function") {
15839
+ buffer.setName(scope ? `${scope}.${name}` : name);
15784
15840
  }
15841
+ return buffer;
15785
15842
  }
15786
- if (hasNewBuffers) {
15787
- set((s) => ({ buffers: { ...s.buffers, ...result } }));
15788
- }
15789
- return result;
15790
- }, [store, scopeDep, readerDep, creatorDep]);
15843
+ });
15844
+ let buffers = created;
15845
+ if (creatorOrScope === void 0) {
15846
+ buffers = storeBuffers;
15847
+ } else if (typeof creatorOrScope === "string") {
15848
+ const scopeData = storeBuffers[creatorOrScope];
15849
+ buffers = scopeData && !isBufferLike(scopeData) ? scopeData : {};
15850
+ }
15791
15851
  return { ...buffers, removeBuffers, clearBuffers, rebuildBuffers, disposeBuffers };
15792
15852
  }
15793
15853
  function rebuildAllBuffers(store, scope) {
15794
- store = store.getState().primaryStore ?? store;
15795
- store.setState((state) => {
15796
- let newBuffers = state.buffers;
15797
- if (scope && scope !== "root") {
15798
- const { [scope]: _, ...rest } = state.buffers;
15799
- newBuffers = rest;
15800
- } else if (scope === "root") {
15801
- newBuffers = {};
15802
- for (const [key, value] of Object.entries(state.buffers)) {
15803
- if (!isBufferLike(value)) newBuffers[key] = value;
15804
- }
15805
- } else {
15806
- newBuffers = {};
15807
- }
15808
- return { buffers: newBuffers, _hmrVersion: state._hmrVersion + 1 };
15809
- });
15854
+ rebuildResource(store, "buffers", scope);
15810
15855
  }
15811
15856
 
15812
15857
  const isStorageLike = (value) => {
@@ -15825,58 +15870,15 @@ const disposeStorage = (storage) => {
15825
15870
  function useGPUStorage(creatorOrScope, scope) {
15826
15871
  const store = usePrimaryStore();
15827
15872
  const removeStorage = React.useCallback(
15828
- (names, targetScope) => {
15829
- const nameArray = Array.isArray(names) ? names : [names];
15830
- store.setState((state) => {
15831
- if (targetScope) {
15832
- const currentScope = { ...state.gpuStorage[targetScope] };
15833
- for (const name of nameArray) delete currentScope[name];
15834
- return { gpuStorage: { ...state.gpuStorage, [targetScope]: currentScope } };
15835
- }
15836
- const gpuStorage2 = { ...state.gpuStorage };
15837
- for (const name of nameArray) if (isStorageLike(gpuStorage2[name])) delete gpuStorage2[name];
15838
- return { gpuStorage: gpuStorage2 };
15839
- });
15840
- },
15873
+ (names, targetScope) => removeResourceEntries(store, "gpuStorage", Array.isArray(names) ? names : [names], targetScope, isStorageLike),
15841
15874
  [store]
15842
15875
  );
15843
15876
  const clearStorage = React.useCallback(
15844
- (targetScope) => {
15845
- store.setState((state) => {
15846
- if (targetScope && targetScope !== "root") {
15847
- const { [targetScope]: _, ...rest } = state.gpuStorage;
15848
- return { gpuStorage: rest };
15849
- }
15850
- if (targetScope === "root") {
15851
- const gpuStorage2 = {};
15852
- for (const [key, value] of Object.entries(state.gpuStorage)) {
15853
- if (!isStorageLike(value)) gpuStorage2[key] = value;
15854
- }
15855
- return { gpuStorage: gpuStorage2 };
15856
- }
15857
- return { gpuStorage: {} };
15858
- });
15859
- },
15877
+ (targetScope) => clearResourceEntries(store, "gpuStorage", targetScope, isStorageLike),
15860
15878
  [store]
15861
15879
  );
15862
15880
  const rebuildStorage = React.useCallback(
15863
- (targetScope) => {
15864
- store.setState((state) => {
15865
- let newStorage = state.gpuStorage;
15866
- if (targetScope && targetScope !== "root") {
15867
- const { [targetScope]: _, ...rest } = state.gpuStorage;
15868
- newStorage = rest;
15869
- } else if (targetScope === "root") {
15870
- newStorage = {};
15871
- for (const [key, value] of Object.entries(state.gpuStorage)) {
15872
- if (!isStorageLike(value)) newStorage[key] = value;
15873
- }
15874
- } else {
15875
- newStorage = {};
15876
- }
15877
- return { gpuStorage: newStorage, _hmrVersion: state._hmrVersion + 1 };
15878
- });
15879
- },
15881
+ (targetScope) => rebuildResource(store, "gpuStorage", targetScope),
15880
15882
  [store]
15881
15883
  );
15882
15884
  const disposeStorageFn = React.useCallback(
@@ -15895,72 +15897,33 @@ function useGPUStorage(creatorOrScope, scope) {
15895
15897
  );
15896
15898
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
15897
15899
  const storeStorage = usePrimaryThree((s) => s.gpuStorage);
15898
- const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
15899
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
15900
- const readerDep = isReader ? storeStorage : null;
15901
- const creatorDep = isReader ? null : hmrVersion;
15902
- const gpuStorage = React.useMemo(() => {
15903
- if (creatorOrScope === void 0) {
15904
- return storeStorage;
15905
- }
15906
- if (typeof creatorOrScope === "string") {
15907
- const scopeData = storeStorage[creatorOrScope];
15908
- if (scopeData && !isStorageLike(scopeData)) return scopeData;
15909
- return {};
15910
- }
15911
- const state = store.getState();
15912
- const set = store.setState;
15913
- const creator = creatorOrScope;
15914
- const wrappedState = createLazyCreatorState(state);
15915
- const created = creator(wrappedState);
15916
- const result = {};
15917
- let hasNewStorage = false;
15918
- if (scope) {
15919
- const currentScope = state.gpuStorage[scope] ?? {};
15920
- for (const [name, storage] of Object.entries(created)) {
15921
- if (currentScope[name]) {
15922
- result[name] = currentScope[name];
15923
- } else {
15924
- if ("setName" in storage && typeof storage.setName === "function") {
15925
- storage.setName(`${scope}.${name}`);
15926
- }
15927
- if ("name" in storage && typeof storage.name === "string") {
15928
- storage.name = `${scope}.${name}`;
15929
- }
15930
- result[name] = storage;
15931
- hasNewStorage = true;
15932
- }
15933
- }
15934
- if (hasNewStorage) {
15935
- set((s) => ({
15936
- gpuStorage: {
15937
- ...s.gpuStorage,
15938
- [scope]: { ...s.gpuStorage[scope], ...result }
15939
- }
15940
- }));
15900
+ const created = useScopedResource({
15901
+ store,
15902
+ kind: "gpuStorage",
15903
+ scope: isReader ? void 0 : scope,
15904
+ isLeaf: isStorageLike,
15905
+ create: () => {
15906
+ if (isReader) return {};
15907
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15908
+ },
15909
+ prepare: (name, storage) => {
15910
+ const label = scope ? `${scope}.${name}` : name;
15911
+ if ("setName" in storage && typeof storage.setName === "function") {
15912
+ storage.setName(label);
15941
15913
  }
15942
- return result;
15943
- }
15944
- for (const [name, storage] of Object.entries(created)) {
15945
- const existing = state.gpuStorage[name];
15946
- if (existing && isStorageLike(existing)) {
15947
- result[name] = existing;
15948
- } else {
15949
- if ("setName" in storage && typeof storage.setName === "function") {
15950
- storage.setName(name);
15951
- }
15952
- if ("name" in storage && typeof storage.name === "string") {
15953
- storage.name = name;
15954
- }
15955
- result[name] = storage;
15956
- hasNewStorage = true;
15914
+ if ("name" in storage && typeof storage.name === "string") {
15915
+ storage.name = label;
15957
15916
  }
15917
+ return storage;
15958
15918
  }
15959
- if (hasNewStorage) {
15960
- set((s) => ({ gpuStorage: { ...s.gpuStorage, ...result } }));
15961
- }
15962
- return result;
15963
- }, [store, scopeDep, readerDep, creatorDep]);
15919
+ });
15920
+ let gpuStorage = created;
15921
+ if (creatorOrScope === void 0) {
15922
+ gpuStorage = storeStorage;
15923
+ } else if (typeof creatorOrScope === "string") {
15924
+ const scopeData = storeStorage[creatorOrScope];
15925
+ gpuStorage = scopeData && !isStorageLike(scopeData) ? scopeData : {};
15926
+ }
15964
15927
  return {
15965
15928
  ...gpuStorage,
15966
15929
  removeStorage,
@@ -15970,22 +15933,7 @@ function useGPUStorage(creatorOrScope, scope) {
15970
15933
  };
15971
15934
  }
15972
15935
  function rebuildAllStorage(store, scope) {
15973
- store = store.getState().primaryStore ?? store;
15974
- store.setState((state) => {
15975
- let newStorage = state.gpuStorage;
15976
- if (scope && scope !== "root") {
15977
- const { [scope]: _, ...rest } = state.gpuStorage;
15978
- newStorage = rest;
15979
- } else if (scope === "root") {
15980
- newStorage = {};
15981
- for (const [key, value] of Object.entries(state.gpuStorage)) {
15982
- if (!isStorageLike(value)) newStorage[key] = value;
15983
- }
15984
- } else {
15985
- newStorage = {};
15986
- }
15987
- return { gpuStorage: newStorage, _hmrVersion: state._hmrVersion + 1 };
15988
- });
15936
+ rebuildResource(store, "gpuStorage", scope);
15989
15937
  }
15990
15938
 
15991
15939
  function useRenderPipeline(mainCB, setupCB) {
@@ -16026,12 +15974,12 @@ function useRenderPipeline(mainCB, setupCB) {
16026
15974
  const state = store.getState();
16027
15975
  const set = store.setState;
16028
15976
  try {
16029
- let pp = state.renderPipeline;
15977
+ let pipeline = state.renderPipeline;
16030
15978
  let currentPasses = { ...state.passes };
16031
- let justCreatedPP = false;
16032
- if (!pp) {
16033
- pp = new webgpu.PostProcessing(renderer);
16034
- justCreatedPP = true;
15979
+ let justCreatedPipeline = false;
15980
+ if (!pipeline) {
15981
+ pipeline = new webgpu.RenderPipeline(renderer);
15982
+ justCreatedPipeline = true;
16035
15983
  }
16036
15984
  const cacheValid = scenePassCacheRef.current && scenePassCacheRef.current.sceneUuid === scene.uuid && scenePassCacheRef.current.cameraUuid === camera.uuid;
16037
15985
  let scenePass;
@@ -16042,9 +15990,9 @@ function useRenderPipeline(mainCB, setupCB) {
16042
15990
  scenePassCacheRef.current = { sceneUuid: scene.uuid, cameraUuid: camera.uuid, scenePass };
16043
15991
  }
16044
15992
  currentPasses.scenePass = scenePass;
16045
- if (!pp.outputNode || justCreatedPP) pp.outputNode = scenePass;
16046
- set({ renderPipeline: pp, passes: currentPasses });
16047
- const shouldRunCallbacks = justCreatedPP || !callbacksRanRef.current || !cacheValid;
15993
+ if (!pipeline.outputNode || justCreatedPipeline) pipeline.outputNode = scenePass;
15994
+ set({ renderPipeline: pipeline, passes: currentPasses });
15995
+ const shouldRunCallbacks = justCreatedPipeline || !callbacksRanRef.current || !cacheValid;
16048
15996
  if (shouldRunCallbacks) {
16049
15997
  if (setupCBRef.current) {
16050
15998
  const freshState = store.getState();
@@ -16065,7 +16013,7 @@ function useRenderPipeline(mainCB, setupCB) {
16065
16013
  callbacksRanRef.current = true;
16066
16014
  }
16067
16015
  } catch (error) {
16068
- console.error("[useRenderPipeline] Setup error:", error);
16016
+ console.warn("[useRenderPipeline] Setup failed; the render pipeline was not configured:", error);
16069
16017
  }
16070
16018
  }, [store, renderer, scene, camera, isLegacy, rebuildVersion]);
16071
16019
  const passes = useThree((s) => s.passes);
@@ -16102,7 +16050,6 @@ exports.REACT_INTERNAL_PROPS = REACT_INTERNAL_PROPS;
16102
16050
  exports.RESERVED_PROPS = RESERVED_PROPS;
16103
16051
  exports.Texture = Texture;
16104
16052
  exports._roots = _roots;
16105
- exports.act = act;
16106
16053
  exports.addAfterEffect = addAfterEffect;
16107
16054
  exports.addEffect = addEffect;
16108
16055
  exports.addTail = addTail;