@react-three/fiber 10.0.0-canary.1b98c17 → 10.0.0-canary.1be335a

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,8 +12,10 @@ 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
+ import { getScheduler } from '@pmndrs/scheduler';
18
+ export { Scheduler, getScheduler } from '@pmndrs/scheduler';
17
19
  import { suspend, preload, clear } from 'suspend-react';
18
20
  import { dequal } from 'dequal/lite';
19
21
  import 'zustand/shallow';
@@ -41,13 +43,16 @@ const WebGLRenderer = class WebGLRenderer2 {
41
43
  }
42
44
  };
43
45
  const WebGLRenderTarget = null;
46
+ const WebGLCubeRenderTarget = null;
44
47
 
45
48
  const THREE = /*#__PURE__*/_mergeNamespaces({
46
49
  __proto__: null,
50
+ CubeRenderTargetCompat: CubeRenderTarget,
47
51
  Inspector: Inspector,
48
52
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
49
53
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
50
54
  RenderTargetCompat: RenderTarget,
55
+ WebGLCubeRenderTarget: WebGLCubeRenderTarget,
51
56
  WebGLRenderTarget: WebGLRenderTarget,
52
57
  WebGLRenderer: WebGLRenderer
53
58
  }, [webgpu]);
@@ -321,15 +326,16 @@ function EnvironmentPortal({
321
326
  preset = void 0,
322
327
  extensions
323
328
  }) {
324
- const gl = useThree$1((state) => state.gl);
329
+ const renderer = useThree$1((state) => state.renderer);
330
+ const isLegacy = useThree$1((state) => state.isLegacy);
325
331
  const defaultScene = useThree$1((state) => state.scene);
326
332
  const camera = React.useRef(null);
327
333
  const [virtualScene] = React.useState(() => new Scene());
328
334
  const fbo = React.useMemo(() => {
329
- const fbo2 = new WebGLCubeRenderTarget(resolution);
335
+ const fbo2 = isLegacy ? new WebGLCubeRenderTarget(resolution) : new CubeRenderTarget(resolution);
330
336
  fbo2.texture.type = HalfFloatType;
331
337
  return fbo2;
332
- }, [resolution]);
338
+ }, [resolution, isLegacy]);
333
339
  React.useEffect(() => {
334
340
  return () => {
335
341
  fbo.dispose();
@@ -337,10 +343,10 @@ function EnvironmentPortal({
337
343
  }, [fbo]);
338
344
  React.useLayoutEffect(() => {
339
345
  if (frames === 1) {
340
- const autoClear = gl.autoClear;
341
- gl.autoClear = true;
342
- camera.current.update(gl, virtualScene);
343
- gl.autoClear = autoClear;
346
+ const autoClear = renderer.autoClear;
347
+ renderer.autoClear = true;
348
+ camera.current.update(renderer, virtualScene);
349
+ renderer.autoClear = autoClear;
344
350
  }
345
351
  return setEnvProps(background, scene, defaultScene, fbo.texture, {
346
352
  backgroundBlurriness: blur ?? backgroundBlurriness,
@@ -357,7 +363,7 @@ function EnvironmentPortal({
357
363
  defaultScene,
358
364
  background,
359
365
  frames,
360
- gl,
366
+ renderer,
361
367
  blur,
362
368
  backgroundBlurriness,
363
369
  backgroundIntensity,
@@ -368,10 +374,10 @@ function EnvironmentPortal({
368
374
  let count = 1;
369
375
  useFrame$1(() => {
370
376
  if (frames === Infinity || count < frames) {
371
- const autoClear = gl.autoClear;
372
- gl.autoClear = true;
373
- camera.current.update(gl, virtualScene);
374
- gl.autoClear = autoClear;
377
+ const autoClear = renderer.autoClear;
378
+ renderer.autoClear = true;
379
+ camera.current.update(renderer, virtualScene);
380
+ renderer.autoClear = autoClear;
375
381
  count++;
376
382
  }
377
383
  });
@@ -435,9 +441,9 @@ function Environment(props) {
435
441
  return props.ground ? /* @__PURE__ */ jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsx(EnvironmentCube, { ...props });
436
442
  }
437
443
 
438
- var __defProp$3 = Object.defineProperty;
439
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
440
- var __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
444
+ var __defProp$1 = Object.defineProperty;
445
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
446
+ var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
441
447
  const act = React["act"];
442
448
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React.useLayoutEffect : React.useEffect;
443
449
  function useMutableCallback(fn) {
@@ -469,7 +475,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
469
475
  return _a = class extends React.Component {
470
476
  constructor() {
471
477
  super(...arguments);
472
- __publicField$3(this, "state", { error: false });
478
+ __publicField$1(this, "state", { error: false });
473
479
  }
474
480
  componentDidCatch(err) {
475
481
  this.props.set(err);
@@ -477,7 +483,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
477
483
  render() {
478
484
  return this.state.error ? null : this.props.children;
479
485
  }
480
- }, __publicField$3(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
486
+ }, __publicField$1(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
481
487
  })();
482
488
 
483
489
  const is = {
@@ -614,8 +620,7 @@ function prepare(target, root, type, props) {
614
620
  object,
615
621
  eventCount: 0,
616
622
  handlers: {},
617
- isHidden: false,
618
- deferredRefs: []
623
+ isHidden: false
619
624
  };
620
625
  if (object) object.__r3f = instance;
621
626
  }
@@ -772,6 +777,17 @@ function unregisterVisibility(store, object) {
772
777
  internal.visibilityRegistry.delete(object.uuid);
773
778
  internal.occlusionCache.delete(object);
774
779
  }
780
+ function updateVisibilityHandlers(store, object, handlers) {
781
+ const { internal } = store.getState();
782
+ const entry = internal.visibilityRegistry.get(object.uuid);
783
+ if (!entry) return false;
784
+ entry.handlers = handlers;
785
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
786
+ object.occlusionTest = true;
787
+ enableOcclusion(store);
788
+ }
789
+ return true;
790
+ }
775
791
  function checkVisibility(state) {
776
792
  const { internal, camera } = state;
777
793
  const registry = internal.visibilityRegistry;
@@ -932,9 +948,9 @@ function diffProps(instance, newProps) {
932
948
  const { root, key } = resolve(instance.object, prop);
933
949
  if (root.constructor && root.constructor.length === 0) {
934
950
  const ctor = getMemoizedPrototype(root);
935
- if (!is.und(ctor)) changedProps[key] = ctor[key];
951
+ if (!is.und(ctor)) changedProps[prop] = ctor[key];
936
952
  } else {
937
- changedProps[key] = 0;
953
+ changedProps[prop] = 0;
938
954
  }
939
955
  }
940
956
  return changedProps;
@@ -959,10 +975,7 @@ function applyProps(object, props) {
959
975
  continue;
960
976
  }
961
977
  if (value === void 0) continue;
962
- if (isFromRef(value)) {
963
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
964
- continue;
965
- }
978
+ if (isFromRef(value)) continue;
966
979
  if (isOnce(value)) {
967
980
  if (instance?.appliedOnce?.has(prop)) continue;
968
981
  if (instance) {
@@ -998,6 +1011,19 @@ function applyProps(object, props) {
998
1011
  } else if (isVectorLike(target) && is.num(value)) {
999
1012
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
1000
1013
  else target.set(value);
1014
+ } else if (root instanceof ShaderMaterial && key === "uniforms" && is.obj(value)) {
1015
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1016
+ const uniforms = root.uniforms;
1017
+ const nextUniforms = value;
1018
+ for (const name in nextUniforms) {
1019
+ const uniform = nextUniforms[name];
1020
+ const targetUniform = uniforms[name];
1021
+ if (targetUniform) Object.assign(targetUniform, uniform);
1022
+ else {
1023
+ const nextUniform = uniform instanceof Uniform ? uniform.clone() : new Uniform(uniform.value);
1024
+ uniforms[name] = nextUniform;
1025
+ }
1026
+ }
1001
1027
  } else {
1002
1028
  root[key] = value;
1003
1029
  if (key.endsWith("Node") && root.isMaterial) {
@@ -1016,6 +1042,9 @@ function applyProps(object, props) {
1016
1042
  if (instance.eventCount && object2.raycast !== null) {
1017
1043
  rootState.internal.interaction.push(object2);
1018
1044
  }
1045
+ }
1046
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1047
+ const object2 = instance.object;
1019
1048
  const root = findInitialRoot(instance);
1020
1049
  const visibilityHandlers = {
1021
1050
  onFramed: instance.handlers.onFramed,
@@ -1023,7 +1052,9 @@ function applyProps(object, props) {
1023
1052
  onVisible: instance.handlers.onVisible
1024
1053
  };
1025
1054
  if (hasVisibilityHandlers(visibilityHandlers)) {
1026
- registerVisibility(root, object2, visibilityHandlers);
1055
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1056
+ registerVisibility(root, object2, visibilityHandlers);
1057
+ }
1027
1058
  } else {
1028
1059
  unregisterVisibility(root, object2);
1029
1060
  }
@@ -1551,6 +1582,7 @@ function createPointerEvents(store) {
1551
1582
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1552
1583
  }
1553
1584
  },
1585
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1554
1586
  registerPointer: (config) => {
1555
1587
  const pointerId = nextXRPointerId++;
1556
1588
  xrPointers.set(pointerId, config);
@@ -1637,1229 +1669,206 @@ function notifyAlpha({ message, link }) {
1637
1669
  }
1638
1670
  }
1639
1671
 
1640
- var __defProp$2 = Object.defineProperty;
1641
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1642
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
1643
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1644
- class PhaseGraph {
1645
- constructor() {
1646
- /** Ordered list of phase nodes */
1647
- __publicField$2(this, "phases", []);
1648
- /** Quick lookup by name */
1649
- __publicField$2(this, "phaseMap", /* @__PURE__ */ new Map());
1650
- /** Cached ordered names (invalidated on changes) */
1651
- __publicField$2(this, "orderedNamesCache", null);
1652
- this.initializeDefaultPhases();
1653
- }
1654
- //* Initialization --------------------------------
1655
- initializeDefaultPhases() {
1656
- for (const name of DEFAULT_PHASES) {
1657
- const node = { name, isAutoGenerated: false };
1658
- this.phases.push(node);
1659
- this.phaseMap.set(name, node);
1660
- }
1661
- this.invalidateCache();
1662
- }
1663
- //* Public API --------------------------------
1664
- /**
1665
- * Add a named phase to the graph
1666
- * @param name - Phase name (must be unique)
1667
- * @param options - Position options (before or after another phase)
1668
- */
1669
- addPhase(name, options = {}) {
1670
- if (this.phaseMap.has(name)) {
1671
- console.warn(`[useFrame] Phase "${name}" already exists`);
1672
- return;
1673
- }
1674
- const { before, after } = options;
1675
- const node = { name, isAutoGenerated: false };
1676
- let insertIndex = this.phases.length;
1677
- const targetIndex = this.getPhaseIndex(before ?? after);
1678
- if (targetIndex !== -1) {
1679
- insertIndex = before ? targetIndex : targetIndex + 1;
1680
- } else {
1681
- const constraintType = before ? "before" : "after";
1682
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1683
- }
1684
- this.phases.splice(insertIndex, 0, node);
1685
- this.phaseMap.set(name, node);
1686
- this.invalidateCache();
1687
- }
1688
- /**
1689
- * Get ordered list of phase names
1690
- */
1691
- getOrderedPhases() {
1692
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1693
- return this.orderedNamesCache;
1694
- }
1695
- /**
1696
- * Check if a phase exists
1697
- */
1698
- hasPhase(name) {
1699
- return this.phaseMap.has(name);
1700
- }
1701
- /**
1702
- * Get the index of a phase (-1 if not found)
1703
- */
1704
- getPhaseIndex(name) {
1705
- if (!name) return -1;
1706
- return this.phases.findIndex((p) => p.name === name);
1707
- }
1708
- /**
1709
- * Ensure a phase exists, creating an auto-generated one if needed.
1710
- * Used for resolving before/after constraints.
1711
- *
1712
- * @param name - The phase name to ensure exists
1713
- * @returns The phase name (may be auto-generated like 'before:render')
1714
- */
1715
- ensurePhase(name) {
1716
- if (this.phaseMap.has(name)) return name;
1717
- const node = { name, isAutoGenerated: true };
1718
- this.phases.push(node);
1719
- this.phaseMap.set(name, node);
1720
- this.invalidateCache();
1721
- return name;
1722
- }
1723
- /**
1724
- * Resolve where a job with before/after constraints should go.
1725
- * Creates auto-generated phases if needed.
1726
- *
1727
- * @param before - Phase(s) to run before
1728
- * @param after - Phase(s) to run after
1729
- * @returns The resolved phase name
1730
- */
1731
- resolveConstraintPhase(before, after) {
1732
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1733
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1734
- if (beforeArr.length > 0) {
1735
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1736
- }
1737
- if (afterArr.length > 0) {
1738
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1739
- }
1740
- return "update";
1741
- }
1742
- /**
1743
- * Ensure an auto-generated phase exists relative to a target phase.
1744
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1745
- *
1746
- * @param target - The target phase name to position relative to
1747
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1748
- * @param offset - Insertion offset (0 for before, 1 for after)
1749
- * @returns The auto-generated phase name
1750
- */
1751
- ensureAutoPhase(target, prefix, offset) {
1752
- const autoName = `${prefix}:${target}`;
1753
- if (this.phaseMap.has(autoName)) return autoName;
1754
- const node = { name: autoName, isAutoGenerated: true };
1755
- const targetIndex = this.getPhaseIndex(target);
1756
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1757
- else this.phases.push(node);
1758
- this.phaseMap.set(autoName, node);
1759
- this.invalidateCache();
1760
- return autoName;
1761
- }
1762
- // Internal --------------------------------
1763
- invalidateCache() {
1764
- this.orderedNamesCache = null;
1765
- }
1672
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1673
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1674
+ if (!stack) return false;
1675
+ const caller = stack.split("\n")[callerDepth] ?? "";
1676
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
1766
1677
  }
1767
1678
 
1768
- function rebuildSortedJobs(jobs, phaseGraph) {
1769
- const orderedPhases = phaseGraph.getOrderedPhases();
1770
- const buckets = /* @__PURE__ */ new Map();
1771
- for (const phase of orderedPhases) {
1772
- buckets.set(phase, []);
1773
- }
1774
- for (const job of jobs.values()) {
1775
- if (!job.enabled) continue;
1776
- let bucket = buckets.get(job.phase);
1777
- if (!bucket) {
1778
- bucket = [];
1779
- buckets.set(job.phase, bucket);
1780
- }
1781
- bucket.push(job);
1782
- }
1783
- const sortedBuckets = [];
1784
- for (const phase of orderedPhases) {
1785
- const bucket = buckets.get(phase);
1786
- if (!bucket || bucket.length === 0) continue;
1787
- bucket.sort((a, b) => {
1788
- if (a.priority !== b.priority) return b.priority - a.priority;
1789
- return a.index - b.index;
1790
- });
1791
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1792
- }
1793
- for (const [phase, bucket] of buckets) {
1794
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1795
- bucket.sort((a, b) => {
1796
- if (a.priority !== b.priority) return b.priority - a.priority;
1797
- return a.index - b.index;
1798
- });
1799
- sortedBuckets.push(bucket);
1800
- }
1801
- }
1802
- return sortedBuckets.flat();
1803
- }
1804
- function hasCrossJobConstraints(bucket) {
1805
- const jobIds = new Set(bucket.map((j) => j.id));
1806
- for (const job of bucket) {
1807
- for (const ref of job.before) {
1808
- if (jobIds.has(ref)) return true;
1809
- }
1810
- for (const ref of job.after) {
1811
- if (jobIds.has(ref)) return true;
1812
- }
1813
- }
1814
- return false;
1815
- }
1816
- function topologicalSort(jobs) {
1817
- const n = jobs.length;
1818
- if (n <= 1) return jobs;
1819
- const jobMap = /* @__PURE__ */ new Map();
1820
- const inDegree = /* @__PURE__ */ new Map();
1821
- const adjacency = /* @__PURE__ */ new Map();
1822
- for (const job of jobs) {
1823
- jobMap.set(job.id, job);
1824
- inDegree.set(job.id, 0);
1825
- adjacency.set(job.id, []);
1826
- }
1827
- for (const job of jobs) {
1828
- for (const ref of job.before) {
1829
- if (jobMap.has(ref)) {
1830
- adjacency.get(job.id).push(ref);
1831
- inDegree.set(ref, inDegree.get(ref) + 1);
1679
+ const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
1680
+ const context = globalThis[R3F_CONTEXT] ?? (globalThis[R3F_CONTEXT] = React.createContext(null));
1681
+ const createStore = (invalidate, advance) => {
1682
+ const rootStore = createWithEqualityFn((set, get) => {
1683
+ const position = new Vector3();
1684
+ const defaultTarget = new Vector3();
1685
+ const tempTarget = new Vector3();
1686
+ function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
1687
+ const { width, height, top, left } = size;
1688
+ const aspect = width / height;
1689
+ if (target.isVector3) tempTarget.copy(target);
1690
+ else tempTarget.set(...target);
1691
+ const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
1692
+ if (isOrthographicCamera(camera)) {
1693
+ return { width: width / camera.zoom, height: height / camera.zoom, top, left, factor: 1, distance, aspect };
1694
+ } else {
1695
+ const fov = camera.fov * Math.PI / 180;
1696
+ const h = 2 * Math.tan(fov / 2) * distance;
1697
+ const w = h * (width / height);
1698
+ return { width: w, height: h, top, left, factor: width / w, distance, aspect };
1832
1699
  }
1833
1700
  }
1834
- for (const ref of job.after) {
1835
- if (jobMap.has(ref)) {
1836
- adjacency.get(ref).push(job.id);
1837
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1701
+ let performanceTimeout = void 0;
1702
+ const setPerformanceCurrent = (current) => set((state2) => ({ performance: { ...state2.performance, current } }));
1703
+ const pointer = new Vector2();
1704
+ const rootState = {
1705
+ set,
1706
+ get,
1707
+ // Mock objects that have to be configured
1708
+ // primaryStore is set after store creation (self-reference for primary, primary's store for secondary)
1709
+ primaryStore: null,
1710
+ gl: null,
1711
+ renderer: null,
1712
+ camera: null,
1713
+ frustum: new Frustum(),
1714
+ autoUpdateFrustum: true,
1715
+ raycaster: null,
1716
+ events: {
1717
+ priority: 1,
1718
+ enabled: true,
1719
+ connected: false,
1720
+ frameTimedRaycasts: true,
1721
+ alwaysFireOnScroll: true,
1722
+ updateOnFrame: false
1723
+ },
1724
+ scene: null,
1725
+ rootScene: null,
1726
+ xr: null,
1727
+ inspector: null,
1728
+ invalidate: (frames = 1, stackFrames = false) => invalidate(get(), frames, stackFrames),
1729
+ advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
1730
+ textureColorSpace: SRGBColorSpace,
1731
+ isLegacy: false,
1732
+ webGPUSupported: false,
1733
+ isNative: false,
1734
+ controls: null,
1735
+ pointer,
1736
+ mouse: pointer,
1737
+ frameloop: "always",
1738
+ onPointerMissed: void 0,
1739
+ onDragOverMissed: void 0,
1740
+ onDropMissed: void 0,
1741
+ performance: {
1742
+ current: 1,
1743
+ min: 0.5,
1744
+ max: 1,
1745
+ debounce: 200,
1746
+ regress: () => {
1747
+ const state2 = get();
1748
+ if (performanceTimeout) clearTimeout(performanceTimeout);
1749
+ if (state2.performance.current !== state2.performance.min) setPerformanceCurrent(state2.performance.min);
1750
+ performanceTimeout = setTimeout(
1751
+ () => setPerformanceCurrent(get().performance.max),
1752
+ state2.performance.debounce
1753
+ );
1754
+ }
1755
+ },
1756
+ size: { width: 0, height: 0, top: 0, left: 0 },
1757
+ viewport: {
1758
+ initialDpr: 0,
1759
+ dpr: 0,
1760
+ width: 0,
1761
+ height: 0,
1762
+ top: 0,
1763
+ left: 0,
1764
+ aspect: 0,
1765
+ distance: 0,
1766
+ factor: 0,
1767
+ getCurrentViewport
1768
+ },
1769
+ setEvents: (events) => set((state2) => ({ ...state2, events: { ...state2.events, ...events } })),
1770
+ setSize: (width, height, top, left) => {
1771
+ const state2 = get();
1772
+ if (width === void 0) {
1773
+ set({ _sizeImperative: false });
1774
+ if (state2._sizeProps) {
1775
+ const { width: propW, height: propH } = state2._sizeProps;
1776
+ if (propW !== void 0 || propH !== void 0) {
1777
+ const currentSize = state2.size;
1778
+ const newSize = {
1779
+ width: propW ?? currentSize.width,
1780
+ height: propH ?? currentSize.height,
1781
+ top: currentSize.top,
1782
+ left: currentSize.left
1783
+ };
1784
+ set((s) => ({
1785
+ size: newSize,
1786
+ viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
1787
+ }));
1788
+ getScheduler().invalidate();
1789
+ }
1790
+ }
1791
+ return;
1792
+ }
1793
+ const w = width;
1794
+ const h = height ?? width;
1795
+ const t = top ?? state2.size.top;
1796
+ const l = left ?? state2.size.left;
1797
+ const size = { width: w, height: h, top: t, left: l };
1798
+ set((s) => ({
1799
+ size,
1800
+ viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
1801
+ _sizeImperative: true
1802
+ }));
1803
+ getScheduler().invalidate();
1804
+ },
1805
+ setDpr: (dpr) => set((state2) => {
1806
+ const resolved = calculateDpr(dpr);
1807
+ return { viewport: { ...state2.viewport, dpr: resolved, initialDpr: state2.viewport.initialDpr || resolved } };
1808
+ }),
1809
+ setFrameloop: (frameloop = "always") => {
1810
+ set(() => ({ frameloop }));
1811
+ getScheduler().frameloop = frameloop;
1812
+ },
1813
+ setError: (error) => set(() => ({ error })),
1814
+ error: null,
1815
+ //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
1816
+ uniforms: {},
1817
+ nodes: {},
1818
+ buffers: {},
1819
+ gpuStorage: {},
1820
+ textures: /* @__PURE__ */ new Map(),
1821
+ _textureRefs: /* @__PURE__ */ new Map(),
1822
+ renderPipeline: null,
1823
+ passes: {},
1824
+ _hmrVersion: 0,
1825
+ _sizeImperative: false,
1826
+ _sizeProps: null,
1827
+ previousRoot: void 0,
1828
+ internal: {
1829
+ // Events
1830
+ interaction: [],
1831
+ subscribers: [],
1832
+ // Per-pointer state (new unified structure)
1833
+ pointerMap: /* @__PURE__ */ new Map(),
1834
+ pointerDirty: /* @__PURE__ */ new Map(),
1835
+ lastEvent: React.createRef(),
1836
+ // Deprecated but kept for backwards compatibility
1837
+ hovered: /* @__PURE__ */ new Map(),
1838
+ initialClick: [0, 0],
1839
+ initialHits: [],
1840
+ capturedMap: /* @__PURE__ */ new Map(),
1841
+ // Visibility tracking (onFramed, onOccluded, onVisible)
1842
+ visibilityRegistry: /* @__PURE__ */ new Map(),
1843
+ // Occlusion system (WebGPU only)
1844
+ occlusionEnabled: false,
1845
+ occlusionObserver: null,
1846
+ occlusionCache: /* @__PURE__ */ new Map(),
1847
+ helperGroup: null,
1848
+ // Updates
1849
+ active: false,
1850
+ frames: 0,
1851
+ priority: 0,
1852
+ subscribe: (ref, priority, store) => {
1853
+ const internal = get().internal;
1854
+ internal.priority = internal.priority + (priority > 0 ? 1 : 0);
1855
+ internal.subscribers.push({ ref, priority, store });
1856
+ internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority);
1857
+ return () => {
1858
+ const internal2 = get().internal;
1859
+ if (internal2?.subscribers) {
1860
+ internal2.priority = internal2.priority - (priority > 0 ? 1 : 0);
1861
+ internal2.subscribers = internal2.subscribers.filter((s) => s.ref !== ref);
1862
+ }
1863
+ };
1864
+ },
1865
+ // Renderer Storage (single source of truth)
1866
+ actualRenderer: null,
1867
+ // Scheduler for useFrameNext (initialized in renderer.tsx)
1868
+ scheduler: null
1838
1869
  }
1839
- }
1840
- }
1841
- const queue = [];
1842
- for (const job of jobs) {
1843
- if (inDegree.get(job.id) === 0) {
1844
- queue.push(job);
1845
- }
1846
- }
1847
- queue.sort((a, b) => {
1848
- if (a.priority !== b.priority) return b.priority - a.priority;
1849
- return a.index - b.index;
1850
- });
1851
- const result = [];
1852
- while (queue.length > 0) {
1853
- const job = queue.shift();
1854
- result.push(job);
1855
- const neighbors = adjacency.get(job.id) || [];
1856
- for (const neighborId of neighbors) {
1857
- const newDegree = inDegree.get(neighborId) - 1;
1858
- inDegree.set(neighborId, newDegree);
1859
- if (newDegree === 0) {
1860
- const neighbor = jobMap.get(neighborId);
1861
- insertSorted(queue, neighbor);
1862
- }
1863
- }
1864
- }
1865
- if (result.length !== n) {
1866
- console.warn("[useFrame] Circular dependency detected in job constraints");
1867
- const resultIds = new Set(result.map((j) => j.id));
1868
- for (const job of jobs) {
1869
- if (!resultIds.has(job.id)) result.push(job);
1870
- }
1871
- }
1872
- return result;
1873
- }
1874
- function insertSorted(arr, job) {
1875
- let i = 0;
1876
- while (i < arr.length) {
1877
- const cmp = arr[i];
1878
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1879
- break;
1880
- }
1881
- i++;
1882
- }
1883
- arr.splice(i, 0, job);
1884
- }
1885
-
1886
- function shouldRun(job, now) {
1887
- if (!job.enabled) return false;
1888
- if (!job.fps) return true;
1889
- const minInterval = 1e3 / job.fps;
1890
- const lastRun = job.lastRun ?? 0;
1891
- const elapsed = now - lastRun;
1892
- if (elapsed < minInterval - 1) return false;
1893
- if (job.drop) {
1894
- job.lastRun = now;
1895
- } else {
1896
- const steps = Math.floor(elapsed / minInterval);
1897
- job.lastRun = lastRun + steps * minInterval;
1898
- if (job.lastRun < now - minInterval) {
1899
- job.lastRun = now;
1900
- }
1901
- }
1902
- return true;
1903
- }
1904
- function resetJobTiming(job) {
1905
- job.lastRun = void 0;
1906
- }
1907
-
1908
- var __defProp$1 = Object.defineProperty;
1909
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1910
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1911
- const hmrData = (() => {
1912
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1913
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1914
- try {
1915
- return (0, eval)("import.meta.hot");
1916
- } catch {
1917
- return void 0;
1918
- }
1919
- })();
1920
- const _Scheduler = class _Scheduler {
1921
- //* Constructor ================================
1922
- constructor() {
1923
- //* Critical State ================================
1924
- __publicField$1(this, "roots", /* @__PURE__ */ new Map());
1925
- __publicField$1(this, "phaseGraph");
1926
- __publicField$1(this, "loopState", {
1927
- running: false,
1928
- rafHandle: null,
1929
- lastTime: null,
1930
- // null = uninitialized, 0+ = valid timestamp
1931
- frameCount: 0,
1932
- elapsedTime: 0,
1933
- createdAt: performance.now()
1934
- });
1935
- __publicField$1(this, "stoppedTime", 0);
1936
- //* Private State ================================
1937
- __publicField$1(this, "nextRootIndex", 0);
1938
- __publicField$1(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1939
- __publicField$1(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1940
- __publicField$1(this, "nextGlobalIndex", 0);
1941
- __publicField$1(this, "idleCallbacks", /* @__PURE__ */ new Set());
1942
- __publicField$1(this, "nextJobIndex", 0);
1943
- __publicField$1(this, "jobStateListeners", /* @__PURE__ */ new Map());
1944
- __publicField$1(this, "pendingFrames", 0);
1945
- __publicField$1(this, "_frameloop", "always");
1946
- //* Independent Mode & Error Handling State ================================
1947
- __publicField$1(this, "_independent", false);
1948
- __publicField$1(this, "errorHandler", null);
1949
- __publicField$1(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1950
- //* Core Loop Execution Methods ================================
1951
- /**
1952
- * Main RAF loop callback.
1953
- * Executes frame, handles demand mode, and schedules next frame.
1954
- * @param {number} timestamp - RAF timestamp in milliseconds
1955
- * @returns {void}
1956
- * @private
1957
- */
1958
- __publicField$1(this, "loop", (timestamp) => {
1959
- if (!this.loopState.running) return;
1960
- this.executeFrame(timestamp);
1961
- if (this._frameloop === "demand") {
1962
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1963
- if (this.pendingFrames === 0) {
1964
- this.notifyIdle(timestamp);
1965
- return this.stop();
1966
- }
1967
- }
1968
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1969
- });
1970
- this.phaseGraph = new PhaseGraph();
1971
- }
1972
- static get instance() {
1973
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1974
- }
1975
- static set instance(value) {
1976
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1977
- }
1978
- /**
1979
- * Get the global scheduler instance (creates if doesn't exist).
1980
- * Uses HMR data to preserve instance across hot reloads.
1981
- * @returns {Scheduler} The singleton scheduler instance
1982
- */
1983
- static get() {
1984
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1985
- _Scheduler.instance = hmrData.data.scheduler;
1986
- }
1987
- if (!_Scheduler.instance) {
1988
- _Scheduler.instance = new _Scheduler();
1989
- if (hmrData?.data) {
1990
- hmrData.data.scheduler = _Scheduler.instance;
1991
- }
1992
- }
1993
- return _Scheduler.instance;
1994
- }
1995
- /**
1996
- * Reset the singleton instance. Stops the loop and clears all state.
1997
- * Primarily used for testing to ensure clean state between tests.
1998
- * @returns {void}
1999
- */
2000
- static reset() {
2001
- if (_Scheduler.instance) {
2002
- _Scheduler.instance.stop();
2003
- _Scheduler.instance = null;
2004
- }
2005
- if (hmrData?.data) {
2006
- hmrData.data.scheduler = null;
2007
- }
2008
- }
2009
- //* Getters & Setters ================================
2010
- get phases() {
2011
- return this.phaseGraph.getOrderedPhases();
2012
- }
2013
- get frameloop() {
2014
- return this._frameloop;
2015
- }
2016
- set frameloop(mode) {
2017
- if (this._frameloop === mode) return;
2018
- const wasAlways = this._frameloop === "always";
2019
- this._frameloop = mode;
2020
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
2021
- else if (mode !== "always" && wasAlways) this.stop();
2022
- }
2023
- get isRunning() {
2024
- return this.loopState.running;
2025
- }
2026
- get isReady() {
2027
- return this.roots.size > 0;
2028
- }
2029
- get independent() {
2030
- return this._independent;
2031
- }
2032
- set independent(value) {
2033
- this._independent = value;
2034
- if (value) this.ensureDefaultRoot();
2035
- }
2036
- //* Root Management Methods ================================
2037
- /**
2038
- * Register a root (Canvas) with the scheduler.
2039
- * The first root to register starts the RAF loop (if frameloop='always').
2040
- * @param {string} id - Unique identifier for this root
2041
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
2042
- * @returns {() => void} Unsubscribe function to remove this root
2043
- */
2044
- registerRoot(id, options = {}) {
2045
- if (this.roots.has(id)) {
2046
- console.warn(`[Scheduler] Root "${id}" already registered`);
2047
- return () => this.unregisterRoot(id);
2048
- }
2049
- const entry = {
2050
- id,
2051
- getState: options.getState ?? (() => ({})),
2052
- jobs: /* @__PURE__ */ new Map(),
2053
- sortedJobs: [],
2054
- needsRebuild: false
2055
- };
2056
- if (options.onError) {
2057
- this.errorHandler = options.onError;
2058
- }
2059
- this.roots.set(id, entry);
2060
- if (this.roots.size === 1) {
2061
- this.notifyRootReady();
2062
- if (this._frameloop === "always") this.start();
2063
- }
2064
- return () => this.unregisterRoot(id);
2065
- }
2066
- /**
2067
- * Unregister a root from the scheduler.
2068
- * Cleans up all job state listeners for this root's jobs.
2069
- * The last root to unregister stops the RAF loop.
2070
- * @param {string} id - The root ID to unregister
2071
- * @returns {void}
2072
- */
2073
- unregisterRoot(id) {
2074
- const root = this.roots.get(id);
2075
- if (!root) return;
2076
- for (const jobId of root.jobs.keys()) {
2077
- this.jobStateListeners.delete(jobId);
2078
- }
2079
- this.roots.delete(id);
2080
- if (this.roots.size === 0) {
2081
- this.stop();
2082
- this.errorHandler = null;
2083
- }
2084
- }
2085
- /**
2086
- * Subscribe to be notified when a root becomes available.
2087
- * Fires immediately if a root already exists.
2088
- * @param {() => void} callback - Function called when first root registers
2089
- * @returns {() => void} Unsubscribe function
2090
- */
2091
- onRootReady(callback) {
2092
- if (this.roots.size > 0) {
2093
- callback();
2094
- return () => {
2095
- };
2096
- }
2097
- this.rootReadyCallbacks.add(callback);
2098
- return () => this.rootReadyCallbacks.delete(callback);
2099
- }
2100
- /**
2101
- * Notify all registered root-ready callbacks.
2102
- * Called when the first root registers.
2103
- * @returns {void}
2104
- * @private
2105
- */
2106
- notifyRootReady() {
2107
- for (const cb of this.rootReadyCallbacks) {
2108
- try {
2109
- cb();
2110
- } catch (error) {
2111
- console.error("[Scheduler] Error in root-ready callback:", error);
2112
- }
2113
- }
2114
- this.rootReadyCallbacks.clear();
2115
- }
2116
- /**
2117
- * Ensure a default root exists for independent mode.
2118
- * Creates a minimal root with no state provider.
2119
- * @returns {void}
2120
- * @private
2121
- */
2122
- ensureDefaultRoot() {
2123
- if (!this.roots.has("__default__")) {
2124
- this.registerRoot("__default__");
2125
- }
2126
- }
2127
- /**
2128
- * Trigger error handling for job errors.
2129
- * Uses the bound error handler if available, otherwise logs to console.
2130
- * @param {Error} error - The error to handle
2131
- * @returns {void}
2132
- */
2133
- triggerError(error) {
2134
- if (this.errorHandler) this.errorHandler(error);
2135
- else console.error("[Scheduler]", error);
2136
- }
2137
- //* Phase Management Methods ================================
2138
- /**
2139
- * Add a named phase to the scheduler's execution order.
2140
- * Marks all roots for rebuild to incorporate the new phase.
2141
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
2142
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
2143
- * @returns {void}
2144
- * @example
2145
- * scheduler.addPhase('physics', { before: 'update' });
2146
- * scheduler.addPhase('postprocess', { after: 'render' });
2147
- */
2148
- addPhase(name, options) {
2149
- this.phaseGraph.addPhase(name, options);
2150
- for (const root of this.roots.values()) {
2151
- root.needsRebuild = true;
2152
- }
2153
- }
2154
- /**
2155
- * Check if a phase exists in the scheduler.
2156
- * @param {string} name - The phase name to check
2157
- * @returns {boolean} True if the phase exists
2158
- */
2159
- hasPhase(name) {
2160
- return this.phaseGraph.hasPhase(name);
2161
- }
2162
- //* Global Job Registration Methods (Deprecated APIs) ================================
2163
- /**
2164
- * Register a global job that runs once per frame (not per-root).
2165
- * Used internally by deprecated addEffect/addAfterEffect APIs.
2166
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
2167
- * @param {string} id - Unique identifier for this global job
2168
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
2169
- * @returns {() => void} Unsubscribe function to remove this global job
2170
- * @deprecated Use useFrame with phases instead
2171
- */
2172
- registerGlobal(phase, id, callback) {
2173
- const job = { id, callback };
2174
- if (phase === "before") {
2175
- this.globalBeforeJobs.set(id, job);
2176
- } else {
2177
- this.globalAfterJobs.set(id, job);
2178
- }
2179
- return () => {
2180
- if (phase === "before") this.globalBeforeJobs.delete(id);
2181
- else this.globalAfterJobs.delete(id);
2182
- };
2183
- }
2184
- //* Idle Callback Methods (Deprecated API) ================================
2185
- /**
2186
- * Register an idle callback that fires when the loop stops.
2187
- * Used internally by deprecated addTail API.
2188
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
2189
- * @returns {() => void} Unsubscribe function to remove this idle callback
2190
- * @deprecated Use demand mode with invalidate() instead
2191
- */
2192
- onIdle(callback) {
2193
- this.idleCallbacks.add(callback);
2194
- return () => this.idleCallbacks.delete(callback);
2195
- }
2196
- /**
2197
- * Notify all registered idle callbacks.
2198
- * Called when the loop stops in demand mode.
2199
- * @param {number} timestamp - The RAF timestamp when idle occurred
2200
- * @returns {void}
2201
- * @private
2202
- */
2203
- notifyIdle(timestamp) {
2204
- for (const cb of this.idleCallbacks) {
2205
- try {
2206
- cb(timestamp);
2207
- } catch (error) {
2208
- console.error("[Scheduler] Error in idle callback:", error);
2209
- }
2210
- }
2211
- }
2212
- //* Job Registration & Management Methods ================================
2213
- /**
2214
- * Register a job (frame callback) with a specific root.
2215
- * This is the core registration method used by useFrame internally.
2216
- * @param {FrameNextCallback} callback - The function to call each frame
2217
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2218
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2219
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2220
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
2221
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2222
- * @param {number} [options.fps] - FPS throttle limit
2223
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
2224
- * @param {boolean} [options.enabled] - Whether job is active (default true)
2225
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2226
- * @returns {() => void} Unsubscribe function to remove this job
2227
- */
2228
- register(callback, options = {}) {
2229
- const rootId = options.rootId;
2230
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2231
- if (!root) {
2232
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2233
- return () => {
2234
- };
2235
- }
2236
- const id = options.id ?? this.generateJobId();
2237
- let phase = options.phase ?? "update";
2238
- if (!options.phase && (options.before || options.after)) {
2239
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2240
- }
2241
- const before = this.normalizeConstraints(options.before);
2242
- const after = this.normalizeConstraints(options.after);
2243
- const job = {
2244
- id,
2245
- callback,
2246
- phase,
2247
- before,
2248
- after,
2249
- priority: options.priority ?? 0,
2250
- index: this.nextJobIndex++,
2251
- fps: options.fps,
2252
- drop: options.drop ?? true,
2253
- enabled: options.enabled ?? true,
2254
- system: options.system ?? false
2255
- };
2256
- if (root.jobs.has(id)) {
2257
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2258
- }
2259
- root.jobs.set(id, job);
2260
- root.needsRebuild = true;
2261
- return () => this.unregister(id, root.id);
2262
- }
2263
- /**
2264
- * Unregister a job by its ID.
2265
- * Searches all roots if rootId is not provided.
2266
- * @param {string} id - The job ID to unregister
2267
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2268
- * @returns {void}
2269
- */
2270
- unregister(id, rootId) {
2271
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2272
- if (root?.jobs.delete(id)) {
2273
- root.needsRebuild = true;
2274
- this.jobStateListeners.delete(id);
2275
- }
2276
- }
2277
- /**
2278
- * Update a job's options dynamically.
2279
- * Searches all roots to find the job by ID.
2280
- * Phase/constraint changes trigger a rebuild of the sorted job list.
2281
- * @param {string} id - The job ID to update
2282
- * @param {Partial<JobOptions>} options - The options to update
2283
- * @returns {void}
2284
- */
2285
- updateJob(id, options) {
2286
- let job;
2287
- let root;
2288
- for (const r of this.roots.values()) {
2289
- job = r.jobs.get(id);
2290
- if (job) {
2291
- root = r;
2292
- break;
2293
- }
2294
- }
2295
- if (!job || !root) return;
2296
- if (options.priority !== void 0) job.priority = options.priority;
2297
- if (options.fps !== void 0) job.fps = options.fps;
2298
- if (options.drop !== void 0) job.drop = options.drop;
2299
- if (options.enabled !== void 0) {
2300
- const wasEnabled = job.enabled;
2301
- job.enabled = options.enabled;
2302
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2303
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2304
- }
2305
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2306
- if (options.phase) job.phase = options.phase;
2307
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2308
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2309
- root.needsRebuild = true;
2310
- }
2311
- }
2312
- //* Job State Management Methods ================================
2313
- /**
2314
- * Check if a job is currently paused (disabled).
2315
- * @param {string} id - The job ID to check
2316
- * @returns {boolean} True if the job exists and is paused
2317
- */
2318
- isJobPaused(id) {
2319
- for (const root of this.roots.values()) {
2320
- const job = root.jobs.get(id);
2321
- if (job) return !job.enabled;
2322
- }
2323
- return false;
2324
- }
2325
- /**
2326
- * Subscribe to state changes for a specific job.
2327
- * Listener is called when job is paused or resumed.
2328
- * @param {string} id - The job ID to subscribe to
2329
- * @param {() => void} listener - Callback invoked on state changes
2330
- * @returns {() => void} Unsubscribe function
2331
- */
2332
- subscribeJobState(id, listener) {
2333
- if (!this.jobStateListeners.has(id)) {
2334
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2335
- }
2336
- this.jobStateListeners.get(id).add(listener);
2337
- return () => {
2338
- this.jobStateListeners.get(id)?.delete(listener);
2339
- if (this.jobStateListeners.get(id)?.size === 0) {
2340
- this.jobStateListeners.delete(id);
2341
- }
2342
- };
2343
- }
2344
- /**
2345
- * Notify all listeners that a job's state has changed.
2346
- * @param {string} id - The job ID that changed
2347
- * @returns {void}
2348
- * @private
2349
- */
2350
- notifyJobStateChange(id) {
2351
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2352
- }
2353
- /**
2354
- * Pause a job by ID (sets enabled=false).
2355
- * Notifies any subscribed state listeners.
2356
- * @param {string} id - The job ID to pause
2357
- * @returns {void}
2358
- */
2359
- pauseJob(id) {
2360
- this.updateJob(id, { enabled: false });
2361
- this.notifyJobStateChange(id);
2362
- }
2363
- /**
2364
- * Resume a paused job by ID (sets enabled=true).
2365
- * Resets job timing to prevent frame accumulation.
2366
- * Notifies any subscribed state listeners.
2367
- * @param {string} id - The job ID to resume
2368
- * @returns {void}
2369
- */
2370
- resumeJob(id) {
2371
- this.updateJob(id, { enabled: true });
2372
- this.notifyJobStateChange(id);
2373
- }
2374
- //* Frame Loop Control Methods ================================
2375
- /**
2376
- * Start the requestAnimationFrame loop.
2377
- * Resets timing state (elapsedTime, frameCount) on start.
2378
- * No-op if already running.
2379
- * @returns {void}
2380
- */
2381
- start() {
2382
- if (this.loopState.running) return;
2383
- const { elapsedTime, createdAt } = this.loopState;
2384
- let adjustedCreated = 0;
2385
- if (this.stoppedTime > 0) {
2386
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2387
- this.stoppedTime = 0;
2388
- }
2389
- Object.assign(this.loopState, {
2390
- running: true,
2391
- elapsedTime: elapsedTime ?? 0,
2392
- lastTime: performance.now(),
2393
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2394
- frameCount: 0,
2395
- rafHandle: requestAnimationFrame(this.loop)
2396
- });
2397
- }
2398
- /**
2399
- * Stop the requestAnimationFrame loop.
2400
- * Cancels any pending RAF callback.
2401
- * No-op if not running.
2402
- * @returns {void}
2403
- */
2404
- stop() {
2405
- if (!this.loopState.running) return;
2406
- this.loopState.running = false;
2407
- if (this.loopState.rafHandle !== null) {
2408
- cancelAnimationFrame(this.loopState.rafHandle);
2409
- this.loopState.rafHandle = null;
2410
- }
2411
- this.stoppedTime = performance.now();
2412
- }
2413
- /**
2414
- * Request frames to be rendered in demand mode.
2415
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2416
- * No-op if frameloop is not 'demand'.
2417
- * @param {number} [frames=1] - Number of frames to request
2418
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2419
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2420
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2421
- * @returns {void}
2422
- * @example
2423
- * // Request a single frame render
2424
- * scheduler.invalidate();
2425
- *
2426
- * @example
2427
- * // Request 5 frames (e.g., for animations)
2428
- * scheduler.invalidate(5);
2429
- *
2430
- * @example
2431
- * // Set pending frames to exactly 3 (don't stack with existing)
2432
- * scheduler.invalidate(3, false);
2433
- *
2434
- * @example
2435
- * // Add 2 more frames to existing pending count
2436
- * scheduler.invalidate(2, true);
2437
- */
2438
- invalidate(frames = 1, stackFrames = false) {
2439
- if (this._frameloop !== "demand") return;
2440
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2441
- this.pendingFrames = Math.min(60, baseFrames + frames);
2442
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2443
- }
2444
- /**
2445
- * Reset timing state for deterministic testing.
2446
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2447
- * @returns {void}
2448
- */
2449
- resetTiming() {
2450
- this.loopState.lastTime = null;
2451
- this.loopState.frameCount = 0;
2452
- this.loopState.elapsedTime = 0;
2453
- this.loopState.createdAt = performance.now();
2454
- }
2455
- //* Manual Stepping Methods ================================
2456
- /**
2457
- * Manually execute a single frame for all roots.
2458
- * Useful for frameloop='never' mode or testing scenarios.
2459
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2460
- * @returns {void}
2461
- * @example
2462
- * // Manual control mode
2463
- * scheduler.frameloop = 'never';
2464
- * scheduler.step(); // Execute one frame
2465
- */
2466
- step(timestamp) {
2467
- const now = timestamp ?? performance.now();
2468
- this.executeFrame(now);
2469
- }
2470
- /**
2471
- * Manually execute a single job by its ID.
2472
- * Useful for testing individual job callbacks in isolation.
2473
- * @param {string} id - The job ID to step
2474
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2475
- * @returns {void}
2476
- */
2477
- stepJob(id, timestamp) {
2478
- let job;
2479
- let root;
2480
- for (const r of this.roots.values()) {
2481
- job = r.jobs.get(id);
2482
- if (job) {
2483
- root = r;
2484
- break;
2485
- }
2486
- }
2487
- if (!job || !root) {
2488
- console.warn(`[Scheduler] Job "${id}" not found`);
2489
- return;
2490
- }
2491
- const now = timestamp ?? performance.now();
2492
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2493
- const delta = deltaMs / 1e3;
2494
- const elapsed = now - this.loopState.createdAt;
2495
- const providedState = root.getState?.() ?? {};
2496
- const frameState = {
2497
- ...providedState,
2498
- time: now,
2499
- delta,
2500
- elapsed,
2501
- frame: this.loopState.frameCount
2502
- };
2503
- try {
2504
- job.callback(frameState, delta);
2505
- } catch (error) {
2506
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2507
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2508
- }
2509
- }
2510
- /**
2511
- * Execute a single frame across all roots.
2512
- * Order: globalBefore → each root's jobs → globalAfter
2513
- * @param {number} timestamp - RAF timestamp in milliseconds
2514
- * @returns {void}
2515
- * @private
2516
- */
2517
- executeFrame(timestamp) {
2518
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2519
- const delta = deltaMs / 1e3;
2520
- this.loopState.lastTime = timestamp;
2521
- this.loopState.frameCount++;
2522
- this.loopState.elapsedTime += deltaMs;
2523
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2524
- for (const root of this.roots.values()) {
2525
- this.tickRoot(root, timestamp, delta);
2526
- }
2527
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2528
- }
2529
- /**
2530
- * Run all global jobs from a job map.
2531
- * Catches and logs errors without stopping execution.
2532
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2533
- * @param {number} timestamp - RAF timestamp in milliseconds
2534
- * @returns {void}
2535
- * @private
2536
- */
2537
- runGlobalJobs(jobs, timestamp) {
2538
- for (const job of jobs.values()) {
2539
- try {
2540
- job.callback(timestamp);
2541
- } catch (error) {
2542
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2543
- }
2544
- }
2545
- }
2546
- /**
2547
- * Execute all jobs for a single root in sorted order.
2548
- * Rebuilds sorted job list if needed, then dispatches each job.
2549
- * Errors are caught and propagated via triggerError.
2550
- * @param {RootEntry} root - The root entry to tick
2551
- * @param {number} timestamp - RAF timestamp in milliseconds
2552
- * @param {number} delta - Time since last frame in seconds
2553
- * @returns {void}
2554
- * @private
2555
- */
2556
- tickRoot(root, timestamp, delta) {
2557
- if (root.needsRebuild) {
2558
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2559
- root.needsRebuild = false;
2560
- }
2561
- const providedState = root.getState?.() ?? {};
2562
- const frameState = {
2563
- ...providedState,
2564
- time: timestamp,
2565
- delta,
2566
- elapsed: this.loopState.elapsedTime / 1e3,
2567
- // Convert ms to seconds
2568
- frame: this.loopState.frameCount
2569
- };
2570
- for (const job of root.sortedJobs) {
2571
- if (!shouldRun(job, timestamp)) continue;
2572
- try {
2573
- job.callback(frameState, delta);
2574
- } catch (error) {
2575
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2576
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2577
- }
2578
- }
2579
- }
2580
- //* Debug & Inspection Methods ================================
2581
- /**
2582
- * Get the total number of registered jobs across all roots.
2583
- * Includes both per-root jobs and global before/after jobs.
2584
- * @returns {number} Total job count
2585
- */
2586
- getJobCount() {
2587
- let count = 0;
2588
- for (const root of this.roots.values()) {
2589
- count += root.jobs.size;
2590
- }
2591
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2592
- }
2593
- /**
2594
- * Get all registered job IDs across all roots.
2595
- * Includes both per-root jobs and global before/after jobs.
2596
- * @returns {string[]} Array of all job IDs
2597
- */
2598
- getJobIds() {
2599
- const ids = [];
2600
- for (const root of this.roots.values()) {
2601
- ids.push(...root.jobs.keys());
2602
- }
2603
- ids.push(...this.globalBeforeJobs.keys());
2604
- ids.push(...this.globalAfterJobs.keys());
2605
- return ids;
2606
- }
2607
- /**
2608
- * Get the number of registered roots (Canvas instances).
2609
- * @returns {number} Number of registered roots
2610
- */
2611
- getRootCount() {
2612
- return this.roots.size;
2613
- }
2614
- /**
2615
- * Check if any user (non-system) jobs are registered in a specific phase.
2616
- * Used by the default render job to know if a user has taken over rendering.
2617
- *
2618
- * @param phase The phase to check
2619
- * @param rootId Optional root ID to check (checks all roots if not provided)
2620
- * @returns true if any user jobs exist in the phase
2621
- */
2622
- hasUserJobsInPhase(phase, rootId) {
2623
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2624
- return rootsToCheck.some((root) => {
2625
- if (!root) return false;
2626
- for (const job of root.jobs.values()) {
2627
- if (job.phase === phase && !job.system && job.enabled) return true;
2628
- }
2629
- return false;
2630
- });
2631
- }
2632
- //* Utility Methods ================================
2633
- /**
2634
- * Generate a unique root ID for automatic root registration.
2635
- * @returns {string} A unique root ID in the format 'root_N'
2636
- */
2637
- generateRootId() {
2638
- return `root_${this.nextRootIndex++}`;
2639
- }
2640
- /**
2641
- * Generate a unique job ID.
2642
- * @returns {string} A unique job ID in the format 'job_N'
2643
- * @private
2644
- */
2645
- generateJobId() {
2646
- return `job_${this.nextJobIndex}`;
2647
- }
2648
- /**
2649
- * Normalize before/after constraints to a Set.
2650
- * Handles undefined, single string, or array inputs.
2651
- * @param {string | string[] | undefined} value - The constraint value(s)
2652
- * @returns {Set<string>} Normalized Set of constraint strings
2653
- * @private
2654
- */
2655
- normalizeConstraints(value) {
2656
- if (!value) return /* @__PURE__ */ new Set();
2657
- if (Array.isArray(value)) return new Set(value);
2658
- return /* @__PURE__ */ new Set([value]);
2659
- }
2660
- };
2661
- //* Static State & Methods (Singleton Usage) ================================
2662
- //* Cross-Bundle Singleton Key ==============================
2663
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2664
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2665
- __publicField$1(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2666
- let Scheduler = _Scheduler;
2667
- const getScheduler = () => Scheduler.get();
2668
- if (hmrData) {
2669
- hmrData.accept?.();
2670
- }
2671
-
2672
- const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
2673
- const context = globalThis[R3F_CONTEXT] ?? (globalThis[R3F_CONTEXT] = React.createContext(null));
2674
- const createStore = (invalidate, advance) => {
2675
- const rootStore = createWithEqualityFn((set, get) => {
2676
- const position = new Vector3();
2677
- const defaultTarget = new Vector3();
2678
- const tempTarget = new Vector3();
2679
- function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
2680
- const { width, height, top, left } = size;
2681
- const aspect = width / height;
2682
- if (target.isVector3) tempTarget.copy(target);
2683
- else tempTarget.set(...target);
2684
- const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
2685
- if (isOrthographicCamera(camera)) {
2686
- return { width: width / camera.zoom, height: height / camera.zoom, top, left, factor: 1, distance, aspect };
2687
- } else {
2688
- const fov = camera.fov * Math.PI / 180;
2689
- const h = 2 * Math.tan(fov / 2) * distance;
2690
- const w = h * (width / height);
2691
- return { width: w, height: h, top, left, factor: width / w, distance, aspect };
2692
- }
2693
- }
2694
- let performanceTimeout = void 0;
2695
- const setPerformanceCurrent = (current) => set((state2) => ({ performance: { ...state2.performance, current } }));
2696
- const pointer = new Vector2();
2697
- const rootState = {
2698
- set,
2699
- get,
2700
- // Mock objects that have to be configured
2701
- // primaryStore is set after store creation (self-reference for primary, primary's store for secondary)
2702
- primaryStore: null,
2703
- gl: null,
2704
- renderer: null,
2705
- camera: null,
2706
- frustum: new Frustum(),
2707
- autoUpdateFrustum: true,
2708
- raycaster: null,
2709
- events: {
2710
- priority: 1,
2711
- enabled: true,
2712
- connected: false,
2713
- frameTimedRaycasts: true,
2714
- alwaysFireOnScroll: true,
2715
- updateOnFrame: false
2716
- },
2717
- scene: null,
2718
- rootScene: null,
2719
- xr: null,
2720
- inspector: null,
2721
- invalidate: (frames = 1, stackFrames = false) => invalidate(get(), frames, stackFrames),
2722
- advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
2723
- textureColorSpace: SRGBColorSpace,
2724
- isLegacy: false,
2725
- webGPUSupported: false,
2726
- isNative: false,
2727
- controls: null,
2728
- pointer,
2729
- mouse: pointer,
2730
- frameloop: "always",
2731
- onPointerMissed: void 0,
2732
- onDragOverMissed: void 0,
2733
- onDropMissed: void 0,
2734
- performance: {
2735
- current: 1,
2736
- min: 0.5,
2737
- max: 1,
2738
- debounce: 200,
2739
- regress: () => {
2740
- const state2 = get();
2741
- if (performanceTimeout) clearTimeout(performanceTimeout);
2742
- if (state2.performance.current !== state2.performance.min) setPerformanceCurrent(state2.performance.min);
2743
- performanceTimeout = setTimeout(
2744
- () => setPerformanceCurrent(get().performance.max),
2745
- state2.performance.debounce
2746
- );
2747
- }
2748
- },
2749
- size: { width: 0, height: 0, top: 0, left: 0 },
2750
- viewport: {
2751
- initialDpr: 0,
2752
- dpr: 0,
2753
- width: 0,
2754
- height: 0,
2755
- top: 0,
2756
- left: 0,
2757
- aspect: 0,
2758
- distance: 0,
2759
- factor: 0,
2760
- getCurrentViewport
2761
- },
2762
- setEvents: (events) => set((state2) => ({ ...state2, events: { ...state2.events, ...events } })),
2763
- setSize: (width, height, top, left) => {
2764
- const state2 = get();
2765
- if (width === void 0) {
2766
- set({ _sizeImperative: false });
2767
- if (state2._sizeProps) {
2768
- const { width: propW, height: propH } = state2._sizeProps;
2769
- if (propW !== void 0 || propH !== void 0) {
2770
- const currentSize = state2.size;
2771
- const newSize = {
2772
- width: propW ?? currentSize.width,
2773
- height: propH ?? currentSize.height,
2774
- top: currentSize.top,
2775
- left: currentSize.left
2776
- };
2777
- set((s) => ({
2778
- size: newSize,
2779
- viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
2780
- }));
2781
- getScheduler().invalidate();
2782
- }
2783
- }
2784
- return;
2785
- }
2786
- const w = width;
2787
- const h = height ?? width;
2788
- const t = top ?? state2.size.top;
2789
- const l = left ?? state2.size.left;
2790
- const size = { width: w, height: h, top: t, left: l };
2791
- set((s) => ({
2792
- size,
2793
- viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
2794
- _sizeImperative: true
2795
- }));
2796
- getScheduler().invalidate();
2797
- },
2798
- setDpr: (dpr) => set((state2) => {
2799
- const resolved = calculateDpr(dpr);
2800
- return { viewport: { ...state2.viewport, dpr: resolved, initialDpr: state2.viewport.initialDpr || resolved } };
2801
- }),
2802
- setFrameloop: (frameloop = "always") => {
2803
- set(() => ({ frameloop }));
2804
- },
2805
- setError: (error) => set(() => ({ error })),
2806
- error: null,
2807
- //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
2808
- uniforms: {},
2809
- nodes: {},
2810
- buffers: {},
2811
- gpuStorage: {},
2812
- textures: /* @__PURE__ */ new Map(),
2813
- renderPipeline: null,
2814
- passes: {},
2815
- _hmrVersion: 0,
2816
- _sizeImperative: false,
2817
- _sizeProps: null,
2818
- previousRoot: void 0,
2819
- internal: {
2820
- // Events
2821
- interaction: [],
2822
- subscribers: [],
2823
- // Per-pointer state (new unified structure)
2824
- pointerMap: /* @__PURE__ */ new Map(),
2825
- pointerDirty: /* @__PURE__ */ new Map(),
2826
- lastEvent: React.createRef(),
2827
- // Deprecated but kept for backwards compatibility
2828
- hovered: /* @__PURE__ */ new Map(),
2829
- initialClick: [0, 0],
2830
- initialHits: [],
2831
- capturedMap: /* @__PURE__ */ new Map(),
2832
- // Visibility tracking (onFramed, onOccluded, onVisible)
2833
- visibilityRegistry: /* @__PURE__ */ new Map(),
2834
- // Occlusion system (WebGPU only)
2835
- occlusionEnabled: false,
2836
- occlusionObserver: null,
2837
- occlusionCache: /* @__PURE__ */ new Map(),
2838
- helperGroup: null,
2839
- // Updates
2840
- active: false,
2841
- frames: 0,
2842
- priority: 0,
2843
- subscribe: (ref, priority, store) => {
2844
- const internal = get().internal;
2845
- internal.priority = internal.priority + (priority > 0 ? 1 : 0);
2846
- internal.subscribers.push({ ref, priority, store });
2847
- internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority);
2848
- return () => {
2849
- const internal2 = get().internal;
2850
- if (internal2?.subscribers) {
2851
- internal2.priority = internal2.priority - (priority > 0 ? 1 : 0);
2852
- internal2.subscribers = internal2.subscribers.filter((s) => s.ref !== ref);
2853
- }
2854
- };
2855
- },
2856
- // Renderer Storage (single source of truth)
2857
- actualRenderer: null,
2858
- // Scheduler for useFrameNext (initialized in renderer.tsx)
2859
- scheduler: null
2860
- }
2861
- };
2862
- return rootState;
1870
+ };
1871
+ return rootState;
2863
1872
  });
2864
1873
  const state = rootStore.getState();
2865
1874
  Object.defineProperty(state, "gl", {
@@ -2867,8 +1876,7 @@ const createStore = (invalidate, advance) => {
2867
1876
  const currentState = rootStore.getState();
2868
1877
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2869
1878
  const stack = new Error().stack || "";
2870
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2871
- if (!isInternalAccess) {
1879
+ if (!isInternalRendererAccess(stack)) {
2872
1880
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2873
1881
  notifyDepreciated({
2874
1882
  heading: "Accessing state.gl in WebGPU mode",
@@ -2981,19 +1989,25 @@ function loadingFn(extensions, onProgress) {
2981
1989
  );
2982
1990
  };
2983
1991
  }
2984
- function useLoader(loader, input, extensions, onProgress) {
2985
- const keys = Array.isArray(input) ? input : [input];
1992
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
1993
+ const inputs = Array.isArray(input) ? input : [input];
1994
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2986
1995
  const fn = loadingFn(extensions, onProgress);
2987
- const results = keys.map((key) => suspend(fn, [loader, key], { equal: is.equ }));
1996
+ const results = cacheKeys.map(
1997
+ (key, index) => suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
1998
+ );
2988
1999
  return Array.isArray(input) ? results : results[0];
2989
2000
  }
2990
- useLoader.preload = function(loader, input, extensions, onProgress) {
2991
- const keys = Array.isArray(input) ? input : [input];
2992
- keys.forEach((key) => preload(loadingFn(extensions, onProgress), [loader, key]));
2001
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2002
+ const inputs = Array.isArray(input) ? input : [input];
2003
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2004
+ cacheKeys.forEach(
2005
+ (key, index) => preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2006
+ );
2993
2007
  };
2994
- useLoader.clear = function(loader, input) {
2995
- const keys = Array.isArray(input) ? input : [input];
2996
- keys.forEach((key) => clear([loader, key]));
2008
+ useLoader.clear = function(loader, input, cacheKey) {
2009
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2010
+ cacheKeys.forEach((key) => clear([loader, key]));
2997
2011
  };
2998
2012
  useLoader.loader = getLoader;
2999
2013
 
@@ -3069,20 +2083,14 @@ function useFrame(callback, priorityOrOptions) {
3069
2083
  }
3070
2084
  };
3071
2085
  } else {
3072
- const registerOutside = () => {
3073
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
3074
- };
3075
- if (scheduler.independent || scheduler.isReady) {
3076
- return registerOutside();
3077
- }
3078
- let unregisterJob = null;
3079
- const unsubReady = scheduler.onRootReady(() => {
3080
- unregisterJob = registerOutside();
3081
- });
3082
- return () => {
3083
- unsubReady();
3084
- unregisterJob?.();
3085
- };
2086
+ return scheduler.register(
2087
+ (state, delta) => {
2088
+ const frameState = state;
2089
+ if (!frameState.renderer) return;
2090
+ callbackRef.current?.(frameState, delta);
2091
+ },
2092
+ { id, ...options }
2093
+ );
3086
2094
  }
3087
2095
  }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
3088
2096
  const isPaused = React.useSyncExternalStore(
@@ -3173,18 +2181,18 @@ function buildFromCache(input, textureCache) {
3173
2181
  function useTexture(input, optionsOrOnLoad) {
3174
2182
  const renderer = useThree((state) => state.internal.actualRenderer);
3175
2183
  const store = useStore();
3176
- const textureCache = useThree((state) => state.textures);
3177
2184
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
3178
- const { onLoad, cache = false } = options;
2185
+ const { onLoad, cache = true } = options;
3179
2186
  const onLoadRef = useRef(onLoad);
3180
2187
  onLoadRef.current = onLoad;
3181
2188
  const onLoadCalledForRef = useRef(null);
3182
2189
  const urls = useMemo(() => getUrls(input), [input]);
3183
2190
  const cachedResult = useMemo(() => {
3184
2191
  if (!cache) return null;
3185
- if (!allUrlsCached(urls, textureCache)) return null;
3186
- return buildFromCache(input, textureCache);
3187
- }, [cache, urls, textureCache, input]);
2192
+ const textures = store.getState().textures;
2193
+ if (!allUrlsCached(urls, textures)) return null;
2194
+ return buildFromCache(input, textures);
2195
+ }, [cache, urls, input, store]);
3188
2196
  const loadedTextures = useLoader(
3189
2197
  TextureLoader,
3190
2198
  IsObject(input) ? Object.values(input) : input
@@ -3228,8 +2236,6 @@ function useTexture(input, optionsOrOnLoad) {
3228
2236
  }, [input, loadedTextures, cachedResult]);
3229
2237
  useEffect(() => {
3230
2238
  if (!cache) return;
3231
- if (cachedResult) return;
3232
- const set = store.setState;
3233
2239
  const urlTextureMap = [];
3234
2240
  if (typeof input === "string") {
3235
2241
  urlTextureMap.push([input, mappedTextures]);
@@ -3243,18 +2249,32 @@ function useTexture(input, optionsOrOnLoad) {
3243
2249
  urlTextureMap.push([url, textureRecord[key]]);
3244
2250
  }
3245
2251
  }
3246
- set((state) => {
3247
- const newMap = new Map(state.textures);
3248
- let changed = false;
2252
+ store.setState((state) => {
2253
+ const refs = new Map(state._textureRefs);
2254
+ let textures = state.textures;
2255
+ let added = false;
3249
2256
  for (const [url, texture] of urlTextureMap) {
3250
- if (!newMap.has(url)) {
3251
- newMap.set(url, texture);
3252
- changed = true;
2257
+ if (!textures.has(url)) {
2258
+ if (!added) {
2259
+ textures = new Map(textures);
2260
+ added = true;
2261
+ }
2262
+ textures.set(url, texture);
3253
2263
  }
2264
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3254
2265
  }
3255
- return changed ? { textures: newMap } : state;
2266
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
3256
2267
  });
3257
- }, [cache, input, mappedTextures, store, cachedResult]);
2268
+ return () => store.setState((state) => {
2269
+ const refs = new Map(state._textureRefs);
2270
+ for (const [url] of urlTextureMap) {
2271
+ const next = (refs.get(url) ?? 0) - 1;
2272
+ if (next <= 0) refs.delete(url);
2273
+ else refs.set(url, next);
2274
+ }
2275
+ return { _textureRefs: refs };
2276
+ });
2277
+ }, [cache, input, mappedTextures, store]);
3258
2278
  return mappedTextures;
3259
2279
  }
3260
2280
  useTexture.preload = (url) => useLoader.preload(TextureLoader, url);
@@ -3270,96 +2290,63 @@ const Texture = ({
3270
2290
  return /* @__PURE__ */ jsx(Fragment, { children: children?.(ret) });
3271
2291
  };
3272
2292
 
3273
- function getTextureValue(entry) {
3274
- if (entry instanceof Texture$1) return entry;
3275
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof Texture$1) {
3276
- return entry.value;
3277
- }
3278
- return null;
3279
- }
3280
- function useTextures() {
2293
+ function useTextures(selector) {
3281
2294
  const store = useStore();
3282
- return useMemo(() => {
3283
- const set = store.setState;
2295
+ const registry = useMemo(() => {
3284
2296
  const getState = store.getState;
3285
- const add = (key, value) => {
3286
- set((state) => {
3287
- const newMap = new Map(state.textures);
3288
- newMap.set(key, value);
3289
- return { textures: newMap };
3290
- });
3291
- };
3292
- const addMultiple = (items) => {
3293
- set((state) => {
3294
- const newMap = new Map(state.textures);
3295
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
3296
- for (const [key, value] of entries) {
3297
- newMap.set(key, value);
3298
- }
3299
- return { textures: newMap };
3300
- });
3301
- };
3302
- const remove = (key) => {
3303
- set((state) => {
3304
- const newMap = new Map(state.textures);
3305
- newMap.delete(key);
3306
- return { textures: newMap };
3307
- });
3308
- };
3309
- const removeMultiple = (keys) => {
3310
- set((state) => {
3311
- const newMap = new Map(state.textures);
3312
- for (const key of keys) newMap.delete(key);
3313
- return { textures: newMap };
3314
- });
3315
- };
3316
- const dispose = (key) => {
3317
- const entry = getState().textures.get(key);
3318
- if (entry) {
3319
- const tex = getTextureValue(entry);
3320
- tex?.dispose();
3321
- }
3322
- remove(key);
3323
- };
3324
- const disposeMultiple = (keys) => {
3325
- const textures = getState().textures;
3326
- for (const key of keys) {
3327
- const entry = textures.get(key);
3328
- if (entry) {
3329
- const tex = getTextureValue(entry);
3330
- tex?.dispose();
3331
- }
3332
- }
3333
- removeMultiple(keys);
3334
- };
3335
- const disposeAll = () => {
3336
- const textures = getState().textures;
3337
- for (const entry of textures.values()) {
3338
- const tex = getTextureValue(entry);
3339
- tex?.dispose();
3340
- }
3341
- set({ textures: /* @__PURE__ */ new Map() });
3342
- };
2297
+ const setState = store.setState;
2298
+ const getOne = (key) => getState().textures.get(key);
3343
2299
  return {
3344
- // Getter for the textures Map (reactive via getState)
3345
- get textures() {
2300
+ get all() {
3346
2301
  return getState().textures;
3347
2302
  },
3348
- // Read
3349
- get: (key) => getState().textures.get(key),
2303
+ get(input) {
2304
+ if (typeof input === "string") return getOne(input);
2305
+ if (Array.isArray(input)) return input.map(getOne);
2306
+ const out = {};
2307
+ for (const name in input) out[name] = getOne(input[name]);
2308
+ return out;
2309
+ },
3350
2310
  has: (key) => getState().textures.has(key),
3351
- // Write
3352
- add,
3353
- addMultiple,
3354
- // Remove (cache only)
3355
- remove,
3356
- removeMultiple,
3357
- // Dispose (GPU + cache)
3358
- dispose,
3359
- disposeMultiple,
3360
- disposeAll
2311
+ add(keyOrRecord, texture) {
2312
+ setState((state) => {
2313
+ const textures = new Map(state.textures);
2314
+ if (typeof keyOrRecord === "string") {
2315
+ textures.set(keyOrRecord, texture);
2316
+ } else {
2317
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2318
+ }
2319
+ return { textures };
2320
+ });
2321
+ },
2322
+ dispose(key, options) {
2323
+ const state = getState();
2324
+ const refs = state._textureRefs.get(key) ?? 0;
2325
+ if (refs > 0 && !options?.force) {
2326
+ console.warn(
2327
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2328
+ );
2329
+ return false;
2330
+ }
2331
+ state.textures.get(key)?.dispose();
2332
+ setState((s) => {
2333
+ const textures = new Map(s.textures);
2334
+ textures.delete(key);
2335
+ const nextRefs = new Map(s._textureRefs);
2336
+ nextRefs.delete(key);
2337
+ return { textures, _textureRefs: nextRefs };
2338
+ });
2339
+ return true;
2340
+ },
2341
+ disposeAll() {
2342
+ for (const texture of getState().textures.values()) texture.dispose();
2343
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2344
+ }
3361
2345
  };
3362
2346
  }, [store]);
2347
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2348
+ const selected = useThree(subscribe);
2349
+ return selector ? selected : registry;
3363
2350
  }
3364
2351
 
3365
2352
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3440,7 +2427,7 @@ function advance(timestamp) {
3440
2427
  getScheduler().step(timestamp);
3441
2428
  }
3442
2429
 
3443
- const version = "10.0.0-alpha.2";
2430
+ const version = "10.0.0-alpha.3";
3444
2431
  const packageData = {
3445
2432
  version: version};
3446
2433
 
@@ -14696,7 +13683,7 @@ function n0() {
14696
13683
  var t0 = n0();
14697
13684
  const r0 = Xb(t0);
14698
13685
 
14699
- const t = 1, o = 8, r = 32, e = 2;
13686
+ const t = 1, o = 8, r = 32, e = 2, i$1 = 268435456;
14700
13687
 
14701
13688
  function createReconciler(config) {
14702
13689
  const reconciler2 = r0(config);
@@ -14861,7 +13848,15 @@ function setFiberRef(fiber, publicInstance) {
14861
13848
  }
14862
13849
  }
14863
13850
  const reconstructed = [];
14864
- function swapInstances() {
13851
+ function flushReconstructedInstances() {
13852
+ if (reconstructed.length === 0) return;
13853
+ try {
13854
+ swapReconstructedInstances();
13855
+ } finally {
13856
+ reconstructed.length = 0;
13857
+ }
13858
+ }
13859
+ function swapReconstructedInstances() {
14865
13860
  for (const [instance] of reconstructed) {
14866
13861
  const parent = instance.parent;
14867
13862
  if (parent) {
@@ -14879,6 +13874,7 @@ function swapInstances() {
14879
13874
  }
14880
13875
  }
14881
13876
  if (instance.isHidden) unhideInstance(instance);
13877
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14882
13878
  if (instance.object.__r3f) delete instance.object.__r3f;
14883
13879
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14884
13880
  }
@@ -14891,6 +13887,8 @@ function swapInstances() {
14891
13887
  instance.object.__r3f = instance;
14892
13888
  setFiberRef(fiber, instance.object);
14893
13889
  delete instance.appliedOnce;
13890
+ instance.eventCount = 0;
13891
+ instance.handlers = {};
14894
13892
  applyProps(instance.object, instance.props);
14895
13893
  if (instance.props.attach) {
14896
13894
  attach(parent, instance);
@@ -14907,14 +13905,114 @@ function swapInstances() {
14907
13905
  invalidateInstance(instance);
14908
13906
  }
14909
13907
  }
14910
- reconstructed.length = 0;
14911
13908
  }
14912
13909
  const handleTextInstance = () => {
14913
13910
  };
14914
13911
  const NO_CONTEXT = {};
14915
13912
  let currentUpdatePriority = NoEventPriority;
14916
- const NoFlags = 0;
14917
- const Update = 4;
13913
+ function getEventPriority(type) {
13914
+ switch (type) {
13915
+ case "beforetoggle":
13916
+ case "cancel":
13917
+ case "click":
13918
+ case "close":
13919
+ case "contextmenu":
13920
+ case "copy":
13921
+ case "cut":
13922
+ case "auxclick":
13923
+ case "dblclick":
13924
+ case "dragend":
13925
+ case "dragstart":
13926
+ case "drop":
13927
+ case "focusin":
13928
+ case "focusout":
13929
+ case "input":
13930
+ case "invalid":
13931
+ case "keydown":
13932
+ case "keypress":
13933
+ case "keyup":
13934
+ case "mousedown":
13935
+ case "mouseup":
13936
+ case "paste":
13937
+ case "pause":
13938
+ case "play":
13939
+ case "pointercancel":
13940
+ case "pointerdown":
13941
+ case "pointerup":
13942
+ case "ratechange":
13943
+ case "reset":
13944
+ case "resize":
13945
+ case "seeked":
13946
+ case "submit":
13947
+ case "touchcancel":
13948
+ case "touchend":
13949
+ case "touchstart":
13950
+ case "volumechange":
13951
+ case "change":
13952
+ case "selectionchange":
13953
+ case "compositionstart":
13954
+ case "compositionend":
13955
+ case "compositionupdate":
13956
+ case "beforeinput":
13957
+ case "blur":
13958
+ case "fullscreenchange":
13959
+ case "focus":
13960
+ case "hashchange":
13961
+ case "popstate":
13962
+ case "select":
13963
+ case "selectstart":
13964
+ return e;
13965
+ case "drag":
13966
+ case "dragenter":
13967
+ case "dragexit":
13968
+ case "dragleave":
13969
+ case "dragover":
13970
+ case "mousemove":
13971
+ case "mouseout":
13972
+ case "mouseover":
13973
+ case "pointermove":
13974
+ case "pointerout":
13975
+ case "pointerover":
13976
+ case "scroll":
13977
+ case "touchmove":
13978
+ case "wheel":
13979
+ case "mouseenter":
13980
+ case "mouseleave":
13981
+ case "pointerenter":
13982
+ case "pointerleave":
13983
+ return o;
13984
+ case "message": {
13985
+ switch (unstable_getCurrentPriorityLevel()) {
13986
+ case unstable_ImmediatePriority:
13987
+ return e;
13988
+ case unstable_UserBlockingPriority:
13989
+ return o;
13990
+ case unstable_NormalPriority:
13991
+ case unstable_LowPriority:
13992
+ return r;
13993
+ case unstable_IdlePriority:
13994
+ return i$1;
13995
+ default:
13996
+ return r;
13997
+ }
13998
+ }
13999
+ default:
14000
+ return r;
14001
+ }
14002
+ }
14003
+ function scheduleMicrotask(callback) {
14004
+ if (typeof queueMicrotask === "function") {
14005
+ queueMicrotask(callback);
14006
+ } else if (typeof Promise !== "undefined") {
14007
+ Promise.resolve().then(callback).catch((error) => {
14008
+ setTimeout(() => {
14009
+ throw error;
14010
+ });
14011
+ });
14012
+ } else {
14013
+ setTimeout(callback);
14014
+ }
14015
+ }
14918
14016
  const reconciler = /* @__PURE__ */ createReconciler({
14919
14017
  isPrimaryRenderer: false,
14920
14018
  warnsIfNotActing: false,
@@ -14953,16 +14051,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14953
14051
  else if (newProps.args?.length !== oldProps.args?.length) reconstruct = true;
14954
14052
  else if (newProps.args?.some((value, index) => value !== oldProps.args?.[index])) reconstruct = true;
14955
14053
  if (reconstruct) {
14956
- reconstructed.push([instance, { ...newProps }, fiber]);
14054
+ reconstructed.push([instance, getInstanceProps(newProps), fiber]);
14957
14055
  } else {
14958
14056
  const changedProps = diffProps(instance, newProps);
14959
- if (Object.keys(changedProps).length) {
14960
- Object.assign(instance.props, changedProps);
14961
- applyProps(instance.object, changedProps);
14962
- }
14057
+ const attach2 = instance.props.attach;
14058
+ instance.props = getInstanceProps(newProps);
14059
+ if (attach2 !== void 0) instance.props.attach = attach2;
14060
+ else delete instance.props.attach;
14061
+ if (Object.keys(changedProps).length) applyProps(instance.object, changedProps);
14963
14062
  }
14964
- const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
14965
- if (isTailSibling) swapInstances();
14966
14063
  },
14967
14064
  finalizeInitialChildren: (instance) => {
14968
14065
  for (const prop in instance.props) {
@@ -14987,8 +14084,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
14987
14084
  const target = container.getState().internal.container ?? container.getState().scene;
14988
14085
  return prepare(target, container, "", {});
14989
14086
  },
14990
- resetAfterCommit: () => {
14991
- },
14087
+ // Reconstructed instances are swapped once all mutations are committed,
14088
+ // before layout effects run so refs point to the new objects
14089
+ resetAfterCommit: flushReconstructedInstances,
14992
14090
  shouldSetTextContent: () => false,
14993
14091
  clearContainer: () => false,
14994
14092
  hideInstance,
@@ -14996,6 +14094,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
14996
14094
  createTextInstance: handleTextInstance,
14997
14095
  hideTextInstance: handleTextInstance,
14998
14096
  unhideTextInstance: handleTextInstance,
14097
+ // Mirrors react-dom, which flushes discrete work in microtasks
14098
+ supportsMicrotasks: true,
14099
+ scheduleMicrotask,
14999
14100
  scheduleTimeout: typeof setTimeout === "function" ? setTimeout : void 0,
15000
14101
  cancelTimeout: typeof clearTimeout === "function" ? clearTimeout : void 0,
15001
14102
  noTimeout: -1,
@@ -15036,28 +14137,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
15036
14137
  },
15037
14138
  resolveUpdatePriority() {
15038
14139
  if (currentUpdatePriority !== NoEventPriority) return currentUpdatePriority;
15039
- switch (typeof window !== "undefined" && window.event?.type) {
15040
- case "click":
15041
- case "contextmenu":
15042
- case "dblclick":
15043
- case "dragenter":
15044
- case "dragleave":
15045
- case "drop":
15046
- case "pointercancel":
15047
- case "pointerdown":
15048
- case "pointerup":
15049
- return e;
15050
- case "dragover":
15051
- case "pointermove":
15052
- case "pointerout":
15053
- case "pointerover":
15054
- case "pointerenter":
15055
- case "pointerleave":
15056
- case "wheel":
15057
- return o;
15058
- default:
15059
- return r;
15060
- }
14140
+ const eventType = typeof window !== "undefined" ? window.event?.type : void 0;
14141
+ if (eventType === void 0) return r;
14142
+ return getEventPriority(eventType);
15061
14143
  },
15062
14144
  resetFormInstance() {
15063
14145
  },
@@ -15106,11 +14188,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
15106
14188
  cloneMutableTextInstance(textInstance) {
15107
14189
  return textInstance;
15108
14190
  },
14191
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14192
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14193
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14194
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14195
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14196
+ // Guarded by a test asserting a full render + unmount never reaches them.
15109
14197
  cloneRootViewTransitionContainer(_rootContainer) {
15110
- throw new Error("Not implemented.");
15111
14198
  },
15112
14199
  removeRootViewTransitionClone(_rootContainer, _clone) {
15113
- throw new Error("Not implemented.");
15114
14200
  },
15115
14201
  // https://github.com/facebook/react/pull/32465
15116
14202
  createFragmentInstance: (_fiber) => null,
@@ -15195,6 +14281,7 @@ function createRoot(canvas) {
15195
14281
  const lastConfiguredProps = {};
15196
14282
  let configured = false;
15197
14283
  let pending = null;
14284
+ let rendererSetup = null;
15198
14285
  return {
15199
14286
  async configure(props = {}) {
15200
14287
  let resolve;
@@ -15225,7 +14312,7 @@ function createRoot(canvas) {
15225
14312
  forceEven
15226
14313
  } = props;
15227
14314
  const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || SRGBColorSpace;
15228
- const state = store.getState();
14315
+ let state = store.getState();
15229
14316
  const defaultGPUProps = {
15230
14317
  canvas,
15231
14318
  antialias: true
@@ -15239,52 +14326,64 @@ function createRoot(canvas) {
15239
14326
  throw new Error("Cannot use both gl and renderer props at the same time");
15240
14327
  }
15241
14328
  let renderer = state.internal.actualRenderer;
15242
- if (primaryCanvas && !state.internal.actualRenderer) {
15243
- const primary = await waitForPrimary(primaryCanvas);
15244
- renderer = primary.renderer;
15245
- state.internal.actualRenderer = renderer;
15246
- const canvasTarget = new CanvasTarget(canvas);
15247
- primary.store.setState((prev) => ({
15248
- internal: { ...prev.internal, isMultiCanvas: true }
15249
- }));
15250
- state.set((prev) => ({
15251
- webGPUSupported: primary.store.getState().webGPUSupported,
15252
- renderer,
15253
- primaryStore: primary.store,
15254
- internal: {
15255
- ...prev.internal,
15256
- canvasTarget,
15257
- isMultiCanvas: true,
15258
- isSecondary: true,
15259
- targetId: primaryCanvas
15260
- }
15261
- }));
15262
- } else if (!state.internal.actualRenderer) {
15263
- renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
15264
- if (!renderer.hasInitialized?.()) {
15265
- const size2 = computeInitialSize(canvas, propsSize);
15266
- if (size2.width > 0 && size2.height > 0) {
15267
- const pixelRatio = calculateDpr(dpr);
15268
- canvas.width = size2.width * pixelRatio;
15269
- canvas.height = size2.height * pixelRatio;
15270
- }
15271
- await renderer.init();
15272
- }
15273
- const backend = renderer.backend;
15274
- const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
15275
- state.internal.actualRenderer = renderer;
15276
- state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
15277
- if (canvasId && !state.internal.isSecondary) {
15278
- const canvasTarget = new CanvasTarget(canvas);
15279
- const unregisterPrimary = registerPrimary(canvasId, renderer, store);
15280
- state.set((prev) => ({
15281
- internal: {
15282
- ...prev.internal,
15283
- canvasTarget,
15284
- unregisterPrimary
14329
+ if (!state.internal.actualRenderer) {
14330
+ if (!rendererSetup) {
14331
+ rendererSetup = (async () => {
14332
+ if (primaryCanvas) {
14333
+ const primary = await waitForPrimary(primaryCanvas);
14334
+ renderer = primary.renderer;
14335
+ state.internal.actualRenderer = renderer;
14336
+ const canvasTarget = new CanvasTarget(canvas);
14337
+ primary.store.setState((prev) => ({
14338
+ internal: { ...prev.internal, isMultiCanvas: true }
14339
+ }));
14340
+ state.set((prev) => ({
14341
+ webGPUSupported: primary.store.getState().webGPUSupported,
14342
+ renderer,
14343
+ primaryStore: primary.store,
14344
+ internal: {
14345
+ ...prev.internal,
14346
+ canvasTarget,
14347
+ isMultiCanvas: true,
14348
+ isSecondary: true,
14349
+ targetId: primaryCanvas
14350
+ }
14351
+ }));
14352
+ } else {
14353
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
14354
+ if (!renderer.hasInitialized?.()) {
14355
+ const size2 = computeInitialSize(canvas, propsSize);
14356
+ if (size2.width > 0 && size2.height > 0) {
14357
+ const pixelRatio = calculateDpr(dpr);
14358
+ canvas.width = size2.width * pixelRatio;
14359
+ canvas.height = size2.height * pixelRatio;
14360
+ }
14361
+ await renderer.init();
14362
+ }
14363
+ const backend = renderer.backend;
14364
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14365
+ state.internal.actualRenderer = renderer;
14366
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14367
+ if (canvasId && !state.internal.isSecondary) {
14368
+ const canvasTarget = new CanvasTarget(canvas);
14369
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14370
+ state.set((prev) => ({
14371
+ internal: {
14372
+ ...prev.internal,
14373
+ canvasTarget,
14374
+ unregisterPrimary
14375
+ }
14376
+ }));
14377
+ }
15285
14378
  }
15286
- }));
14379
+ })().catch((err) => {
14380
+ rendererSetup = null;
14381
+ throw err;
14382
+ });
15287
14383
  }
14384
+ await rendererSetup;
14385
+ state = store.getState();
14386
+ renderer = state.internal.actualRenderer;
15288
14387
  }
15289
14388
  let raycaster = state.raycaster;
15290
14389
  if (!raycaster) state.set({ raycaster: raycaster = new Raycaster() });
@@ -15509,7 +14608,7 @@ function createRoot(canvas) {
15509
14608
  {
15510
14609
  id: `${newRootId}_frustum`,
15511
14610
  rootId: newRootId,
15512
- phase: "preRender",
14611
+ before: "render",
15513
14612
  system: true
15514
14613
  }
15515
14614
  );
@@ -15521,7 +14620,7 @@ function createRoot(canvas) {
15521
14620
  {
15522
14621
  id: `${newRootId}_visibility`,
15523
14622
  rootId: newRootId,
15524
- phase: "preRender",
14623
+ before: "render",
15525
14624
  system: true,
15526
14625
  after: `${newRootId}_frustum`
15527
14626
  }
@@ -15634,7 +14733,8 @@ function unmountComponentAtNode(canvas, callback) {
15634
14733
  dispose(state.scene);
15635
14734
  _roots.delete(canvas);
15636
14735
  if (callback) callback(canvas);
15637
- } catch {
14736
+ } catch (error) {
14737
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15638
14738
  }
15639
14739
  }, 500);
15640
14740
  }
@@ -15697,6 +14797,7 @@ function PortalInner({ state = {}, children, container }) {
15697
14797
  viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(), resolvedSize);
15698
14798
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15699
14799
  }
14800
+ const set = injectState.set;
15700
14801
  return {
15701
14802
  // The intersect consists of the previous root state
15702
14803
  ...rootState,
@@ -15715,33 +14816,205 @@ function PortalInner({ state = {}, children, container }) {
15715
14816
  size: resolvedSize,
15716
14817
  viewport: { ...rootState.viewport, ...viewport },
15717
14818
  // Layers are allowed to override events
15718
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14819
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15719
14820
  // Container for child attachment - the portalScene (injected or container itself)
15720
14821
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15721
14822
  };
15722
14823
  });
15723
- const usePortalStore = useMemo(() => {
15724
- const store = createWithEqualityFn((set, get) => ({ ...rest, set, get }));
15725
- const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
15726
- onMutate(previousRoot.getState());
15727
- return store;
15728
- }, [previousRoot, container]);
15729
- useIsomorphicLayoutEffect(() => {
15730
- const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
15731
- const unsubscribe = previousRoot.subscribe(onMutate);
15732
- return unsubscribe;
15733
- }, [previousRoot, usePortalStore]);
15734
- return (
15735
- // @ts-ignore, reconciler types are not maintained
15736
- /* @__PURE__ */ jsx(Fragment, { children: reconciler.createPortal(
15737
- /* @__PURE__ */ jsx(context.Provider, { value: usePortalStore, children }),
15738
- usePortalStore,
15739
- null
15740
- ) })
15741
- );
14824
+ const usePortalStore = useMemo(() => {
14825
+ const store = createWithEqualityFn((set, get) => ({ ...rest, set, get }));
14826
+ const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
14827
+ onMutate(previousRoot.getState());
14828
+ return store;
14829
+ }, [previousRoot, container]);
14830
+ useIsomorphicLayoutEffect(() => {
14831
+ const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
14832
+ const unsubscribe = previousRoot.subscribe(onMutate);
14833
+ return unsubscribe;
14834
+ }, [previousRoot, usePortalStore]);
14835
+ return (
14836
+ // @ts-ignore, reconciler types are not maintained
14837
+ /* @__PURE__ */ jsx(Fragment, { children: reconciler.createPortal(
14838
+ /* @__PURE__ */ jsx(context.Provider, { value: usePortalStore, children }),
14839
+ usePortalStore,
14840
+ null
14841
+ ) })
14842
+ );
14843
+ }
14844
+ function flushSync(fn) {
14845
+ return reconciler.flushSyncFromReconciler(fn);
14846
+ }
14847
+
14848
+ function parseBackground(background) {
14849
+ if (!background) return null;
14850
+ if (typeof background === "object" && !background.isColor) {
14851
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14852
+ return {
14853
+ ...rest,
14854
+ preset,
14855
+ files: envMap || files,
14856
+ backgroundFiles: backgroundMap,
14857
+ background: true
14858
+ };
14859
+ }
14860
+ if (typeof background === "number") {
14861
+ return { color: background, background: true };
14862
+ }
14863
+ if (typeof background === "string") {
14864
+ if (background in presetsObj) {
14865
+ return { preset: background, background: true };
14866
+ }
14867
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14868
+ return { files: background, background: true };
14869
+ }
14870
+ return { color: background, background: true };
14871
+ }
14872
+ if (background.isColor) {
14873
+ return { color: background, background: true };
14874
+ }
14875
+ return null;
14876
+ }
14877
+
14878
+ function parseRendererConfig(rendererProp) {
14879
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14880
+ if (isRendererConfig) {
14881
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14882
+ return {
14883
+ primaryCanvas: pc,
14884
+ scheduler: sc,
14885
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14886
+ };
14887
+ }
14888
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14889
+ }
14890
+
14891
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14892
+ const ROOT_SCOPE = "";
14893
+ const registries = /* @__PURE__ */ new WeakMap();
14894
+ function getKindRegistry(store, kind) {
14895
+ let registry = registries.get(store);
14896
+ if (!registry) {
14897
+ registry = {
14898
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14899
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14900
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14901
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14902
+ };
14903
+ registries.set(store, registry);
14904
+ }
14905
+ return registry[kind];
14906
+ }
14907
+ function resolvePrimary$1(store) {
14908
+ return store.getState().primaryStore ?? store;
14909
+ }
14910
+ function isScopeValid(store, kind, scopeKey) {
14911
+ return getKindRegistry(store, kind).valid.has(scopeKey);
14912
+ }
14913
+ function peekStaged(store, kind, scopeKey) {
14914
+ return getKindRegistry(store, kind).staged.get(scopeKey);
14915
+ }
14916
+ function stageEntries(store, kind, scopeKey, entries) {
14917
+ const { staged } = getKindRegistry(store, kind);
14918
+ const current = staged.get(scopeKey);
14919
+ if (current) Object.assign(current, entries);
14920
+ else staged.set(scopeKey, { ...entries });
14921
+ }
14922
+ function readCommittedScope(map, scopeKey, isLeaf) {
14923
+ if (scopeKey === ROOT_SCOPE) {
14924
+ const leaves = {};
14925
+ for (const [key, value] of Object.entries(map)) if (isLeaf(value)) leaves[key] = value;
14926
+ return leaves;
14927
+ }
14928
+ const scopeData = map[scopeKey];
14929
+ if (scopeData && typeof scopeData === "object" && !isLeaf(scopeData)) return scopeData;
14930
+ return {};
14931
+ }
14932
+ function withStagedOverlay(store, kind, committed) {
14933
+ const { staged } = getKindRegistry(store, kind);
14934
+ if (staged.size === 0) return committed;
14935
+ const view = { ...committed };
14936
+ for (const [scopeKey, entries] of staged) {
14937
+ if (scopeKey === ROOT_SCOPE) Object.assign(view, entries);
14938
+ else view[scopeKey] = { ...view[scopeKey], ...entries };
14939
+ }
14940
+ return view;
14941
+ }
14942
+ function flushStagedScope(store, kind, scopeKey, isLeaf) {
14943
+ const registry = getKindRegistry(store, kind);
14944
+ const staged = registry.staged.get(scopeKey);
14945
+ if (!staged) return;
14946
+ registry.staged.delete(scopeKey);
14947
+ const replace = !registry.valid.has(scopeKey);
14948
+ store.setState((state) => {
14949
+ const map = state[kind];
14950
+ if (scopeKey === ROOT_SCOPE) {
14951
+ if (!replace) return { [kind]: { ...map, ...staged } };
14952
+ const next = {};
14953
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
14954
+ return { [kind]: { ...next, ...staged } };
14955
+ }
14956
+ const current = replace ? {} : map[scopeKey] ?? {};
14957
+ return { [kind]: { ...map, [scopeKey]: { ...current, ...staged } } };
14958
+ });
14959
+ registry.valid.add(scopeKey);
14960
+ }
14961
+ function invalidateResource(store, kind, scopeKey) {
14962
+ const registry = getKindRegistry(store, kind);
14963
+ if (scopeKey === void 0) {
14964
+ registry.valid.clear();
14965
+ registry.staged.clear();
14966
+ } else {
14967
+ registry.valid.delete(scopeKey);
14968
+ registry.staged.delete(scopeKey);
14969
+ }
14970
+ }
14971
+ function rebuildResource(store, kind, userScope) {
14972
+ const primary = resolvePrimary$1(store);
14973
+ invalidateResource(primary, kind, userScope === "root" ? ROOT_SCOPE : userScope);
14974
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14975
+ }
14976
+ function invalidateAllResources(store) {
14977
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
14978
+ }
14979
+ function removeResourceEntries(store, kind, names, scope, isLeaf) {
14980
+ const staged = peekStaged(store, kind, scope ?? ROOT_SCOPE);
14981
+ if (staged) for (const name of names) delete staged[name];
14982
+ store.setState((state) => {
14983
+ const map = state[kind];
14984
+ if (scope) {
14985
+ const currentScope = { ...map[scope] };
14986
+ for (const name of names) delete currentScope[name];
14987
+ return { [kind]: { ...map, [scope]: currentScope } };
14988
+ }
14989
+ const next = { ...map };
14990
+ for (const name of names) if (isLeaf(next[name])) delete next[name];
14991
+ return { [kind]: next };
14992
+ });
15742
14993
  }
15743
- function flushSync(fn) {
15744
- return reconciler.flushSyncFromReconciler(fn);
14994
+ function clearResourceEntries(store, kind, scope, isLeaf) {
14995
+ const registry = getKindRegistry(store, kind);
14996
+ if (scope && scope !== "root") registry.staged.delete(scope);
14997
+ else if (scope === "root") registry.staged.delete(ROOT_SCOPE);
14998
+ else registry.staged.clear();
14999
+ store.setState((state) => {
15000
+ const map = state[kind];
15001
+ if (scope && scope !== "root") {
15002
+ const { [scope]: _, ...rest } = map;
15003
+ return { [kind]: rest };
15004
+ }
15005
+ if (scope === "root") {
15006
+ const next = {};
15007
+ for (const [key, value] of Object.entries(map)) if (!isLeaf(value)) next[key] = value;
15008
+ return { [kind]: next };
15009
+ }
15010
+ return { [kind]: {} };
15011
+ });
15012
+ }
15013
+
15014
+ function clearHmrCaches(store) {
15015
+ const primary = store.getState().primaryStore ?? store;
15016
+ invalidateAllResources(primary);
15017
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
15745
15018
  }
15746
15019
 
15747
15020
  function CanvasImpl({
@@ -15764,6 +15037,8 @@ function CanvasImpl({
15764
15037
  raycaster,
15765
15038
  camera,
15766
15039
  scene,
15040
+ autoUpdateFrustum,
15041
+ occlusion,
15767
15042
  onPointerMissed,
15768
15043
  onDragOverMissed,
15769
15044
  onDropMissed,
@@ -15775,49 +15050,10 @@ function CanvasImpl({
15775
15050
  forceEven,
15776
15051
  ...props
15777
15052
  }) {
15778
- const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
15779
- let primaryCanvas;
15780
- let scheduler;
15781
- let renderer;
15782
- if (isRendererConfig) {
15783
- const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
15784
- primaryCanvas = pc;
15785
- scheduler = sc;
15786
- renderer = Object.keys(rest).length > 0 ? rest : rendererProp;
15787
- } else {
15788
- renderer = rendererProp;
15789
- }
15053
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15790
15054
  React.useMemo(() => extend(THREE), []);
15791
15055
  const Bridge = useBridge();
15792
- const backgroundProps = React.useMemo(() => {
15793
- if (!background) return null;
15794
- if (typeof background === "object" && !background.isColor) {
15795
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15796
- return {
15797
- ...rest,
15798
- preset,
15799
- files: envMap || files,
15800
- backgroundFiles: backgroundMap,
15801
- background: true
15802
- };
15803
- }
15804
- if (typeof background === "number") {
15805
- return { color: background, background: true };
15806
- }
15807
- if (typeof background === "string") {
15808
- if (background in presetsObj) {
15809
- return { preset: background, background: true };
15810
- }
15811
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15812
- return { files: background, background: true };
15813
- }
15814
- return { color: background, background: true };
15815
- }
15816
- if (background.isColor) {
15817
- return { color: background, background: true };
15818
- }
15819
- return null;
15820
- }, [background]);
15056
+ const backgroundProps = React.useMemo(() => parseBackground(background), [background]);
15821
15057
  const hasInitialSizeRef = React.useRef(false);
15822
15058
  const measureConfig = React.useMemo(() => {
15823
15059
  if (!hasInitialSizeRef.current) {
@@ -15859,6 +15095,7 @@ function CanvasImpl({
15859
15095
  const handleDropMissed = useMutableCallback(onDropMissed);
15860
15096
  const [block, setBlock] = React.useState(false);
15861
15097
  const [error, setError] = React.useState(false);
15098
+ const [fallbackVisible, setFallbackVisible] = React.useState(false);
15862
15099
  if (block) throw block;
15863
15100
  if (error) throw error;
15864
15101
  const root = React.useRef(null);
@@ -15866,6 +15103,7 @@ function CanvasImpl({
15866
15103
  const unsubscribeErrorRef = React.useRef(null);
15867
15104
  useIsomorphicLayoutEffect(() => {
15868
15105
  effectActiveRef.current = true;
15106
+ if (fallbackVisible) return;
15869
15107
  const canvas = canvasRef.current;
15870
15108
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15871
15109
  if (!root.current) {
@@ -15886,7 +15124,7 @@ function CanvasImpl({
15886
15124
  }
15887
15125
  async function run() {
15888
15126
  if (!effectActiveRef.current || !root.current) return;
15889
- await root.current.configure({
15127
+ const configured = await root.current.configure({
15890
15128
  id,
15891
15129
  primaryCanvas,
15892
15130
  scheduler,
@@ -15901,6 +15139,8 @@ function CanvasImpl({
15901
15139
  performance,
15902
15140
  raycaster,
15903
15141
  camera,
15142
+ autoUpdateFrustum,
15143
+ occlusion,
15904
15144
  size: effectiveSize,
15905
15145
  // Store size props for reset functionality
15906
15146
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15925,8 +15165,20 @@ function CanvasImpl({
15925
15165
  }
15926
15166
  onCreated?.(state);
15927
15167
  }
15928
- });
15929
- if (!effectActiveRef.current || !root.current) return;
15168
+ }).then(
15169
+ () => true,
15170
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
15171
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
15172
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
15173
+ (setupError) => {
15174
+ if (effectActiveRef.current) {
15175
+ if (fallback != null) setFallbackVisible(true);
15176
+ else setError(setupError);
15177
+ }
15178
+ return false;
15179
+ }
15180
+ );
15181
+ if (!configured || !effectActiveRef.current || !root.current) return;
15930
15182
  root.current.render(
15931
15183
  /* @__PURE__ */ jsx(Bridge, { children: /* @__PURE__ */ jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxs(React.Suspense, { fallback: /* @__PURE__ */ jsx(Block, { set: setBlock }), children: [
15932
15184
  backgroundProps && /* @__PURE__ */ jsx(Environment, { ...backgroundProps }),
@@ -15960,14 +15212,7 @@ function CanvasImpl({
15960
15212
  const handleHMR = () => {
15961
15213
  queueMicrotask(() => {
15962
15214
  const rootEntry = _roots.get(canvas);
15963
- if (rootEntry?.store) {
15964
- console.log("[R3F] HMR detected \u2014 rebuilding nodes/uniforms");
15965
- rootEntry.store.setState((state) => ({
15966
- nodes: {},
15967
- uniforms: {},
15968
- _hmrVersion: state._hmrVersion + 1
15969
- }));
15970
- }
15215
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15971
15216
  });
15972
15217
  };
15973
15218
  if (typeof import.meta !== "undefined" && import.meta.hot) {
@@ -15996,7 +15241,11 @@ function CanvasImpl({
15996
15241
  ...style
15997
15242
  },
15998
15243
  ...props,
15999
- children: /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
15244
+ children: fallbackVisible ? (
15245
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15246
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15247
+ fallback
15248
+ ) : /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
16000
15249
  "canvas",
16001
15250
  {
16002
15251
  ref: canvasRef,
@@ -16078,35 +15327,50 @@ let ScopedStore = _ScopedStore;
16078
15327
  function createScopedStore(data) {
16079
15328
  return new ScopedStore(data);
16080
15329
  }
16081
- function createLazyCreatorState(state) {
15330
+ function createLazyCreatorState(state, store) {
16082
15331
  let _uniforms = null;
16083
15332
  let _nodes = null;
16084
15333
  let _buffers = null;
16085
15334
  let _gpuStorage = null;
15335
+ const view = (kind) => store ? withStagedOverlay(store, kind, state[kind]) : state[kind];
16086
15336
  return Object.create(state, {
16087
15337
  uniforms: {
16088
15338
  get() {
16089
- return _uniforms ?? (_uniforms = createScopedStore(state.uniforms));
15339
+ return _uniforms ?? (_uniforms = createScopedStore(view("uniforms")));
16090
15340
  }
16091
15341
  },
16092
15342
  nodes: {
16093
15343
  get() {
16094
- return _nodes ?? (_nodes = createScopedStore(state.nodes));
15344
+ return _nodes ?? (_nodes = createScopedStore(view("nodes")));
16095
15345
  }
16096
15346
  },
16097
15347
  buffers: {
16098
15348
  get() {
16099
- return _buffers ?? (_buffers = createScopedStore(state.buffers));
15349
+ return _buffers ?? (_buffers = createScopedStore(view("buffers")));
16100
15350
  }
16101
15351
  },
16102
15352
  gpuStorage: {
16103
15353
  get() {
16104
- return _gpuStorage ?? (_gpuStorage = createScopedStore(state.gpuStorage));
15354
+ return _gpuStorage ?? (_gpuStorage = createScopedStore(view("gpuStorage")));
16105
15355
  }
16106
15356
  }
16107
15357
  });
16108
15358
  }
16109
15359
 
15360
+ function resolvePrimary(local) {
15361
+ return local.getState().primaryStore ?? local;
15362
+ }
15363
+ function usePrimaryStore() {
15364
+ const local = useStore();
15365
+ const primary = local.getState().primaryStore;
15366
+ return useMemo(() => primary ?? local, [primary, local]);
15367
+ }
15368
+ function usePrimaryThree(selector = (state) => state, equalityFn) {
15369
+ const local = useStore();
15370
+ const primary = resolvePrimary(local);
15371
+ return primary(selector, equalityFn);
15372
+ }
15373
+
16110
15374
  function addTexture(set, key, value) {
16111
15375
  set((state) => {
16112
15376
  const newMap = new Map(state.textures);
@@ -16210,65 +15474,56 @@ function useCompareMemoize(value, deep) {
16210
15474
  return ref.current;
16211
15475
  }
16212
15476
 
15477
+ function useScopedResource(options) {
15478
+ const { store, kind, scope, isLeaf, create, prepare, reconcile, input } = options;
15479
+ const scopeKey = scope ?? ROOT_SCOPE;
15480
+ const version = store((s) => s._hmrVersion);
15481
+ const entries = useMemo(() => {
15482
+ const staged = peekStaged(store, kind, scopeKey);
15483
+ const reusable = isScopeValid(store, kind, scopeKey);
15484
+ const map = store.getState()[kind];
15485
+ const committed = reusable ? readCommittedScope(map, scopeKey, isLeaf) : void 0;
15486
+ const result = {};
15487
+ let fresh = null;
15488
+ for (const [name, candidate] of Object.entries(create())) {
15489
+ const existing = staged?.[name] ?? committed?.[name];
15490
+ if (existing !== void 0) {
15491
+ result[name] = existing;
15492
+ reconcile?.(existing, candidate);
15493
+ } else {
15494
+ const value = prepare ? prepare(name, candidate) : candidate;
15495
+ result[name] = value;
15496
+ (fresh ?? (fresh = {}))[name] = value;
15497
+ }
15498
+ }
15499
+ if (fresh) stageEntries(store, kind, scopeKey, fresh);
15500
+ return result;
15501
+ }, [store, kind, scopeKey, version, input]);
15502
+ useIsomorphicLayoutEffect(() => {
15503
+ flushStagedScope(store, kind, scopeKey, isLeaf);
15504
+ });
15505
+ return entries;
15506
+ }
15507
+
16213
15508
  const isUniformNode$1 = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
16214
15509
  function useUniforms(creatorOrScope, scope) {
16215
- const store = useStore();
15510
+ const store = usePrimaryStore();
16216
15511
  const removeUniforms2 = useCallback(
16217
- (names, targetScope) => {
16218
- const nameArray = Array.isArray(names) ? names : [names];
16219
- store.setState((state) => {
16220
- if (targetScope) {
16221
- const currentScope = { ...state.uniforms[targetScope] };
16222
- for (const name of nameArray) delete currentScope[name];
16223
- return { uniforms: { ...state.uniforms, [targetScope]: currentScope } };
16224
- }
16225
- const uniforms2 = { ...state.uniforms };
16226
- for (const name of nameArray) if (isUniformNode$1(uniforms2[name])) delete uniforms2[name];
16227
- return { uniforms: uniforms2 };
16228
- });
16229
- },
15512
+ (names, targetScope) => removeResourceEntries(store, "uniforms", Array.isArray(names) ? names : [names], targetScope, isUniformNode$1),
16230
15513
  [store]
16231
15514
  );
16232
15515
  const clearUniforms = useCallback(
16233
- (targetScope) => {
16234
- store.setState((state) => {
16235
- if (targetScope && targetScope !== "root") {
16236
- const { [targetScope]: _, ...rest } = state.uniforms;
16237
- return { uniforms: rest };
16238
- }
16239
- if (targetScope === "root") {
16240
- const uniforms2 = {};
16241
- for (const [key, value] of Object.entries(state.uniforms)) {
16242
- if (!isUniformNode$1(value)) uniforms2[key] = value;
16243
- }
16244
- return { uniforms: uniforms2 };
16245
- }
16246
- return { uniforms: {} };
16247
- });
16248
- },
15516
+ (targetScope) => clearResourceEntries(store, "uniforms", targetScope, isUniformNode$1),
16249
15517
  [store]
16250
15518
  );
16251
15519
  const rebuildUniforms = useCallback(
16252
- (targetScope) => {
16253
- store.setState((state) => {
16254
- let newUniforms = {};
16255
- if (targetScope && targetScope !== "root") {
16256
- const { [targetScope]: _, ...rest } = state.uniforms;
16257
- newUniforms = rest;
16258
- } else if (targetScope === "root") {
16259
- for (const [key, value] of Object.entries(state.uniforms)) {
16260
- if (!isUniformNode$1(value)) newUniforms[key] = value;
16261
- }
16262
- }
16263
- return { uniforms: newUniforms, _hmrVersion: state._hmrVersion + 1 };
16264
- });
16265
- },
15520
+ (targetScope) => rebuildResource(store, "uniforms", targetScope),
16266
15521
  [store]
16267
15522
  );
16268
15523
  const inputForMemoization = useMemo(() => {
16269
15524
  let raw = creatorOrScope;
16270
15525
  if (is.fun(creatorOrScope)) {
16271
- const wrappedState = createLazyCreatorState(store.getState());
15526
+ const wrappedState = createLazyCreatorState(store.getState(), store);
16272
15527
  raw = creatorOrScope(wrappedState);
16273
15528
  }
16274
15529
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
@@ -16282,80 +15537,44 @@ function useUniforms(creatorOrScope, scope) {
16282
15537
  }, [creatorOrScope, store]);
16283
15538
  const memoizedInput = useCompareMemoize(inputForMemoization);
16284
15539
  const isReader = memoizedInput === void 0 || typeof memoizedInput === "string";
16285
- const storeUniforms = useThree((s) => s.uniforms);
16286
- const hmrVersion = useThree((s) => s._hmrVersion);
16287
- const readerDep = isReader ? storeUniforms : null;
16288
- const creatorDep = isReader ? null : hmrVersion;
16289
- const uniforms = useMemo(() => {
16290
- if (memoizedInput === void 0) {
16291
- return storeUniforms;
16292
- }
16293
- if (typeof memoizedInput === "string") {
16294
- const scopeData = storeUniforms[memoizedInput];
16295
- if (scopeData && !isUniformNode$1(scopeData)) return scopeData;
16296
- return {};
16297
- }
16298
- const state = store.getState();
16299
- const set = store.setState;
16300
- if (typeof memoizedInput !== "object" || memoizedInput === null) {
16301
- throw new Error("Invalid uniform input");
16302
- }
16303
- const created = memoizedInput;
16304
- const result = {};
16305
- let hasNewUniforms = false;
16306
- let targetRecord = state.uniforms;
16307
- if (scope) {
16308
- if (!state.uniforms[scope]) state.uniforms[scope] = {};
16309
- targetRecord = state.uniforms[scope];
16310
- }
16311
- for (const [name, node] of Object.entries(created)) {
16312
- if (targetRecord[name]) {
16313
- result[name] = targetRecord[name];
16314
- const existingVal = result[name].value;
16315
- const newVal = vectorize(node);
16316
- let equals = newVal === existingVal;
16317
- if (!equals && hasEqualsMethod(existingVal) && hasEqualsMethod(newVal)) {
16318
- if (isThreeVector(existingVal) && isThreeVector(newVal)) {
16319
- equals = vectorEquals(existingVal, newVal);
16320
- } else if (isSameThreeType(existingVal, newVal)) {
16321
- equals = existingVal.equals(newVal);
16322
- }
15540
+ const storeUniforms = usePrimaryThree((s) => s.uniforms);
15541
+ const created = useScopedResource({
15542
+ store,
15543
+ kind: "uniforms",
15544
+ scope: isReader ? void 0 : scope,
15545
+ isLeaf: isUniformNode$1,
15546
+ input: memoizedInput,
15547
+ create: () => {
15548
+ if (isReader) return {};
15549
+ if (typeof memoizedInput !== "object" || memoizedInput === null) throw new Error("Invalid uniform input");
15550
+ return memoizedInput;
15551
+ },
15552
+ prepare: (name, candidate) => createUniform(name, candidate, scope),
15553
+ reconcile: (existing, candidate) => {
15554
+ const existingVal = existing.value;
15555
+ const newVal = vectorize(candidate);
15556
+ let equals = newVal === existingVal;
15557
+ if (!equals && hasEqualsMethod(existingVal) && hasEqualsMethod(newVal)) {
15558
+ if (isThreeVector(existingVal) && isThreeVector(newVal)) {
15559
+ equals = vectorEquals(existingVal, newVal);
15560
+ } else if (isSameThreeType(existingVal, newVal)) {
15561
+ equals = existingVal.equals(newVal);
16323
15562
  }
16324
- if (!equals) result[name].value = newVal;
16325
- } else {
16326
- result[name] = createUniform(name, node, scope);
16327
- hasNewUniforms = true;
16328
- }
16329
- }
16330
- if (hasNewUniforms) {
16331
- if (scope) {
16332
- set((s) => ({
16333
- uniforms: {
16334
- ...s.uniforms,
16335
- [scope]: { ...s.uniforms[scope], ...result }
16336
- }
16337
- }));
16338
- } else {
16339
- set((s) => ({ uniforms: { ...s.uniforms, ...result } }));
16340
15563
  }
15564
+ if (!equals) existing.value = newVal;
16341
15565
  }
16342
- return result;
16343
- }, [store, memoizedInput, scope, readerDep, creatorDep]);
15566
+ });
15567
+ let uniforms = created;
15568
+ if (memoizedInput === void 0) {
15569
+ uniforms = storeUniforms;
15570
+ } else if (typeof memoizedInput === "string") {
15571
+ const scopeData = storeUniforms[memoizedInput];
15572
+ uniforms = scopeData && !isUniformNode$1(scopeData) ? scopeData : {};
15573
+ }
16344
15574
  return { ...uniforms, removeUniforms: removeUniforms2, clearUniforms, rebuildUniforms };
16345
15575
  }
16346
15576
  function rebuildAllUniforms(store, scope) {
16347
- store.setState((state) => {
16348
- let newUniforms = {};
16349
- if (scope && scope !== "root") {
16350
- const { [scope]: _, ...rest } = state.uniforms;
16351
- newUniforms = rest;
16352
- } else if (scope === "root") {
16353
- for (const [key, value] of Object.entries(state.uniforms)) {
16354
- if (!isUniformNode$1(value)) newUniforms[key] = value;
16355
- }
16356
- }
16357
- return { uniforms: newUniforms, _hmrVersion: state._hmrVersion + 1 };
16358
- });
15577
+ rebuildResource(store, "uniforms", scope);
16359
15578
  }
16360
15579
  function removeUniforms(set, names, scope) {
16361
15580
  set((state) => {
@@ -16419,191 +15638,91 @@ function isSameThreeType(a, b) {
16419
15638
  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;
16420
15639
  }
16421
15640
 
15641
+ const uniformOf = uniform;
16422
15642
  const isUniformNode = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
16423
15643
  const isTSLNode$1 = (value) => value !== null && typeof value === "object" && "uuid" in value && "nodeType" in value;
16424
15644
  function useUniform(name, value) {
16425
15645
  const store = useStore();
16426
- const hmrVersion = useThree((s) => s._hmrVersion);
16427
- return useMemo(() => {
16428
- const state = store.getState();
16429
- const set = store.setState;
16430
- const existing = state.uniforms[name];
16431
- if (existing && isUniformNode(existing)) {
15646
+ const registered = useScopedResource({
15647
+ store,
15648
+ kind: "uniforms",
15649
+ scope: void 0,
15650
+ isLeaf: isUniformNode,
15651
+ input: name,
15652
+ create: () => value === void 0 ? {} : { [name]: value },
15653
+ prepare: createNamedUniform,
15654
+ reconcile: (existing2) => {
16432
15655
  if (value !== void 0 && !isTSLNode$1(value) && !isUniformNode(value)) {
16433
- existing.value = typeof value === "string" ? new Color(value) : value;
15656
+ existing2.value = typeof value === "string" ? new Color(value) : value;
16434
15657
  }
16435
- return existing;
16436
- }
16437
- if (value === void 0) {
16438
- throw new Error(
16439
- `[useUniform] Uniform "${name}" not found. Create it first with: useUniform('${name}', initialValue)`
16440
- );
16441
- }
16442
- if (isUniformNode(value)) {
16443
- const node2 = value;
16444
- if (typeof node2.setName === "function") {
16445
- node2.setName(name);
16446
- }
16447
- set((s) => ({
16448
- uniforms: { ...s.uniforms, [name]: node2 }
16449
- }));
16450
- return node2;
16451
- }
16452
- let node;
16453
- if (isTSLNode$1(value)) {
16454
- node = uniform(value);
16455
- } else if (typeof value === "string") {
16456
- node = uniform(new Color(value));
16457
- } else {
16458
- node = uniform(value);
16459
- }
16460
- if (typeof node.setName === "function") {
16461
- node.setName(name);
16462
15658
  }
16463
- set((s) => ({
16464
- uniforms: {
16465
- ...s.uniforms,
16466
- [name]: node
16467
- }
16468
- }));
16469
- return node;
16470
- }, [store, name, hmrVersion]);
15659
+ });
15660
+ if (registered[name]) return registered[name];
15661
+ const existing = peekStaged(store, "uniforms", ROOT_SCOPE)?.[name] ?? store.getState().uniforms[name];
15662
+ if (existing && isUniformNode(existing)) return existing;
15663
+ throw new Error(
15664
+ `[useUniform] Uniform "${name}" not found. Create it first with: useUniform('${name}', initialValue)`
15665
+ );
15666
+ }
15667
+ function createNamedUniform(name, value) {
15668
+ let node;
15669
+ if (isUniformNode(value)) {
15670
+ node = value;
15671
+ } else if (isTSLNode$1(value)) {
15672
+ node = uniformOf(value);
15673
+ } else if (typeof value === "string") {
15674
+ node = uniform(new Color(value));
15675
+ } else {
15676
+ node = uniformOf(value);
15677
+ }
15678
+ if (typeof node.setName === "function") {
15679
+ node.setName(name);
15680
+ }
15681
+ return node;
16471
15682
  }
16472
15683
 
16473
15684
  const isTSLNode = (value) => value !== null && typeof value === "object" && ("uuid" in value || "nodeType" in value);
16474
15685
  function useNodes(creatorOrScope, scope) {
16475
- const store = useStore();
15686
+ const store = usePrimaryStore();
16476
15687
  const removeNodes2 = useCallback(
16477
- (names, targetScope) => {
16478
- const nameArray = Array.isArray(names) ? names : [names];
16479
- store.setState((state) => {
16480
- if (targetScope) {
16481
- const currentScope = { ...state.nodes[targetScope] };
16482
- for (const name of nameArray) delete currentScope[name];
16483
- return { nodes: { ...state.nodes, [targetScope]: currentScope } };
16484
- }
16485
- const nodes2 = { ...state.nodes };
16486
- for (const name of nameArray) if (isTSLNode(nodes2[name])) delete nodes2[name];
16487
- return { nodes: nodes2 };
16488
- });
16489
- },
15688
+ (names, targetScope) => removeResourceEntries(store, "nodes", Array.isArray(names) ? names : [names], targetScope, isTSLNode),
16490
15689
  [store]
16491
15690
  );
16492
15691
  const clearNodes = useCallback(
16493
- (targetScope) => {
16494
- store.setState((state) => {
16495
- if (targetScope && targetScope !== "root") {
16496
- const { [targetScope]: _, ...rest } = state.nodes;
16497
- return { nodes: rest };
16498
- }
16499
- if (targetScope === "root") {
16500
- const nodes2 = {};
16501
- for (const [key, value] of Object.entries(state.nodes)) {
16502
- if (!isTSLNode(value)) nodes2[key] = value;
16503
- }
16504
- return { nodes: nodes2 };
16505
- }
16506
- return { nodes: {} };
16507
- });
16508
- },
15692
+ (targetScope) => clearResourceEntries(store, "nodes", targetScope, isTSLNode),
16509
15693
  [store]
16510
15694
  );
16511
15695
  const rebuildNodes = useCallback(
16512
- (targetScope) => {
16513
- store.setState((state) => {
16514
- let newNodes = state.nodes;
16515
- if (targetScope && targetScope !== "root") {
16516
- const { [targetScope]: _, ...rest } = state.nodes;
16517
- newNodes = rest;
16518
- } else if (targetScope === "root") {
16519
- newNodes = {};
16520
- for (const [key, value] of Object.entries(state.nodes)) {
16521
- if (!isTSLNode(value)) newNodes[key] = value;
16522
- }
16523
- } else {
16524
- newNodes = {};
16525
- }
16526
- return { nodes: newNodes, _hmrVersion: state._hmrVersion + 1 };
16527
- });
16528
- },
15696
+ (targetScope) => rebuildResource(store, "nodes", targetScope),
16529
15697
  [store]
16530
15698
  );
16531
15699
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16532
- const storeNodes = useThree((s) => s.nodes);
16533
- const hmrVersion = useThree((s) => s._hmrVersion);
16534
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16535
- const readerDep = isReader ? storeNodes : null;
16536
- const creatorDep = isReader ? null : hmrVersion;
16537
- const nodes = useMemo(() => {
16538
- if (creatorOrScope === void 0) {
16539
- return storeNodes;
16540
- }
16541
- if (typeof creatorOrScope === "string") {
16542
- const scopeData = storeNodes[creatorOrScope];
16543
- if (scopeData && !isTSLNode(scopeData)) return scopeData;
16544
- return {};
16545
- }
16546
- const state = store.getState();
16547
- const set = store.setState;
16548
- const creator = creatorOrScope;
16549
- const wrappedState = createLazyCreatorState(state);
16550
- const created = creator(wrappedState);
16551
- const result = {};
16552
- let hasNewNodes = false;
16553
- if (scope) {
16554
- const currentScope = state.nodes[scope] ?? {};
16555
- for (const [name, node] of Object.entries(created)) {
16556
- if (currentScope[name]) {
16557
- result[name] = currentScope[name];
16558
- } else {
16559
- node.setName?.(`${scope}.${name}`);
16560
- result[name] = node;
16561
- hasNewNodes = true;
16562
- }
16563
- }
16564
- if (hasNewNodes) {
16565
- set((s) => ({
16566
- nodes: {
16567
- ...s.nodes,
16568
- [scope]: { ...s.nodes[scope], ...result }
16569
- }
16570
- }));
16571
- }
16572
- return result;
16573
- }
16574
- for (const [name, node] of Object.entries(created)) {
16575
- const existing = state.nodes[name];
16576
- if (existing && isTSLNode(existing)) {
16577
- result[name] = existing;
16578
- } else {
16579
- node.setName?.(name);
16580
- result[name] = node;
16581
- hasNewNodes = true;
16582
- }
16583
- }
16584
- if (hasNewNodes) {
16585
- set((s) => ({ nodes: { ...s.nodes, ...result } }));
15700
+ const storeNodes = usePrimaryThree((s) => s.nodes);
15701
+ const created = useScopedResource({
15702
+ store,
15703
+ kind: "nodes",
15704
+ scope: isReader ? void 0 : scope,
15705
+ isLeaf: isTSLNode,
15706
+ create: () => {
15707
+ if (isReader) return {};
15708
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15709
+ },
15710
+ prepare: (name, node) => {
15711
+ node.setName?.(scope ? `${scope}.${name}` : name);
15712
+ return node;
16586
15713
  }
16587
- return result;
16588
- }, [store, scopeDep, readerDep, creatorDep]);
15714
+ });
15715
+ let nodes = created;
15716
+ if (creatorOrScope === void 0) {
15717
+ nodes = storeNodes;
15718
+ } else if (typeof creatorOrScope === "string") {
15719
+ const scopeData = storeNodes[creatorOrScope];
15720
+ nodes = scopeData && !isTSLNode(scopeData) ? scopeData : {};
15721
+ }
16589
15722
  return { ...nodes, removeNodes: removeNodes2, clearNodes, rebuildNodes };
16590
15723
  }
16591
15724
  function rebuildAllNodes(store, scope) {
16592
- store.setState((state) => {
16593
- let newNodes = state.nodes;
16594
- if (scope && scope !== "root") {
16595
- const { [scope]: _, ...rest } = state.nodes;
16596
- newNodes = rest;
16597
- } else if (scope === "root") {
16598
- newNodes = {};
16599
- for (const [key, value] of Object.entries(state.nodes)) {
16600
- if (!isTSLNode(value)) newNodes[key] = value;
16601
- }
16602
- } else {
16603
- newNodes = {};
16604
- }
16605
- return { nodes: newNodes, _hmrVersion: state._hmrVersion + 1 };
16606
- });
15725
+ rebuildResource(store, "nodes", scope);
16607
15726
  }
16608
15727
  function removeNodes(set, names, scope) {
16609
15728
  set((state) => {
@@ -16633,13 +15752,13 @@ function clearRootNodes(set) {
16633
15752
  });
16634
15753
  }
16635
15754
  function useLocalNodes(creator) {
16636
- const store = useStore();
16637
- const uniforms = useThree((s) => s.uniforms);
16638
- const nodes = useThree((s) => s.nodes);
16639
- const textures = useThree((s) => s.textures);
16640
- const hmrVersion = useThree((s) => s._hmrVersion);
15755
+ const store = usePrimaryStore();
15756
+ const uniforms = usePrimaryThree((s) => s.uniforms);
15757
+ const nodes = usePrimaryThree((s) => s.nodes);
15758
+ const textures = usePrimaryThree((s) => s.textures);
15759
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16641
15760
  return useMemo(() => {
16642
- const wrappedState = createLazyCreatorState(store.getState());
15761
+ const wrappedState = createLazyCreatorState(store.getState(), store);
16643
15762
  return creator(wrappedState);
16644
15763
  }, [store, creator, uniforms, nodes, textures, hmrVersion]);
16645
15764
  }
@@ -16658,60 +15777,17 @@ const disposeBuffer = (buffer) => {
16658
15777
  }
16659
15778
  };
16660
15779
  function useBuffers(creatorOrScope, scope) {
16661
- const store = useStore();
15780
+ const store = usePrimaryStore();
16662
15781
  const removeBuffers = useCallback(
16663
- (names, targetScope) => {
16664
- const nameArray = Array.isArray(names) ? names : [names];
16665
- store.setState((state) => {
16666
- if (targetScope) {
16667
- const currentScope = { ...state.buffers[targetScope] };
16668
- for (const name of nameArray) delete currentScope[name];
16669
- return { buffers: { ...state.buffers, [targetScope]: currentScope } };
16670
- }
16671
- const buffers2 = { ...state.buffers };
16672
- for (const name of nameArray) if (isBufferLike(buffers2[name])) delete buffers2[name];
16673
- return { buffers: buffers2 };
16674
- });
16675
- },
15782
+ (names, targetScope) => removeResourceEntries(store, "buffers", Array.isArray(names) ? names : [names], targetScope, isBufferLike),
16676
15783
  [store]
16677
15784
  );
16678
15785
  const clearBuffers = useCallback(
16679
- (targetScope) => {
16680
- store.setState((state) => {
16681
- if (targetScope && targetScope !== "root") {
16682
- const { [targetScope]: _, ...rest } = state.buffers;
16683
- return { buffers: rest };
16684
- }
16685
- if (targetScope === "root") {
16686
- const buffers2 = {};
16687
- for (const [key, value] of Object.entries(state.buffers)) {
16688
- if (!isBufferLike(value)) buffers2[key] = value;
16689
- }
16690
- return { buffers: buffers2 };
16691
- }
16692
- return { buffers: {} };
16693
- });
16694
- },
15786
+ (targetScope) => clearResourceEntries(store, "buffers", targetScope, isBufferLike),
16695
15787
  [store]
16696
15788
  );
16697
15789
  const rebuildBuffers = useCallback(
16698
- (targetScope) => {
16699
- store.setState((state) => {
16700
- let newBuffers = state.buffers;
16701
- if (targetScope && targetScope !== "root") {
16702
- const { [targetScope]: _, ...rest } = state.buffers;
16703
- newBuffers = rest;
16704
- } else if (targetScope === "root") {
16705
- newBuffers = {};
16706
- for (const [key, value] of Object.entries(state.buffers)) {
16707
- if (!isBufferLike(value)) newBuffers[key] = value;
16708
- }
16709
- } else {
16710
- newBuffers = {};
16711
- }
16712
- return { buffers: newBuffers, _hmrVersion: state._hmrVersion + 1 };
16713
- });
16714
- },
15790
+ (targetScope) => rebuildResource(store, "buffers", targetScope),
16715
15791
  [store]
16716
15792
  );
16717
15793
  const disposeBuffers = useCallback(
@@ -16729,85 +15805,34 @@ function useBuffers(creatorOrScope, scope) {
16729
15805
  [store, removeBuffers]
16730
15806
  );
16731
15807
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16732
- const storeBuffers = useThree((s) => s.buffers);
16733
- const hmrVersion = useThree((s) => s._hmrVersion);
16734
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16735
- const readerDep = isReader ? storeBuffers : null;
16736
- const creatorDep = isReader ? null : hmrVersion;
16737
- const buffers = useMemo(() => {
16738
- if (creatorOrScope === void 0) {
16739
- return storeBuffers;
16740
- }
16741
- if (typeof creatorOrScope === "string") {
16742
- const scopeData = storeBuffers[creatorOrScope];
16743
- if (scopeData && !isBufferLike(scopeData)) return scopeData;
16744
- return {};
16745
- }
16746
- const state = store.getState();
16747
- const set = store.setState;
16748
- const creator = creatorOrScope;
16749
- const wrappedState = createLazyCreatorState(state);
16750
- const created = creator(wrappedState);
16751
- const result = {};
16752
- let hasNewBuffers = false;
16753
- if (scope) {
16754
- const currentScope = state.buffers[scope] ?? {};
16755
- for (const [name, buffer] of Object.entries(created)) {
16756
- if (currentScope[name]) {
16757
- result[name] = currentScope[name];
16758
- } else {
16759
- if ("setName" in buffer && typeof buffer.setName === "function") {
16760
- buffer.setName(`${scope}.${name}`);
16761
- }
16762
- result[name] = buffer;
16763
- hasNewBuffers = true;
16764
- }
16765
- }
16766
- if (hasNewBuffers) {
16767
- set((s) => ({
16768
- buffers: {
16769
- ...s.buffers,
16770
- [scope]: { ...s.buffers[scope], ...result }
16771
- }
16772
- }));
16773
- }
16774
- return result;
16775
- }
16776
- for (const [name, buffer] of Object.entries(created)) {
16777
- const existing = state.buffers[name];
16778
- if (existing && isBufferLike(existing)) {
16779
- result[name] = existing;
16780
- } else {
16781
- if ("setName" in buffer && typeof buffer.setName === "function") {
16782
- buffer.setName(name);
16783
- }
16784
- result[name] = buffer;
16785
- hasNewBuffers = true;
15808
+ const storeBuffers = usePrimaryThree((s) => s.buffers);
15809
+ const created = useScopedResource({
15810
+ store,
15811
+ kind: "buffers",
15812
+ scope: isReader ? void 0 : scope,
15813
+ isLeaf: isBufferLike,
15814
+ create: () => {
15815
+ if (isReader) return {};
15816
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15817
+ },
15818
+ prepare: (name, buffer) => {
15819
+ if ("setName" in buffer && typeof buffer.setName === "function") {
15820
+ buffer.setName(scope ? `${scope}.${name}` : name);
16786
15821
  }
15822
+ return buffer;
16787
15823
  }
16788
- if (hasNewBuffers) {
16789
- set((s) => ({ buffers: { ...s.buffers, ...result } }));
16790
- }
16791
- return result;
16792
- }, [store, scopeDep, readerDep, creatorDep]);
15824
+ });
15825
+ let buffers = created;
15826
+ if (creatorOrScope === void 0) {
15827
+ buffers = storeBuffers;
15828
+ } else if (typeof creatorOrScope === "string") {
15829
+ const scopeData = storeBuffers[creatorOrScope];
15830
+ buffers = scopeData && !isBufferLike(scopeData) ? scopeData : {};
15831
+ }
16793
15832
  return { ...buffers, removeBuffers, clearBuffers, rebuildBuffers, disposeBuffers };
16794
15833
  }
16795
15834
  function rebuildAllBuffers(store, scope) {
16796
- store.setState((state) => {
16797
- let newBuffers = state.buffers;
16798
- if (scope && scope !== "root") {
16799
- const { [scope]: _, ...rest } = state.buffers;
16800
- newBuffers = rest;
16801
- } else if (scope === "root") {
16802
- newBuffers = {};
16803
- for (const [key, value] of Object.entries(state.buffers)) {
16804
- if (!isBufferLike(value)) newBuffers[key] = value;
16805
- }
16806
- } else {
16807
- newBuffers = {};
16808
- }
16809
- return { buffers: newBuffers, _hmrVersion: state._hmrVersion + 1 };
16810
- });
15835
+ rebuildResource(store, "buffers", scope);
16811
15836
  }
16812
15837
 
16813
15838
  const isStorageLike = (value) => {
@@ -16824,60 +15849,17 @@ const disposeStorage = (storage) => {
16824
15849
  }
16825
15850
  };
16826
15851
  function useGPUStorage(creatorOrScope, scope) {
16827
- const store = useStore();
15852
+ const store = usePrimaryStore();
16828
15853
  const removeStorage = useCallback(
16829
- (names, targetScope) => {
16830
- const nameArray = Array.isArray(names) ? names : [names];
16831
- store.setState((state) => {
16832
- if (targetScope) {
16833
- const currentScope = { ...state.gpuStorage[targetScope] };
16834
- for (const name of nameArray) delete currentScope[name];
16835
- return { gpuStorage: { ...state.gpuStorage, [targetScope]: currentScope } };
16836
- }
16837
- const gpuStorage2 = { ...state.gpuStorage };
16838
- for (const name of nameArray) if (isStorageLike(gpuStorage2[name])) delete gpuStorage2[name];
16839
- return { gpuStorage: gpuStorage2 };
16840
- });
16841
- },
15854
+ (names, targetScope) => removeResourceEntries(store, "gpuStorage", Array.isArray(names) ? names : [names], targetScope, isStorageLike),
16842
15855
  [store]
16843
15856
  );
16844
15857
  const clearStorage = useCallback(
16845
- (targetScope) => {
16846
- store.setState((state) => {
16847
- if (targetScope && targetScope !== "root") {
16848
- const { [targetScope]: _, ...rest } = state.gpuStorage;
16849
- return { gpuStorage: rest };
16850
- }
16851
- if (targetScope === "root") {
16852
- const gpuStorage2 = {};
16853
- for (const [key, value] of Object.entries(state.gpuStorage)) {
16854
- if (!isStorageLike(value)) gpuStorage2[key] = value;
16855
- }
16856
- return { gpuStorage: gpuStorage2 };
16857
- }
16858
- return { gpuStorage: {} };
16859
- });
16860
- },
15858
+ (targetScope) => clearResourceEntries(store, "gpuStorage", targetScope, isStorageLike),
16861
15859
  [store]
16862
15860
  );
16863
15861
  const rebuildStorage = useCallback(
16864
- (targetScope) => {
16865
- store.setState((state) => {
16866
- let newStorage = state.gpuStorage;
16867
- if (targetScope && targetScope !== "root") {
16868
- const { [targetScope]: _, ...rest } = state.gpuStorage;
16869
- newStorage = rest;
16870
- } else if (targetScope === "root") {
16871
- newStorage = {};
16872
- for (const [key, value] of Object.entries(state.gpuStorage)) {
16873
- if (!isStorageLike(value)) newStorage[key] = value;
16874
- }
16875
- } else {
16876
- newStorage = {};
16877
- }
16878
- return { gpuStorage: newStorage, _hmrVersion: state._hmrVersion + 1 };
16879
- });
16880
- },
15862
+ (targetScope) => rebuildResource(store, "gpuStorage", targetScope),
16881
15863
  [store]
16882
15864
  );
16883
15865
  const disposeStorageFn = useCallback(
@@ -16895,73 +15877,34 @@ function useGPUStorage(creatorOrScope, scope) {
16895
15877
  [store, removeStorage]
16896
15878
  );
16897
15879
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16898
- const storeStorage = useThree((s) => s.gpuStorage);
16899
- const hmrVersion = useThree((s) => s._hmrVersion);
16900
- const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16901
- const readerDep = isReader ? storeStorage : null;
16902
- const creatorDep = isReader ? null : hmrVersion;
16903
- const gpuStorage = useMemo(() => {
16904
- if (creatorOrScope === void 0) {
16905
- return storeStorage;
16906
- }
16907
- if (typeof creatorOrScope === "string") {
16908
- const scopeData = storeStorage[creatorOrScope];
16909
- if (scopeData && !isStorageLike(scopeData)) return scopeData;
16910
- return {};
16911
- }
16912
- const state = store.getState();
16913
- const set = store.setState;
16914
- const creator = creatorOrScope;
16915
- const wrappedState = createLazyCreatorState(state);
16916
- const created = creator(wrappedState);
16917
- const result = {};
16918
- let hasNewStorage = false;
16919
- if (scope) {
16920
- const currentScope = state.gpuStorage[scope] ?? {};
16921
- for (const [name, storage] of Object.entries(created)) {
16922
- if (currentScope[name]) {
16923
- result[name] = currentScope[name];
16924
- } else {
16925
- if ("setName" in storage && typeof storage.setName === "function") {
16926
- storage.setName(`${scope}.${name}`);
16927
- }
16928
- if ("name" in storage && typeof storage.name === "string") {
16929
- storage.name = `${scope}.${name}`;
16930
- }
16931
- result[name] = storage;
16932
- hasNewStorage = true;
16933
- }
16934
- }
16935
- if (hasNewStorage) {
16936
- set((s) => ({
16937
- gpuStorage: {
16938
- ...s.gpuStorage,
16939
- [scope]: { ...s.gpuStorage[scope], ...result }
16940
- }
16941
- }));
15880
+ const storeStorage = usePrimaryThree((s) => s.gpuStorage);
15881
+ const created = useScopedResource({
15882
+ store,
15883
+ kind: "gpuStorage",
15884
+ scope: isReader ? void 0 : scope,
15885
+ isLeaf: isStorageLike,
15886
+ create: () => {
15887
+ if (isReader) return {};
15888
+ return creatorOrScope(createLazyCreatorState(store.getState(), store));
15889
+ },
15890
+ prepare: (name, storage) => {
15891
+ const label = scope ? `${scope}.${name}` : name;
15892
+ if ("setName" in storage && typeof storage.setName === "function") {
15893
+ storage.setName(label);
16942
15894
  }
16943
- return result;
16944
- }
16945
- for (const [name, storage] of Object.entries(created)) {
16946
- const existing = state.gpuStorage[name];
16947
- if (existing && isStorageLike(existing)) {
16948
- result[name] = existing;
16949
- } else {
16950
- if ("setName" in storage && typeof storage.setName === "function") {
16951
- storage.setName(name);
16952
- }
16953
- if ("name" in storage && typeof storage.name === "string") {
16954
- storage.name = name;
16955
- }
16956
- result[name] = storage;
16957
- hasNewStorage = true;
15895
+ if ("name" in storage && typeof storage.name === "string") {
15896
+ storage.name = label;
16958
15897
  }
15898
+ return storage;
16959
15899
  }
16960
- if (hasNewStorage) {
16961
- set((s) => ({ gpuStorage: { ...s.gpuStorage, ...result } }));
16962
- }
16963
- return result;
16964
- }, [store, scopeDep, readerDep, creatorDep]);
15900
+ });
15901
+ let gpuStorage = created;
15902
+ if (creatorOrScope === void 0) {
15903
+ gpuStorage = storeStorage;
15904
+ } else if (typeof creatorOrScope === "string") {
15905
+ const scopeData = storeStorage[creatorOrScope];
15906
+ gpuStorage = scopeData && !isStorageLike(scopeData) ? scopeData : {};
15907
+ }
16965
15908
  return {
16966
15909
  ...gpuStorage,
16967
15910
  removeStorage,
@@ -16971,21 +15914,7 @@ function useGPUStorage(creatorOrScope, scope) {
16971
15914
  };
16972
15915
  }
16973
15916
  function rebuildAllStorage(store, scope) {
16974
- store.setState((state) => {
16975
- let newStorage = state.gpuStorage;
16976
- if (scope && scope !== "root") {
16977
- const { [scope]: _, ...rest } = state.gpuStorage;
16978
- newStorage = rest;
16979
- } else if (scope === "root") {
16980
- newStorage = {};
16981
- for (const [key, value] of Object.entries(state.gpuStorage)) {
16982
- if (!isStorageLike(value)) newStorage[key] = value;
16983
- }
16984
- } else {
16985
- newStorage = {};
16986
- }
16987
- return { gpuStorage: newStorage, _hmrVersion: state._hmrVersion + 1 };
16988
- });
15917
+ rebuildResource(store, "gpuStorage", scope);
16989
15918
  }
16990
15919
 
16991
15920
  function useRenderPipeline(mainCB, setupCB) {
@@ -17026,12 +15955,12 @@ function useRenderPipeline(mainCB, setupCB) {
17026
15955
  const state = store.getState();
17027
15956
  const set = store.setState;
17028
15957
  try {
17029
- let pp = state.renderPipeline;
15958
+ let pipeline = state.renderPipeline;
17030
15959
  let currentPasses = { ...state.passes };
17031
- let justCreatedPP = false;
17032
- if (!pp) {
17033
- pp = new PostProcessing(renderer);
17034
- justCreatedPP = true;
15960
+ let justCreatedPipeline = false;
15961
+ if (!pipeline) {
15962
+ pipeline = new RenderPipeline(renderer);
15963
+ justCreatedPipeline = true;
17035
15964
  }
17036
15965
  const cacheValid = scenePassCacheRef.current && scenePassCacheRef.current.sceneUuid === scene.uuid && scenePassCacheRef.current.cameraUuid === camera.uuid;
17037
15966
  let scenePass;
@@ -17042,9 +15971,9 @@ function useRenderPipeline(mainCB, setupCB) {
17042
15971
  scenePassCacheRef.current = { sceneUuid: scene.uuid, cameraUuid: camera.uuid, scenePass };
17043
15972
  }
17044
15973
  currentPasses.scenePass = scenePass;
17045
- if (!pp.outputNode || justCreatedPP) pp.outputNode = scenePass;
17046
- set({ renderPipeline: pp, passes: currentPasses });
17047
- const shouldRunCallbacks = justCreatedPP || !callbacksRanRef.current || !cacheValid;
15974
+ if (!pipeline.outputNode || justCreatedPipeline) pipeline.outputNode = scenePass;
15975
+ set({ renderPipeline: pipeline, passes: currentPasses });
15976
+ const shouldRunCallbacks = justCreatedPipeline || !callbacksRanRef.current || !cacheValid;
17048
15977
  if (shouldRunCallbacks) {
17049
15978
  if (setupCBRef.current) {
17050
15979
  const freshState = store.getState();
@@ -17065,7 +15994,7 @@ function useRenderPipeline(mainCB, setupCB) {
17065
15994
  callbacksRanRef.current = true;
17066
15995
  }
17067
15996
  } catch (error) {
17068
- console.error("[useRenderPipeline] Setup error:", error);
15997
+ console.warn("[useRenderPipeline] Setup failed; the render pipeline was not configured:", error);
17069
15998
  }
17070
15999
  }, [store, renderer, scene, camera, isLegacy, rebuildVersion]);
17071
16000
  const passes = useThree((s) => s.passes);
@@ -17083,4 +16012,4 @@ function useRenderPipeline(mainCB, setupCB) {
17083
16012
 
17084
16013
  extend(THREE);
17085
16014
 
17086
- export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Scheduler, 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, getScheduler, 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 };
16015
+ 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 };