@react-three/fiber 10.0.0-canary.5c62eb9 → 10.0.0-canary.60e7a38

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
  }
@@ -1068,6 +1096,41 @@ function releaseInternalPointerCapture(internal, obj, pointerId) {
1068
1096
  captureData.target.releasePointerCapture(pointerId);
1069
1097
  }
1070
1098
  }
1099
+ function swapInteractivity(store, object, newObject) {
1100
+ const { internal } = store.getState();
1101
+ for (let i = 0; i < internal.interaction.length; i++) {
1102
+ if (internal.interaction[i] === object) internal.interaction[i] = newObject;
1103
+ }
1104
+ for (const pointerState of internal.pointerMap.values()) {
1105
+ for (let i = 0; i < pointerState.initialHits.length; i++) {
1106
+ if (pointerState.initialHits[i] === object) pointerState.initialHits[i] = newObject;
1107
+ }
1108
+ pointerState.hovered.forEach((value, key) => {
1109
+ if (value.eventObject === object || value.object === object) {
1110
+ pointerState.hovered.delete(key);
1111
+ const next = {
1112
+ ...value,
1113
+ eventObject: value.eventObject === object ? newObject : value.eventObject,
1114
+ object: value.object === object ? newObject : value.object
1115
+ };
1116
+ pointerState.hovered.set(makeId(next), next);
1117
+ }
1118
+ });
1119
+ const captureData = pointerState.captured.get(object);
1120
+ if (captureData) {
1121
+ pointerState.captured.delete(object);
1122
+ pointerState.captured.set(newObject, {
1123
+ ...captureData,
1124
+ intersection: {
1125
+ ...captureData.intersection,
1126
+ object: captureData.intersection.object === object ? newObject : captureData.intersection.object,
1127
+ eventObject: captureData.intersection.eventObject === object ? newObject : captureData.intersection.eventObject
1128
+ }
1129
+ });
1130
+ }
1131
+ }
1132
+ unregisterVisibility(store, object);
1133
+ }
1071
1134
  function removeInteractivity(store, object) {
1072
1135
  const { internal } = store.getState();
1073
1136
  internal.interaction = internal.interaction.filter((o) => o !== object);
@@ -1553,6 +1616,7 @@ function createPointerEvents(store) {
1553
1616
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1554
1617
  }
1555
1618
  },
1619
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1556
1620
  registerPointer: (config) => {
1557
1621
  const pointerId = nextXRPointerId++;
1558
1622
  xrPointers.set(pointerId, config);
@@ -1640,11 +1704,10 @@ function notifyAlpha({ message, link }) {
1640
1704
  }
1641
1705
 
1642
1706
  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
1707
  function isInternalRendererAccess(stack, callerDepth = 2) {
1645
1708
  if (!stack) return false;
1646
1709
  const caller = stack.split("\n")[callerDepth] ?? "";
1647
- return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m)) || INTERNAL_FIBER_MARKERS.some((m) => caller.includes(m));
1710
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
1648
1711
  }
1649
1712
 
1650
1713
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
@@ -1779,6 +1842,7 @@ const createStore = (invalidate, advance) => {
1779
1842
  }),
1780
1843
  setFrameloop: (frameloop = "always") => {
1781
1844
  set(() => ({ frameloop }));
1845
+ getScheduler().frameloop = frameloop;
1782
1846
  },
1783
1847
  setError: (error) => set(() => ({ error })),
1784
1848
  error: null,
@@ -1959,19 +2023,25 @@ function loadingFn(extensions, onProgress) {
1959
2023
  );
1960
2024
  };
1961
2025
  }
1962
- function useLoader(loader, input, extensions, onProgress) {
1963
- const keys = Array.isArray(input) ? input : [input];
2026
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
2027
+ const inputs = Array.isArray(input) ? input : [input];
2028
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
1964
2029
  const fn = loadingFn(extensions, onProgress);
1965
- const results = keys.map((key) => suspend(fn, [loader, key], { equal: is.equ }));
2030
+ const results = cacheKeys.map(
2031
+ (key, index) => suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
2032
+ );
1966
2033
  return Array.isArray(input) ? results : results[0];
1967
2034
  }
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]));
2035
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2036
+ const inputs = Array.isArray(input) ? input : [input];
2037
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2038
+ cacheKeys.forEach(
2039
+ (key, index) => preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2040
+ );
1971
2041
  };
