@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.
@@ -1,5 +1,5 @@
1
1
  import * as webgpu from 'three/webgpu';
2
- import { RenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene, WebGLCubeRenderTarget, HalfFloatType, Color, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, SRGBColorSpace, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, CanvasTarget, Raycaster, OrthographicCamera, PerspectiveCamera, PCFShadowMap, VSMShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGPURenderer, Vector4, PostProcessing } from 'three/webgpu';
2
+ import { CubeRenderTarget, RenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene, HalfFloatType, Color, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, ShaderMaterial, Uniform, SRGBColorSpace, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, CanvasTarget, Raycaster, OrthographicCamera, PerspectiveCamera, PCFShadowMap, VSMShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGPURenderer, Vector4, RenderPipeline } from 'three/webgpu';
3
3
  import { Inspector } from 'three/addons/inspector/Inspector.js';
4
4
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
5
5
  import * as React from 'react';
@@ -12,7 +12,7 @@ import { HDRLoader } from 'three/examples/jsm/loaders/HDRLoader.js';
12
12
  import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js';
13
13
  import { UltraHDRLoader } from 'three/examples/jsm/loaders/UltraHDRLoader.js';
14
14
  import { GainMapLoader } from '@monogrid/gainmap-js';
15
- import Tb, { unstable_scheduleCallback, unstable_IdlePriority } from 'scheduler';
15
+ import Tb, { unstable_getCurrentPriorityLevel, unstable_IdlePriority, unstable_LowPriority, unstable_NormalPriority, unstable_UserBlockingPriority, unstable_ImmediatePriority, unstable_scheduleCallback } from 'scheduler';
16
16
  import { createWithEqualityFn } from 'zustand/traditional';
17
17
  import { getScheduler } from '@pmndrs/scheduler';
18
18
  export { Scheduler, getScheduler } from '@pmndrs/scheduler';
@@ -43,13 +43,16 @@ const WebGLRenderer = class WebGLRenderer2 {
43
43
  }
44
44
  };
45
45
  const WebGLRenderTarget = null;
46
+ const WebGLCubeRenderTarget = null;
46
47
 
47
48
  const THREE = /*#__PURE__*/_mergeNamespaces({
48
49
  __proto__: null,
50
+ CubeRenderTargetCompat: CubeRenderTarget,
49
51
  Inspector: Inspector,
50
52
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
51
53
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
52
54
  RenderTargetCompat: RenderTarget,
55
+ WebGLCubeRenderTarget: WebGLCubeRenderTarget,
53
56
  WebGLRenderTarget: WebGLRenderTarget,
54
57
  WebGLRenderer: WebGLRenderer
55
58
  }, [webgpu]);