1972
- useLoader.clear = function(loader, input) {
1973
- const keys = Array.isArray(input) ? input : [input];
1974
- keys.forEach((key) => clear([loader, key]));
2042
+ useLoader.clear = function(loader, input, cacheKey) {
2043
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2044
+ cacheKeys.forEach((key) => clear([loader, key]));
1975
2045
  };
1976
2046
  useLoader.loader = getLoader;
1977
2047
 
@@ -2391,7 +2461,7 @@ function advance(timestamp) {
2391
2461
  getScheduler().step(timestamp);
2392
2462
  }
2393
2463
 
2394
- const version = "10.0.0-alpha.2";
2464
+ const version = "10.0.0-alpha.3";
2395
2465
  const packageData = {
2396
2466
  version: version};
2397
2467
 
@@ -13647,7 +13717,7 @@ function n0() {
13647
13717
  var t0 = n0();
13648
13718
  const r0 = Xb(t0);
13649
13719
 
13650
- const t = 1, o = 8, r = 32, e = 2;
13720
+ const t = 1, o = 8, r = 32, e = 2, i$1 = 268435456;
13651
13721
 
13652
13722
  function createReconciler(config) {
13653
13723
  const reconciler2 = r0(config);
@@ -13812,7 +13882,15 @@ function setFiberRef(fiber, publicInstance) {
13812
13882
  }
13813
13883
  }
13814
13884
  const reconstructed = [];
13815
- function swapInstances() {
13885
+ function flushReconstructedInstances() {
13886
+ if (reconstructed.length === 0) return;
13887
+ try {
13888
+ swapReconstructedInstances();
13889
+ } finally {
13890
+ reconstructed.length = 0;
13891
+ }
13892
+ }
13893
+ function swapReconstructedInstances() {
13816
13894
  for (const [instance] of reconstructed) {
13817
13895
  const parent = instance.parent;
13818
13896
  if (parent) {
@@ -13830,6 +13908,9 @@ function swapInstances() {
13830
13908
  }
13831
13909
  }
13832
13910
  if (instance.isHidden) unhideInstance(instance);
13911
+ if (isObject3D(instance.object) && !instance.parent) {
13912
+ removeInteractivity(findInitialRoot(instance), instance.object);
13913
+ }
13833
13914
  if (instance.object.__r3f) delete instance.object.__r3f;
13834
13915
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
13835
13916
  }
@@ -13838,10 +13919,16 @@ function swapInstances() {
13838
13919
  const parent = instance.parent;
13839
13920
  if (parent) {
13840
13921
  const target = catalogue[toPascalCase(instance.type)];
13922
+ const prevObject = instance.object;
13841
13923
  instance.object = instance.props.object ?? new target(...instance.props.args ?? []);
13842
13924
  instance.object.__r3f = instance;
13843
13925
  setFiberRef(fiber, instance.object);
13926
+ if (isObject3D(prevObject) && isObject3D(instance.object)) {
13927
+ swapInteractivity(findInitialRoot(instance), prevObject, instance.object);
13928
+ }
13844
13929
  delete instance.appliedOnce;
13930
+ instance.eventCount = 0;
13931
+ instance.handlers = {};
13845
13932
  applyProps(instance.object, instance.props);
13846
13933
  if (instance.props.attach) {
13847
13934
  attach(parent, instance);
@@ -13858,14 +13945,114 @@ function swapInstances() {
13858
13945
  invalidateInstance(instance);
13859
13946
  }
13860
13947
  }
13861
- reconstructed.length = 0;
13862
13948
  }
13863
13949
  const handleTextInstance = () => {
13864
13950
  };
13865
13951
  const NO_CONTEXT = {};
13866
13952
  let currentUpdatePriority = NoEventPriority;
13867
- const NoFlags = 0;
13868
- const Update = 4;
13953
+ function getEventPriority(type) {
13954
+ switch (type) {
13955
+ case "beforetoggle":
13956
+ case "cancel":
13957
+ case "click":
13958
+ case "close":
13959
+ case "contextmenu":
13960
+ case "copy":
13961
+ case "cut":
13962
+ case "auxclick":
13963
+ case "dblclick":
13964
+ case "dragend":
13965
+ case "dragstart":
13966
+ case "drop":
13967
+ case "focusin":
13968
+ case "focusout":
13969
+ case "input":
13970
+ case "invalid":
13971
+ case "keydown":
13972
+ case "keypress":
13973
+ case "keyup":
13974
+ case "mousedown":
13975
+ case "mouseup":
13976
+ case "paste":
13977
+ case "pause":
13978
+ case "play":
13979
+ case "pointercancel":
13980
+ case "pointerdown":
13981
+ case "pointerup":
13982
+ case "ratechange":
13983
+ case "reset":
13984
+ case "resize":
13985
+ case "seeked":
13986
+ case "submit":
13987
+ case "touchcancel":
13988
+ case "touchend":
13989
+ case "touchstart":
13990
+ case "volumechange":
13991
+ case "change":
13992
+ case "selectionchange":
13993
+ case "compositionstart":
13994
+ case "compositionend":
13995
+ case "compositionupdate":
13996
+ case "beforeinput":
13997
+ case "blur":
13998
+ case "fullscreenchange":
13999
+ case "focus":
14000
+ case "hashchange":
14001
+ case "popstate":
14002
+ case "select":
14003
+ case "selectstart":
14004
+ return e;
14005
+ case "drag":
14006
+ case "dragenter":
14007
+ case "dragexit":
14008
+ case "dragleave":
14009
+ case "dragover":
14010
+ case "mousemove":
14011
+ case "mouseout":
14012
+ case "mouseover":
14013
+ case "pointermove":
14014
+ case "pointerout":
14015
+ case "pointerover":
14016
+ case "scroll":
14017
+ case "touchmove":
14018
+ case "wheel":
14019
+ case "mouseenter":
14020
+ case "mouseleave":
14021
+ case "pointerenter":
14022
+ case "pointerleave":
14023
+ return o;
14024
+ case "message": {
14025
+ switch (unstable_getCurrentPriorityLevel()) {
14026
+ case unstable_ImmediatePriority:
14027
+ return e;
14028
+ case unstable_UserBlockingPriority:
14029
+ return o;
14030
+ case unstable_NormalPriority:
14031
+ case unstable_LowPriority:
14032
+ return r;
14033
+ case unstable_IdlePriority:
14034
+ return i$1;
14035
+ default:
14036
+ return r;
14037
+ }
14038
+ }
14039
+ default:
14040
+ return r;
14041
+ }
14042
+ }
14043
+ function scheduleMicrotask(callback) {
14044
+ if (typeof queueMicrotask === "function") {
14045
+ queueMicrotask(callback);
14046
+ } else if (typeof Promise !== "undefined") {
14047
+ Promise.resolve().then(callback).catch((error) => {
14048
+ setTimeout(() => {
14049
+ throw error;
14050
+ });
14051
+ });
14052
+ } else {
14053
+ setTimeout(callback);
14054
+ }
14055
+ }
13869
14056
  const reconciler = /* @__PURE__ */ createReconciler({
13870
14057
  isPrimaryRenderer: false,
13871
14058
  warnsIfNotActing: false,
@@ -13904,16 +14091,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
13904
14091
  else if (newProps.args?.length !== oldProps.args?.length) reconstruct = true;
13905
14092
  else if (newProps.args?.some((value, index) => value !== oldProps.args?.[index])) reconstruct = true;
13906
14093
  if (reconstruct) {
13907
- reconstructed.push([instance, { ...newProps }, fiber]);
14094
+ reconstructed.push([instance, getInstanceProps(newProps), fiber]);
13908
14095
  } else {
13909
14096
  const changedProps = diffProps(instance, newProps);
13910
- if (Object.keys(changedProps).length) {
13911
- Object.assign(instance.props, changedProps);
13912
- applyProps(instance.object, changedProps);
13913
- }
14097
+ const attach2 = instance.props.attach;
14098
+ instance.props = getInstanceProps(newProps);
14099
+ if (attach2 !== void 0) instance.props.attach = attach2;
14100
+ else delete instance.props.attach;
14101
+ if (Object.keys(changedProps).length) applyProps(instance.object, changedProps);
13914
14102
  }
13915
- const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
13916
- if (isTailSibling) swapInstances();
13917
14103
  },
13918
14104
  finalizeInitialChildren: (instance) => {
13919
14105
  for (const prop in instance.props) {
@@ -13938,8 +14124,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
13938
14124
  const target = container.getState().internal.container ?? container.getState().scene;
13939
14125
  return prepare(target, container, "", {});
13940
14126
  },
13941
- resetAfterCommit: () => {
13942
- },
14127
+ // Reconstructed instances are swapped once all mutations are committed,
14128
+ // before layout effects run so refs point to the new objects
14129
+ resetAfterCommit: flushReconstructedInstances,
13943
14130
  shouldSetTextContent: () => false,
13944
14131
  clearContainer: () => false,
13945
14132
  hideInstance,
@@ -13947,6 +14134,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
13947
14134
  createTextInstance: handleTextInstance,
13948
14135
  hideTextInstance: handleTextInstance,
13949
14136
  unhideTextInstance: handleTextInstance,
14137
+ // Mirrors react-dom, which flushes discrete work in microtasks
14138
+ supportsMicrotasks: true,
14139
+ scheduleMicrotask,
13950
14140
  scheduleTimeout: typeof setTimeout === "function" ? setTimeout : void 0,
13951
14141
  cancelTimeout: typeof clearTimeout === "function" ? clearTimeout : void 0,
13952
14142
  noTimeout: -1,
@@ -13987,28 +14177,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
13987
14177
  },
13988
14178
  resolveUpdatePriority() {
13989
14179
  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
- }
14180
+ const eventType = typeof window !== "undefined" ? window.event?.type : void 0;
14181
+ if (eventType === void 0) return r;
14182
+ return getEventPriority(eventType);
14012
14183
  },
14013
14184
  resetFormInstance() {
14014
14185
  },
@@ -14057,11 +14228,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14057
14228
  cloneMutableTextInstance(textInstance) {
14058
14229
  return textInstance;
14059
14230
  },
14231
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14232
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14233
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14234
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14235
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14236
+ // Guarded by a test asserting a full render + unmount never reaches them.
14060
14237
  cloneRootViewTransitionContainer(_rootContainer) {
14061
- throw new Error("Not implemented.");
14062
14238
  },
14063
14239
  removeRootViewTransitionClone(_rootContainer, _clone) {
14064
- throw new Error("Not implemented.");
14065
14240
  },
14066
14241
  // https://github.com/facebook/react/pull/32465
14067
14242
  createFragmentInstance: (_fiber) => null,
@@ -14146,6 +14321,7 @@ function createRoot(canvas) {
14146
14321
  const lastConfiguredProps = {};
14147
14322
  let configured = false;
14148
14323
  let pending = null;
14324
+ let rendererSetup = null;
14149
14325
  return {
14150
14326
  async configure(props = {}) {
14151
14327
  let resolve;
@@ -14176,7 +14352,7 @@ function createRoot(canvas) {
14176
14352
  forceEven
14177
14353
  } = props;
14178
14354
  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();
14355
+ let state = store.getState();
14180
14356
  const defaultGPUProps = {
14181
14357
  canvas,
14182
14358
  antialias: true
@@ -14190,52 +14366,64 @@ function createRoot(canvas) {
14190
14366
  throw new Error("Cannot use both gl and renderer props at the same time");
14191
14367
  }
14192
14368
  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
14369
+ if (!state.internal.actualRenderer) {
14370
+ if (!rendererSetup) {
14371
+ rendererSetup = (async () => {
14372
+ if (primaryCanvas) {
14373
+ const primary = await waitForPrimary(primaryCanvas);
14374
+ renderer = primary.renderer;
14375
+ state.internal.actualRenderer = renderer;
14376
+ const canvasTarget = new CanvasTarget(canvas);
14377
+ primary.store.setState((prev) => ({
14378
+ internal: { ...prev.internal, isMultiCanvas: true }
14379
+ }));
14380
+ state.set((prev) => ({
14381
+ webGPUSupported: primary.store.getState().webGPUSupported,
14382
+ renderer,
14383
+ primaryStore: primary.store,
14384
+ internal: {
14385
+ ...prev.internal,
14386
+ canvasTarget,
14387
+ isMultiCanvas: true,
14388
+ isSecondary: true,
14389
+ targetId: primaryCanvas
14390
+ }
14391
+ }));
14392
+ } else {
14393
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
14394
+ if (!renderer.hasInitialized?.()) {
14395
+ const size2 = computeInitialSize(canvas, propsSize);
14396
+ if (size2.width > 0 && size2.height > 0) {
14397
+ const pixelRatio = calculateDpr(dpr);
14398
+ canvas.width = size2.width * pixelRatio;
14399
+ canvas.height = size2.height * pixelRatio;
14400
+ }
14401
+ await renderer.init();
14402
+ }
14403
+ const backend = renderer.backend;
14404
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14405
+ state.internal.actualRenderer = renderer;
14406
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14407
+ if (canvasId && !state.internal.isSecondary) {
14408
+ const canvasTarget = new CanvasTarget(canvas);
14409
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14410
+ state.set((prev) => ({
14411
+ internal: {
14412
+ ...prev.internal,
14413
+ canvasTarget,
14414
+ unregisterPrimary
14415
+ }
14416
+ }));
14417
+ }
14236
14418
  }
14237
- }));
14419
+ })().catch((err) => {
14420
+ rendererSetup = null;
14421
+ throw err;
14422
+ });
14238
14423
  }
14424
+ await rendererSetup;
14425
+ state = store.getState();
14426
+ renderer = state.internal.actualRenderer;
14239
14427
  }
14240
14428
  let raycaster = state.raycaster;
14241
14429
  if (!raycaster) state.set({ raycaster: raycaster = new Raycaster() });
@@ -14585,7 +14773,8 @@ function unmountComponentAtNode(canvas, callback) {
14585
14773
  dispose(state.scene);
14586
14774
  _roots.delete(canvas);
14587
14775
  if (callback) callback(canvas);
14588
- } catch {
14776
+ } catch (error) {
14777
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
14589
14778
  }
14590
14779
  }, 500);
14591
14780
  }
@@ -14648,6 +14837,7 @@ function PortalInner({ state = {}, children, container }) {
14648
14837
  viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(), resolvedSize);
14649
14838
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
14650
14839
  }
14840
+ const set = injectState.set;
14651
14841
  return {
14652
14842
  // The intersect consists of the previous root state
14653
14843
  ...rootState,
@@ -14666,7 +14856,7 @@ function PortalInner({ state = {}, children, container }) {
14666
14856
  size: resolvedSize,
14667
14857
  viewport: { ...rootState.viewport, ...viewport },
14668
14858
  // Layers are allowed to override events
14669
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14859
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14670
14860
  // Container for child attachment - the portalScene (injected or container itself)
14671
14861
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
14672
14862
  };
@@ -14738,14 +14928,133 @@ function parseRendererConfig(rendererProp) {
14738
14928
  return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14739
14929
  }
14740
14930
 
14931
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14932
+ const ROOT_SCOPE = "";
14933
+ const registries = /* @__PURE__ */ new WeakMap();
14934
+ function getKindRegistry(store, kind) {
14935
+ let registry = registries.get(store);
14936
+ if (!registry) {
14937
+ registry = {
14938
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14939
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14940
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14941
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14942
+ };
14943
+ registries.set(store, registry);
14944
+ }
14945
+ return registry[kind];
14946
+ }
14947
+ function resolvePrimary$1(store) {
14948
+ return store.getState().primaryStore ?? store;
14949
+ }
14950
+ function isScopeValid(store, kind, scopeKey) {
14951
+ return getKindRegistry(store, kind).valid.has(scopeKey);
14952
+ }
14953
+ function peekStaged(store, kind, scopeKey) {
14954
+ return getKindRegistry(store, kind).staged.get(scopeKey);
14955
+ }
14956
+ function stageEntries(store, kind, scopeKey, entries) {
14957
+ const { staged } = getKindRegistry(store, kind);
14958
+ const current = staged.get(scopeKey);
14959
+ if (current) Object.assign(current, entries);
14960
+ else staged.set(scopeKey, { ...entries });
14961
+ }
14962
+ function readCommittedScope(map, scopeKey, isLeaf) {
14963
+ if (scopeKey === ROOT_SCOPE) {
14964
+ const leaves = {};
14965
+ for (const [key, value] of Object.entries(map)) if (isLeaf(value)) leaves[key] = value;
14966
+ return leaves;
14967
+ }
14968
+ const scopeData = map[scopeKey];
14969
+ if (scopeData && typeof scopeData === "object" && !isLeaf(scopeData)) return scopeData;
14970
+ return {};
14971
+ }
14972
+ function withStagedOverlay(store, kind, committed) {
14973
+ const { staged } = getKindRegistry(store, kind);
14974
+ if (staged.size === 0) return committed;
14975
+ const view = { ...committed };
14976
+ for (const [scopeKey, entries] of staged) {
14977
+ if (scopeKey === ROOT_SCOPE) Object.assign(view, entries);
14978
+ else view[scopeKey] = { ...view[scopeKey], ...entries };
14979
+ }
14980
+ return view;
14981
+ }
14982
+ function flushStagedScope(store, kind, scopeKey, isLeaf) {
14983
+ const registry = getKindRegistry(store, kind);
14984
+ const staged = registry.staged.get(scopeKey);
14985
+ if (!staged) return;
14986
+ registry.staged.delete(scopeKey);
14987
+ const replace = !registry.valid.has(scopeKey);
14988
+ store.setState((state) => {
14989
+ const map = state[kind];
14990
+ if (scopeKey === ROOT_SCOPE) {
14991
+ if (!replace) return { [kind]: { ...map, ...staged } };
14992
+ const next = {};
14993
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
14994
+ return { [kind]: { ...next, ...staged } };
14995
+ }
14996
+ const current = replace ? {} : map[scopeKey] ?? {};
14997
+ return { [kind]: { ...map, [scopeKey]: { ...current, ...staged } } };
14998
+ });
14999
+ registry.valid.add(scopeKey);
15000
+ }
15001
+ function invalidateResource(store, kind, scopeKey) {
15002
+ const registry = getKindRegistry(store, kind);
15003
+ if (scopeKey === void 0) {
15004
+ registry.valid.clear();
15005
+ registry.staged.clear();
15006
+ } else {
15007
+ registry.valid.delete(scopeKey);
15008
+ registry.staged.delete(scopeKey);
15009
+ }
15010
+ }
15011
+ function rebuildResource(store, kind, userScope) {
15012
+ const primary = resolvePrimary$1(store);
15013
+ invalidateResource(primary, kind, userScope === "root" ? ROOT_SCOPE : userScope);
15014
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
15015
+ }
15016
+ function invalidateAllResources(store) {
15017
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
15018
+ }
15019
+ function removeResourceEntries(store, kind, names, scope, isLeaf) {
15020
+ const staged = peekStaged(store, kind, scope ?? ROOT_SCOPE);
15021
+ if (staged) for (const name of names) delete staged[name];
15022
+ store.setState((state) => {
15023
+ const map = state[kind];
15024
+ if (scope) {
15025
+ const currentScope = { ...map[scope] };
15026
+ for (const name of names) delete currentScope[name];
15027
+ return { [kind]: { ...map, [scope]: currentScope } };
15028
+ }
15029
+ const next = { ...map };
15030
+ for (const name of names) if (isLeaf(next[name])) delete next[name];
15031
+ return { [kind]: next };
15032
+ });
15033
+ }
15034
+ function clearResourceEntries(store, kind, scope, isLeaf) {
15035
+ const registry = getKindRegistry(store, kind);
15036
+ if (scope && scope !== "root") registry.staged.delete(scope);
15037
+ else if (scope === "root") registry.staged.delete(ROOT_SCOPE);
15038
+ else registry.staged.clear();
15039
+ store.setState((state) => {
15040
+ const map = state[kind];
15041
+ if (scope && scope !== "root") {
15042
+ const { [scope]: _, ...rest } = map;
15043
+ return { [kind]: rest };
15044
+ }
15045
+ if (scope === "root") {
15046
+ const next = {};
15047
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
15048
+ return { [kind]: next };
15049
+ }
15050
+ return { [kind]: {} };
15051
+ });
15052
+ }
15053
+
14741
15054
  function clearHmrCaches(store) {
14742
- store.setState((state) => ({
14743
- nodes: {},
14744
- uniforms: {},
14745
- buffers: {},
14746
- gpuStorage: {},
14747
- _hmrVersion: state._hmrVersion + 1
14748
- }));
15055
+ const primary = store.getState().primaryStore ?? store;
15056
+ invalidateAllResources(primary);
15057
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14749
15058
  }
14750
15059
 
14751
15060
  function CanvasImpl({
@@ -14826,6 +15135,7 @@ function CanvasImpl({
14826
15135
  const handleDropMissed = useMutableCallback(onDropMissed);
14827
15136
  const [block, setBlock] = React.useState(false);
14828
15137
  const [error, setError] = React.useState(false);
15138
+ const [fallbackVisible, setFallbackVisible] = React.useState(false);
14829
15139
  if (block) throw block;
14830
15140
  if (error) throw error;
14831
15141
  const root = React.useRef(null);
@@ -14833,6 +15143,7 @@ function CanvasImpl({
14833
15143
  const unsubscribeErrorRef = React.useRef(null);
14834
15144
  useIsomorphicLayoutEffect(() => {
14835
15145
  effectActiveRef.current = true;
15146
+ if (fallbackVisible) return;
14836
15147
  const canvas = canvasRef.current;
14837
15148
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
14838
15149
  if (!root.current) {
@@ -14853,7 +15164,7 @@ function CanvasImpl({
14853
15164
  }
14854
15165
  async function run() {
14855
15166
  if (!effectActiveRef.current || !root.current) return;
14856
- await root.current.configure({
15167
+ const configured = await root.current.configure({
14857
15168
  id,
14858
15169
  primaryCanvas,
14859
15170
  scheduler,
@@ -14894,8 +15205,20 @@ function CanvasImpl({
14894
15205
  }
14895
15206
  onCreated?.(state);
14896
15207
  }
14897
- });
14898
- if (!effectActiveRef.current || !root.current) return;
15208
+ }).then(
15209
+ () => true,
15210
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
15211
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
15212
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
15213
+ (setupError) => {
15214
+ if (effectActiveRef.current) {
15215
+ if (fallback != null) setFallbackVisible(true);
15216
+ else setError(setupError);
15217
+ }
15218
+ return false;
15219
+ }
15220
+ );
15221
+ if (!configured || !effectActiveRef.current || !root.current) return;
14899
15222
  root.current.render(
14900
15223
  /* @__PURE__ */ jsx(Bridge, { children: /* @__PURE__ */ jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxs(React.Suspense, { fallback: /* @__PURE__ */ jsx(Block, { set: setBlock }), children: [
14901
15224
  backgroundProps && /* @__PURE__ */ jsx(Environment, { ...backgroundProps }),
@@ -14958,7 +15281,11 @@ function CanvasImpl({
14958
15281
  ...style
14959
15282
  },
14960
15283
  ...props,
14961
- children: /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
15284
+ children: fallbackVisible ? (
15285
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15286
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15287
+ fallback
15288
+ ) : /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
14962
15289
  "canvas",
14963
15290
  {
14964
15291
  ref: canvasRef,
@@ -15040,30 +15367,31 @@ let ScopedStore = _ScopedStore;
15040
15367
  function createScopedStore(data) {
15041
15368
  return new ScopedStore(data);
15042
15369
  }
15043
- function createLazyCreatorState(state) {
15370
+ function createLazyCreatorState(state, store) {
15044
15371
  let _uniforms = null;
15045
15372
  let _nodes = null;
15046
15373
  let _buffers = null;
15047
15374
  let _gpuStorage = null;
15375
+ const view = (kind) => store ? withStagedOverlay(store, kind, state[kind]) : state[kind];
15048
15376
  return Object.create(state, {
15049
15377
  uniforms: {
15050
15378
  get() {
15051
- return _uniforms ?? (_uniforms = createScopedStore(state.uniforms));
15379
+ return _uniforms ?? (_uniforms = createScopedStore(view("uniforms")));
15052
15380
  }
15053
15381
  },
15054
15382
  nodes: {
15055
15383
  get() {
15056
- return _nodes ?? (_nodes = createScopedStore(state.nodes));
15384
+ return _nodes ?? (_nodes = createScopedStore(view("nodes")));
15057
15385
  }
15058
15386
  },
15059
15387
  buffers: {
15060
15388
  get() {
15061
- return _buffers ?? (_buffers = createScopedStore(state.buffers));
15389
+ return _buffers ?? (_buffers = createScopedStore(view("buffers")));
15062
15390
  }
15063
15391
  },
15064
15392
  gpuStorage: {
15065
15393
  get() {
15066
- return _gpuStorage ?? (_gpuStorage = createScopedStore(state.gpuStorage));
15394
+ return _gpuStorage ?? (_gpuStorage = createScopedStore(view("gpuStorage")));
15067
15395
  }
15068
15396
  }
15069
15397
  });
@@ -15186,65 +15514,56 @@ function useCompareMemoize(value, deep) {
15186
15514
  return ref.current;
15187
15515
  }
15188
15516
 
15517
+ function useScopedResource(options) {
15518
+ const { store, kind, scope, isLeaf, create, prepare, reconcile, input } = options;
15519
+ const scopeKey = scope ?? ROOT_SCOPE;
15520
+ const version = store((s) => s._hmrVersion);
15521
+ const entries = useMemo(() => {
15522
+ const staged = peekStaged(store, kind, scopeKey);
15523
+ const reusable = isScopeValid(store, kind, scopeKey);
15524
+ const map = store.getState()[kind];
15525
+ const committed = reusable ? readCommittedScope(map, scopeKey, isLeaf) : void 0;
15526
+ const result = {};
15527
+ let fresh = null;
15528
+ for (const [name, candidate] of Object.entries(create())) {
15529
+ const existing = staged?.[name] ?? committed?.[name];
15530
+ if (existing !== void 0) {
15531
+ result[name] = existing;
15532
+ reconcile?.(existing, candidate);
15533
+ } else {
15534
+ const value = prepare ? prepare(name, candidate) : candidate;
15535
+ result[name] = value;
15536
+ (fresh ?? (fresh = {}))[name] = value;
15537
+ }
15538
+ }
15539
+ if (fresh) stageEntries(store, kind, scopeKey, fresh);
15540
+ return result;
15541
+ }, [store, kind, scopeKey, version, input]);
15542
+ useIsomorphicLayoutEffect(() => {
15543
+ flushStagedScope(store, kind, scopeKey, isLeaf);
15544
+ });
15545
+ return entries;
15546
+ }
15547
+
15189
15548
  const isUniformNode$1 = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
15190
15549
  function useUniforms(creatorOrScope, scope) {
15191
15550
  const store = usePrimaryStore();
15192
15551
  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
- },
15552
+ (names, targetScope) => removeResourceEntries(store, "uniforms", Array.isArray(names) ? names : [names], targetScope, isUniformNode$1),
15206
15553
  [store]
15207
15554
  );
15208
15555
  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
- },
15556
+ (targetScope) => clearResourceEntries(store, "uniforms", targetScope, isUniformNode$1),
15225
15557
  [store]
15226
15558
  );
15227
15559
  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
- },
15560
+ (targetScope) => rebuildResource(store, "uniforms", targetScope),
15242
15561
  [store]
15243
15562
  );
15244
15563
  const inputForMemoization = useMemo(() => {
15245
15564
  let raw = creatorOrScope;
15246
15565
  if (is.fun(creatorOrScope)) {
15247
- const wrappedState = createLazyCreatorState(store.getState());
15566
+ const wrappedState = createLazyCreatorState(store.getState(), store);
15248
15567
  raw = creatorOrScope(wrappedState);
15249
15568
  }
15250
15569
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
@@ -15259,80 +15578,43 @@ function useUniforms(creatorOrScope, scope) {
15259
15578
  const memoizedInput = useCompareMemoize(inputForMemoization);
15260
15579
  const isReader = memoizedInput === void 0 || typeof memoizedInput === "string";
15261
15580
  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
- }
15581
+ const created = useScopedResource({
15582
+ store,
15583
+ kind: "uniforms",
15584
+ scope: isReader ? void 0 : scope,
15585
+ isLeaf: isUniformNode$1,
15586
+ input: memoizedInput,
15587
+ create: () => {
15588
+ if (isReader) return {};
15589
+ if (typeof memoizedInput !== "object" || memoizedInput === null) throw new Error("Invalid uniform input");
15590
+ return memoizedInput;
15591
+ },
15592
+ prepare: (name, candidate) => createUniform(name, candidate, scope),
15593
+ reconcile: (existing, candidate) => {
15594
+ const existingVal = existing.value;
15595
+ const newVal = vectorize(candidate);
15596
+ let equals = newVal === existingVal;
15597
+ if (!equals && hasEqualsMethod(existingVal) && hasEqualsMethod(newVal)) {
15598
+ if (isThreeVector(existingVal) && isThreeVector(newVal)) {
15599
+ equals = vectorEquals(existingVal, newVal);
15600
+ } else if (isSameThreeType(existingVal, newVal)) {
15601
+ equals = existingVal.equals(newVal);
15602
+ }
15603
+ }
15604
+ if (!equals) existing.value = newVal;
15317
15605
  }
15318
- return result;
15319
- }, [store, memoizedInput, scope, readerDep, creatorDep]);
15606
+ });
15607
+ let uniforms = created;
15608
+ if (memoizedInput === void 0) {
15609
+ uniforms = storeUniforms;
15610
+ } else if (typeof memoizedInput === "string") {
15611
+ const scopeData = storeUniforms[memoizedInput];
15612
+ uniforms = scopeData && !isUniformNode$1(scopeData) ? scopeData : {};
15613
+ }
15320
15614
  return { ...uniforms, removeUniforms: removeUniforms2, clearUniforms, rebuildUniforms };
15321
15615
  }
15322
15616
  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
- });
15617
+ rebuildResource(store, "uniforms", scope);
15336
15618
  }
15337
15619
  function removeUniforms(set, names, scope) {
15338
15620
  set((state) => {
@@ -15396,192 +15678,91 @@ function isSameThreeType(a, b) {
15396
15678
  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
15679
  }
15398
15680
 
15681
+ const uniformOf = uniform;
15399
15682
  const isUniformNode = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
15400
15683
  const isTSLNode$1 = (value) => value !== null && typeof value === "object" && "uuid" in value && "nodeType" in value;
15401
15684
  function useUniform(name, value) {
15402
15685
  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)) {
15686
+ const registered = useScopedResource({
15687
+ store,
15688
+ kind: "uniforms",
15689
+ scope: void 0,
15690
+ isLeaf: isUniformNode,
15691
+ input: name,
15692
+ create: () => value === void 0 ? {} : { [name]: value },
15693
+ prepare: createNamedUniform,
15694
+ reconcile: (existing2) => {
15409
15695
  if (value !== void 0 && !isTSLNode$1(value) && !isUniformNode(value)) {
15410
- existing.value = typeof value === "string" ? new Color(value) : value;
15696
+ existing2.value = typeof value === "string" ? new Color(value) : value;
15411
15697
  }
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
- }
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
15698
  }
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]);
15699
+ });
15700
+ if (registered[name]) return registered[name];
15701
+ const existing = peekStaged(store, "uniforms", ROOT_SCOPE)?.[name] ?? store.getState().uniforms[name];
15702
+ if (existing && isUniformNode(existing)) return existing;
15703
+ throw new Error(
15704
+ `[useUniform] Uniform "${name}" not found. Create it first with: useUniform('${name}', initialValue)`
15705
+ );
15706
+ }
15707
+ function createNamedUniform(name, value) {
15708
+ let node;
15709
+ if (isUniformNode(value)) {
15710
+ node = value;
15711
+ } else if (isTSLNode$1(value)) {
15712
+ node = uniformOf(value);
15713
+ } else if (typeof value === "string") {
15714
+ node = uniform(new Color(value));
15715
+ } else {
15716
+ node = uniformOf(value);
15717
+ }
15718
+ if (typeof node.setName === "function") {
15719
+ node.setName(name);
15720
+ }
15721
+ return node;
15448
15722
  }
15449
15723
 
15450
15724
  const isTSLNode = (value) => value !== null && typeof value === "object" && ("uuid" in value || "nodeType" in value);
15451
15725
  function useNodes(creatorOrScope, scope) {
15452
15726
  const store = usePrimaryStore();
15453
15727
  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
- },
15728
+ (names, targetScope) => removeResourceEntries(store, "nodes", Array.isArray(names) ? names : [names], targetScope, isTSLNode),
15467
15729
  [store]
15468
15730
  );
15469
15731
  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
- },
15732
+ (targetScope) => clearResourceEntries(store, "nodes", targetScope, isTSLNode),
15486
15733
  [store]
15487
15734
  );
15488
15735
  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
- },
15736
+ (targetScope) => rebuildResource(store, "nodes", targetScope),
15506
15737
  [store]
15507
15738
  );
15508
15739
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
15509
15740
  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 } }));
15741
+ const created = useScopedResource({
15742
+ store,
15743
+ kind: "nodes",
15744
+ scope: isReader ? void 0 : scope,
15745
+ isLeaf: isTSLNode,
15746
+ create: () => {
15747
+ if (isReader) return {};
15748
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15749
+ },
15750
+ prepare: (name, node) => {
15751
+ node.setName?.(scope ? `${scope}.${name}` : name);
15752
+ return node;
15563
15753
  }
15564
- return result;
15565
- }, [store, scopeDep, readerDep, creatorDep]);
15754
+ });
15755
+ let nodes = created;
15756
+ if (creatorOrScope === void 0) {
15757
+ nodes = storeNodes;
15758
+ } else if (typeof creatorOrScope === "string") {
15759
+ const scopeData = storeNodes[creatorOrScope];
15760
+ nodes = scopeData && !isTSLNode(scopeData) ? scopeData : {};
15761
+ }
15566
15762
  return { ...nodes, removeNodes: removeNodes2, clearNodes, rebuildNodes };
15567
15763
  }
15568
15764
  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
- });
15765
+ rebuildResource(store, "nodes", scope);
15585
15766
  }
15586
15767
  function removeNodes(set, names, scope) {
15587
15768
  set((state) => {
@@ -15617,7 +15798,7 @@ function useLocalNodes(creator) {
15617
15798
  const textures = usePrimaryThree((s) => s.textures);
15618
15799
  const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
15619
15800
  return useMemo(() => {
15620
- const wrappedState = createLazyCreatorState(store.getState());
15801
+ const wrappedState = createLazyCreatorState(store.getState(), store);
15621
15802
  return creator(wrappedState);
15622
15803
  }, [store, creator, uniforms, nodes, textures, hmrVersion]);
15623
15804
  }
@@ -15638,58 +15819,15 @@ const disposeBuffer = (buffer) => {
15638
15819
  function useBuffers(creatorOrScope, scope) {
15639
15820
  const store = usePrimaryStore();
15640
15821
  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
- },
15822
+ (names, targetScope) => removeResourceEntries(store, "buffers", Array.isArray(names) ? names : [names], targetScope, isBufferLike),
15654
15823
  [store]
15655
15824
  );
15656
15825
  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
- },
15826
+ (targetScope) => clearResourceEntries(store, "buffers", targetScope, isBufferLike),
15673
15827
  [store]
15674
15828
  );
15675
15829
  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
- },
15830
+ (targetScope) => rebuildResource(store, "buffers", targetScope),
15693
15831
  [store]