@@ -323,15 +326,16 @@ function EnvironmentPortal({
323
326
  preset = void 0,
324
327
  extensions
325
328
  }) {
326
- const gl = useThree$1((state) => state.gl);
329
+ const renderer = useThree$1((state) => state.renderer);
330
+ const isLegacy = useThree$1((state) => state.isLegacy);
327
331
  const defaultScene = useThree$1((state) => state.scene);
328
332
  const camera = React.useRef(null);
329
333
  const [virtualScene] = React.useState(() => new Scene());
330
334
  const fbo = React.useMemo(() => {
331
- const fbo2 = new WebGLCubeRenderTarget(resolution);
335
+ const fbo2 = isLegacy ? new WebGLCubeRenderTarget(resolution) : new CubeRenderTarget(resolution);
332
336
  fbo2.texture.type = HalfFloatType;
333
337
  return fbo2;
334
- }, [resolution]);
338
+ }, [resolution, isLegacy]);
335
339
  React.useEffect(() => {
336
340
  return () => {
337
341
  fbo.dispose();
@@ -339,10 +343,10 @@ function EnvironmentPortal({
339
343
  }, [fbo]);
340
344
  React.useLayoutEffect(() => {
341
345
  if (frames === 1) {
342
- const autoClear = gl.autoClear;
343
- gl.autoClear = true;
344
- camera.current.update(gl, virtualScene);
345
- gl.autoClear = autoClear;
346
+ const autoClear = renderer.autoClear;
347
+ renderer.autoClear = true;
348
+ camera.current.update(renderer, virtualScene);
349
+ renderer.autoClear = autoClear;
346
350
  }
347
351
  return setEnvProps(background, scene, defaultScene, fbo.texture, {
348
352
  backgroundBlurriness: blur ?? backgroundBlurriness,
@@ -359,7 +363,7 @@ function EnvironmentPortal({
359
363
  defaultScene,
360
364
  background,
361
365
  frames,
362
- gl,
366
+ renderer,
363
367
  blur,
364
368
  backgroundBlurriness,
365
369
  backgroundIntensity,
@@ -370,10 +374,10 @@ function EnvironmentPortal({
370
374
  let count = 1;
371
375
  useFrame$1(() => {
372
376
  if (frames === Infinity || count < frames) {
373
- const autoClear = gl.autoClear;
374
- gl.autoClear = true;
375
- camera.current.update(gl, virtualScene);
376
- gl.autoClear = autoClear;
377
+ const autoClear = renderer.autoClear;
378
+ renderer.autoClear = true;
379
+ camera.current.update(renderer, virtualScene);
380
+ renderer.autoClear = autoClear;
377
381
  count++;
378
382
  }
379
383
  });
@@ -440,7 +444,6 @@ function Environment(props) {
440
444
  var __defProp$1 = Object.defineProperty;
441
445
  var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
442
446
  var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
443
- const act = React["act"];
444
447
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React.useLayoutEffect : React.useEffect;
445
448
  function useMutableCallback(fn) {
446
449
  const ref = React.useRef(fn);
@@ -616,8 +619,7 @@ function prepare(target, root, type, props) {
616
619
  object,
617
620
  eventCount: 0,
618
621
  handlers: {},
619
- isHidden: false,
620
- deferredRefs: []
622
+ isHidden: false
621
623
  };
622
624
  if (object) object.__r3f = instance;
623
625
  }
@@ -774,6 +776,17 @@ function unregisterVisibility(store, object) {
774
776
  internal.visibilityRegistry.delete(object.uuid);
775
777
  internal.occlusionCache.delete(object);
776
778
  }
779
+ function updateVisibilityHandlers(store, object, handlers) {
780
+ const { internal } = store.getState();
781
+ const entry = internal.visibilityRegistry.get(object.uuid);
782
+ if (!entry) return false;
783
+ entry.handlers = handlers;
784
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
785
+ object.occlusionTest = true;
786
+ enableOcclusion(store);
787
+ }
788
+ return true;
789
+ }
777
790
  function checkVisibility(state) {
778
791
  const { internal, camera } = state;
779
792
  const registry = internal.visibilityRegistry;
@@ -934,9 +947,9 @@ function diffProps(instance, newProps) {
934
947
  const { root, key } = resolve(instance.object, prop);
935
948
  if (root.constructor && root.constructor.length === 0) {
936
949
  const ctor = getMemoizedPrototype(root);
937
- if (!is.und(ctor)) changedProps[key] = ctor[key];
950
+ if (!is.und(ctor)) changedProps[prop] = ctor[key];
938
951
  } else {
939
- changedProps[key] = 0;
952
+ changedProps[prop] = 0;
940
953
  }
941
954
  }
942
955
  return changedProps;
@@ -961,10 +974,7 @@ function applyProps(object, props) {
961
974
  continue;
962
975
  }
963
976
  if (value === void 0) continue;
964
- if (isFromRef(value)) {
965
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
966
- continue;
967
- }
977
+ if (isFromRef(value)) continue;
968
978
  if (isOnce(value)) {
969
979
  if (instance?.appliedOnce?.has(prop)) continue;
970
980
  if (instance) {
@@ -1000,6 +1010,19 @@ function applyProps(object, props) {
1000
1010
  } else if (isVectorLike(target) && is.num(value)) {
1001
1011
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
1002
1012
  else target.set(value);
1013
+ } else if (root instanceof ShaderMaterial && key === "uniforms" && is.obj(value)) {
1014
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1015
+ const uniforms = root.uniforms;
1016
+ const nextUniforms = value;
1017
+ for (const name in nextUniforms) {
1018
+ const uniform = nextUniforms[name];
1019
+ const targetUniform = uniforms[name];
1020
+ if (targetUniform) Object.assign(targetUniform, uniform);
1021
+ else {
1022
+ const nextUniform = uniform instanceof Uniform ? uniform.clone() : new Uniform(uniform.value);
1023
+ uniforms[name] = nextUniform;
1024
+ }
1025
+ }
1003
1026
  } else {
1004
1027
  root[key] = value;
1005
1028
  if (key.endsWith("Node") && root.isMaterial) {
@@ -1018,6 +1041,9 @@ function applyProps(object, props) {
1018
1041
  if (instance.eventCount && object2.raycast !== null) {
1019
1042
  rootState.internal.interaction.push(object2);
1020
1043
  }
1044
+ }
1045
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1046
+ const object2 = instance.object;
1021
1047
  const root = findInitialRoot(instance);
1022
1048
  const visibilityHandlers = {
1023
1049
  onFramed: instance.handlers.onFramed,
@@ -1025,7 +1051,9 @@ function applyProps(object, props) {
1025
1051
  onVisible: instance.handlers.onVisible
1026
1052
  };
1027
1053
  if (hasVisibilityHandlers(visibilityHandlers)) {
1028
- registerVisibility(root, object2, visibilityHandlers);
1054
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1055
+ registerVisibility(root, object2, visibilityHandlers);
1056
+ }
1029
1057
  } else {
1030
1058
  unregisterVisibility(root, object2);
1031
1059
  }
@@ -1553,6 +1581,7 @@ function createPointerEvents(store) {
1553
1581
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1554
1582
  }
1555
1583
  },
1584
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1556
1585
  registerPointer: (config) => {
1557
1586
  const pointerId = nextXRPointerId++;
1558
1587
  xrPointers.set(pointerId, config);
@@ -1640,11 +1669,10 @@ function notifyAlpha({ message, link }) {
1640
1669
  }
1641
1670
 
1642
1671
  const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1643
- const INTERNAL_FIBER_MARKERS = ["packages/fiber/src", "packages/fiber/dist", "@react-three/fiber", "@react-three_fiber"];
1644
1672
  function isInternalRendererAccess(stack, callerDepth = 2) {
1645
1673
  if (!stack) return false;
1646
1674
  const caller = stack.split("\n")[callerDepth] ?? "";
1647
- return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m)) || INTERNAL_FIBER_MARKERS.some((m) => caller.includes(m));
1675
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
1648
1676
  }
1649
1677
 
1650
1678
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
@@ -1779,6 +1807,7 @@ const createStore = (invalidate, advance) => {
1779
1807
  }),
1780
1808
  setFrameloop: (frameloop = "always") => {
1781
1809
  set(() => ({ frameloop }));
1810
+ getScheduler().frameloop = frameloop;
1782
1811
  },
1783
1812
  setError: (error) => set(() => ({ error })),
1784
1813
  error: null,
@@ -1959,19 +1988,25 @@ function loadingFn(extensions, onProgress) {
1959
1988
  );
1960
1989
  };
1961
1990
  }
1962
- function useLoader(loader, input, extensions, onProgress) {
1963
- const keys = Array.isArray(input) ? input : [input];
1991
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
1992
+ const inputs = Array.isArray(input) ? input : [input];
1993
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
1964
1994
  const fn = loadingFn(extensions, onProgress);
1965
- const results = keys.map((key) => suspend(fn, [loader, key], { equal: is.equ }));
1995
+ const results = cacheKeys.map(
1996
+ (key, index) => suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
1997
+ );
1966
1998
  return Array.isArray(input) ? results : results[0];
1967
1999
  }
1968
- useLoader.preload = function(loader, input, extensions, onProgress) {
1969
- const keys = Array.isArray(input) ? input : [input];
1970
- keys.forEach((key) => preload(loadingFn(extensions, onProgress), [loader, key]));
2000
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2001
+ const inputs = Array.isArray(input) ? input : [input];
2002
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2003
+ cacheKeys.forEach(
2004
+ (key, index) => preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2005
+ );
1971
2006
  };
1972
- useLoader.clear = function(loader, input) {
1973
- const keys = Array.isArray(input) ? input : [input];
1974
- keys.forEach((key) => clear([loader, key]));
2007
+ useLoader.clear = function(loader, input, cacheKey) {
2008
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2009
+ cacheKeys.forEach((key) => clear([loader, key]));
1975
2010
  };
1976
2011
  useLoader.loader = getLoader;
1977
2012
 
@@ -2391,7 +2426,7 @@ function advance(timestamp) {
2391
2426
  getScheduler().step(timestamp);
2392
2427
  }
2393
2428
 
2394
- const version = "10.0.0-alpha.2";
2429
+ const version = "10.0.0-alpha.3";
2395
2430
  const packageData = {
2396
2431
  version: version};
2397
2432
 
@@ -13647,7 +13682,7 @@ function n0() {
13647
13682
  var t0 = n0();
13648
13683
  const r0 = Xb(t0);
13649
13684
 
13650
- const t = 1, o = 8, r = 32, e = 2;
13685
+ const t = 1, o = 8, r = 32, e = 2, i$1 = 268435456;
13651
13686
 
13652
13687
  function createReconciler(config) {
13653
13688
  const reconciler2 = r0(config);
@@ -13812,7 +13847,15 @@ function setFiberRef(fiber, publicInstance) {
13812
13847
  }
13813
13848
  }
13814
13849
  const reconstructed = [];
13815
- function swapInstances() {
13850
+ function flushReconstructedInstances() {
13851
+ if (reconstructed.length === 0) return;
13852
+ try {
13853
+ swapReconstructedInstances();
13854
+ } finally {
13855
+ reconstructed.length = 0;
13856
+ }
13857
+ }
13858
+ function swapReconstructedInstances() {
13816
13859
  for (const [instance] of reconstructed) {
13817
13860
  const parent = instance.parent;
13818
13861
  if (parent) {
@@ -13830,6 +13873,7 @@ function swapInstances() {
13830
13873
  }
13831
13874
  }
13832
13875
  if (instance.isHidden) unhideInstance(instance);
13876
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
13833
13877
  if (instance.object.__r3f) delete instance.object.__r3f;
13834
13878
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
13835
13879
  }
@@ -13842,6 +13886,8 @@ function swapInstances() {
13842
13886
  instance.object.__r3f = instance;
13843
13887
  setFiberRef(fiber, instance.object);
13844
13888
  delete instance.appliedOnce;
13889
+ instance.eventCount = 0;
13890
+ instance.handlers = {};
13845
13891
  applyProps(instance.object, instance.props);
13846
13892
  if (instance.props.attach) {
13847
13893
  attach(parent, instance);
@@ -13858,14 +13904,114 @@ function swapInstances() {
13858
13904
  invalidateInstance(instance);
13859
13905
  }
13860
13906
  }
13861
- reconstructed.length = 0;
13862
13907
  }
13863
13908
  const handleTextInstance = () => {
13864
13909
  };
13865
13910
  const NO_CONTEXT = {};
13866
13911
  let currentUpdatePriority = NoEventPriority;
13867
- const NoFlags = 0;
13868
- const Update = 4;
13912
+ function getEventPriority(type) {
13913
+ switch (type) {
13914
+ case "beforetoggle":
13915
+ case "cancel":
13916
+ case "click":
13917
+ case "close":
13918
+ case "contextmenu":
13919
+ case "copy":
13920
+ case "cut":
13921
+ case "auxclick":
13922
+ case "dblclick":
13923
+ case "dragend":
13924
+ case "dragstart":
13925
+ case "drop":
13926
+ case "focusin":
13927
+ case "focusout":
13928
+ case "input":
13929
+ case "invalid":
13930
+ case "keydown":
13931
+ case "keypress":
13932
+ case "keyup":
13933
+ case "mousedown":
13934
+ case "mouseup":
13935
+ case "paste":
13936
+ case "pause":
13937
+ case "play":
13938
+ case "pointercancel":
13939
+ case "pointerdown":
13940
+ case "pointerup":
13941
+ case "ratechange":
13942
+ case "reset":
13943
+ case "resize":
13944
+ case "seeked":
13945
+ case "submit":
13946
+ case "touchcancel":
13947
+ case "touchend":
13948
+ case "touchstart":
13949
+ case "volumechange":
13950
+ case "change":
13951
+ case "selectionchange":
13952
+ case "compositionstart":
13953
+ case "compositionend":
13954
+ case "compositionupdate":
13955
+ case "beforeinput":
13956
+ case "blur":
13957
+ case "fullscreenchange":
13958
+ case "focus":
13959
+ case "hashchange":
13960
+ case "popstate":
13961
+ case "select":
13962
+ case "selectstart":
13963
+ return e;
13964
+ case "drag":
13965
+ case "dragenter":
13966
+ case "dragexit":
13967
+ case "dragleave":
13968
+ case "dragover":
13969
+ case "mousemove":
13970
+ case "mouseout":
13971
+ case "mouseover":
13972
+ case "pointermove":
13973
+ case "pointerout":
13974
+ case "pointerover":
13975
+ case "scroll":
13976
+ case "touchmove":
13977
+ case "wheel":
13978
+ case "mouseenter":
13979
+ case "mouseleave":
13980
+ case "pointerenter":
13981
+ case "pointerleave":
13982
+ return o;
13983
+ case "message": {
13984
+ switch (unstable_getCurrentPriorityLevel()) {
13985
+ case unstable_ImmediatePriority:
13986
+ return e;
13987
+ case unstable_UserBlockingPriority:
13988
+ return o;
13989
+ case unstable_NormalPriority:
13990
+ case unstable_LowPriority:
13991
+ return r;
13992
+ case unstable_IdlePriority:
13993
+ return i$1;
13994
+ default:
13995
+ return r;
13996
+ }
13997
+ }
13998
+ default:
13999
+ return r;
14000
+ }
14001
+ }
14002
+ function scheduleMicrotask(callback) {
14003
+ if (typeof queueMicrotask === "function") {
14004
+ queueMicrotask(callback);
14005
+ } else if (typeof Promise !== "undefined") {
14006
+ Promise.resolve().then(callback).catch((error) => {
14007
+ setTimeout(() => {
14008
+ throw error;
14009
+ });
14010
+ });
14011
+ } else {
14012
+ setTimeout(callback);
14013
+ }
14014
+ }
13869
14015
  const reconciler = /* @__PURE__ */ createReconciler({
13870
14016
  isPrimaryRenderer: false,
13871
14017
  warnsIfNotActing: false,
@@ -13904,16 +14050,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
13904
14050
  else if (newProps.args?.length !== oldProps.args?.length) reconstruct = true;
13905
14051
  else if (newProps.args?.some((value, index) => value !== oldProps.args?.[index])) reconstruct = true;
13906
14052
  if (reconstruct) {
13907
- reconstructed.push([instance, { ...newProps }, fiber]);
14053
+ reconstructed.push([instance, getInstanceProps(newProps), fiber]);
13908
14054
  } else {
13909
14055
  const changedProps = diffProps(instance, newProps);
13910
- if (Object.keys(changedProps).length) {
13911
- Object.assign(instance.props, changedProps);
13912
- applyProps(instance.object, changedProps);
13913
- }
14056
+ const attach2 = instance.props.attach;
14057
+ instance.props = getInstanceProps(newProps);
14058
+ if (attach2 !== void 0) instance.props.attach = attach2;
14059
+ else delete instance.props.attach;
14060
+ if (Object.keys(changedProps).length) applyProps(instance.object, changedProps);
13914
14061
  }
13915
- const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
13916
- if (isTailSibling) swapInstances();
13917
14062
  },
13918
14063
  finalizeInitialChildren: (instance) => {
13919
14064
  for (const prop in instance.props) {
@@ -13938,8 +14083,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
13938
14083
  const target = container.getState().internal.container ?? container.getState().scene;
13939
14084
  return prepare(target, container, "", {});
13940
14085
  },
13941
- resetAfterCommit: () => {
13942
- },
14086
+ // Reconstructed instances are swapped once all mutations are committed,
14087
+ // before layout effects run so refs point to the new objects
14088
+ resetAfterCommit: flushReconstructedInstances,
13943
14089
  shouldSetTextContent: () => false,
13944
14090
  clearContainer: () => false,
13945
14091
  hideInstance,
@@ -13947,6 +14093,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
13947
14093
  createTextInstance: handleTextInstance,
13948
14094
  hideTextInstance: handleTextInstance,
13949
14095
  unhideTextInstance: handleTextInstance,
14096
+ // Mirrors react-dom, which flushes discrete work in microtasks
14097
+ supportsMicrotasks: true,
14098
+ scheduleMicrotask,
13950
14099
  scheduleTimeout: typeof setTimeout === "function" ? setTimeout : void 0,
13951
14100
  cancelTimeout: typeof clearTimeout === "function" ? clearTimeout : void 0,
13952
14101
  noTimeout: -1,
@@ -13987,28 +14136,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
13987
14136
  },
13988
14137
  resolveUpdatePriority() {
13989
14138
  if (currentUpdatePriority !== NoEventPriority) return currentUpdatePriority;
13990
- switch (typeof window !== "undefined" && window.event?.type) {
13991
- case "click":
13992
- case "contextmenu":
13993
- case "dblclick":
13994
- case "dragenter":
13995
- case "dragleave":
13996
- case "drop":
13997
- case "pointercancel":
13998
- case "pointerdown":
13999
- case "pointerup":
14000
- return e;
14001
- case "dragover":
14002
- case "pointermove":
14003
- case "pointerout":
14004
- case "pointerover":
14005
- case "pointerenter":
14006
- case "pointerleave":
14007
- case "wheel":
14008
- return o;
14009
- default:
14010
- return r;
14011
- }
14139
+ const eventType = typeof window !== "undefined" ? window.event?.type : void 0;
14140
+ if (eventType === void 0) return r;
14141
+ return getEventPriority(eventType);
14012
14142
  },
14013
14143
  resetFormInstance() {
14014
14144
  },
@@ -14057,11 +14187,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14057
14187
  cloneMutableTextInstance(textInstance) {
14058
14188
  return textInstance;
14059
14189
  },
14190
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14191
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14192
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14193
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14194
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14195
+ // Guarded by a test asserting a full render + unmount never reaches them.
14060
14196
  cloneRootViewTransitionContainer(_rootContainer) {
14061
- throw new Error("Not implemented.");
14062
14197
  },
14063
14198
  removeRootViewTransitionClone(_rootContainer, _clone) {
14064
- throw new Error("Not implemented.");
14065
14199
  },
14066
14200
  // https://github.com/facebook/react/pull/32465
14067
14201
  createFragmentInstance: (_fiber) => null,
@@ -14146,6 +14280,7 @@ function createRoot(canvas) {
14146
14280
  const lastConfiguredProps = {};
14147
14281
  let configured = false;
14148
14282
  let pending = null;
14283
+ let rendererSetup = null;
14149
14284
  return {
14150
14285
  async configure(props = {}) {
14151
14286
  let resolve;
@@ -14176,7 +14311,7 @@ function createRoot(canvas) {
14176
14311
  forceEven
14177
14312
  } = props;
14178
14313
  const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || SRGBColorSpace;
14179
- const state = store.getState();
14314
+ let state = store.getState();
14180
14315
  const defaultGPUProps = {
14181
14316
  canvas,
14182
14317
  antialias: true
@@ -14190,52 +14325,64 @@ function createRoot(canvas) {
14190
14325
  throw new Error("Cannot use both gl and renderer props at the same time");
14191
14326
  }
14192
14327
  let renderer = state.internal.actualRenderer;
14193
- if (primaryCanvas && !state.internal.actualRenderer) {
14194
- const primary = await waitForPrimary(primaryCanvas);
14195
- renderer = primary.renderer;
14196
- state.internal.actualRenderer = renderer;
14197
- const canvasTarget = new CanvasTarget(canvas);
14198
- primary.store.setState((prev) => ({
14199
- internal: { ...prev.internal, isMultiCanvas: true }
14200
- }));
14201
- state.set((prev) => ({
14202
- webGPUSupported: primary.store.getState().webGPUSupported,
14203
- renderer,
14204
- primaryStore: primary.store,
14205
- internal: {
14206
- ...prev.internal,
14207
- canvasTarget,
14208
- isMultiCanvas: true,
14209
- isSecondary: true,
14210
- targetId: primaryCanvas
14211
- }
14212
- }));
14213
- } else if (!state.internal.actualRenderer) {
14214
- renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
14215
- if (!renderer.hasInitialized?.()) {
14216
- const size2 = computeInitialSize(canvas, propsSize);
14217
- if (size2.width > 0 && size2.height > 0) {
14218
- const pixelRatio = calculateDpr(dpr);
14219
- canvas.width = size2.width * pixelRatio;
14220
- canvas.height = size2.height * pixelRatio;
14221
- }
14222
- await renderer.init();
14223
- }
14224
- const backend = renderer.backend;
14225
- const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14226
- state.internal.actualRenderer = renderer;
14227
- state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14228
- if (canvasId && !state.internal.isSecondary) {
14229
- const canvasTarget = new CanvasTarget(canvas);
14230
- const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14231
- state.set((prev) => ({
14232
- internal: {
14233
- ...prev.internal,
14234
- canvasTarget,
14235
- unregisterPrimary
14328
+ if (!state.internal.actualRenderer) {
14329
+ if (!rendererSetup) {
14330
+ rendererSetup = (async () => {
14331
+ if (primaryCanvas) {
14332
+ const primary = await waitForPrimary(primaryCanvas);
14333
+ renderer = primary.renderer;
14334
+ state.internal.actualRenderer = renderer;
14335
+ const canvasTarget = new CanvasTarget(canvas);
14336
+ primary.store.setState((prev) => ({
14337
+ internal: { ...prev.internal, isMultiCanvas: true }
14338
+ }));
14339
+ state.set((prev) => ({
14340
+ webGPUSupported: primary.store.getState().webGPUSupported,
14341
+ renderer,
14342
+ primaryStore: primary.store,
14343
+ internal: {
14344
+ ...prev.internal,
14345
+ canvasTarget,
14346
+ isMultiCanvas: true,
14347
+ isSecondary: true,
14348
+ targetId: primaryCanvas
14349
+ }
14350
+ }));
14351
+ } else {
14352
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
14353
+ if (!renderer.hasInitialized?.()) {
14354
+ const size2 = computeInitialSize(canvas, propsSize);
14355
+ if (size2.width > 0 && size2.height > 0) {
14356
+ const pixelRatio = calculateDpr(dpr);
14357
+ canvas.width = size2.width * pixelRatio;
14358
+ canvas.height = size2.height * pixelRatio;
14359
+ }
14360
+ await renderer.init();
14361
+ }
14362
+ const backend = renderer.backend;
14363
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14364
+ state.internal.actualRenderer = renderer;
14365
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14366
+ if (canvasId && !state.internal.isSecondary) {
14367
+ const canvasTarget = new CanvasTarget(canvas);
14368
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14369
+ state.set((prev) => ({
14370
+ internal: {
14371
+ ...prev.internal,
14372
+ canvasTarget,
14373
+ unregisterPrimary
14374
+ }
14375
+ }));
14376
+ }
14236
14377
  }
14237
- }));
14378
+ })().catch((err) => {
14379
+ rendererSetup = null;
14380
+ throw err;
14381
+ });
14238
14382
  }
14383
+ await rendererSetup;
14384
+ state = store.getState();
14385
+ renderer = state.internal.actualRenderer;
14239
14386
  }
14240
14387
  let raycaster = state.raycaster;
14241
14388
  if (!raycaster) state.set({ raycaster: raycaster = new Raycaster() });
@@ -14585,7 +14732,8 @@ function unmountComponentAtNode(canvas, callback) {
14585
14732
  dispose(state.scene);
14586
14733
  _roots.delete(canvas);
14587
14734
  if (callback) callback(canvas);
14588
- } catch {
14735
+ } catch (error) {
14736
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
14589
14737
  }
14590
14738
  }, 500);
14591
14739
  }
@@ -14648,6 +14796,7 @@ function PortalInner({ state = {}, children, container }) {
14648
14796
  viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(), resolvedSize);
14649
14797
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
14650
14798
  }
14799
+ const set = injectState.set;
14651
14800
  return {
14652
14801
  // The intersect consists of the previous root state
14653
14802
  ...rootState,
@@ -14666,7 +14815,7 @@ function PortalInner({ state = {}, children, container }) {
14666
14815
  size: resolvedSize,
14667
14816
  viewport: { ...rootState.viewport, ...viewport },
14668
14817
  // Layers are allowed to override events
14669
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14818
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14670
14819
  // Container for child attachment - the portalScene (injected or container itself)
14671
14820
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
14672
14821
  };
@@ -14738,14 +14887,133 @@ function parseRendererConfig(rendererProp) {
14738
14887
  return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14739
14888
  }
14740
14889
 
14890
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14891
+ const ROOT_SCOPE = "";
14892
+ const registries = /* @__PURE__ */ new WeakMap();
14893
+ function getKindRegistry(store, kind) {
14894
+ let registry = registries.get(store);
14895
+ if (!registry) {
14896
+ registry = {
14897
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14898
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14899
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14900
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14901
+ };
14902
+ registries.set(store, registry);
14903
+ }
14904
+ return registry[kind];
14905
+ }
14906
+ function resolvePrimary$1(store) {
14907
+ return store.getState().primaryStore ?? store;
14908
+ }
14909
+ function isScopeValid(store, kind, scopeKey) {
14910
+ return getKindRegistry(store, kind).valid.has(scopeKey);
14911
+ }
14912
+ function peekStaged(store, kind, scopeKey) {
14913
+ return getKindRegistry(store, kind).staged.get(scopeKey);
14914
+ }
14915
+ function stageEntries(store, kind, scopeKey, entries) {
14916
+ const { staged } = getKindRegistry(store, kind);
14917
+ const current = staged.get(scopeKey);
14918
+ if (current) Object.assign(current, entries);
14919
+ else staged.set(scopeKey, { ...entries });
14920
+ }
14921
+ function readCommittedScope(map, scopeKey, isLeaf) {
14922
+ if (scopeKey === ROOT_SCOPE) {
14923
+ const leaves = {};
14924
+ for (const [key, value] of Object.entries(map)) if (isLeaf(value)) leaves[key] = value;
14925
+ return leaves;
14926
+ }
14927
+ const scopeData = map[scopeKey];
14928
+ if (scopeData && typeof scopeData === "object" && !isLeaf(scopeData)) return scopeData;
14929
+ return {};
14930
+ }
14931
+ function withStagedOverlay(store, kind, committed) {
14932
+ const { staged } = getKindRegistry(store, kind);
14933
+ if (staged.size === 0) return committed;
14934
+ const view = { ...committed };
14935
+ for (const [scopeKey, entries] of staged) {
14936
+ if (scopeKey === ROOT_SCOPE) Object.assign(view, entries);
14937
+ else view[scopeKey] = { ...view[scopeKey], ...entries };
14938
+ }
14939
+ return view;
14940
+ }
14941
+ function flushStagedScope(store, kind, scopeKey, isLeaf) {
14942
+ const registry = getKindRegistry(store, kind);
14943
+ const staged = registry.staged.get(scopeKey);
14944
+ if (!staged) return;
14945
+ registry.staged.delete(scopeKey);
14946
+ const replace = !registry.valid.has(scopeKey);
14947
+ store.setState((state) => {
14948
+ const map = state[kind];
14949
+ if (scopeKey === ROOT_SCOPE) {
14950
+ if (!replace) return { [kind]: { ...map, ...staged } };
14951
+ const next = {};
14952
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
14953
+ return { [kind]: { ...next, ...staged } };
14954
+ }
14955
+ const current = replace ? {} : map[scopeKey] ?? {};
14956
+ return { [kind]: { ...map, [scopeKey]: { ...current, ...staged } } };
14957
+ });
14958
+ registry.valid.add(scopeKey);
14959
+ }
14960
+ function invalidateResource(store, kind, scopeKey) {
14961
+ const registry = getKindRegistry(store, kind);
14962
+ if (scopeKey === void 0) {
14963
+ registry.valid.clear();
14964
+ registry.staged.clear();
14965
+ } else {
14966
+ registry.valid.delete(scopeKey);
14967
+ registry.staged.delete(scopeKey);
14968
+ }
14969
+ }
14970
+ function rebuildResource(store, kind, userScope) {
14971
+ const primary = resolvePrimary$1(store);
14972
+ invalidateResource(primary, kind, userScope === "root" ? ROOT_SCOPE : userScope);
14973
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14974
+ }
14975
+ function invalidateAllResources(store) {
14976
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
14977
+ }
14978
+ function removeResourceEntries(store, kind, names, scope, isLeaf) {
14979
+ const staged = peekStaged(store, kind, scope ?? ROOT_SCOPE);
14980
+ if (staged) for (const name of names) delete staged[name];
14981
+ store.setState((state) => {
14982
+ const map = state[kind];
14983
+ if (scope) {
14984
+ const currentScope = { ...map[scope] };
14985
+ for (const name of names) delete currentScope[name];
14986
+ return { [kind]: { ...map, [scope]: currentScope } };
14987
+ }
14988
+ const next = { ...map };
14989
+ for (const name of names) if (isLeaf(next[name])) delete next[name];
14990
+ return { [kind]: next };
14991
+ });
14992
+ }
14993
+ function clearResourceEntries(store, kind, scope, isLeaf) {
14994
+ const registry = getKindRegistry(store, kind);
14995
+ if (scope && scope !== "root") registry.staged.delete(scope);
14996
+ else if (scope === "root") registry.staged.delete(ROOT_SCOPE);
14997
+ else registry.staged.clear();
14998
+ store.setState((state) => {
14999
+ const map = state[kind];
15000
+ if (scope && scope !== "root") {
15001
+ const { [scope]: _, ...rest } = map;
15002
+ return { [kind]: rest };
15003
+ }
15004
+ if (scope === "root") {
15005
+ const next = {};
15006
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
15007
+ return { [kind]: next };
15008
+ }
15009
+ return { [kind]: {} };
15010
+ });
15011
+ }
15012
+
14741
15013
  function clearHmrCaches(store) {
14742
- store.setState((state) => ({
14743
- nodes: {},
14744
- uniforms: {},
14745
- buffers: {},
14746
- gpuStorage: {},
14747
- _hmrVersion: state._hmrVersion + 1
14748
- }));
15014
+ const primary = store.getState().primaryStore ?? store;
15015
+ invalidateAllResources(primary);
15016
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14749
15017
  }
14750
15018
 
14751
15019
  function CanvasImpl({
@@ -14826,6 +15094,7 @@ function CanvasImpl({
14826
15094
  const handleDropMissed = useMutableCallback(onDropMissed);
14827
15095
  const [block, setBlock] = React.useState(false);
14828
15096
  const [error, setError] = React.useState(false);
15097
+ const [fallbackVisible, setFallbackVisible] = React.useState(false);
14829
15098
  if (block) throw block;
14830
15099
  if (error) throw error;
14831
15100
  const root = React.useRef(null);
@@ -14833,6 +15102,7 @@ function CanvasImpl({
14833
15102
  const unsubscribeErrorRef = React.useRef(null);
14834
15103
  useIsomorphicLayoutEffect(() => {
14835
15104
  effectActiveRef.current = true;
15105
+ if (fallbackVisible) return;
14836
15106
  const canvas = canvasRef.current;
14837
15107
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
14838
15108
  if (!root.current) {
@@ -14853,7 +15123,7 @@ function CanvasImpl({
14853
15123
  }
14854
15124
  async function run() {
14855
15125
  if (!effectActiveRef.current || !root.current) return;
14856
- await root.current.configure({
15126
+ const configured = await root.current.configure({
14857
15127
  id,
14858
15128
  primaryCanvas,
14859
15129
  scheduler,
@@ -14894,8 +15164,20 @@ function CanvasImpl({
14894
15164
  }
14895
15165
  onCreated?.(state);
14896
15166
  }
14897
- });
14898
- if (!effectActiveRef.current || !root.current) return;
15167
+ }).then(
15168
+ () => true,
15169
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
15170
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
15171
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
15172
+ (setupError) => {
15173
+ if (effectActiveRef.current) {
15174
+ if (fallback != null) setFallbackVisible(true);
15175
+ else setError(setupError);
15176
+ }
15177
+ return false;
15178
+ }
15179
+ );
15180
+ if (!configured || !effectActiveRef.current || !root.current) return;
14899
15181
  root.current.render(
14900
15182
  /* @__PURE__ */ jsx(Bridge, { children: /* @__PURE__ */ jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxs(React.Suspense, { fallback: /* @__PURE__ */ jsx(Block, { set: setBlock }), children: [
14901
15183
  backgroundProps && /* @__PURE__ */ jsx(Environment, { ...backgroundProps }),
@@ -14958,7 +15240,11 @@ function CanvasImpl({
14958
15240
  ...style
14959
15241
  },
14960
15242
  ...props,
14961
- children: /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
15243
+ children: fallbackVisible ? (
15244
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15245
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15246
+ fallback
15247
+ ) : /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
14962
15248
  "canvas",
14963
15249
  {
14964
15250
  ref: canvasRef,
@@ -15040,30 +15326,31 @@ let ScopedStore = _ScopedStore;
15040
15326
  function createScopedStore(data) {
15041
15327
  return new ScopedStore(data);
15042
15328
  }
15043
- function createLazyCreatorState(state) {
15329
+ function createLazyCreatorState(state, store) {
15044
15330
  let _uniforms = null;
15045
15331
  let _nodes = null;
15046
15332
  let _buffers = null;
15047
15333
  let _gpuStorage = null;
15334
+ const view = (kind) => store ? withStagedOverlay(store, kind, state[kind]) : state[kind];
15048
15335
  return Object.create(state, {
15049
15336
  uniforms: {
15050
15337
  get() {
15051
- return _uniforms ?? (_uniforms = createScopedStore(state.uniforms));
15338
+ return _uniforms ?? (_uniforms = createScopedStore(view("uniforms")));
15052
15339
  }
15053
15340
  },
15054
15341
  nodes: {
15055
15342
  get() {
15056
- return _nodes ?? (_nodes = createScopedStore(state.nodes));
15343
+ return _nodes ?? (_nodes = createScopedStore(view("nodes")));
15057
15344
  }
15058
15345
  },
15059
15346
  buffers: {
15060
15347
  get() {
15061
- return _buffers ?? (_buffers = createScopedStore(state.buffers));
15348
+ return _buffers ?? (_buffers = createScopedStore(view("buffers")));
15062
15349
  }
15063
15350
  },
15064
15351
  gpuStorage: {
15065
15352
  get() {
15066
- return _gpuStorage ?? (_gpuStorage = createScopedStore(state.gpuStorage));
15353
+ return _gpuStorage ?? (_gpuStorage = createScopedStore(view("gpuStorage")));
15067
15354
  }
15068
15355
  }
15069
15356
  });
@@ -15186,65 +15473,56 @@ function useCompareMemoize(value, deep) {
15186
15473
  return ref.current;
15187
15474
  }
15188
15475
 
15476
+ function useScopedResource(options) {
15477
+ const { store, kind, scope, isLeaf, create, prepare, reconcile, input } = options;
15478
+ const scopeKey = scope ?? ROOT_SCOPE;
15479
+ const version = store((s) => s._hmrVersion);
15480
+ const entries = useMemo(() => {
15481
+ const staged = peekStaged(store, kind, scopeKey);
15482
+ const reusable = isScopeValid(store, kind, scopeKey);
15483
+ const map = store.getState()[kind];
15484
+ const committed = reusable ? readCommittedScope(map, scopeKey, isLeaf) : void 0;
15485
+ const result = {};
15486
+ let fresh = null;
15487
+ for (const [name, candidate] of Object.entries(create())) {
15488
+ const existing = staged?.[name] ?? committed?.[name];
15489
+ if (existing !== void 0) {
15490
+ result[name] = existing;
15491
+ reconcile?.(existing, candidate);
15492
+ } else {
15493
+ const value = prepare ? prepare(name, candidate) : candidate;
15494
+ result[name] = value;
15495
+ (fresh ?? (fresh = {}))[name] = value;
15496
+ }
15497
+ }
15498
+ if (fresh) stageEntries(store, kind, scopeKey, fresh);
15499
+ return result;
15500
+ }, [store, kind, scopeKey, version, input]);
15501
+ useIsomorphicLayoutEffect(() => {
15502
+ flushStagedScope(store, kind, scopeKey, isLeaf);
15503
+ });
15504
+ return entries;
15505
+ }
15506
+
15189
15507
  const isUniformNode$1 = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
15190
15508
  function useUniforms(creatorOrScope, scope) {
15191
15509
  const store = usePrimaryStore();
15192
15510
  const removeUniforms2 = useCallback(
15193
- (names, targetScope) => {
15194
- const nameArray = Array.isArray(names) ? names : [names];
15195
- store.setState((state) => {
15196
- if (targetScope) {
15197
- const currentScope = { ...state.uniforms[targetScope] };
15198
- for (const name of nameArray) delete currentScope[name];
15199
- return { uniforms: { ...state.uniforms, [targetScope]: currentScope } };
15200
- }
15201
- const uniforms2 = { ...state.uniforms };
15202
- for (const name of nameArray) if (isUniformNode$1(uniforms2[name])) delete uniforms2[name];
15203
- return { uniforms: uniforms2 };
15204
- });
15205
- },
15511
+ (names, targetScope) => removeResourceEntries(store, "uniforms", Array.isArray(names) ? names : [names], targetScope, isUniformNode$1),
15206
15512
  [store]
15207
15513
  );
15208
15514
  const clearUniforms = useCallback(
15209
- (targetScope) => {
15210
- store.setState((state) => {
15211
- if (targetScope && targetScope !== "root") {
15212
- const { [targetScope]: _, ...rest } = state.uniforms;
15213
- return { uniforms: rest };
15214
- }
15215
- if (targetScope === "root") {
15216
- const uniforms2 = {};
15217
- for (const [key, value] of Object.entries(state.uniforms)) {
15218
- if (!isUniformNode$1(value)) uniforms2[key] = value;
15219
- }
15220
- return { uniforms: uniforms2 };
15221
- }
15222
- return { uniforms: {} };
15223
- });
15224
- },
15515
+ (targetScope) => clearResourceEntries(store, "uniforms", targetScope, isUniformNode$1),
15225
15516
  [store]
15226
15517
  );
15227
15518
  const rebuildUniforms = useCallback(
15228
- (targetScope) => {
15229
- store.setState((state) => {
15230
- let newUniforms = {};
15231
- if (targetScope && targetScope !== "root") {
15232
- const { [targetScope]: _, ...rest } = state.uniforms;
15233
- newUniforms = rest;
15234
- } else if (targetScope === "root") {
15235
- for (const [key, value] of Object.entries(state.uniforms)) {
15236
- if (!isUniformNode$1(value)) newUniforms[key] = value;
15237
- }
15238
- }
15239
- return { uniforms: newUniforms, _hmrVersion: state._hmrVersion + 1 };
15240
- });
15241
- },
15519
+ (targetScope) => rebuildResource(store, "uniforms", targetScope),
15242
15520
  [store]
15243
15521
  );
15244
15522
  const inputForMemoization = useMemo(() => {
15245
15523
  let raw = creatorOrScope;
15246
15524
  if (is.fun(creatorOrScope)) {
15247
- const wrappedState = createLazyCreatorState(store.getState());
15525
+ const wrappedState = createLazyCreatorState(store.getState(), store);
15248
15526
  raw = creatorOrScope(wrappedState);
15249
15527
  }
15250
15528
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
@@ -15259,80 +15537,43 @@ function useUniforms(creatorOrScope, scope) {
15259
15537
  const memoizedInput = useCompareMemoize(inputForMemoization);
15260
15538
  const isReader = memoizedInput === void 0 || typeof memoizedInput === "string";
15261
15539
  const storeUniforms = usePrimaryThree((s) => s.uniforms);
15262
- const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
15263
- const readerDep = isReader ? storeUniforms : null;
15264
- const creatorDep = isReader ? null : hmrVersion;
15265
- const uniforms = useMemo(() => {
15266
- if (memoizedInput === void 0) {
15267
- return storeUniforms;
15268
- }
15269
- if (typeof memoizedInput === "string") {
15270
- const scopeData = storeUniforms[memoizedInput];
15271
- if (scopeData && !isUniformNode$1(scopeData)) return scopeData;
15272
- return {};
15273
- }
15274
- const state = store.getState();
15275
- const set = store.setState;
15276
- if (typeof memoizedInput !== "object" || memoizedInput === null) {
15277
- throw new Error("Invalid uniform input");
15278
- }
15279
- const created = memoizedInput;
15280
- const result = {};
15281
- let hasNewUniforms = false;
15282
- let targetRecord = state.uniforms;
15283
- if (scope) {
15284
- if (!state.uniforms[scope]) state.uniforms[scope] = {};
15285
- targetRecord = state.uniforms[scope];
15286
- }
15287
- for (const [name, node] of Object.entries(created)) {
15288
- if (targetRecord[name]) {
15289
- result[name] = targetRecord[name];
15290
- const existingVal = result[name].value;
15291
- const newVal = vectorize(node);
15292
- let equals = newVal === existingVal;
15293
- if (!equals && hasEqualsMethod(existingVal) && hasEqualsMethod(newVal)) {
15294
- if (isThreeVector(existingVal) && isThreeVector(newVal)) {
15295
- equals = vectorEquals(existingVal, newVal);
15296
- } else if (isSameThreeType(existingVal, newVal)) {
15297
- equals = existingVal.equals(newVal);
15298
- }
15299
- }
15300
- if (!equals) result[name].value = newVal;
15301
- } else {
15302
- result[name] = createUniform(name, node, scope);
15303
- hasNewUniforms = true;
15304
- }
15305
- }
15306
- if (hasNewUniforms) {
15307
- if (scope) {
15308
- set((s) => ({
15309
- uniforms: {
15310
- ...s.uniforms,
15311
- [scope]: { ...s.uniforms[scope], ...result }
15312
- }
15313
- }));
15314
- } else {
15315
- set((s) => ({ uniforms: { ...s.uniforms, ...result } }));
15316
- }
15540
+ const created = useScopedResource({
15541
+ store,
15542
+ kind: "uniforms",
15543
+ scope: isReader ? void 0 : scope,
15544
+ isLeaf: isUniformNode$1,
15545
+ input: memoizedInput,
15546
+ create: () => {
15547
+ if (isReader) return {};
15548
+ if (typeof memoizedInput !== "object" || memoizedInput === null) throw new Error("Invalid uniform input");
15549
+ return memoizedInput;
15550
+ },
15551
+ prepare: (name, candidate) => createUniform(name, candidate, scope),
15552
+ reconcile: (existing, candidate) => {
15553
+ const existingVal = existing.value;
15554
+ const newVal = vectorize(candidate);
15555
+ let equals = newVal === existingVal;
15556
+ if (!equals && hasEqualsMethod(existingVal) && hasEqualsMethod(newVal)) {
15557
+ if (isThreeVector(existingVal) && isThreeVector(newVal)) {
15558
+ equals = vectorEquals(existingVal, newVal);
15559
+ } else if (isSameThreeType(existingVal, newVal)) {
15560
+ equals = existingVal.equals(newVal);
15561
+ }
15562
+ }
15563
+ if (!equals) existing.value = newVal;
15317
15564
  }
15318
- return result;
15319
- }, [store, memoizedInput, scope, readerDep, creatorDep]);
15565
+ });
15566
+ let uniforms = created;
15567
+ if (memoizedInput === void 0) {
15568
+ uniforms = storeUniforms;
15569
+ } else if (typeof memoizedInput === "string") {
15570
+ const scopeData = storeUniforms[memoizedInput];
15571
+ uniforms = scopeData && !isUniformNode$1(scopeData) ? scopeData : {};
15572
+ }
15320
15573
  return { ...uniforms, removeUniforms: removeUniforms2, clearUniforms, rebuildUniforms };
15321
15574
  }
15322
15575
  function rebuildAllUniforms(store, scope) {
15323
- store = store.getState().primaryStore ?? store;
15324
- store.setState((state) => {
15325
- let newUniforms = {};
15326
- if (scope && scope !== "root") {
15327
- const { [scope]: _, ...rest } = state.uniforms;
15328
- newUniforms = rest;
15329
- } else if (scope === "root") {
15330
- for (const [key, value] of Object.entries(state.uniforms)) {
15331
- if (!isUniformNode$1(value)) newUniforms[key] = value;
15332
- }
15333
- }
15334
- return { uniforms: newUniforms, _hmrVersion: state._hmrVersion + 1 };
15335
- });
15576
+ rebuildResource(store, "uniforms", scope);
15336
15577
  }
15337
15578
  function removeUniforms(set, names, scope) {
15338
15579
  set((state) => {
@@ -15396,192 +15637,91 @@ function isSameThreeType(a, b) {
15396
15637
  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;
15397
15638
  }
15398
15639
 
15640
+ const uniformOf = uniform;
15399
15641
  const isUniformNode = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
15400
15642
  const isTSLNode$1 = (value) => value !== null && typeof value === "object" && "uuid" in value && "nodeType" in value;
15401
15643
  function useUniform(name, value) {
15402
15644
  const store = useStore();
15403
- const hmrVersion = useThree((s) => s._hmrVersion);
15404
- return useMemo(() => {
15405
- const state = store.getState();
15406
- const set = store.setState;
15407
- const existing = state.uniforms[name];
15408
- if (existing && isUniformNode(existing)) {
15645
+ const registered = useScopedResource({
15646
+ store,
15647
+ kind: "uniforms",
15648
+ scope: void 0,
15649
+ isLeaf: isUniformNode,
15650
+ input: name,
15651
+ create: () => value === void 0 ? {} : { [name]: value },
15652
+ prepare: createNamedUniform,
15653
+ reconcile: (existing2) => {
15409
15654
  if (value !== void 0 && !isTSLNode$1(value) && !isUniformNode(value)) {
15410
- existing.value = typeof value === "string" ? new Color(value) : value;
15655
+ existing2.value = typeof value === "string" ? new Color(value) : value;
15411
15656
  }
15412
- return existing;
15413
- }
15414
- if (value === void 0) {
15415
- throw new Error(
15416
- `[useUniform] Uniform "${name}" not found. Create it first with: useUniform('${name}', initialValue)`
15417
- );
15418
- }
15419
- if (isUniformNode(value)) {
15420
- const node2 = value;
15421
- if (typeof node2.setName === "function") {
15422
- node2.setName(name);
15423
- }
15424
- set((s) => ({
15425
- uniforms: { ...s.uniforms, [name]: node2 }
15426
- }));
15427
- return node2;
15428
15657
  }
15429
- let node;
15430
- if (isTSLNode$1(value)) {
15431
- node = uniform(value);
15432
- } else if (typeof value === "string") {
15433
- node = uniform(new Color(value));
15434
- } else {
15435
- node = uniform(value);
15436
- }
15437
- if (typeof node.setName === "function") {
15438
- node.setName(name);
15439
- }
15440
- set((s) => ({
15441
- uniforms: {
15442
- ...s.uniforms,
15443
- [name]: node
15444
- }
15445
- }));
15446
- return node;
15447
- }, [store, name, hmrVersion]);
15658
+ });
15659
+ if (registered[name]) return registered[name];
15660
+ const existing = peekStaged(store, "uniforms", ROOT_SCOPE)?.[name] ?? store.getState().uniforms[name];
15661
+ if (existing && isUniformNode(existing)) return existing;
15662
+ throw new Error(
15663
+ `[useUniform] Uniform "${name}" not found. Create it first with: useUniform('${name}', initialValue)`
15664
+ );
15665
+ }
15666
+ function createNamedUniform(name, value) {
15667
+ let node;
15668
+ if (isUniformNode(value)) {
15669
+ node = value;
15670
+ } else if (isTSLNode$1(value)) {
15671
+ node = uniformOf(value);
15672
+ } else if (typeof value === "string") {
15673
+ node = uniform(new Color(value));
15674
+ } else {
15675
+ node = uniformOf(value);
15676
+ }
15677
+ if (typeof node.setName === "function") {
15678
+ node.setName(name);
15679
+ }
15680
+ return node;
15448
15681
  }
15449
15682
 
15450
15683
  const isTSLNode = (value) => value !== null && typeof value === "object" && ("uuid" in value || "nodeType" in value);
15451
15684
  function useNodes(creatorOrScope, scope) {
15452
15685
  const store = usePrimaryStore();
15453
15686
  const removeNodes2 = useCallback(
15454
- (names, targetScope) => {
15455
- const nameArray = Array.isArray(names) ? names : [names];
15456
- store.setState((state) => {
15457
- if (targetScope) {
15458
- const currentScope = { ...state.nodes[targetScope] };
15459
- for (const name of nameArray) delete currentScope[name];
15460
- return { nodes: { ...state.nodes, [targetScope]: currentScope } };
15461
- }
15462
- const nodes2 = { ...state.nodes };
15463
- for (const name of nameArray) if (isTSLNode(nodes2[name])) delete nodes2[name];
15464
- return { nodes: nodes2 };
15465
- });
15466
- },
15687
+ (names, targetScope) => removeResourceEntries(store, "nodes", Array.isArray(names) ? names : [names], targetScope, isTSLNode),
15467
15688
  [store]
15468
15689
  );
15469
15690
  const clearNodes = useCallback(
15470
- (targetScope) => {
15471
- store.setState((state) => {
15472
- if (targetScope && targetScope !== "root") {
15473
- const { [targetScope]: _, ...rest } = state.nodes;
15474
- return { nodes: rest };
15475
- }
15476
- if (targetScope === "root") {
15477
- const nodes2 = {};
15478
- for (const [key, value] of Object.entries(state.nodes)) {
15479
- if (!isTSLNode(value)) nodes2[key] = value;
15480
- }
15481
- return { nodes: nodes2 };
15482
- }
15483
- return { nodes: {} };
15484
- });
15485
- },
15691
+ (targetScope) => clearResourceEntries(store, "nodes", targetScope, isTSLNode),
15486
15692
  [store]
15487
15693
  );
15488
15694
  const rebuildNodes = useCallback(
15489
- (targetScope) => {
15490
- store.setState((state) => {
15491
- let newNodes = state.nodes;
15492
- if (targetScope && targetScope !== "root") {
15493
- const { [targetScope]: _, ...rest } = state.nodes;
15494
- newNodes = rest;
15495
- } else if (targetScope === "root") {
15496
- newNodes = {};
15497
- for (const [key, value] of Object.entries(state.nodes)) {
15498
- if (!isTSLNode(value)) newNodes[key] = value;
15499
- }
15500
- } else {
15501
- newNodes = {};
15502
- }
15503
- return { nodes: newNodes, _hmrVersion: state._hmrVersion + 1 };
15504
- });
15505
- },
15695
+ (targetScope) => rebuildResource(store, "nodes", targetScope),
15506
15696
  [store]
15507
15697
  );
15508
15698
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
15509
15699
  const storeNodes = usePrimaryThree((s) => s.nodes);
15510
- const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
15511
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
15512
- const readerDep = isReader ? storeNodes : null;
15513
- const creatorDep = isReader ? null : hmrVersion;
15514
- const nodes = useMemo(() => {
15515
- if (creatorOrScope === void 0) {
15516
- return storeNodes;
15517
- }
15518
- if (typeof creatorOrScope === "string") {
15519
- const scopeData = storeNodes[creatorOrScope];
15520
- if (scopeData && !isTSLNode(scopeData)) return scopeData;
15521
- return {};
15522
- }
15523
- const state = store.getState();
15524
- const set = store.setState;
15525
- const creator = creatorOrScope;
15526
- const wrappedState = createLazyCreatorState(state);
15527
- const created = creator(wrappedState);
15528
- const result = {};
15529
- let hasNewNodes = false;
15530
- if (scope) {
15531
- const currentScope = state.nodes[scope] ?? {};
15532
- for (const [name, node] of Object.entries(created)) {
15533
- if (currentScope[name]) {
15534
- result[name] = currentScope[name];
15535
- } else {
15536
- node.setName?.(`${scope}.${name}`);
15537
- result[name] = node;
15538
- hasNewNodes = true;
15539
- }
15540
- }
15541
- if (hasNewNodes) {
15542
- set((s) => ({
15543
- nodes: {
15544
- ...s.nodes,
15545
- [scope]: { ...s.nodes[scope], ...result }
15546
- }
15547
- }));
15548
- }
15549
- return result;
15550
- }
15551
- for (const [name, node] of Object.entries(created)) {
15552
- const existing = state.nodes[name];
15553
- if (existing && isTSLNode(existing)) {
15554
- result[name] = existing;
15555
- } else {
15556
- node.setName?.(name);
15557
- result[name] = node;
15558
- hasNewNodes = true;
15559
- }
15560
- }
15561
- if (hasNewNodes) {
15562
- set((s) => ({ nodes: { ...s.nodes, ...result } }));
15700
+ const created = useScopedResource({
15701
+ store,
15702
+ kind: "nodes",
15703
+ scope: isReader ? void 0 : scope,
15704
+ isLeaf: isTSLNode,
15705
+ create: () => {
15706
+ if (isReader) return {};
15707
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15708
+ },
15709
+ prepare: (name, node) => {
15710
+ node.setName?.(scope ? `${scope}.${name}` : name);
15711
+ return node;
15563
15712
  }
15564
- return result;
15565
- }, [store, scopeDep, readerDep, creatorDep]);
15713
+ });
15714
+ let nodes = created;
15715
+ if (creatorOrScope === void 0) {
15716
+ nodes = storeNodes;
15717
+ } else if (typeof creatorOrScope === "string") {
15718
+ const scopeData = storeNodes[creatorOrScope];
15719
+ nodes = scopeData && !isTSLNode(scopeData) ? scopeData : {};
15720
+ }
15566
15721
  return { ...nodes, removeNodes: removeNodes2, clearNodes, rebuildNodes };
15567
15722
  }
15568
15723
  function rebuildAllNodes(store, scope) {
15569
- store = store.getState().primaryStore ?? store;
15570
- store.setState((state) => {
15571
- let newNodes = state.nodes;
15572
- if (scope && scope !== "root") {
15573
- const { [scope]: _, ...rest } = state.nodes;
15574
- newNodes = rest;
15575
- } else if (scope === "root") {
15576
- newNodes = {};
15577
- for (const [key, value] of Object.entries(state.nodes)) {
15578
- if (!isTSLNode(value)) newNodes[key] = value;
15579
- }
15580
- } else {
15581
- newNodes = {};
15582
- }
15583
- return { nodes: newNodes, _hmrVersion: state._hmrVersion + 1 };
15584
- });
15724
+ rebuildResource(store, "nodes", scope);
15585
15725
  }
15586
15726
  function removeNodes(set, names, scope) {
15587
15727
  set((state) => {
@@ -15617,7 +15757,7 @@ function useLocalNodes(creator) {
15617
15757
  const textures = usePrimaryThree((s) => s.textures);
15618
15758
  const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
15619
15759
  return useMemo(() => {
15620
- const wrappedState = createLazyCreatorState(store.getState());
15760
+ const wrappedState = createLazyCreatorState(store.getState(), store);
15621
15761
  return creator(wrappedState);
15622
15762
  }, [store, creator, uniforms, nodes, textures, hmrVersion]);
15623
15763
  }
@@ -15638,58 +15778,15 @@ const disposeBuffer = (buffer) => {
15638
15778
  function useBuffers(creatorOrScope, scope) {
15639
15779
  const store = usePrimaryStore();
15640
15780
  const removeBuffers = useCallback(
15641
- (names, targetScope) => {
15642
- const nameArray = Array.isArray(names) ? names : [names];
15643
- store.setState((state) => {
15644
- if (targetScope) {
15645
- const currentScope = { ...state.buffers[targetScope] };
15646
- for (const name of nameArray) delete currentScope[name];
15647
- return { buffers: { ...state.buffers, [targetScope]: currentScope } };
15648
- }
15649
- const buffers2 = { ...state.buffers };
15650
- for (const name of nameArray) if (isBufferLike(buffers2[name])) delete buffers2[name];
15651
- return { buffers: buffers2 };
15652
- });
15653
- },
15781
+ (names, targetScope) => removeResourceEntries(store, "buffers", Array.isArray(names) ? names : [names], targetScope, isBufferLike),
15654
15782
  [store]
15655
15783
  );
15656
15784
  const clearBuffers = useCallback(
15657
- (targetScope) => {
15658
- store.setState((state) => {
15659
- if (targetScope && targetScope !== "root") {
15660
- const { [targetScope]: _, ...rest } = state.buffers;
15661
- return { buffers: rest };
15662
- }
15663
- if (targetScope === "root") {
15664
- const buffers2 = {};
15665
- for (const [key, value] of Object.entries(state.buffers)) {
15666
- if (!isBufferLike(value)) buffers2[key] = value;
15667
- }
15668
- return { buffers: buffers2 };
15669
- }
15670
- return { buffers: {} };
15671
- });
15672
- },
15785
+ (targetScope) => clearResourceEntries(store, "buffers", targetScope, isBufferLike),
15673
15786
  [store]
15674
15787
  );
15675
15788
  const rebuildBuffers = useCallback(
15676
- (targetScope) => {
15677
- store.setState((state) => {
15678
- let newBuffers = state.buffers;
15679
- if (targetScope && targetScope !== "root") {
15680
- const { [targetScope]: _, ...rest } = state.buffers;
15681
- newBuffers = rest;
15682
- } else if (targetScope === "root") {
15683
- newBuffers = {};
15684
- for (const [key, value] of Object.entries(state.buffers)) {
15685
- if (!isBufferLike(value)) newBuffers[key] = value;
15686
- }
15687
- } else {
15688
- newBuffers = {};
15689
- }
15690
- return { buffers: newBuffers, _hmrVersion: state._hmrVersion + 1 };
15691
- });
15692
- },
15789
+ (targetScope) => rebuildResource(store, "buffers", targetScope),
15693
15790
  [store]
15694
15791
  );
15695
15792
  const disposeBuffers = useCallback(
@@ -15708,85 +15805,33 @@ function useBuffers(creatorOrScope, scope) {
15708
15805
  );
15709
15806
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
15710
15807
  const storeBuffers = usePrimaryThree((s) => s.buffers);
15711
- const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
15712
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
15713
- const readerDep = isReader ? storeBuffers : null;
15714
- const creatorDep = isReader ? null : hmrVersion;
15715
- const buffers = useMemo(() => {
15716
- if (creatorOrScope === void 0) {
15717
- return storeBuffers;
15718
- }
15719
- if (typeof creatorOrScope === "string") {
15720
- const scopeData = storeBuffers[creatorOrScope];
15721
- if (scopeData && !isBufferLike(scopeData)) return scopeData;
15722
- return {};
15723
- }
15724
- const state = store.getState();
15725
- const set = store.setState;
15726
- const creator = creatorOrScope;
15727
- const wrappedState = createLazyCreatorState(state);
15728
- const created = creator(wrappedState);
15729
- const result = {};
15730
- let hasNewBuffers = false;
15731
- if (scope) {
15732
- const currentScope = state.buffers[scope] ?? {};
15733
- for (const [name, buffer] of Object.entries(created)) {
15734
- if (currentScope[name]) {
15735
- result[name] = currentScope[name];
15736
- } else {
15737
- if ("setName" in buffer && typeof buffer.setName === "function") {
15738
- buffer.setName(`${scope}.${name}`);
15739
- }
15740
- result[name] = buffer;
15741
- hasNewBuffers = true;
15742
- }
15743
- }
15744
- if (hasNewBuffers) {
15745
- set((s) => ({
15746
- buffers: {
15747
- ...s.buffers,
15748
- [scope]: { ...s.buffers[scope], ...result }
15749
- }
15750
- }));
15751
- }
15752
- return result;
15753
- }
15754
- for (const [name, buffer] of Object.entries(created)) {
15755
- const existing = state.buffers[name];
15756
- if (existing && isBufferLike(existing)) {
15757
- result[name] = existing;
15758
- } else {
15759
- if ("setName" in buffer && typeof buffer.setName === "function") {
15760
- buffer.setName(name);
15761
- }
15762
- result[name] = buffer;
15763
- hasNewBuffers = true;
15808
+ const created = useScopedResource({
15809
+ store,
15810
+ kind: "buffers",
15811
+ scope: isReader ? void 0 : scope,
15812
+ isLeaf: isBufferLike,
15813
+ create: () => {
15814
+ if (isReader) return {};
15815
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15816
+ },
15817
+ prepare: (name, buffer) => {
15818
+ if ("setName" in buffer && typeof buffer.setName === "function") {
15819
+ buffer.setName(scope ? `${scope}.${name}` : name);
15764
15820
  }
15821
+ return buffer;
15765
15822
  }
15766
- if (hasNewBuffers) {
15767
- set((s) => ({ buffers: { ...s.buffers, ...result } }));
15768
- }
15769
- return result;
15770
- }, [store, scopeDep, readerDep, creatorDep]);
15823
+ });
15824
+ let buffers = created;
15825
+ if (creatorOrScope === void 0) {
15826
+ buffers = storeBuffers;
15827
+ } else if (typeof creatorOrScope === "string") {
15828
+ const scopeData = storeBuffers[creatorOrScope];
15829
+ buffers = scopeData && !isBufferLike(scopeData) ? scopeData : {};
15830
+ }
15771
15831
  return { ...buffers, removeBuffers, clearBuffers, rebuildBuffers, disposeBuffers };
15772
15832
  }
15773
15833
  function rebuildAllBuffers(store, scope) {
15774
- store = store.getState().primaryStore ?? store;
15775
- store.setState((state) => {
15776
- let newBuffers = state.buffers;
15777
- if (scope && scope !== "root") {
15778
- const { [scope]: _, ...rest } = state.buffers;
15779
- newBuffers = rest;
15780
- } else if (scope === "root") {
15781
- newBuffers = {};
15782
- for (const [key, value] of Object.entries(state.buffers)) {
15783
- if (!isBufferLike(value)) newBuffers[key] = value;
15784
- }
15785
- } else {
15786
- newBuffers = {};
15787
- }
15788
- return { buffers: newBuffers, _hmrVersion: state._hmrVersion + 1 };
15789
- });
15834
+ rebuildResource(store, "buffers", scope);
15790
15835
  }
15791
15836
 
15792
15837
  const isStorageLike = (value) => {
@@ -15805,58 +15850,15 @@ const disposeStorage = (storage) => {
15805
15850
  function useGPUStorage(creatorOrScope, scope) {
15806
15851
  const store = usePrimaryStore();
15807
15852
  const removeStorage = useCallback(
15808
- (names, targetScope) => {
15809
- const nameArray = Array.isArray(names) ? names : [names];
15810
- store.setState((state) => {
15811
- if (targetScope) {
15812
- const currentScope = { ...state.gpuStorage[targetScope] };
15813
- for (const name of nameArray) delete currentScope[name];
15814
- return { gpuStorage: { ...state.gpuStorage, [targetScope]: currentScope } };
15815
- }
15816
- const gpuStorage2 = { ...state.gpuStorage };
15817
- for (const name of nameArray) if (isStorageLike(gpuStorage2[name])) delete gpuStorage2[name];
15818
- return { gpuStorage: gpuStorage2 };
15819
- });
15820
- },
15853
+ (names, targetScope) => removeResourceEntries(store, "gpuStorage", Array.isArray(names) ? names : [names], targetScope, isStorageLike),
15821
15854
  [store]
15822
15855
  );
15823
15856
  const clearStorage = useCallback(
15824
- (targetScope) => {
15825
- store.setState((state) => {
15826
- if (targetScope && targetScope !== "root") {
15827
- const { [targetScope]: _, ...rest } = state.gpuStorage;
15828
- return { gpuStorage: rest };
15829
- }
15830
- if (targetScope === "root") {
15831
- const gpuStorage2 = {};
15832
- for (const [key, value] of Object.entries(state.gpuStorage)) {
15833
- if (!isStorageLike(value)) gpuStorage2[key] = value;
15834
- }
15835
- return { gpuStorage: gpuStorage2 };
15836
- }
15837
- return { gpuStorage: {} };
15838
- });
15839
- },
15857
+ (targetScope) => clearResourceEntries(store, "gpuStorage", targetScope, isStorageLike),
15840
15858
  [store]
15841
15859
  );
15842
15860
  const rebuildStorage = useCallback(
15843
- (targetScope) => {
15844
- store.setState((state) => {
15845
- let newStorage = state.gpuStorage;
15846
- if (targetScope && targetScope !== "root") {
15847
- const { [targetScope]: _, ...rest } = state.gpuStorage;
15848
- newStorage = rest;
15849
- } else if (targetScope === "root") {
15850
- newStorage = {};
15851
- for (const [key, value] of Object.entries(state.gpuStorage)) {
15852
- if (!isStorageLike(value)) newStorage[key] = value;
15853
- }
15854
- } else {
15855
- newStorage = {};
15856
- }
15857
- return { gpuStorage: newStorage, _hmrVersion: state._hmrVersion + 1 };
15858
- });
15859
- },
15861
+ (targetScope) => rebuildResource(store, "gpuStorage", targetScope),
15860
15862
  [store]
15861
15863
  );
15862
15864
  const disposeStorageFn = useCallback(
@@ -15875,72 +15877,33 @@ function useGPUStorage(creatorOrScope, scope) {
15875
15877
  );
15876
15878
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
15877
15879
  const storeStorage = usePrimaryThree((s) => s.gpuStorage);
15878
- const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
15879
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
15880
- const readerDep = isReader ? storeStorage : null;
15881
- const creatorDep = isReader ? null : hmrVersion;
15882
- const gpuStorage = useMemo(() => {
15883
- if (creatorOrScope === void 0) {
15884
- return storeStorage;
15885
- }
15886
- if (typeof creatorOrScope === "string") {
15887
- const scopeData = storeStorage[creatorOrScope];
15888
- if (scopeData && !isStorageLike(scopeData)) return scopeData;
15889
- return {};
15890
- }
15891
- const state = store.getState();
15892
- const set = store.setState;
15893
- const creator = creatorOrScope;
15894
- const wrappedState = createLazyCreatorState(state);
15895
- const created = creator(wrappedState);
15896
- const result = {};
15897
- let hasNewStorage = false;
15898
- if (scope) {
15899
- const currentScope = state.gpuStorage[scope] ?? {};
15900
- for (const [name, storage] of Object.entries(created)) {
15901
- if (currentScope[name]) {
15902
- result[name] = currentScope[name];
15903
- } else {
15904
- if ("setName" in storage && typeof storage.setName === "function") {
15905
- storage.setName(`${scope}.${name}`);
15906
- }
15907
- if ("name" in storage && typeof storage.name === "string") {
15908
- storage.name = `${scope}.${name}`;
15909
- }
15910
- result[name] = storage;
15911
- hasNewStorage = true;
15912
- }
15913
- }
15914
- if (hasNewStorage) {
15915
- set((s) => ({
15916
- gpuStorage: {
15917
- ...s.gpuStorage,
15918
- [scope]: { ...s.gpuStorage[scope], ...result }
15919
- }
15920
- }));
15880
+ const created = useScopedResource({
15881
+ store,
15882
+ kind: "gpuStorage",
15883
+ scope: isReader ? void 0 : scope,
15884
+ isLeaf: isStorageLike,
15885
+ create: () => {
15886
+ if (isReader) return {};
15887
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15888
+ },
15889
+ prepare: (name, storage) => {
15890
+ const label = scope ? `${scope}.${name}` : name;
15891
+ if ("setName" in storage && typeof storage.setName === "function") {
15892
+ storage.setName(label);
15921
15893
  }
15922
- return result;
15923
- }
15924
- for (const [name, storage] of Object.entries(created)) {
15925
- const existing = state.gpuStorage[name];
15926
- if (existing && isStorageLike(existing)) {
15927
- result[name] = existing;
15928
- } else {
15929
- if ("setName" in storage && typeof storage.setName === "function") {
15930
- storage.setName(name);
15931
- }
15932
- if ("name" in storage && typeof storage.name === "string") {
15933
- storage.name = name;
15934
- }
15935
- result[name] = storage;
15936
- hasNewStorage = true;
15894
+ if ("name" in storage && typeof storage.name === "string") {
15895
+ storage.name = label;
15937
15896
  }
15897
+ return storage;
15938
15898
  }
15939
- if (hasNewStorage) {
15940
- set((s) => ({ gpuStorage: { ...s.gpuStorage, ...result } }));
15941
- }
15942
- return result;
15943
- }, [store, scopeDep, readerDep, creatorDep]);
15899
+ });
15900
+ let gpuStorage = created;
15901
+ if (creatorOrScope === void 0) {
15902
+ gpuStorage = storeStorage;
15903
+ } else if (typeof creatorOrScope === "string") {
15904
+ const scopeData = storeStorage[creatorOrScope];
15905
+ gpuStorage = scopeData && !isStorageLike(scopeData) ? scopeData : {};
15906
+ }
15944
15907
  return {
15945
15908
  ...gpuStorage,
15946
15909
  removeStorage,
@@ -15950,22 +15913,7 @@ function useGPUStorage(creatorOrScope, scope) {
15950
15913
  };
15951
15914
  }
15952
15915
  function rebuildAllStorage(store, scope) {
15953
- store = store.getState().primaryStore ?? store;
15954
- store.setState((state) => {
15955
- let newStorage = state.gpuStorage;
15956
- if (scope && scope !== "root") {
15957
- const { [scope]: _, ...rest } = state.gpuStorage;
15958
- newStorage = rest;
15959
- } else if (scope === "root") {
15960
- newStorage = {};
15961
- for (const [key, value] of Object.entries(state.gpuStorage)) {
15962
- if (!isStorageLike(value)) newStorage[key] = value;
15963
- }
15964
- } else {
15965
- newStorage = {};
15966
- }
15967
- return { gpuStorage: newStorage, _hmrVersion: state._hmrVersion + 1 };
15968
- });
15916
+ rebuildResource(store, "gpuStorage", scope);
15969
15917
  }
15970
15918
 
15971
15919
  function useRenderPipeline(mainCB, setupCB) {
@@ -16006,12 +15954,12 @@ function useRenderPipeline(mainCB, setupCB) {
16006
15954
  const state = store.getState();
16007
15955
  const set = store.setState;
16008
15956
  try {
16009
- let pp = state.renderPipeline;
15957
+ let pipeline = state.renderPipeline;
16010
15958
  let currentPasses = { ...state.passes };
16011
- let justCreatedPP = false;
16012
- if (!pp) {
16013
- pp = new PostProcessing(renderer);
16014
- justCreatedPP = true;
15959
+ let justCreatedPipeline = false;
15960
+ if (!pipeline) {
15961
+ pipeline = new RenderPipeline(renderer);
15962
+ justCreatedPipeline = true;
16015
15963
  }
16016
15964
  const cacheValid = scenePassCacheRef.current && scenePassCacheRef.current.sceneUuid === scene.uuid && scenePassCacheRef.current.cameraUuid === camera.uuid;
16017
15965
  let scenePass;
@@ -16022,9 +15970,9 @@ function useRenderPipeline(mainCB, setupCB) {
16022
15970
  scenePassCacheRef.current = { sceneUuid: scene.uuid, cameraUuid: camera.uuid, scenePass };
16023
15971
  }
16024
15972
  currentPasses.scenePass = scenePass;
16025
- if (!pp.outputNode || justCreatedPP) pp.outputNode = scenePass;
16026
- set({ renderPipeline: pp, passes: currentPasses });
16027
- const shouldRunCallbacks = justCreatedPP || !callbacksRanRef.current || !cacheValid;
15973
+ if (!pipeline.outputNode || justCreatedPipeline) pipeline.outputNode = scenePass;
15974
+ set({ renderPipeline: pipeline, passes: currentPasses });
15975
+ const shouldRunCallbacks = justCreatedPipeline || !callbacksRanRef.current || !cacheValid;
16028
15976
  if (shouldRunCallbacks) {
16029
15977
  if (setupCBRef.current) {
16030
15978
  const freshState = store.getState();
@@ -16045,7 +15993,7 @@ function useRenderPipeline(mainCB, setupCB) {
16045
15993
  callbacksRanRef.current = true;
16046
15994
  }
16047
15995
  } catch (error) {
16048
- console.error("[useRenderPipeline] Setup error:", error);
15996
+ console.warn("[useRenderPipeline] Setup failed; the render pipeline was not configured:", error);
16049
15997
  }
16050
15998
  }, [store, renderer, scene, camera, isLegacy, rebuildVersion]);
16051
15999
  const passes = useThree((s) => s.passes);
@@ -16063,4 +16011,4 @@ function useRenderPipeline(mainCB, setupCB) {
16063
16011
 
16064
16012
  extend(THREE);
16065
16013
 
16066
- export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, clearNodeScope, clearRootNodes, clearRootUniforms, clearScope, context, createEvents, createPointerEvents, createPortal, createRoot, createScopedStore, createStore, createTextureOperations, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, rebuildAllBuffers, rebuildAllNodes, rebuildAllStorage, rebuildAllUniforms, reconciler, registerPrimary, removeInteractivity, removeNodes, removeUniforms, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useBuffers, useEnvironment, useFrame, useGPUStorage, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useLocalNodes, useMutableCallback, useNodes, useRenderPipeline, useRenderTarget, useStore, useTexture, useTextures, useThree, useUniform, useUniforms, waitForPrimary };
16014
+ export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Texture, _roots, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, clearNodeScope, clearRootNodes, clearRootUniforms, clearScope, context, createEvents, createPointerEvents, createPortal, createRoot, createScopedStore, createStore, createTextureOperations, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, rebuildAllBuffers, rebuildAllNodes, rebuildAllStorage, rebuildAllUniforms, reconciler, registerPrimary, removeInteractivity, removeNodes, removeUniforms, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useBuffers, useEnvironment, useFrame, useGPUStorage, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useLocalNodes, useMutableCallback, useNodes, useRenderPipeline, useRenderTarget, useStore, useTexture, useTextures, useThree, useUniform, useUniforms, waitForPrimary };