15694
15832
  );
15695
15833
  const disposeBuffers = useCallback(
@@ -15708,85 +15846,33 @@ function useBuffers(creatorOrScope, scope) {
15708
15846
  );
15709
15847
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
15710
15848
  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;
15849
+ const created = useScopedResource({
15850
+ store,
15851
+ kind: "buffers",
15852
+ scope: isReader ? void 0 : scope,
15853
+ isLeaf: isBufferLike,
15854
+ create: () => {
15855
+ if (isReader) return {};
15856
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15857
+ },
15858
+ prepare: (name, buffer) => {
15859
+ if ("setName" in buffer && typeof buffer.setName === "function") {
15860
+ buffer.setName(scope ? `${scope}.${name}` : name);
15764
15861
  }
15862
+ return buffer;
15765
15863
  }
15766
- if (hasNewBuffers) {
15767
- set((s) => ({ buffers: { ...s.buffers, ...result } }));
15768
- }
15769
- return result;
15770
- }, [store, scopeDep, readerDep, creatorDep]);
15864
+ });
15865
+ let buffers = created;
15866
+ if (creatorOrScope === void 0) {
15867
+ buffers = storeBuffers;
15868
+ } else if (typeof creatorOrScope === "string") {
15869
+ const scopeData = storeBuffers[creatorOrScope];
15870
+ buffers = scopeData && !isBufferLike(scopeData) ? scopeData : {};
15871
+ }
15771
15872
  return { ...buffers, removeBuffers, clearBuffers, rebuildBuffers, disposeBuffers };
15772
15873
  }
15773
15874
  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
- });
15875
+ rebuildResource(store, "buffers", scope);
15790
15876
  }
15791
15877
 
15792
15878
  const isStorageLike = (value) => {
@@ -15805,58 +15891,15 @@ const disposeStorage = (storage) => {
15805
15891
  function useGPUStorage(creatorOrScope, scope) {
15806
15892
  const store = usePrimaryStore();
15807
15893
  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
- },
15894
+ (names, targetScope) => removeResourceEntries(store, "gpuStorage", Array.isArray(names) ? names : [names], targetScope, isStorageLike),
15821
15895
  [store]
15822
15896
  );
15823
15897
  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
- },
15898
+ (targetScope) => clearResourceEntries(store, "gpuStorage", targetScope, isStorageLike),
15840
15899
  [store]
15841
15900
  );
15842
15901
  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
- },
15902
+ (targetScope) => rebuildResource(store, "gpuStorage", targetScope),
15860
15903
  [store]
15861
15904
  );
15862
15905
  const disposeStorageFn = useCallback(
@@ -15875,72 +15918,33 @@ function useGPUStorage(creatorOrScope, scope) {
15875
15918
  );
15876
15919
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
15877
15920
  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
- }));
15921
+ const created = useScopedResource({
15922
+ store,
15923
+ kind: "gpuStorage",
15924
+ scope: isReader ? void 0 : scope,
15925
+ isLeaf: isStorageLike,
15926
+ create: () => {
15927
+ if (isReader) return {};
15928
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15929
+ },
15930
+ prepare: (name, storage) => {
15931
+ const label = scope ? `${scope}.${name}` : name;
15932
+ if ("setName" in storage && typeof storage.setName === "function") {
15933
+ storage.setName(label);
15921
15934
  }
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;
15935
+ if ("name" in storage && typeof storage.name === "string") {
15936
+ storage.name = label;
15937
15937
  }
15938
+ return storage;
15938
15939
  }
15939
- if (hasNewStorage) {
15940
- set((s) => ({ gpuStorage: { ...s.gpuStorage, ...result } }));
15941
- }
15942
- return result;
15943
- }, [store, scopeDep, readerDep, creatorDep]);
15940
+ });
15941
+ let gpuStorage = created;
15942
+ if (creatorOrScope === void 0) {
15943
+ gpuStorage = storeStorage;
15944
+ } else if (typeof creatorOrScope === "string") {
15945
+ const scopeData = storeStorage[creatorOrScope];
15946
+ gpuStorage = scopeData && !isStorageLike(scopeData) ? scopeData : {};
15947
+ }
15944
15948
  return {
15945
15949
  ...gpuStorage,
15946
15950
  removeStorage,
@@ -15950,22 +15954,7 @@ function useGPUStorage(creatorOrScope, scope) {
15950
15954
  };
15951
15955
  }
15952
15956
  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
- });
15957
+ rebuildResource(store, "gpuStorage", scope);
15969
15958
  }
15970
15959
 
15971
15960
  function useRenderPipeline(mainCB, setupCB) {
@@ -16006,12 +15995,12 @@ function useRenderPipeline(mainCB, setupCB) {
16006
15995
  const state = store.getState();
16007
15996
  const set = store.setState;
16008
15997
  try {
16009
- let pp = state.renderPipeline;
15998
+ let pipeline = state.renderPipeline;
16010
15999
  let currentPasses = { ...state.passes };
16011
- let justCreatedPP = false;
16012
- if (!pp) {
16013
- pp = new PostProcessing(renderer);
16014
- justCreatedPP = true;
16000
+ let justCreatedPipeline = false;
16001
+ if (!pipeline) {
16002
+ pipeline = new RenderPipeline(renderer);
16003
+ justCreatedPipeline = true;
16015
16004
  }
16016
16005
  const cacheValid = scenePassCacheRef.current && scenePassCacheRef.current.sceneUuid === scene.uuid && scenePassCacheRef.current.cameraUuid === camera.uuid;
16017
16006
  let scenePass;
@@ -16022,9 +16011,9 @@ function useRenderPipeline(mainCB, setupCB) {
16022
16011
  scenePassCacheRef.current = { sceneUuid: scene.uuid, cameraUuid: camera.uuid, scenePass };
16023
16012
  }
16024
16013
  currentPasses.scenePass = scenePass;
16025
- if (!pp.outputNode || justCreatedPP) pp.outputNode = scenePass;
16026
- set({ renderPipeline: pp, passes: currentPasses });
16027
- const shouldRunCallbacks = justCreatedPP || !callbacksRanRef.current || !cacheValid;
16014
+ if (!pipeline.outputNode || justCreatedPipeline) pipeline.outputNode = scenePass;
16015
+ set({ renderPipeline: pipeline, passes: currentPasses });
16016
+ const shouldRunCallbacks = justCreatedPipeline || !callbacksRanRef.current || !cacheValid;
16028
16017
  if (shouldRunCallbacks) {
16029
16018
  if (setupCBRef.current) {
16030
16019
  const freshState = store.getState();
@@ -16045,7 +16034,7 @@ function useRenderPipeline(mainCB, setupCB) {
16045
16034
  callbacksRanRef.current = true;
16046
16035
  }
16047
16036
  } catch (error) {
16048
- console.error("[useRenderPipeline] Setup error:", error);
16037
+ console.warn("[useRenderPipeline] Setup failed; the render pipeline was not configured:", error);
16049
16038
  }
16050
16039
  }, [store, renderer, scene, camera, isLegacy, rebuildVersion]);
16051
16040
  const passes = useThree((s) => s.passes);
@@ -16063,4 +16052,4 @@ function useRenderPipeline(mainCB, setupCB) {
16063
16052
 
16064
16053
  extend(THREE);
16065
16054
 
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 };
16055
+ 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, swapInteractivity, 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 };