@react-three/fiber 10.0.0-canary.604355a → 10.0.0-canary.76d2134

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/legacy.cjs CHANGED
@@ -13,6 +13,7 @@ const UltraHDRLoader_js = require('three/examples/jsm/loaders/UltraHDRLoader.js'
13
13
  const gainmapJs = require('@monogrid/gainmap-js');
14
14
  const Tb = require('scheduler');
15
15
  const traditional = require('zustand/traditional');
16
+ const scheduler = require('@pmndrs/scheduler');
16
17
  const suspendReact = require('suspend-react');
17
18
 
18
19
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -61,9 +62,12 @@ const WebGPURenderer = class WebGPURenderer2 {
61
62
  }
62
63
  };
63
64
  const RenderTarget = null;
65
+ const CubeRenderTarget = null;
64
66
 
65
67
  const THREE = /*#__PURE__*/_mergeNamespaces({
66
68
  __proto__: null,
69
+ CubeRenderTarget: CubeRenderTarget,
70
+ CubeRenderTargetCompat: three.WebGLCubeRenderTarget,
67
71
  Inspector: Inspector,
68
72
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
69
73
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
@@ -169,7 +173,7 @@ function useEnvironment({
169
173
  fiber.useLoader.clear(loader, multiFile ? [files] : files);
170
174
  }
171
175
  renderer.domElement.addEventListener("webglcontextlost", clearGainmapTexture, { once: true });
172
- }, [files, renderer.domElement]);
176
+ }, [extension, files, loader, multiFile, renderer.domElement]);
173
177
  const loaderResult = fiber.useLoader(
174
178
  loader,
175
179
  multiFile ? [files] : files,
@@ -341,15 +345,16 @@ function EnvironmentPortal({
341
345
  preset = void 0,
342
346
  extensions
343
347
  }) {
344
- const gl = fiber.useThree((state) => state.gl);
348
+ const renderer = fiber.useThree((state) => state.renderer);
349
+ const isLegacy = fiber.useThree((state) => state.isLegacy);
345
350
  const defaultScene = fiber.useThree((state) => state.scene);
346
351
  const camera = React__namespace.useRef(null);
347
352
  const [virtualScene] = React__namespace.useState(() => new three.Scene());
348
353
  const fbo = React__namespace.useMemo(() => {
349
- const fbo2 = new three.WebGLCubeRenderTarget(resolution);
354
+ const fbo2 = isLegacy ? new three.WebGLCubeRenderTarget(resolution) : new CubeRenderTarget(resolution);
350
355
  fbo2.texture.type = three.HalfFloatType;
351
356
  return fbo2;
352
- }, [resolution]);
357
+ }, [resolution, isLegacy]);
353
358
  React__namespace.useEffect(() => {
354
359
  return () => {
355
360
  fbo.dispose();
@@ -357,10 +362,10 @@ function EnvironmentPortal({
357
362
  }, [fbo]);
358
363
  React__namespace.useLayoutEffect(() => {
359
364
  if (frames === 1) {
360
- const autoClear = gl.autoClear;
361
- gl.autoClear = true;
362
- camera.current.update(gl, virtualScene);
363
- gl.autoClear = autoClear;
365
+ const autoClear = renderer.autoClear;
366
+ renderer.autoClear = true;
367
+ camera.current.update(renderer, virtualScene);
368
+ renderer.autoClear = autoClear;
364
369
  }
365
370
  return setEnvProps(background, scene, defaultScene, fbo.texture, {
366
371
  backgroundBlurriness: blur ?? backgroundBlurriness,
@@ -369,14 +374,29 @@ function EnvironmentPortal({
369
374
  environmentIntensity,
370
375
  environmentRotation
371
376
  });
372
- }, [children, virtualScene, fbo.texture, scene, defaultScene, background, frames, gl]);
377
+ }, [
378
+ children,
379
+ virtualScene,
380
+ fbo.texture,
381
+ scene,
382
+ defaultScene,
383
+ background,
384
+ frames,
385
+ renderer,
386
+ blur,
387
+ backgroundBlurriness,
388
+ backgroundIntensity,
389
+ backgroundRotation,
390
+ environmentIntensity,
391
+ environmentRotation
392
+ ]);
373
393
  let count = 1;
374
394
  fiber.useFrame(() => {
375
395
  if (frames === Infinity || count < frames) {
376
- const autoClear = gl.autoClear;
377
- gl.autoClear = true;
378
- camera.current.update(gl, virtualScene);
379
- gl.autoClear = autoClear;
396
+ const autoClear = renderer.autoClear;
397
+ renderer.autoClear = true;
398
+ camera.current.update(renderer, virtualScene);
399
+ renderer.autoClear = autoClear;
380
400
  count++;
381
401
  }
382
402
  });
@@ -440,10 +460,9 @@ function Environment(props) {
440
460
  return props.ground ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsxRuntime.jsx(EnvironmentCube, { ...props });
441
461
  }
442
462
 
443
- var __defProp$2 = Object.defineProperty;
444
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
445
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
446
- const act = React__namespace["act"];
463
+ var __defProp = Object.defineProperty;
464
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
465
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
447
466
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
448
467
  function useMutableCallback(fn) {
449
468
  const ref = React__namespace.useRef(fn);
@@ -474,7 +493,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
474
493
  return _a = class extends React__namespace.Component {
475
494
  constructor() {
476
495
  super(...arguments);
477
- __publicField$2(this, "state", { error: false });
496
+ __publicField(this, "state", { error: false });
478
497
  }
479
498
  componentDidCatch(err) {
480
499
  this.props.set(err);
@@ -482,7 +501,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
482
501
  render() {
483
502
  return this.state.error ? null : this.props.children;
484
503
  }
485
- }, __publicField$2(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
504
+ }, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
486
505
  })();
487
506
 
488
507
  const is = {
@@ -619,8 +638,7 @@ function prepare(target, root, type, props) {
619
638
  object,
620
639
  eventCount: 0,
621
640
  handlers: {},
622
- isHidden: false,
623
- deferredRefs: []
641
+ isHidden: false
624
642
  };
625
643
  if (object) object.__r3f = instance;
626
644
  }
@@ -777,6 +795,17 @@ function unregisterVisibility(store, object) {
777
795
  internal.visibilityRegistry.delete(object.uuid);
778
796
  internal.occlusionCache.delete(object);
779
797
  }
798
+ function updateVisibilityHandlers(store, object, handlers) {
799
+ const { internal } = store.getState();
800
+ const entry = internal.visibilityRegistry.get(object.uuid);
801
+ if (!entry) return false;
802
+ entry.handlers = handlers;
803
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
804
+ object.occlusionTest = true;
805
+ enableOcclusion(store);
806
+ }
807
+ return true;
808
+ }
780
809
  function checkVisibility(state) {
781
810
  const { internal, camera } = state;
782
811
  const registry = internal.visibilityRegistry;
@@ -937,9 +966,9 @@ function diffProps(instance, newProps) {
937
966
  const { root, key } = resolve(instance.object, prop);
938
967
  if (root.constructor && root.constructor.length === 0) {
939
968
  const ctor = getMemoizedPrototype(root);
940
- if (!is.und(ctor)) changedProps[key] = ctor[key];
969
+ if (!is.und(ctor)) changedProps[prop] = ctor[key];
941
970
  } else {
942
- changedProps[key] = 0;
971
+ changedProps[prop] = 0;
943
972
  }
944
973
  }
945
974
  return changedProps;
@@ -964,10 +993,7 @@ function applyProps(object, props) {
964
993
  continue;
965
994
  }
966
995
  if (value === void 0) continue;
967
- if (isFromRef(value)) {
968
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
969
- continue;
970
- }
996
+ if (isFromRef(value)) continue;
971
997
  if (isOnce(value)) {
972
998
  if (instance?.appliedOnce?.has(prop)) continue;
973
999
  if (instance) {
@@ -1003,8 +1029,24 @@ function applyProps(object, props) {
1003
1029
  } else if (isVectorLike(target) && is.num(value)) {
1004
1030
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
1005
1031
  else target.set(value);
1032
+ } else if (root instanceof three.ShaderMaterial && key === "uniforms" && is.obj(value)) {
1033
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1034
+ const uniforms = root.uniforms;
1035
+ const nextUniforms = value;
1036
+ for (const name in nextUniforms) {
1037
+ const uniform = nextUniforms[name];
1038
+ const targetUniform = uniforms[name];
1039
+ if (targetUniform) Object.assign(targetUniform, uniform);
1040
+ else {
1041
+ const nextUniform = uniform instanceof three.Uniform ? uniform.clone() : new three.Uniform(uniform.value);
1042
+ uniforms[name] = nextUniform;
1043
+ }
1044
+ }
1006
1045
  } else {
1007
1046
  root[key] = value;
1047
+ if (key.endsWith("Node") && root.isMaterial) {
1048
+ root.needsUpdate = true;
1049
+ }
1008
1050
  if (rootState && rootState.renderer?.outputColorSpace === three.SRGBColorSpace && colorMaps.includes(key) && isTexture(value) && root[key]?.isTexture && // sRGB textures must be RGBA8 since r137 https://github.com/mrdoob/three.js/pull/23129
1009
1051
  root[key].format === three.RGBAFormat && root[key].type === three.UnsignedByteType) {
1010
1052
  root[key].colorSpace = rootState.textureColorSpace;
@@ -1018,6 +1060,9 @@ function applyProps(object, props) {
1018
1060
  if (instance.eventCount && object2.raycast !== null) {
1019
1061
  rootState.internal.interaction.push(object2);
1020
1062
  }
1063
+ }
1064
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1065
+ const object2 = instance.object;
1021
1066
  const root = findInitialRoot(instance);
1022
1067
  const visibilityHandlers = {
1023
1068
  onFramed: instance.handlers.onFramed,
@@ -1025,7 +1070,9 @@ function applyProps(object, props) {
1025
1070
  onVisible: instance.handlers.onVisible
1026
1071
  };
1027
1072
  if (hasVisibilityHandlers(visibilityHandlers)) {
1028
- registerVisibility(root, object2, visibilityHandlers);
1073
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1074
+ registerVisibility(root, object2, visibilityHandlers);
1075
+ }
1029
1076
  } else {
1030
1077
  unregisterVisibility(root, object2);
1031
1078
  }
@@ -1038,38 +1085,95 @@ function applyProps(object, props) {
1038
1085
  return object;
1039
1086
  }
1040
1087
 
1088
+ const DEFAULT_POINTER_ID = 0;
1089
+ const XR_POINTER_ID_START = 1e3;
1090
+ function getPointerState(internal, pointerId) {
1091
+ let state = internal.pointerMap.get(pointerId);
1092
+ if (!state) {
1093
+ state = {
1094
+ hovered: /* @__PURE__ */ new Map(),
1095
+ captured: /* @__PURE__ */ new Map(),
1096
+ initialClick: [0, 0],
1097
+ initialHits: []
1098
+ };
1099
+ internal.pointerMap.set(pointerId, state);
1100
+ }
1101
+ return state;
1102
+ }
1103
+ function getPointerId(event) {
1104
+ return "pointerId" in event ? event.pointerId : DEFAULT_POINTER_ID;
1105
+ }
1041
1106
  function makeId(event) {
1042
1107
  return (event.eventObject || event.object).uuid + "/" + event.index + event.instanceId;
1043
1108
  }
1044
- function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
1045
- const captureData = captures.get(obj);
1109
+ function releaseInternalPointerCapture(internal, obj, pointerId) {
1110
+ const pointerState = internal.pointerMap.get(pointerId);
1111
+ if (!pointerState) return;
1112
+ const captureData = pointerState.captured.get(obj);
1046
1113
  if (captureData) {
1047
- captures.delete(obj);
1048
- if (captures.size === 0) {
1049
- capturedMap.delete(pointerId);
1050
- captureData.target.releasePointerCapture(pointerId);
1114
+ pointerState.captured.delete(obj);
1115
+ captureData.target.releasePointerCapture(pointerId);
1116
+ }
1117
+ }
1118
+ function swapInteractivity(store, object, newObject) {
1119
+ const { internal } = store.getState();
1120
+ for (let i = 0; i < internal.interaction.length; i++) {
1121
+ if (internal.interaction[i] === object) internal.interaction[i] = newObject;
1122
+ }
1123
+ for (const pointerState of internal.pointerMap.values()) {
1124
+ for (let i = 0; i < pointerState.initialHits.length; i++) {
1125
+ if (pointerState.initialHits[i] === object) pointerState.initialHits[i] = newObject;
1126
+ }
1127
+ pointerState.hovered.forEach((value, key) => {
1128
+ if (value.eventObject === object || value.object === object) {
1129
+ pointerState.hovered.delete(key);
1130
+ const next = {
1131
+ ...value,
1132
+ eventObject: value.eventObject === object ? newObject : value.eventObject,
1133
+ object: value.object === object ? newObject : value.object
1134
+ };
1135
+ pointerState.hovered.set(makeId(next), next);
1136
+ }
1137
+ });
1138
+ const captureData = pointerState.captured.get(object);
1139
+ if (captureData) {
1140
+ pointerState.captured.delete(object);
1141
+ pointerState.captured.set(newObject, {
1142
+ ...captureData,
1143
+ intersection: {
1144
+ ...captureData.intersection,
1145
+ object: captureData.intersection.object === object ? newObject : captureData.intersection.object,
1146
+ eventObject: captureData.intersection.eventObject === object ? newObject : captureData.intersection.eventObject
1147
+ }
1148
+ });
1051
1149
  }
1052
1150
  }
1151
+ unregisterVisibility(store, object);
1053
1152
  }
1054
1153
  function removeInteractivity(store, object) {
1055
1154
  const { internal } = store.getState();
1056
1155
  internal.interaction = internal.interaction.filter((o) => o !== object);
1057
- internal.initialHits = internal.initialHits.filter((o) => o !== object);
1058
- internal.hovered.forEach((value, key) => {
1059
- if (value.eventObject === object || value.object === object) {
1060
- internal.hovered.delete(key);
1156
+ for (const [pointerId, pointerState] of internal.pointerMap) {
1157
+ pointerState.initialHits = pointerState.initialHits.filter((o) => o !== object);
1158
+ pointerState.hovered.forEach((value, key) => {
1159
+ if (value.eventObject === object || value.object === object) {
1160
+ pointerState.hovered.delete(key);
1161
+ }
1162
+ });
1163
+ if (pointerState.captured.has(object)) {
1164
+ releaseInternalPointerCapture(internal, object, pointerId);
1061
1165
  }
1062
- });
1063
- internal.capturedMap.forEach((captures, pointerId) => {
1064
- releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
1065
- });
1166
+ }
1066
1167
  unregisterVisibility(store, object);
1067
1168
  }
1068
1169
  function createEvents(store) {
1069
- function calculateDistance(event) {
1170
+ function calculateDistance(event, pointerId) {
1070
1171
  const { internal } = store.getState();
1071
- const dx = event.offsetX - internal.initialClick[0];
1072
- const dy = event.offsetY - internal.initialClick[1];
1172
+ const pointerState = internal.pointerMap.get(pointerId);
1173
+ if (!pointerState) return 0;
1174
+ const [initialX, initialY] = pointerState.initialClick;
1175
+ const dx = event.offsetX - initialX;
1176
+ const dy = event.offsetY - initialY;
1073
1177
  return Math.round(Math.sqrt(dx * dx + dy * dy));
1074
1178
  }
1075
1179
  function filterPointerEvents(objects) {
@@ -1105,6 +1209,15 @@ function createEvents(store) {
1105
1209
  return state2.raycaster.camera ? state2.raycaster.intersectObject(obj, true) : [];
1106
1210
  }
1107
1211
  let hits = eventsObjects.flatMap(handleRaycast).sort((a, b) => {
1212
+ const aInteractivePriority = a.object.userData?.interactivePriority;
1213
+ const bInteractivePriority = b.object.userData?.interactivePriority;
1214
+ if (aInteractivePriority !== void 0 || bInteractivePriority !== void 0) {
1215
+ if (aInteractivePriority !== void 0 && bInteractivePriority === void 0) return -1;
1216
+ if (bInteractivePriority !== void 0 && aInteractivePriority === void 0) return 1;
1217
+ if (aInteractivePriority !== bInteractivePriority) {
1218
+ return (bInteractivePriority ?? 0) - (aInteractivePriority ?? 0);
1219
+ }
1220
+ }
1108
1221
  const aState = getRootState(a.object);
1109
1222
  const bState = getRootState(b.object);
1110
1223
  const aPriority = aState?.events?.priority ?? 1;
@@ -1126,9 +1239,13 @@ function createEvents(store) {
1126
1239
  eventObject = eventObject.parent;
1127
1240
  }
1128
1241
  }
1129
- if ("pointerId" in event && state.internal.capturedMap.has(event.pointerId)) {
1130
- for (const captureData of state.internal.capturedMap.get(event.pointerId).values()) {
1131
- if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
1242
+ if ("pointerId" in event) {
1243
+ const pointerId = event.pointerId;
1244
+ const pointerState = state.internal.pointerMap.get(pointerId);
1245
+ if (pointerState?.captured.size) {
1246
+ for (const captureData of pointerState.captured.values()) {
1247
+ if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
1248
+ }
1132
1249
  }
1133
1250
  }
1134
1251
  return intersections;
@@ -1141,27 +1258,25 @@ function createEvents(store) {
1141
1258
  if (state) {
1142
1259
  const { raycaster, pointer, camera, internal } = state;
1143
1260
  const unprojectedPoint = new three.Vector3(pointer.x, pointer.y, 0).unproject(camera);
1144
- const hasPointerCapture = (id) => internal.capturedMap.get(id)?.has(hit.eventObject) ?? false;
1261
+ const hasPointerCapture = (id) => {
1262
+ const pointerState = internal.pointerMap.get(id);
1263
+ return pointerState?.captured.has(hit.eventObject) ?? false;
1264
+ };
1145
1265
  const setPointerCapture = (id) => {
1146
1266
  const captureData = { intersection: hit, target: event.target };
1147
- if (internal.capturedMap.has(id)) {
1148
- internal.capturedMap.get(id).set(hit.eventObject, captureData);
1149
- } else {
1150
- internal.capturedMap.set(id, /* @__PURE__ */ new Map([[hit.eventObject, captureData]]));
1151
- }
1267
+ const pointerState = getPointerState(internal, id);
1268
+ pointerState.captured.set(hit.eventObject, captureData);
1152
1269
  event.target.setPointerCapture(id);
1153
1270
  };
1154
1271
  const releasePointerCapture = (id) => {
1155
- const captures = internal.capturedMap.get(id);
1156
- if (captures) {
1157
- releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
1158
- }
1272
+ releaseInternalPointerCapture(internal, hit.eventObject, id);
1159
1273
  };
1160
1274
  const extractEventProps = {};
1161
1275
  for (const prop in event) {
1162
1276
  const property = event[prop];
1163
1277
  if (typeof property !== "function") extractEventProps[prop] = property;
1164
1278
  }
1279
+ const eventPointerId = "pointerId" in event ? event.pointerId : void 0;
1165
1280
  const raycastEvent = {
1166
1281
  ...hit,
1167
1282
  ...extractEventProps,
@@ -1172,18 +1287,19 @@ function createEvents(store) {
1172
1287
  unprojectedPoint,
1173
1288
  ray: raycaster.ray,
1174
1289
  camera,
1290
+ pointerId: eventPointerId,
1175
1291
  // Hijack stopPropagation, which just sets a flag
1176
1292
  stopPropagation() {
1177
- const capturesForPointer = "pointerId" in event && internal.capturedMap.get(event.pointerId);
1293
+ const pointerState = eventPointerId !== void 0 ? internal.pointerMap.get(eventPointerId) : void 0;
1178
1294
  if (
1179
1295
  // ...if this pointer hasn't been captured
1180
- !capturesForPointer || // ... or if the hit object is capturing the pointer
1181
- capturesForPointer.has(hit.eventObject)
1296
+ !pointerState?.captured.size || // ... or if the hit object is capturing the pointer
1297
+ pointerState.captured.has(hit.eventObject)
1182
1298
  ) {
1183
1299
  raycastEvent.stopped = localState.stopped = true;
1184
- if (internal.hovered.size && Array.from(internal.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
1300
+ if (pointerState?.hovered.size && Array.from(pointerState.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
1185
1301
  const higher = intersections.slice(0, intersections.indexOf(hit));
1186
- cancelPointer([...higher, hit]);
1302
+ cancelPointer([...higher, hit], eventPointerId);
1187
1303
  }
1188
1304
  }
1189
1305
  },
@@ -1199,15 +1315,18 @@ function createEvents(store) {
1199
1315
  }
1200
1316
  return intersections;
1201
1317
  }
1202
- function cancelPointer(intersections) {
1318
+ function cancelPointer(intersections, pointerId) {
1203
1319
  const { internal } = store.getState();
1204
- for (const hoveredObj of internal.hovered.values()) {
1320
+ const pid = pointerId ?? DEFAULT_POINTER_ID;
1321
+ const pointerState = internal.pointerMap.get(pid);
1322
+ if (!pointerState) return;
1323
+ for (const [hoveredId, hoveredObj] of pointerState.hovered) {
1205
1324
  if (!intersections.length || !intersections.find(
1206
1325
  (hit) => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId
1207
1326
  )) {
1208
1327
  const eventObject = hoveredObj.eventObject;
1209
1328
  const instance = eventObject.__r3f;
1210
- internal.hovered.delete(makeId(hoveredObj));
1329
+ pointerState.hovered.delete(hoveredId);
1211
1330
  if (instance?.eventCount) {
1212
1331
  const handlers = instance.handlers;
1213
1332
  const data = { ...hoveredObj, intersections };
@@ -1236,41 +1355,118 @@ function createEvents(store) {
1236
1355
  instance?.handlers.onDropMissed?.(event);
1237
1356
  }
1238
1357
  }
1358
+ function cleanupPointer(pointerId) {
1359
+ const { internal } = store.getState();
1360
+ const pointerState = internal.pointerMap.get(pointerId);
1361
+ if (pointerState) {
1362
+ for (const [, hoveredObj] of pointerState.hovered) {
1363
+ const eventObject = hoveredObj.eventObject;
1364
+ const instance = eventObject.__r3f;
1365
+ if (instance?.eventCount) {
1366
+ const handlers = instance.handlers;
1367
+ const data = { ...hoveredObj, intersections: [] };
1368
+ handlers.onPointerOut?.(data);
1369
+ handlers.onPointerLeave?.(data);
1370
+ }
1371
+ }
1372
+ internal.pointerMap.delete(pointerId);
1373
+ }
1374
+ internal.pointerDirty.delete(pointerId);
1375
+ }
1376
+ function processDeferredPointer(event, pointerId) {
1377
+ const state = store.getState();
1378
+ const { internal } = state;
1379
+ if (!state.events.enabled) return;
1380
+ const filter = filterPointerEvents;
1381
+ const hits = intersect(event, filter);
1382
+ cancelPointer(hits, pointerId);
1383
+ function onIntersect(data) {
1384
+ const eventObject = data.eventObject;
1385
+ const instance = eventObject.__r3f;
1386
+ if (!instance?.eventCount) return;
1387
+ const handlers = instance.handlers;
1388
+ if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
1389
+ const id = makeId(data);
1390
+ const pointerState = getPointerState(internal, pointerId);
1391
+ const hoveredItem = pointerState.hovered.get(id);
1392
+ if (!hoveredItem) {
1393
+ pointerState.hovered.set(id, data);
1394
+ handlers.onPointerOver?.(data);
1395
+ handlers.onPointerEnter?.(data);
1396
+ } else if (hoveredItem.stopped) {
1397
+ data.stopPropagation();
1398
+ }
1399
+ }
1400
+ handlers.onPointerMove?.(data);
1401
+ }
1402
+ handleIntersects(hits, event, 0, onIntersect);
1403
+ }
1239
1404
  function handlePointer(name) {
1240
1405
  switch (name) {
1241
1406
  case "onPointerLeave":
1242
- case "onPointerCancel":
1243
1407
  case "onDragLeave":
1244
1408
  return () => cancelPointer([]);
1409
+ // Global cancel of these events
1410
+ case "onPointerCancel":
1411
+ return (event) => {
1412
+ const pointerId = getPointerId(event);
1413
+ cleanupPointer(pointerId);
1414
+ };
1245
1415
  case "onLostPointerCapture":
1246
1416
  return (event) => {
1247
1417
  const { internal } = store.getState();
1248
- if ("pointerId" in event && internal.capturedMap.has(event.pointerId)) {
1418
+ const pointerId = getPointerId(event);
1419
+ const pointerState = internal.pointerMap.get(pointerId);
1420
+ if (pointerState?.captured.size) {
1249
1421
  requestAnimationFrame(() => {
1250
- if (internal.capturedMap.has(event.pointerId)) {
1251
- internal.capturedMap.delete(event.pointerId);
1252
- cancelPointer([]);
1422
+ const pointerState2 = internal.pointerMap.get(pointerId);
1423
+ if (pointerState2?.captured.size) {
1424
+ pointerState2.captured.clear();
1253
1425
  }
1426
+ cancelPointer([], pointerId);
1254
1427
  });
1255
1428
  }
1256
1429
  };
1257
1430
  }
1258
1431
  return function handleEvent(event) {
1259
1432
  const state = store.getState();
1260
- const { onPointerMissed, onDragOverMissed, onDropMissed, internal } = state;
1433
+ const { onPointerMissed, onDragOverMissed, onDropMissed, internal, events } = state;
1434
+ const pointerId = getPointerId(event);
1261
1435
  internal.lastEvent.current = event;
1262
- if (!state.events.enabled) return;
1436
+ if (!events.enabled) return;
1263
1437
  const isPointerMove = name === "onPointerMove";
1264
1438
  const isDragOver = name === "onDragOver";
1265
1439
  const isDrop = name === "onDrop";
1266
1440
  const isClickEvent = name === "onClick" || name === "onContextMenu" || name === "onDoubleClick";
1441
+ const isPointerDown = name === "onPointerDown";
1442
+ const isPointerUp = name === "onPointerUp";
1443
+ const isWheel = name === "onWheel";
1444
+ const canDeferRaycasts = events.frameTimedRaycasts && state.frameloop === "always";
1445
+ if (isPointerMove && canDeferRaycasts) {
1446
+ events.compute?.(event, state);
1447
+ internal.pointerDirty.set(pointerId, event);
1448
+ return;
1449
+ }
1450
+ if (isWheel && canDeferRaycasts && !events.alwaysFireOnScroll) {
1451
+ events.compute?.(event, state);
1452
+ internal.pointerDirty.set(pointerId, event);
1453
+ return;
1454
+ }
1455
+ if ((isClickEvent || isPointerDown || isPointerUp) && internal.pointerDirty.has(pointerId)) {
1456
+ const deferredEvent = internal.pointerDirty.get(pointerId);
1457
+ internal.pointerDirty.delete(pointerId);
1458
+ processDeferredPointer(deferredEvent, pointerId);
1459
+ }
1267
1460
  const filter = isPointerMove || isDragOver || isDrop ? filterPointerEvents : void 0;
1268
1461
  const hits = intersect(event, filter);
1269
- const delta = isClickEvent ? calculateDistance(event) : 0;
1270
- if (name === "onPointerDown") {
1271
- internal.initialClick = [event.offsetX, event.offsetY];
1272
- internal.initialHits = hits.map((hit) => hit.eventObject);
1273
- }
1462
+ const delta = isClickEvent ? calculateDistance(event, pointerId) : 0;
1463
+ if (isPointerDown) {
1464
+ const pointerState2 = getPointerState(internal, pointerId);
1465
+ pointerState2.initialClick = [event.offsetX, event.offsetY];
1466
+ pointerState2.initialHits = hits.map((hit) => hit.eventObject);
1467
+ }
1468
+ const pointerState = internal.pointerMap.get(pointerId);
1469
+ const initialHits = pointerState?.initialHits ?? [];
1274
1470
  if (isClickEvent && !hits.length) {
1275
1471
  if (delta <= 2) {
1276
1472
  pointerMissed(event, internal.interaction);
@@ -1285,7 +1481,9 @@ function createEvents(store) {
1285
1481
  dropMissed(event, internal.interaction);
1286
1482
  if (onDropMissed) onDropMissed(event);
1287
1483
  }
1288
- if (isPointerMove || isDragOver) cancelPointer(hits);
1484
+ if (isPointerMove || isDragOver) {
1485
+ cancelPointer(hits, pointerId);
1486
+ }
1289
1487
  function onIntersect(data) {
1290
1488
  const eventObject = data.eventObject;
1291
1489
  const instance = eventObject.__r3f;
@@ -1294,9 +1492,10 @@ function createEvents(store) {
1294
1492
  if (isPointerMove) {
1295
1493
  if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
1296
1494
  const id = makeId(data);
1297
- const hoveredItem = internal.hovered.get(id);
1495
+ const pointerState2 = getPointerState(internal, pointerId);
1496
+ const hoveredItem = pointerState2.hovered.get(id);
1298
1497
  if (!hoveredItem) {
1299
- internal.hovered.set(id, data);
1498
+ pointerState2.hovered.set(id, data);
1300
1499
  handlers.onPointerOver?.(data);
1301
1500
  handlers.onPointerEnter?.(data);
1302
1501
  } else if (hoveredItem.stopped) {
@@ -1306,9 +1505,10 @@ function createEvents(store) {
1306
1505
  handlers.onPointerMove?.(data);
1307
1506
  } else if (isDragOver) {
1308
1507
  const id = makeId(data);
1309
- const hoveredItem = internal.hovered.get(id);
1508
+ const pointerState2 = getPointerState(internal, pointerId);
1509
+ const hoveredItem = pointerState2.hovered.get(id);
1310
1510
  if (!hoveredItem) {
1311
- internal.hovered.set(id, data);
1511
+ pointerState2.hovered.set(id, data);
1312
1512
  handlers.onDragOverEnter?.(data);
1313
1513
  } else if (hoveredItem.stopped) {
1314
1514
  data.stopPropagation();
@@ -1319,18 +1519,18 @@ function createEvents(store) {
1319
1519
  } else {
1320
1520
  const handler = handlers[name];
1321
1521
  if (handler) {
1322
- if (!isClickEvent || internal.initialHits.includes(eventObject)) {
1522
+ if (!isClickEvent || initialHits.includes(eventObject)) {
1323
1523
  pointerMissed(
1324
1524
  event,
1325
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1525
+ internal.interaction.filter((object) => !initialHits.includes(object))
1326
1526
  );
1327
1527
  handler(data);
1328
1528
  }
1329
1529
  } else {
1330
- if (isClickEvent && internal.initialHits.includes(eventObject)) {
1530
+ if (isClickEvent && initialHits.includes(eventObject)) {
1331
1531
  pointerMissed(
1332
1532
  event,
1333
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1533
+ internal.interaction.filter((object) => !initialHits.includes(object))
1334
1534
  );
1335
1535
  }
1336
1536
  }
@@ -1339,7 +1539,15 @@ function createEvents(store) {
1339
1539
  handleIntersects(hits, event, delta, onIntersect);
1340
1540
  };
1341
1541
  }
1342
- return { handlePointer };
1542
+ function flushDeferredPointers() {
1543
+ const { internal, events } = store.getState();
1544
+ if (!events.frameTimedRaycasts) return;
1545
+ for (const [pointerId, event] of internal.pointerDirty) {
1546
+ processDeferredPointer(event, pointerId);
1547
+ }
1548
+ internal.pointerDirty.clear();
1549
+ }
1550
+ return { handlePointer, flushDeferredPointers, processDeferredPointer };
1343
1551
  }
1344
1552
  const DOM_EVENTS = {
1345
1553
  onClick: ["click", false],
@@ -1358,10 +1566,15 @@ const DOM_EVENTS = {
1358
1566
  onLostPointerCapture: ["lostpointercapture", true]
1359
1567
  };
1360
1568
  function createPointerEvents(store) {
1361
- const { handlePointer } = createEvents(store);
1569
+ const { handlePointer, flushDeferredPointers, processDeferredPointer } = createEvents(store);
1570
+ let nextXRPointerId = XR_POINTER_ID_START;
1571
+ const xrPointers = /* @__PURE__ */ new Map();
1362
1572
  return {
1363
1573
  priority: 1,
1364
1574
  enabled: true,
1575
+ frameTimedRaycasts: true,
1576
+ alwaysFireOnScroll: true,
1577
+ updateOnFrame: false,
1365
1578
  compute(event, state) {
1366
1579
  state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1);
1367
1580
  state.raycaster.setFromCamera(state.pointer, state.camera);
@@ -1371,11 +1584,33 @@ function createPointerEvents(store) {
1371
1584
  (acc, key) => ({ ...acc, [key]: handlePointer(key) }),
1372
1585
  {}
1373
1586
  ),
1374
- update: () => {
1587
+ update: (pointerId) => {
1588
+ const { events, internal } = store.getState();
1589
+ if (!events.handlers) return;
1590
+ if (pointerId !== void 0) {
1591
+ const event = internal.pointerDirty.get(pointerId);
1592
+ if (event) {
1593
+ internal.pointerDirty.delete(pointerId);
1594
+ processDeferredPointer(event, pointerId);
1595
+ } else if (internal.lastEvent?.current) {
1596
+ processDeferredPointer(internal.lastEvent.current, pointerId);
1597
+ }
1598
+ } else {
1599
+ flushDeferredPointers();
1600
+ if (internal.lastEvent?.current) {
1601
+ events.handlers.onPointerMove(internal.lastEvent.current);
1602
+ }
1603
+ }
1604
+ },
1605
+ flush: () => {
1375
1606
  const { events, internal } = store.getState();
1376
- if (internal.lastEvent?.current && events.handlers) events.handlers.onPointerMove(internal.lastEvent.current);
1607
+ flushDeferredPointers();
1608
+ if (events.updateOnFrame && internal.lastEvent?.current && events.handlers) {
1609
+ events.handlers.onPointerMove(internal.lastEvent.current);
1610
+ }
1377
1611
  },
1378
1612
  connect: (target) => {
1613
+ if (!target) return;
1379
1614
  const { set, events } = store.getState();
1380
1615
  events.disconnect?.();
1381
1616
  set((state) => ({ events: { ...state.events, connected: target } }));
@@ -1399,6 +1634,33 @@ function createPointerEvents(store) {
1399
1634
  }
1400
1635
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1401
1636
  }
1637
+ },
1638
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1639
+ registerPointer: (config) => {
1640
+ const pointerId = nextXRPointerId++;
1641
+ xrPointers.set(pointerId, config);
1642
+ const { internal } = store.getState();
1643
+ getPointerState(internal, pointerId);
1644
+ return pointerId;
1645
+ },
1646
+ unregisterPointer: (pointerId) => {
1647
+ xrPointers.delete(pointerId);
1648
+ const { internal } = store.getState();
1649
+ const pointerState = internal.pointerMap.get(pointerId);
1650
+ if (pointerState) {
1651
+ for (const [, hoveredObj] of pointerState.hovered) {
1652
+ const eventObject = hoveredObj.eventObject;
1653
+ const instance = eventObject.__r3f;
1654
+ if (instance?.eventCount) {
1655
+ const handlers = instance.handlers;
1656
+ const data = { ...hoveredObj, intersections: [] };
1657
+ handlers.onPointerOut?.(data);
1658
+ handlers.onPointerLeave?.(data);
1659
+ }
1660
+ }
1661
+ internal.pointerMap.delete(pointerId);
1662
+ }
1663
+ internal.pointerDirty.delete(pointerId);
1402
1664
  }
1403
1665
  };
1404
1666
  }
@@ -1460,1036 +1722,11 @@ function notifyAlpha({ message, link }) {
1460
1722
  }
1461
1723
  }
1462
1724
 
1463
- var __defProp$1 = Object.defineProperty;
1464
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1465
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1466
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1467
- class PhaseGraph {
1468
- constructor() {
1469
- /** Ordered list of phase nodes */
1470
- __publicField$1(this, "phases", []);
1471
- /** Quick lookup by name */
1472
- __publicField$1(this, "phaseMap", /* @__PURE__ */ new Map());
1473
- /** Cached ordered names (invalidated on changes) */
1474
- __publicField$1(this, "orderedNamesCache", null);
1475
- this.initializeDefaultPhases();
1476
- }
1477
- //* Initialization --------------------------------
1478
- initializeDefaultPhases() {
1479
- for (const name of DEFAULT_PHASES) {
1480
- const node = { name, isAutoGenerated: false };
1481
- this.phases.push(node);
1482
- this.phaseMap.set(name, node);
1483
- }
1484
- this.invalidateCache();
1485
- }
1486
- //* Public API --------------------------------
1487
- /**
1488
- * Add a named phase to the graph
1489
- * @param name - Phase name (must be unique)
1490
- * @param options - Position options (before or after another phase)
1491
- */
1492
- addPhase(name, options = {}) {
1493
- if (this.phaseMap.has(name)) {
1494
- console.warn(`[useFrame] Phase "${name}" already exists`);
1495
- return;
1496
- }
1497
- const { before, after } = options;
1498
- const node = { name, isAutoGenerated: false };
1499
- let insertIndex = this.phases.length;
1500
- const targetIndex = this.getPhaseIndex(before ?? after);
1501
- if (targetIndex !== -1) {
1502
- insertIndex = before ? targetIndex : targetIndex + 1;
1503
- } else {
1504
- const constraintType = before ? "before" : "after";
1505
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1506
- }
1507
- this.phases.splice(insertIndex, 0, node);
1508
- this.phaseMap.set(name, node);
1509
- this.invalidateCache();
1510
- }
1511
- /**
1512
- * Get ordered list of phase names
1513
- */
1514
- getOrderedPhases() {
1515
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1516
- return this.orderedNamesCache;
1517
- }
1518
- /**
1519
- * Check if a phase exists
1520
- */
1521
- hasPhase(name) {
1522
- return this.phaseMap.has(name);
1523
- }
1524
- /**
1525
- * Get the index of a phase (-1 if not found)
1526
- */
1527
- getPhaseIndex(name) {
1528
- if (!name) return -1;
1529
- return this.phases.findIndex((p) => p.name === name);
1530
- }
1531
- /**
1532
- * Ensure a phase exists, creating an auto-generated one if needed.
1533
- * Used for resolving before/after constraints.
1534
- *
1535
- * @param name - The phase name to ensure exists
1536
- * @returns The phase name (may be auto-generated like 'before:render')
1537
- */
1538
- ensurePhase(name) {
1539
- if (this.phaseMap.has(name)) return name;
1540
- const node = { name, isAutoGenerated: true };
1541
- this.phases.push(node);
1542
- this.phaseMap.set(name, node);
1543
- this.invalidateCache();
1544
- return name;
1545
- }
1546
- /**
1547
- * Resolve where a job with before/after constraints should go.
1548
- * Creates auto-generated phases if needed.
1549
- *
1550
- * @param before - Phase(s) to run before
1551
- * @param after - Phase(s) to run after
1552
- * @returns The resolved phase name
1553
- */
1554
- resolveConstraintPhase(before, after) {
1555
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1556
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1557
- if (beforeArr.length > 0) {
1558
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1559
- }
1560
- if (afterArr.length > 0) {
1561
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1562
- }
1563
- return "update";
1564
- }
1565
- /**
1566
- * Ensure an auto-generated phase exists relative to a target phase.
1567
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1568
- *
1569
- * @param target - The target phase name to position relative to
1570
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1571
- * @param offset - Insertion offset (0 for before, 1 for after)
1572
- * @returns The auto-generated phase name
1573
- */
1574
- ensureAutoPhase(target, prefix, offset) {
1575
- const autoName = `${prefix}:${target}`;
1576
- if (this.phaseMap.has(autoName)) return autoName;
1577
- const node = { name: autoName, isAutoGenerated: true };
1578
- const targetIndex = this.getPhaseIndex(target);
1579
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1580
- else this.phases.push(node);
1581
- this.phaseMap.set(autoName, node);
1582
- this.invalidateCache();
1583
- return autoName;
1584
- }
1585
- // Internal --------------------------------
1586
- invalidateCache() {
1587
- this.orderedNamesCache = null;
1588
- }
1589
- }
1590
-
1591
- function rebuildSortedJobs(jobs, phaseGraph) {
1592
- const orderedPhases = phaseGraph.getOrderedPhases();
1593
- const buckets = /* @__PURE__ */ new Map();
1594
- for (const phase of orderedPhases) {
1595
- buckets.set(phase, []);
1596
- }
1597
- for (const job of jobs.values()) {
1598
- if (!job.enabled) continue;
1599
- let bucket = buckets.get(job.phase);
1600
- if (!bucket) {
1601
- bucket = [];
1602
- buckets.set(job.phase, bucket);
1603
- }
1604
- bucket.push(job);
1605
- }
1606
- const sortedBuckets = [];
1607
- for (const phase of orderedPhases) {
1608
- const bucket = buckets.get(phase);
1609
- if (!bucket || bucket.length === 0) continue;
1610
- bucket.sort((a, b) => {
1611
- if (a.priority !== b.priority) return b.priority - a.priority;
1612
- return a.index - b.index;
1613
- });
1614
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1615
- }
1616
- for (const [phase, bucket] of buckets) {
1617
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1618
- bucket.sort((a, b) => {
1619
- if (a.priority !== b.priority) return b.priority - a.priority;
1620
- return a.index - b.index;
1621
- });
1622
- sortedBuckets.push(bucket);
1623
- }
1624
- }
1625
- return sortedBuckets.flat();
1626
- }
1627
- function hasCrossJobConstraints(bucket) {
1628
- const jobIds = new Set(bucket.map((j) => j.id));
1629
- for (const job of bucket) {
1630
- for (const ref of job.before) {
1631
- if (jobIds.has(ref)) return true;
1632
- }
1633
- for (const ref of job.after) {
1634
- if (jobIds.has(ref)) return true;
1635
- }
1636
- }
1637
- return false;
1638
- }
1639
- function topologicalSort(jobs) {
1640
- const n = jobs.length;
1641
- if (n <= 1) return jobs;
1642
- const jobMap = /* @__PURE__ */ new Map();
1643
- const inDegree = /* @__PURE__ */ new Map();
1644
- const adjacency = /* @__PURE__ */ new Map();
1645
- for (const job of jobs) {
1646
- jobMap.set(job.id, job);
1647
- inDegree.set(job.id, 0);
1648
- adjacency.set(job.id, []);
1649
- }
1650
- for (const job of jobs) {
1651
- for (const ref of job.before) {
1652
- if (jobMap.has(ref)) {
1653
- adjacency.get(job.id).push(ref);
1654
- inDegree.set(ref, inDegree.get(ref) + 1);
1655
- }
1656
- }
1657
- for (const ref of job.after) {
1658
- if (jobMap.has(ref)) {
1659
- adjacency.get(ref).push(job.id);
1660
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1661
- }
1662
- }
1663
- }
1664
- const queue = [];
1665
- for (const job of jobs) {
1666
- if (inDegree.get(job.id) === 0) {
1667
- queue.push(job);
1668
- }
1669
- }
1670
- queue.sort((a, b) => {
1671
- if (a.priority !== b.priority) return b.priority - a.priority;
1672
- return a.index - b.index;
1673
- });
1674
- const result = [];
1675
- while (queue.length > 0) {
1676
- const job = queue.shift();
1677
- result.push(job);
1678
- const neighbors = adjacency.get(job.id) || [];
1679
- for (const neighborId of neighbors) {
1680
- const newDegree = inDegree.get(neighborId) - 1;
1681
- inDegree.set(neighborId, newDegree);
1682
- if (newDegree === 0) {
1683
- const neighbor = jobMap.get(neighborId);
1684
- insertSorted(queue, neighbor);
1685
- }
1686
- }
1687
- }
1688
- if (result.length !== n) {
1689
- console.warn("[useFrame] Circular dependency detected in job constraints");
1690
- const resultIds = new Set(result.map((j) => j.id));
1691
- for (const job of jobs) {
1692
- if (!resultIds.has(job.id)) result.push(job);
1693
- }
1694
- }
1695
- return result;
1696
- }
1697
- function insertSorted(arr, job) {
1698
- let i = 0;
1699
- while (i < arr.length) {
1700
- const cmp = arr[i];
1701
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1702
- break;
1703
- }
1704
- i++;
1705
- }
1706
- arr.splice(i, 0, job);
1707
- }
1708
-
1709
- function shouldRun(job, now) {
1710
- if (!job.enabled) return false;
1711
- if (!job.fps) return true;
1712
- const minInterval = 1e3 / job.fps;
1713
- const lastRun = job.lastRun ?? 0;
1714
- const elapsed = now - lastRun;
1715
- if (elapsed < minInterval) return false;
1716
- if (job.drop) {
1717
- job.lastRun = now;
1718
- } else {
1719
- const steps = Math.floor(elapsed / minInterval);
1720
- job.lastRun = lastRun + steps * minInterval;
1721
- if (job.lastRun < now - minInterval) {
1722
- job.lastRun = now;
1723
- }
1724
- }
1725
- return true;
1726
- }
1727
- function resetJobTiming(job) {
1728
- job.lastRun = void 0;
1729
- }
1730
-
1731
- var __defProp = Object.defineProperty;
1732
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1733
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1734
- const hmrData = (() => {
1735
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1736
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1737
- try {
1738
- return (0, eval)("import.meta.hot");
1739
- } catch {
1740
- return void 0;
1741
- }
1742
- })();
1743
- const _Scheduler = class _Scheduler {
1744
- //* Constructor ================================
1745
- constructor() {
1746
- //* Critical State ================================
1747
- __publicField(this, "roots", /* @__PURE__ */ new Map());
1748
- __publicField(this, "phaseGraph");
1749
- __publicField(this, "loopState", {
1750
- running: false,
1751
- rafHandle: null,
1752
- lastTime: null,
1753
- // null = uninitialized, 0+ = valid timestamp
1754
- frameCount: 0,
1755
- elapsedTime: 0,
1756
- createdAt: performance.now()
1757
- });
1758
- __publicField(this, "stoppedTime", 0);
1759
- //* Private State ================================
1760
- __publicField(this, "nextRootIndex", 0);
1761
- __publicField(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1762
- __publicField(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1763
- __publicField(this, "nextGlobalIndex", 0);
1764
- __publicField(this, "idleCallbacks", /* @__PURE__ */ new Set());
1765
- __publicField(this, "nextJobIndex", 0);
1766
- __publicField(this, "jobStateListeners", /* @__PURE__ */ new Map());
1767
- __publicField(this, "pendingFrames", 0);
1768
- __publicField(this, "_frameloop", "always");
1769
- //* Independent Mode & Error Handling State ================================
1770
- __publicField(this, "_independent", false);
1771
- __publicField(this, "errorHandler", null);
1772
- __publicField(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1773
- //* Core Loop Execution Methods ================================
1774
- /**
1775
- * Main RAF loop callback.
1776
- * Executes frame, handles demand mode, and schedules next frame.
1777
- * @param {number} timestamp - RAF timestamp in milliseconds
1778
- * @returns {void}
1779
- * @private
1780
- */
1781
- __publicField(this, "loop", (timestamp) => {
1782
- if (!this.loopState.running) return;
1783
- this.executeFrame(timestamp);
1784
- if (this._frameloop === "demand") {
1785
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1786
- if (this.pendingFrames === 0) {
1787
- this.notifyIdle(timestamp);
1788
- return this.stop();
1789
- }
1790
- }
1791
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1792
- });
1793
- this.phaseGraph = new PhaseGraph();
1794
- }
1795
- static get instance() {
1796
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1797
- }
1798
- static set instance(value) {
1799
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1800
- }
1801
- /**
1802
- * Get the global scheduler instance (creates if doesn't exist).
1803
- * Uses HMR data to preserve instance across hot reloads.
1804
- * @returns {Scheduler} The singleton scheduler instance
1805
- */
1806
- static get() {
1807
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1808
- _Scheduler.instance = hmrData.data.scheduler;
1809
- }
1810
- if (!_Scheduler.instance) {
1811
- _Scheduler.instance = new _Scheduler();
1812
- if (hmrData?.data) {
1813
- hmrData.data.scheduler = _Scheduler.instance;
1814
- }
1815
- }
1816
- return _Scheduler.instance;
1817
- }
1818
- /**
1819
- * Reset the singleton instance. Stops the loop and clears all state.
1820
- * Primarily used for testing to ensure clean state between tests.
1821
- * @returns {void}
1822
- */
1823
- static reset() {
1824
- if (_Scheduler.instance) {
1825
- _Scheduler.instance.stop();
1826
- _Scheduler.instance = null;
1827
- }
1828
- if (hmrData?.data) {
1829
- hmrData.data.scheduler = null;
1830
- }
1831
- }
1832
- //* Getters & Setters ================================
1833
- get phases() {
1834
- return this.phaseGraph.getOrderedPhases();
1835
- }
1836
- get frameloop() {
1837
- return this._frameloop;
1838
- }
1839
- set frameloop(mode) {
1840
- if (this._frameloop === mode) return;
1841
- const wasAlways = this._frameloop === "always";
1842
- this._frameloop = mode;
1843
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
1844
- else if (mode !== "always" && wasAlways) this.stop();
1845
- }
1846
- get isRunning() {
1847
- return this.loopState.running;
1848
- }
1849
- get isReady() {
1850
- return this.roots.size > 0;
1851
- }
1852
- get independent() {
1853
- return this._independent;
1854
- }
1855
- set independent(value) {
1856
- this._independent = value;
1857
- if (value) this.ensureDefaultRoot();
1858
- }
1859
- //* Root Management Methods ================================
1860
- /**
1861
- * Register a root (Canvas) with the scheduler.
1862
- * The first root to register starts the RAF loop (if frameloop='always').
1863
- * @param {string} id - Unique identifier for this root
1864
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
1865
- * @returns {() => void} Unsubscribe function to remove this root
1866
- */
1867
- registerRoot(id, options = {}) {
1868
- if (this.roots.has(id)) {
1869
- console.warn(`[Scheduler] Root "${id}" already registered`);
1870
- return () => this.unregisterRoot(id);
1871
- }
1872
- const entry = {
1873
- id,
1874
- getState: options.getState ?? (() => ({})),
1875
- jobs: /* @__PURE__ */ new Map(),
1876
- sortedJobs: [],
1877
- needsRebuild: false
1878
- };
1879
- if (options.onError) {
1880
- this.errorHandler = options.onError;
1881
- }
1882
- this.roots.set(id, entry);
1883
- if (this.roots.size === 1) {
1884
- this.notifyRootReady();
1885
- if (this._frameloop === "always") this.start();
1886
- }
1887
- return () => this.unregisterRoot(id);
1888
- }
1889
- /**
1890
- * Unregister a root from the scheduler.
1891
- * Cleans up all job state listeners for this root's jobs.
1892
- * The last root to unregister stops the RAF loop.
1893
- * @param {string} id - The root ID to unregister
1894
- * @returns {void}
1895
- */
1896
- unregisterRoot(id) {
1897
- const root = this.roots.get(id);
1898
- if (!root) return;
1899
- for (const jobId of root.jobs.keys()) {
1900
- this.jobStateListeners.delete(jobId);
1901
- }
1902
- this.roots.delete(id);
1903
- if (this.roots.size === 0) {
1904
- this.stop();
1905
- this.errorHandler = null;
1906
- }
1907
- }
1908
- /**
1909
- * Subscribe to be notified when a root becomes available.
1910
- * Fires immediately if a root already exists.
1911
- * @param {() => void} callback - Function called when first root registers
1912
- * @returns {() => void} Unsubscribe function
1913
- */
1914
- onRootReady(callback) {
1915
- if (this.roots.size > 0) {
1916
- callback();
1917
- return () => {
1918
- };
1919
- }
1920
- this.rootReadyCallbacks.add(callback);
1921
- return () => this.rootReadyCallbacks.delete(callback);
1922
- }
1923
- /**
1924
- * Notify all registered root-ready callbacks.
1925
- * Called when the first root registers.
1926
- * @returns {void}
1927
- * @private
1928
- */
1929
- notifyRootReady() {
1930
- for (const cb of this.rootReadyCallbacks) {
1931
- try {
1932
- cb();
1933
- } catch (error) {
1934
- console.error("[Scheduler] Error in root-ready callback:", error);
1935
- }
1936
- }
1937
- this.rootReadyCallbacks.clear();
1938
- }
1939
- /**
1940
- * Ensure a default root exists for independent mode.
1941
- * Creates a minimal root with no state provider.
1942
- * @returns {void}
1943
- * @private
1944
- */
1945
- ensureDefaultRoot() {
1946
- if (!this.roots.has("__default__")) {
1947
- this.registerRoot("__default__");
1948
- }
1949
- }
1950
- /**
1951
- * Trigger error handling for job errors.
1952
- * Uses the bound error handler if available, otherwise logs to console.
1953
- * @param {Error} error - The error to handle
1954
- * @returns {void}
1955
- */
1956
- triggerError(error) {
1957
- if (this.errorHandler) this.errorHandler(error);
1958
- else console.error("[Scheduler]", error);
1959
- }
1960
- //* Phase Management Methods ================================
1961
- /**
1962
- * Add a named phase to the scheduler's execution order.
1963
- * Marks all roots for rebuild to incorporate the new phase.
1964
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
1965
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
1966
- * @returns {void}
1967
- * @example
1968
- * scheduler.addPhase('physics', { before: 'update' });
1969
- * scheduler.addPhase('postprocess', { after: 'render' });
1970
- */
1971
- addPhase(name, options) {
1972
- this.phaseGraph.addPhase(name, options);
1973
- for (const root of this.roots.values()) {
1974
- root.needsRebuild = true;
1975
- }
1976
- }
1977
- /**
1978
- * Check if a phase exists in the scheduler.
1979
- * @param {string} name - The phase name to check
1980
- * @returns {boolean} True if the phase exists
1981
- */
1982
- hasPhase(name) {
1983
- return this.phaseGraph.hasPhase(name);
1984
- }
1985
- //* Global Job Registration Methods (Deprecated APIs) ================================
1986
- /**
1987
- * Register a global job that runs once per frame (not per-root).
1988
- * Used internally by deprecated addEffect/addAfterEffect APIs.
1989
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
1990
- * @param {string} id - Unique identifier for this global job
1991
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
1992
- * @returns {() => void} Unsubscribe function to remove this global job
1993
- * @deprecated Use useFrame with phases instead
1994
- */
1995
- registerGlobal(phase, id, callback) {
1996
- const job = { id, callback };
1997
- if (phase === "before") {
1998
- this.globalBeforeJobs.set(id, job);
1999
- } else {
2000
- this.globalAfterJobs.set(id, job);
2001
- }
2002
- return () => {
2003
- if (phase === "before") this.globalBeforeJobs.delete(id);
2004
- else this.globalAfterJobs.delete(id);
2005
- };
2006
- }
2007
- //* Idle Callback Methods (Deprecated API) ================================
2008
- /**
2009
- * Register an idle callback that fires when the loop stops.
2010
- * Used internally by deprecated addTail API.
2011
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
2012
- * @returns {() => void} Unsubscribe function to remove this idle callback
2013
- * @deprecated Use demand mode with invalidate() instead
2014
- */
2015
- onIdle(callback) {
2016
- this.idleCallbacks.add(callback);
2017
- return () => this.idleCallbacks.delete(callback);
2018
- }
2019
- /**
2020
- * Notify all registered idle callbacks.
2021
- * Called when the loop stops in demand mode.
2022
- * @param {number} timestamp - The RAF timestamp when idle occurred
2023
- * @returns {void}
2024
- * @private
2025
- */
2026
- notifyIdle(timestamp) {
2027
- for (const cb of this.idleCallbacks) {
2028
- try {
2029
- cb(timestamp);
2030
- } catch (error) {
2031
- console.error("[Scheduler] Error in idle callback:", error);
2032
- }
2033
- }
2034
- }
2035
- //* Job Registration & Management Methods ================================
2036
- /**
2037
- * Register a job (frame callback) with a specific root.
2038
- * This is the core registration method used by useFrame internally.
2039
- * @param {FrameNextCallback} callback - The function to call each frame
2040
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2041
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2042
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2043
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
2044
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2045
- * @param {number} [options.fps] - FPS throttle limit
2046
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
2047
- * @param {boolean} [options.enabled] - Whether job is active (default true)
2048
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2049
- * @returns {() => void} Unsubscribe function to remove this job
2050
- */
2051
- register(callback, options = {}) {
2052
- const rootId = options.rootId;
2053
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2054
- if (!root) {
2055
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2056
- return () => {
2057
- };
2058
- }
2059
- const id = options.id ?? this.generateJobId();
2060
- let phase = options.phase ?? "update";
2061
- if (!options.phase && (options.before || options.after)) {
2062
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2063
- }
2064
- const before = this.normalizeConstraints(options.before);
2065
- const after = this.normalizeConstraints(options.after);
2066
- const job = {
2067
- id,
2068
- callback,
2069
- phase,
2070
- before,
2071
- after,
2072
- priority: options.priority ?? 0,
2073
- index: this.nextJobIndex++,
2074
- fps: options.fps,
2075
- drop: options.drop ?? true,
2076
- enabled: options.enabled ?? true,
2077
- system: options.system ?? false
2078
- };
2079
- if (root.jobs.has(id)) {
2080
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2081
- }
2082
- root.jobs.set(id, job);
2083
- root.needsRebuild = true;
2084
- return () => this.unregister(id, root.id);
2085
- }
2086
- /**
2087
- * Unregister a job by its ID.
2088
- * Searches all roots if rootId is not provided.
2089
- * @param {string} id - The job ID to unregister
2090
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2091
- * @returns {void}
2092
- */
2093
- unregister(id, rootId) {
2094
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2095
- if (root?.jobs.delete(id)) {
2096
- root.needsRebuild = true;
2097
- this.jobStateListeners.delete(id);
2098
- }
2099
- }
2100
- /**
2101
- * Update a job's options dynamically.
2102
- * Searches all roots to find the job by ID.
2103
- * Phase/constraint changes trigger a rebuild of the sorted job list.
2104
- * @param {string} id - The job ID to update
2105
- * @param {Partial<JobOptions>} options - The options to update
2106
- * @returns {void}
2107
- */
2108
- updateJob(id, options) {
2109
- let job;
2110
- let root;
2111
- for (const r of this.roots.values()) {
2112
- job = r.jobs.get(id);
2113
- if (job) {
2114
- root = r;
2115
- break;
2116
- }
2117
- }
2118
- if (!job || !root) return;
2119
- if (options.priority !== void 0) job.priority = options.priority;
2120
- if (options.fps !== void 0) job.fps = options.fps;
2121
- if (options.drop !== void 0) job.drop = options.drop;
2122
- if (options.enabled !== void 0) {
2123
- const wasEnabled = job.enabled;
2124
- job.enabled = options.enabled;
2125
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2126
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2127
- }
2128
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2129
- if (options.phase) job.phase = options.phase;
2130
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2131
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2132
- root.needsRebuild = true;
2133
- }
2134
- }
2135
- //* Job State Management Methods ================================
2136
- /**
2137
- * Check if a job is currently paused (disabled).
2138
- * @param {string} id - The job ID to check
2139
- * @returns {boolean} True if the job exists and is paused
2140
- */
2141
- isJobPaused(id) {
2142
- for (const root of this.roots.values()) {
2143
- const job = root.jobs.get(id);
2144
- if (job) return !job.enabled;
2145
- }
2146
- return false;
2147
- }
2148
- /**
2149
- * Subscribe to state changes for a specific job.
2150
- * Listener is called when job is paused or resumed.
2151
- * @param {string} id - The job ID to subscribe to
2152
- * @param {() => void} listener - Callback invoked on state changes
2153
- * @returns {() => void} Unsubscribe function
2154
- */
2155
- subscribeJobState(id, listener) {
2156
- if (!this.jobStateListeners.has(id)) {
2157
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2158
- }
2159
- this.jobStateListeners.get(id).add(listener);
2160
- return () => {
2161
- this.jobStateListeners.get(id)?.delete(listener);
2162
- if (this.jobStateListeners.get(id)?.size === 0) {
2163
- this.jobStateListeners.delete(id);
2164
- }
2165
- };
2166
- }
2167
- /**
2168
- * Notify all listeners that a job's state has changed.
2169
- * @param {string} id - The job ID that changed
2170
- * @returns {void}
2171
- * @private
2172
- */
2173
- notifyJobStateChange(id) {
2174
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2175
- }
2176
- /**
2177
- * Pause a job by ID (sets enabled=false).
2178
- * Notifies any subscribed state listeners.
2179
- * @param {string} id - The job ID to pause
2180
- * @returns {void}
2181
- */
2182
- pauseJob(id) {
2183
- this.updateJob(id, { enabled: false });
2184
- this.notifyJobStateChange(id);
2185
- }
2186
- /**
2187
- * Resume a paused job by ID (sets enabled=true).
2188
- * Resets job timing to prevent frame accumulation.
2189
- * Notifies any subscribed state listeners.
2190
- * @param {string} id - The job ID to resume
2191
- * @returns {void}
2192
- */
2193
- resumeJob(id) {
2194
- this.updateJob(id, { enabled: true });
2195
- this.notifyJobStateChange(id);
2196
- }
2197
- //* Frame Loop Control Methods ================================
2198
- /**
2199
- * Start the requestAnimationFrame loop.
2200
- * Resets timing state (elapsedTime, frameCount) on start.
2201
- * No-op if already running.
2202
- * @returns {void}
2203
- */
2204
- start() {
2205
- if (this.loopState.running) return;
2206
- const { elapsedTime, createdAt } = this.loopState;
2207
- let adjustedCreated = 0;
2208
- if (this.stoppedTime > 0) {
2209
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2210
- this.stoppedTime = 0;
2211
- }
2212
- Object.assign(this.loopState, {
2213
- running: true,
2214
- elapsedTime: elapsedTime ?? 0,
2215
- lastTime: performance.now(),
2216
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2217
- frameCount: 0,
2218
- rafHandle: requestAnimationFrame(this.loop)
2219
- });
2220
- }
2221
- /**
2222
- * Stop the requestAnimationFrame loop.
2223
- * Cancels any pending RAF callback.
2224
- * No-op if not running.
2225
- * @returns {void}
2226
- */
2227
- stop() {
2228
- if (!this.loopState.running) return;
2229
- this.loopState.running = false;
2230
- if (this.loopState.rafHandle !== null) {
2231
- cancelAnimationFrame(this.loopState.rafHandle);
2232
- this.loopState.rafHandle = null;
2233
- }
2234
- this.stoppedTime = performance.now();
2235
- }
2236
- /**
2237
- * Request frames to be rendered in demand mode.
2238
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2239
- * No-op if frameloop is not 'demand'.
2240
- * @param {number} [frames=1] - Number of frames to request
2241
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2242
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2243
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2244
- * @returns {void}
2245
- * @example
2246
- * // Request a single frame render
2247
- * scheduler.invalidate();
2248
- *
2249
- * @example
2250
- * // Request 5 frames (e.g., for animations)
2251
- * scheduler.invalidate(5);
2252
- *
2253
- * @example
2254
- * // Set pending frames to exactly 3 (don't stack with existing)
2255
- * scheduler.invalidate(3, false);
2256
- *
2257
- * @example
2258
- * // Add 2 more frames to existing pending count
2259
- * scheduler.invalidate(2, true);
2260
- */
2261
- invalidate(frames = 1, stackFrames = false) {
2262
- if (this._frameloop !== "demand") return;
2263
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2264
- this.pendingFrames = Math.min(60, baseFrames + frames);
2265
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2266
- }
2267
- /**
2268
- * Reset timing state for deterministic testing.
2269
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2270
- * @returns {void}
2271
- */
2272
- resetTiming() {
2273
- this.loopState.lastTime = null;
2274
- this.loopState.frameCount = 0;
2275
- this.loopState.elapsedTime = 0;
2276
- this.loopState.createdAt = performance.now();
2277
- }
2278
- //* Manual Stepping Methods ================================
2279
- /**
2280
- * Manually execute a single frame for all roots.
2281
- * Useful for frameloop='never' mode or testing scenarios.
2282
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2283
- * @returns {void}
2284
- * @example
2285
- * // Manual control mode
2286
- * scheduler.frameloop = 'never';
2287
- * scheduler.step(); // Execute one frame
2288
- */
2289
- step(timestamp) {
2290
- const now = timestamp ?? performance.now();
2291
- this.executeFrame(now);
2292
- }
2293
- /**
2294
- * Manually execute a single job by its ID.
2295
- * Useful for testing individual job callbacks in isolation.
2296
- * @param {string} id - The job ID to step
2297
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2298
- * @returns {void}
2299
- */
2300
- stepJob(id, timestamp) {
2301
- let job;
2302
- let root;
2303
- for (const r of this.roots.values()) {
2304
- job = r.jobs.get(id);
2305
- if (job) {
2306
- root = r;
2307
- break;
2308
- }
2309
- }
2310
- if (!job || !root) {
2311
- console.warn(`[Scheduler] Job "${id}" not found`);
2312
- return;
2313
- }
2314
- const now = timestamp ?? performance.now();
2315
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2316
- const delta = deltaMs / 1e3;
2317
- const elapsed = now - this.loopState.createdAt;
2318
- const providedState = root.getState?.() ?? {};
2319
- const frameState = {
2320
- ...providedState,
2321
- time: now,
2322
- delta,
2323
- elapsed,
2324
- frame: this.loopState.frameCount
2325
- };
2326
- try {
2327
- job.callback(frameState, delta);
2328
- } catch (error) {
2329
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2330
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2331
- }
2332
- }
2333
- /**
2334
- * Execute a single frame across all roots.
2335
- * Order: globalBefore → each root's jobs → globalAfter
2336
- * @param {number} timestamp - RAF timestamp in milliseconds
2337
- * @returns {void}
2338
- * @private
2339
- */
2340
- executeFrame(timestamp) {
2341
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2342
- const delta = deltaMs / 1e3;
2343
- this.loopState.lastTime = timestamp;
2344
- this.loopState.frameCount++;
2345
- this.loopState.elapsedTime += deltaMs;
2346
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2347
- for (const root of this.roots.values()) {
2348
- this.tickRoot(root, timestamp, delta);
2349
- }
2350
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2351
- }
2352
- /**
2353
- * Run all global jobs from a job map.
2354
- * Catches and logs errors without stopping execution.
2355
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2356
- * @param {number} timestamp - RAF timestamp in milliseconds
2357
- * @returns {void}
2358
- * @private
2359
- */
2360
- runGlobalJobs(jobs, timestamp) {
2361
- for (const job of jobs.values()) {
2362
- try {
2363
- job.callback(timestamp);
2364
- } catch (error) {
2365
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2366
- }
2367
- }
2368
- }
2369
- /**
2370
- * Execute all jobs for a single root in sorted order.
2371
- * Rebuilds sorted job list if needed, then dispatches each job.
2372
- * Errors are caught and propagated via triggerError.
2373
- * @param {RootEntry} root - The root entry to tick
2374
- * @param {number} timestamp - RAF timestamp in milliseconds
2375
- * @param {number} delta - Time since last frame in seconds
2376
- * @returns {void}
2377
- * @private
2378
- */
2379
- tickRoot(root, timestamp, delta) {
2380
- if (root.needsRebuild) {
2381
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2382
- root.needsRebuild = false;
2383
- }
2384
- const providedState = root.getState?.() ?? {};
2385
- const frameState = {
2386
- ...providedState,
2387
- time: timestamp,
2388
- delta,
2389
- elapsed: this.loopState.elapsedTime / 1e3,
2390
- // Convert ms to seconds
2391
- frame: this.loopState.frameCount
2392
- };
2393
- for (const job of root.sortedJobs) {
2394
- if (!shouldRun(job, timestamp)) continue;
2395
- try {
2396
- job.callback(frameState, delta);
2397
- } catch (error) {
2398
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2399
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2400
- }
2401
- }
2402
- }
2403
- //* Debug & Inspection Methods ================================
2404
- /**
2405
- * Get the total number of registered jobs across all roots.
2406
- * Includes both per-root jobs and global before/after jobs.
2407
- * @returns {number} Total job count
2408
- */
2409
- getJobCount() {
2410
- let count = 0;
2411
- for (const root of this.roots.values()) {
2412
- count += root.jobs.size;
2413
- }
2414
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2415
- }
2416
- /**
2417
- * Get all registered job IDs across all roots.
2418
- * Includes both per-root jobs and global before/after jobs.
2419
- * @returns {string[]} Array of all job IDs
2420
- */
2421
- getJobIds() {
2422
- const ids = [];
2423
- for (const root of this.roots.values()) {
2424
- ids.push(...root.jobs.keys());
2425
- }
2426
- ids.push(...this.globalBeforeJobs.keys());
2427
- ids.push(...this.globalAfterJobs.keys());
2428
- return ids;
2429
- }
2430
- /**
2431
- * Get the number of registered roots (Canvas instances).
2432
- * @returns {number} Number of registered roots
2433
- */
2434
- getRootCount() {
2435
- return this.roots.size;
2436
- }
2437
- /**
2438
- * Check if any user (non-system) jobs are registered in a specific phase.
2439
- * Used by the default render job to know if a user has taken over rendering.
2440
- *
2441
- * @param phase The phase to check
2442
- * @param rootId Optional root ID to check (checks all roots if not provided)
2443
- * @returns true if any user jobs exist in the phase
2444
- */
2445
- hasUserJobsInPhase(phase, rootId) {
2446
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2447
- return rootsToCheck.some((root) => {
2448
- if (!root) return false;
2449
- for (const job of root.jobs.values()) {
2450
- if (job.phase === phase && !job.system && job.enabled) return true;
2451
- }
2452
- return false;
2453
- });
2454
- }
2455
- //* Utility Methods ================================
2456
- /**
2457
- * Generate a unique root ID for automatic root registration.
2458
- * @returns {string} A unique root ID in the format 'root_N'
2459
- */
2460
- generateRootId() {
2461
- return `root_${this.nextRootIndex++}`;
2462
- }
2463
- /**
2464
- * Generate a unique job ID.
2465
- * @returns {string} A unique job ID in the format 'job_N'
2466
- * @private
2467
- */
2468
- generateJobId() {
2469
- return `job_${this.nextJobIndex}`;
2470
- }
2471
- /**
2472
- * Normalize before/after constraints to a Set.
2473
- * Handles undefined, single string, or array inputs.
2474
- * @param {string | string[] | undefined} value - The constraint value(s)
2475
- * @returns {Set<string>} Normalized Set of constraint strings
2476
- * @private
2477
- */
2478
- normalizeConstraints(value) {
2479
- if (!value) return /* @__PURE__ */ new Set();
2480
- if (Array.isArray(value)) return new Set(value);
2481
- return /* @__PURE__ */ new Set([value]);
2482
- }
2483
- };
2484
- //* Static State & Methods (Singleton Usage) ================================
2485
- //* Cross-Bundle Singleton Key ==============================
2486
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2487
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2488
- __publicField(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2489
- let Scheduler = _Scheduler;
2490
- const getScheduler = () => Scheduler.get();
2491
- if (hmrData) {
2492
- hmrData.accept?.();
1725
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1726
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1727
+ if (!stack) return false;
1728
+ const caller = stack.split("\n")[callerDepth] ?? "";
1729
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
2493
1730
  }
2494
1731
 
2495
1732
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
@@ -2529,7 +1766,14 @@ const createStore = (invalidate, advance) => {
2529
1766
  frustum: new three.Frustum(),
2530
1767
  autoUpdateFrustum: true,
2531
1768
  raycaster: null,
2532
- events: { priority: 1, enabled: true, connected: false },
1769
+ events: {
1770
+ priority: 1,
1771
+ enabled: true,
1772
+ connected: false,
1773
+ frameTimedRaycasts: true,
1774
+ alwaysFireOnScroll: true,
1775
+ updateOnFrame: false
1776
+ },
2533
1777
  scene: null,
2534
1778
  rootScene: null,
2535
1779
  xr: null,
@@ -2594,7 +1838,7 @@ const createStore = (invalidate, advance) => {
2594
1838
  size: newSize,
2595
1839
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
2596
1840
  }));
2597
- getScheduler().invalidate();
1841
+ scheduler.getScheduler().invalidate();
2598
1842
  }
2599
1843
  }
2600
1844
  return;
@@ -2609,7 +1853,7 @@ const createStore = (invalidate, advance) => {
2609
1853
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
2610
1854
  _sizeImperative: true
2611
1855
  }));
2612
- getScheduler().invalidate();
1856
+ scheduler.getScheduler().invalidate();
2613
1857
  },
2614
1858
  setDpr: (dpr) => set((state2) => {
2615
1859
  const resolved = calculateDpr(dpr);
@@ -2617,14 +1861,18 @@ const createStore = (invalidate, advance) => {
2617
1861
  }),
2618
1862
  setFrameloop: (frameloop = "always") => {
2619
1863
  set(() => ({ frameloop }));
1864
+ scheduler.getScheduler().frameloop = frameloop;
2620
1865
  },
2621
1866
  setError: (error) => set(() => ({ error })),
2622
1867
  error: null,
2623
- //* TSL State (managed via hooks: useUniforms, useNodes, useTextures, usePostProcessing) ==============================
1868
+ //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
2624
1869
  uniforms: {},
2625
1870
  nodes: {},
1871
+ buffers: {},
1872
+ gpuStorage: {},
2626
1873
  textures: /* @__PURE__ */ new Map(),
2627
- postProcessing: null,
1874
+ _textureRefs: /* @__PURE__ */ new Map(),
1875
+ renderPipeline: null,
2628
1876
  passes: {},
2629
1877
  _hmrVersion: 0,
2630
1878
  _sizeImperative: false,
@@ -2633,12 +1881,16 @@ const createStore = (invalidate, advance) => {
2633
1881
  internal: {
2634
1882
  // Events
2635
1883
  interaction: [],
2636
- hovered: /* @__PURE__ */ new Map(),
2637
1884
  subscribers: [],
1885
+ // Per-pointer state (new unified structure)
1886
+ pointerMap: /* @__PURE__ */ new Map(),
1887
+ pointerDirty: /* @__PURE__ */ new Map(),
1888
+ lastEvent: React__namespace.createRef(),
1889
+ // Deprecated but kept for backwards compatibility
1890
+ hovered: /* @__PURE__ */ new Map(),
2638
1891
  initialClick: [0, 0],
2639
1892
  initialHits: [],
2640
1893
  capturedMap: /* @__PURE__ */ new Map(),
2641
- lastEvent: React__namespace.createRef(),
2642
1894
  // Visibility tracking (onFramed, onOccluded, onVisible)
2643
1895
  visibilityRegistry: /* @__PURE__ */ new Map(),
2644
1896
  // Occlusion system (WebGPU only)
@@ -2677,8 +1929,7 @@ const createStore = (invalidate, advance) => {
2677
1929
  const currentState = rootStore.getState();
2678
1930
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2679
1931
  const stack = new Error().stack || "";
2680
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2681
- if (!isInternalAccess) {
1932
+ if (!isInternalRendererAccess(stack)) {
2682
1933
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2683
1934
  notifyDepreciated({
2684
1935
  heading: "Accessing state.gl in WebGPU mode",
@@ -2726,14 +1977,16 @@ const createStore = (invalidate, advance) => {
2726
1977
  oldSize = size;
2727
1978
  oldDpr = viewport.dpr;
2728
1979
  updateCamera(camera, size);
2729
- if (canvasTarget) {
1980
+ if (internal.isSecondary && canvasTarget) {
2730
1981
  if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
2731
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && canvasTarget.domElement instanceof HTMLCanvasElement;
2732
- canvasTarget.setSize(size.width, size.height, updateStyle);
1982
+ canvasTarget.setSize(size.width, size.height, false);
2733
1983
  } else {
2734
1984
  if (viewport.dpr > 0) actualRenderer.setPixelRatio(viewport.dpr);
2735
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && actualRenderer.domElement instanceof HTMLCanvasElement;
2736
- actualRenderer.setSize(size.width, size.height, updateStyle);
1985
+ actualRenderer.setSize(size.width, size.height, false);
1986
+ if (canvasTarget) {
1987
+ if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
1988
+ canvasTarget.setSize(size.width, size.height, false);
1989
+ }
2737
1990
  }
2738
1991
  }
2739
1992
  if (camera !== oldCamera) {
@@ -2789,26 +2042,32 @@ function loadingFn(extensions, onProgress) {
2789
2042
  );
2790
2043
  };
2791
2044
  }
2792
- function useLoader(loader, input, extensions, onProgress) {
2793
- const keys = Array.isArray(input) ? input : [input];
2045
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
2046
+ const inputs = Array.isArray(input) ? input : [input];
2047
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2794
2048
  const fn = loadingFn(extensions, onProgress);
2795
- const results = keys.map((key) => suspendReact.suspend(fn, [loader, key], { equal: is.equ }));
2049
+ const results = cacheKeys.map(
2050
+ (key, index) => suspendReact.suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
2051
+ );
2796
2052
  return Array.isArray(input) ? results : results[0];
2797
2053
  }
2798
- useLoader.preload = function(loader, input, extensions, onProgress) {
2799
- const keys = Array.isArray(input) ? input : [input];
2800
- keys.forEach((key) => suspendReact.preload(loadingFn(extensions, onProgress), [loader, key]));
2054
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2055
+ const inputs = Array.isArray(input) ? input : [input];
2056
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2057
+ cacheKeys.forEach(
2058
+ (key, index) => suspendReact.preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2059
+ );
2801
2060
  };
2802
- useLoader.clear = function(loader, input) {
2803
- const keys = Array.isArray(input) ? input : [input];
2804
- keys.forEach((key) => suspendReact.clear([loader, key]));
2061
+ useLoader.clear = function(loader, input, cacheKey) {
2062
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2063
+ cacheKeys.forEach((key) => suspendReact.clear([loader, key]));
2805
2064
  };
2806
2065
  useLoader.loader = getLoader;
2807
2066
 
2808
2067
  function useFrame(callback, priorityOrOptions) {
2809
2068
  const store = React__namespace.useContext(context);
2810
2069
  const isInsideCanvas = store !== null;
2811
- const scheduler = getScheduler();
2070
+ const scheduler$1 = scheduler.getScheduler();
2812
2071
  const optionsKey = typeof priorityOrOptions === "number" ? `p:${priorityOrOptions}` : priorityOrOptions ? JSON.stringify({
2813
2072
  id: priorityOrOptions.id,
2814
2073
  phase: priorityOrOptions.phase,
@@ -2856,7 +2115,7 @@ function useFrame(callback, priorityOrOptions) {
2856
2115
  };
2857
2116
  callbackRef.current?.(mergedState, delta);
2858
2117
  };
2859
- const unregister = scheduler.register(wrappedCallback, {
2118
+ const unregister = scheduler$1.register(wrappedCallback, {
2860
2119
  id,
2861
2120
  rootId,
2862
2121
  ...options
@@ -2877,37 +2136,31 @@ function useFrame(callback, priorityOrOptions) {
2877
2136
  }
2878
2137
  };
2879
2138
  } else {
2880
- const registerOutside = () => {
2881
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
2882
- };
2883
- if (scheduler.independent || scheduler.isReady) {
2884
- return registerOutside();
2885
- }
2886
- let unregisterJob = null;
2887
- const unsubReady = scheduler.onRootReady(() => {
2888
- unregisterJob = registerOutside();
2889
- });
2890
- return () => {
2891
- unsubReady();
2892
- unregisterJob?.();
2893
- };
2139
+ return scheduler$1.register(
2140
+ (state, delta) => {
2141
+ const frameState = state;
2142
+ if (!frameState.renderer) return;
2143
+ callbackRef.current?.(frameState, delta);
2144
+ },
2145
+ { id, ...options }
2146
+ );
2894
2147
  }
2895
- }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2148
+ }, [store, scheduler$1, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2896
2149
  const isPaused = React__namespace.useSyncExternalStore(
2897
2150
  // Subscribe function
2898
2151
  React__namespace.useCallback(
2899
2152
  (onStoreChange) => {
2900
- return getScheduler().subscribeJobState(id, onStoreChange);
2153
+ return scheduler.getScheduler().subscribeJobState(id, onStoreChange);
2901
2154
  },
2902
2155
  [id]
2903
2156
  ),
2904
2157
  // getSnapshot function
2905
- React__namespace.useCallback(() => getScheduler().isJobPaused(id), [id]),
2158
+ React__namespace.useCallback(() => scheduler.getScheduler().isJobPaused(id), [id]),
2906
2159
  // getServerSnapshot function (SSR)
2907
2160
  React__namespace.useCallback(() => false, [])
2908
2161
  );
2909
2162
  const controls = React__namespace.useMemo(() => {
2910
- const scheduler2 = getScheduler();
2163
+ const scheduler2 = scheduler.getScheduler();
2911
2164
  return {
2912
2165
  /** The job's unique ID */
2913
2166
  id,
@@ -2922,7 +2175,7 @@ function useFrame(callback, priorityOrOptions) {
2922
2175
  * @param timestamp Optional timestamp (defaults to performance.now())
2923
2176
  */
2924
2177
  step: (timestamp) => {
2925
- getScheduler().stepJob(id, timestamp);
2178
+ scheduler.getScheduler().stepJob(id, timestamp);
2926
2179
  },
2927
2180
  /**
2928
2181
  * Manually step ALL jobs in the scheduler.
@@ -2930,20 +2183,20 @@ function useFrame(callback, priorityOrOptions) {
2930
2183
  * @param timestamp Optional timestamp (defaults to performance.now())
2931
2184
  */
2932
2185
  stepAll: (timestamp) => {
2933
- getScheduler().step(timestamp);
2186
+ scheduler.getScheduler().step(timestamp);
2934
2187
  },
2935
2188
  /**
2936
2189
  * Pause this job (set enabled=false).
2937
2190
  * Job remains registered but won't run.
2938
2191
  */
2939
2192
  pause: () => {
2940
- getScheduler().pauseJob(id);
2193
+ scheduler.getScheduler().pauseJob(id);
2941
2194
  },
2942
2195
  /**
2943
2196
  * Resume this job (set enabled=true).
2944
2197
  */
2945
2198
  resume: () => {
2946
- getScheduler().resumeJob(id);
2199
+ scheduler.getScheduler().resumeJob(id);
2947
2200
  },
2948
2201
  /**
2949
2202
  * Reactive paused state - automatically updates when pause/resume is called.
@@ -2981,18 +2234,18 @@ function buildFromCache(input, textureCache) {
2981
2234
  function useTexture(input, optionsOrOnLoad) {
2982
2235
  const renderer = useThree((state) => state.internal.actualRenderer);
2983
2236
  const store = useStore();
2984
- const textureCache = useThree((state) => state.textures);
2985
2237
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
2986
- const { onLoad, cache = false } = options;
2238
+ const { onLoad, cache = true } = options;
2987
2239
  const onLoadRef = React.useRef(onLoad);
2988
2240
  onLoadRef.current = onLoad;
2989
2241
  const onLoadCalledForRef = React.useRef(null);
2990
2242
  const urls = React.useMemo(() => getUrls(input), [input]);
2991
2243
  const cachedResult = React.useMemo(() => {
2992
2244
  if (!cache) return null;
2993
- if (!allUrlsCached(urls, textureCache)) return null;
2994
- return buildFromCache(input, textureCache);
2995
- }, [cache, urls, textureCache, input]);
2245
+ const textures = store.getState().textures;
2246
+ if (!allUrlsCached(urls, textures)) return null;
2247
+ return buildFromCache(input, textures);
2248
+ }, [cache, urls, input, store]);
2996
2249
  const loadedTextures = useLoader(
2997
2250
  three.TextureLoader,
2998
2251
  IsObject(input) ? Object.values(input) : input
@@ -3036,8 +2289,6 @@ function useTexture(input, optionsOrOnLoad) {
3036
2289
  }, [input, loadedTextures, cachedResult]);
3037
2290
  React.useEffect(() => {
3038
2291
  if (!cache) return;
3039
- if (cachedResult) return;
3040
- const set = store.setState;
3041
2292
  const urlTextureMap = [];
3042
2293
  if (typeof input === "string") {
3043
2294
  urlTextureMap.push([input, mappedTextures]);
@@ -3051,18 +2302,32 @@ function useTexture(input, optionsOrOnLoad) {
3051
2302
  urlTextureMap.push([url, textureRecord[key]]);
3052
2303
  }
3053
2304
  }
3054
- set((state) => {
3055
- const newMap = new Map(state.textures);
3056
- let changed = false;
2305
+ store.setState((state) => {
2306
+ const refs = new Map(state._textureRefs);
2307
+ let textures = state.textures;
2308
+ let added = false;
3057
2309
  for (const [url, texture] of urlTextureMap) {
3058
- if (!newMap.has(url)) {
3059
- newMap.set(url, texture);
3060
- changed = true;
2310
+ if (!textures.has(url)) {
2311
+ if (!added) {
2312
+ textures = new Map(textures);
2313
+ added = true;
2314
+ }
2315
+ textures.set(url, texture);
3061
2316
  }
2317
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3062
2318
  }
3063
- return changed ? { textures: newMap } : state;
2319
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
2320
+ });
2321
+ return () => store.setState((state) => {
2322
+ const refs = new Map(state._textureRefs);
2323
+ for (const [url] of urlTextureMap) {
2324
+ const next = (refs.get(url) ?? 0) - 1;
2325
+ if (next <= 0) refs.delete(url);
2326
+ else refs.set(url, next);
2327
+ }
2328
+ return { _textureRefs: refs };
3064
2329
  });
3065
- }, [cache, input, mappedTextures, store, cachedResult]);
2330
+ }, [cache, input, mappedTextures, store]);
3066
2331
  return mappedTextures;
3067
2332
  }
3068
2333
  useTexture.preload = (url) => useLoader.preload(three.TextureLoader, url);
@@ -3078,96 +2343,63 @@ const Texture = ({
3078
2343
  return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: children?.(ret) });
3079
2344
  };
3080
2345
 
3081
- function getTextureValue(entry) {
3082
- if (entry instanceof three.Texture) return entry;
3083
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof three.Texture) {
3084
- return entry.value;
3085
- }
3086
- return null;
3087
- }
3088
- function useTextures() {
2346
+ function useTextures(selector) {
3089
2347
  const store = useStore();
3090
- return React.useMemo(() => {
3091
- const set = store.setState;
2348
+ const registry = React.useMemo(() => {
3092
2349
  const getState = store.getState;
3093
- const add = (key, value) => {
3094
- set((state) => {
3095
- const newMap = new Map(state.textures);
3096
- newMap.set(key, value);
3097
- return { textures: newMap };
3098
- });
3099
- };
3100
- const addMultiple = (items) => {
3101
- set((state) => {
3102
- const newMap = new Map(state.textures);
3103
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
3104
- for (const [key, value] of entries) {
3105
- newMap.set(key, value);
3106
- }
3107
- return { textures: newMap };
3108
- });
3109
- };
3110
- const remove = (key) => {
3111
- set((state) => {
3112
- const newMap = new Map(state.textures);
3113
- newMap.delete(key);
3114
- return { textures: newMap };
3115
- });
3116
- };
3117
- const removeMultiple = (keys) => {
3118
- set((state) => {
3119
- const newMap = new Map(state.textures);
3120
- for (const key of keys) newMap.delete(key);
3121
- return { textures: newMap };
3122
- });
3123
- };
3124
- const dispose = (key) => {
3125
- const entry = getState().textures.get(key);
3126
- if (entry) {
3127
- const tex = getTextureValue(entry);
3128
- tex?.dispose();
3129
- }
3130
- remove(key);
3131
- };
3132
- const disposeMultiple = (keys) => {
3133
- const textures = getState().textures;
3134
- for (const key of keys) {
3135
- const entry = textures.get(key);
3136
- if (entry) {
3137
- const tex = getTextureValue(entry);
3138
- tex?.dispose();
3139
- }
3140
- }
3141
- removeMultiple(keys);
3142
- };
3143
- const disposeAll = () => {
3144
- const textures = getState().textures;
3145
- for (const entry of textures.values()) {
3146
- const tex = getTextureValue(entry);
3147
- tex?.dispose();
3148
- }
3149
- set({ textures: /* @__PURE__ */ new Map() });
3150
- };
2350
+ const setState = store.setState;
2351
+ const getOne = (key) => getState().textures.get(key);
3151
2352
  return {
3152
- // Getter for the textures Map (reactive via getState)
3153
- get textures() {
2353
+ get all() {
3154
2354
  return getState().textures;
3155
2355
  },
3156
- // Read
3157
- get: (key) => getState().textures.get(key),
2356
+ get(input) {
2357
+ if (typeof input === "string") return getOne(input);
2358
+ if (Array.isArray(input)) return input.map(getOne);
2359
+ const out = {};
2360
+ for (const name in input) out[name] = getOne(input[name]);
2361
+ return out;
2362
+ },
3158
2363
  has: (key) => getState().textures.has(key),
3159
- // Write
3160
- add,
3161
- addMultiple,
3162
- // Remove (cache only)
3163
- remove,
3164
- removeMultiple,
3165
- // Dispose (GPU + cache)
3166
- dispose,
3167
- disposeMultiple,
3168
- disposeAll
2364
+ add(keyOrRecord, texture) {
2365
+ setState((state) => {
2366
+ const textures = new Map(state.textures);
2367
+ if (typeof keyOrRecord === "string") {
2368
+ textures.set(keyOrRecord, texture);
2369
+ } else {
2370
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2371
+ }
2372
+ return { textures };
2373
+ });
2374
+ },
2375
+ dispose(key, options) {
2376
+ const state = getState();
2377
+ const refs = state._textureRefs.get(key) ?? 0;
2378
+ if (refs > 0 && !options?.force) {
2379
+ console.warn(
2380
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2381
+ );
2382
+ return false;
2383
+ }
2384
+ state.textures.get(key)?.dispose();
2385
+ setState((s) => {
2386
+ const textures = new Map(s.textures);
2387
+ textures.delete(key);
2388
+ const nextRefs = new Map(s._textureRefs);
2389
+ nextRefs.delete(key);
2390
+ return { textures, _textureRefs: nextRefs };
2391
+ });
2392
+ return true;
2393
+ },
2394
+ disposeAll() {
2395
+ for (const texture of getState().textures.values()) texture.dispose();
2396
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2397
+ }
3169
2398
  };
3170
2399
  }, [store]);
2400
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2401
+ const selected = useThree(subscribe);
2402
+ return selector ? selected : registry;
3171
2403
  }
3172
2404
 
3173
2405
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3222,7 +2454,7 @@ function addEffect(callback) {
3222
2454
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3223
2455
  });
3224
2456
  const id = `legacy_effect_${effectId++}`;
3225
- return getScheduler().registerGlobal("before", id, callback);
2457
+ return scheduler.getScheduler().registerGlobal("before", id, callback);
3226
2458
  }
3227
2459
  function addAfterEffect(callback) {
3228
2460
  notifyDepreciated({
@@ -3231,7 +2463,7 @@ function addAfterEffect(callback) {
3231
2463
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3232
2464
  });
3233
2465
  const id = `legacy_afterEffect_${effectId++}`;
3234
- return getScheduler().registerGlobal("after", id, callback);
2466
+ return scheduler.getScheduler().registerGlobal("after", id, callback);
3235
2467
  }
3236
2468
  function addTail(callback) {
3237
2469
  notifyDepreciated({
@@ -3239,16 +2471,16 @@ function addTail(callback) {
3239
2471
  body: "Use scheduler.onIdle(callback) instead.\naddTail will be removed in a future version.",
3240
2472
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3241
2473
  });
3242
- return getScheduler().onIdle(callback);
2474
+ return scheduler.getScheduler().onIdle(callback);
3243
2475
  }
3244
2476
  function invalidate(state, frames = 1, stackFrames = false) {
3245
- getScheduler().invalidate(frames, stackFrames);
2477
+ scheduler.getScheduler().invalidate(frames, stackFrames);
3246
2478
  }
3247
2479
  function advance(timestamp) {
3248
- getScheduler().step(timestamp);
2480
+ scheduler.getScheduler().step(timestamp);
3249
2481
  }
3250
2482
 
3251
- const version = "10.0.0-alpha.2";
2483
+ const version = "10.0.0-alpha.3";
3252
2484
  const packageData = {
3253
2485
  version: version};
3254
2486
 
@@ -14504,7 +13736,7 @@ function n0() {
14504
13736
  var t0 = n0();
14505
13737
  const r0 = Xb(t0);
14506
13738
 
14507
- const t = 1, o = 8, r = 32, e = 2;
13739
+ const t = 1, o = 8, r = 32, e = 2, i$1 = 268435456;
14508
13740
 
14509
13741
  function createReconciler(config) {
14510
13742
  const reconciler2 = r0(config);
@@ -14669,7 +13901,15 @@ function setFiberRef(fiber, publicInstance) {
14669
13901
  }
14670
13902
  }
14671
13903
  const reconstructed = [];
14672
- function swapInstances() {
13904
+ function flushReconstructedInstances() {
13905
+ if (reconstructed.length === 0) return;
13906
+ try {
13907
+ swapReconstructedInstances();
13908
+ } finally {
13909
+ reconstructed.length = 0;
13910
+ }
13911
+ }
13912
+ function swapReconstructedInstances() {
14673
13913
  for (const [instance] of reconstructed) {
14674
13914
  const parent = instance.parent;
14675
13915
  if (parent) {
@@ -14687,6 +13927,9 @@ function swapInstances() {
14687
13927
  }
14688
13928
  }
14689
13929
  if (instance.isHidden) unhideInstance(instance);
13930
+ if (isObject3D(instance.object) && !instance.parent) {
13931
+ removeInteractivity(findInitialRoot(instance), instance.object);
13932
+ }
14690
13933
  if (instance.object.__r3f) delete instance.object.__r3f;
14691
13934
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14692
13935
  }
@@ -14695,10 +13938,16 @@ function swapInstances() {
14695
13938
  const parent = instance.parent;
14696
13939
  if (parent) {
14697
13940
  const target = catalogue[toPascalCase(instance.type)];
13941
+ const prevObject = instance.object;
14698
13942
  instance.object = instance.props.object ?? new target(...instance.props.args ?? []);
14699
13943
  instance.object.__r3f = instance;
14700
13944
  setFiberRef(fiber, instance.object);
13945
+ if (isObject3D(prevObject) && isObject3D(instance.object)) {
13946
+ swapInteractivity(findInitialRoot(instance), prevObject, instance.object);
13947
+ }
14701
13948
  delete instance.appliedOnce;
13949
+ instance.eventCount = 0;
13950
+ instance.handlers = {};
14702
13951
  applyProps(instance.object, instance.props);
14703
13952
  if (instance.props.attach) {
14704
13953
  attach(parent, instance);
@@ -14715,14 +13964,114 @@ function swapInstances() {
14715
13964
  invalidateInstance(instance);
14716
13965
  }
14717
13966
  }
14718
- reconstructed.length = 0;
14719
13967
  }
14720
13968
  const handleTextInstance = () => {
14721
13969
  };
14722
13970
  const NO_CONTEXT = {};
14723
13971
  let currentUpdatePriority = NoEventPriority;
14724
- const NoFlags = 0;
14725
- const Update = 4;
13972
+ function getEventPriority(type) {
13973
+ switch (type) {
13974
+ case "beforetoggle":
13975
+ case "cancel":
13976
+ case "click":
13977
+ case "close":
13978
+ case "contextmenu":
13979
+ case "copy":
13980
+ case "cut":
13981
+ case "auxclick":
13982
+ case "dblclick":
13983
+ case "dragend":
13984
+ case "dragstart":
13985
+ case "drop":
13986
+ case "focusin":
13987
+ case "focusout":
13988
+ case "input":
13989
+ case "invalid":
13990
+ case "keydown":
13991
+ case "keypress":
13992
+ case "keyup":
13993
+ case "mousedown":
13994
+ case "mouseup":
13995
+ case "paste":
13996
+ case "pause":
13997
+ case "play":
13998
+ case "pointercancel":
13999
+ case "pointerdown":
14000
+ case "pointerup":
14001
+ case "ratechange":
14002
+ case "reset":
14003
+ case "resize":
14004
+ case "seeked":
14005
+ case "submit":
14006
+ case "touchcancel":
14007
+ case "touchend":
14008
+ case "touchstart":
14009
+ case "volumechange":
14010
+ case "change":
14011
+ case "selectionchange":
14012
+ case "compositionstart":
14013
+ case "compositionend":
14014
+ case "compositionupdate":
14015
+ case "beforeinput":
14016
+ case "blur":
14017
+ case "fullscreenchange":
14018
+ case "focus":
14019
+ case "hashchange":
14020
+ case "popstate":
14021
+ case "select":
14022
+ case "selectstart":
14023
+ return e;
14024
+ case "drag":
14025
+ case "dragenter":
14026
+ case "dragexit":
14027
+ case "dragleave":
14028
+ case "dragover":
14029
+ case "mousemove":
14030
+ case "mouseout":
14031
+ case "mouseover":
14032
+ case "pointermove":
14033
+ case "pointerout":
14034
+ case "pointerover":
14035
+ case "scroll":
14036
+ case "touchmove":
14037
+ case "wheel":
14038
+ case "mouseenter":
14039
+ case "mouseleave":
14040
+ case "pointerenter":
14041
+ case "pointerleave":
14042
+ return o;
14043
+ case "message": {
14044
+ switch (Tb.unstable_getCurrentPriorityLevel()) {
14045
+ case Tb.unstable_ImmediatePriority:
14046
+ return e;
14047
+ case Tb.unstable_UserBlockingPriority:
14048
+ return o;
14049
+ case Tb.unstable_NormalPriority:
14050
+ case Tb.unstable_LowPriority:
14051
+ return r;
14052
+ case Tb.unstable_IdlePriority:
14053
+ return i$1;
14054
+ default:
14055
+ return r;
14056
+ }
14057
+ }
14058
+ default:
14059
+ return r;
14060
+ }
14061
+ }
14062
+ function scheduleMicrotask(callback) {
14063
+ if (typeof queueMicrotask === "function") {
14064
+ queueMicrotask(callback);
14065
+ } else if (typeof Promise !== "undefined") {
14066
+ Promise.resolve().then(callback).catch((error) => {
14067
+ setTimeout(() => {
14068
+ throw error;
14069
+ });
14070
+ });
14071
+ } else {
14072
+ setTimeout(callback);
14073
+ }
14074
+ }
14726
14075
  const reconciler = /* @__PURE__ */ createReconciler({
14727
14076
  isPrimaryRenderer: false,
14728
14077
  warnsIfNotActing: false,
@@ -14761,16 +14110,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14761
14110
  else if (newProps.args?.length !== oldProps.args?.length) reconstruct = true;
14762
14111
  else if (newProps.args?.some((value, index) => value !== oldProps.args?.[index])) reconstruct = true;
14763
14112
  if (reconstruct) {
14764
- reconstructed.push([instance, { ...newProps }, fiber]);
14113
+ reconstructed.push([instance, getInstanceProps(newProps), fiber]);
14765
14114
  } else {
14766
14115
  const changedProps = diffProps(instance, newProps);
14767
- if (Object.keys(changedProps).length) {
14768
- Object.assign(instance.props, changedProps);
14769
- applyProps(instance.object, changedProps);
14770
- }
14116
+ const attach2 = instance.props.attach;
14117
+ instance.props = getInstanceProps(newProps);
14118
+ if (attach2 !== void 0) instance.props.attach = attach2;
14119
+ else delete instance.props.attach;
14120
+ if (Object.keys(changedProps).length) applyProps(instance.object, changedProps);
14771
14121
  }
14772
- const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
14773
- if (isTailSibling) swapInstances();
14774
14122
  },
14775
14123
  finalizeInitialChildren: (instance) => {
14776
14124
  for (const prop in instance.props) {
@@ -14795,8 +14143,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
14795
14143
  const target = container.getState().internal.container ?? container.getState().scene;
14796
14144
  return prepare(target, container, "", {});
14797
14145
  },
14798
- resetAfterCommit: () => {
14799
- },
14146
+ // Reconstructed instances are swapped once all mutations are committed,
14147
+ // before layout effects run so refs point to the new objects
14148
+ resetAfterCommit: flushReconstructedInstances,
14800
14149
  shouldSetTextContent: () => false,
14801
14150
  clearContainer: () => false,
14802
14151
  hideInstance,
@@ -14804,6 +14153,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
14804
14153
  createTextInstance: handleTextInstance,
14805
14154
  hideTextInstance: handleTextInstance,
14806
14155
  unhideTextInstance: handleTextInstance,
14156
+ // Mirrors react-dom, which flushes discrete work in microtasks
14157
+ supportsMicrotasks: true,
14158
+ scheduleMicrotask,
14807
14159
  scheduleTimeout: typeof setTimeout === "function" ? setTimeout : void 0,
14808
14160
  cancelTimeout: typeof clearTimeout === "function" ? clearTimeout : void 0,
14809
14161
  noTimeout: -1,
@@ -14844,28 +14196,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
14844
14196
  },
14845
14197
  resolveUpdatePriority() {
14846
14198
  if (currentUpdatePriority !== NoEventPriority) return currentUpdatePriority;
14847
- switch (typeof window !== "undefined" && window.event?.type) {
14848
- case "click":
14849
- case "contextmenu":
14850
- case "dblclick":
14851
- case "dragenter":
14852
- case "dragleave":
14853
- case "drop":
14854
- case "pointercancel":
14855
- case "pointerdown":
14856
- case "pointerup":
14857
- return e;
14858
- case "dragover":
14859
- case "pointermove":
14860
- case "pointerout":
14861
- case "pointerover":
14862
- case "pointerenter":
14863
- case "pointerleave":
14864
- case "wheel":
14865
- return o;
14866
- default:
14867
- return r;
14868
- }
14199
+ const eventType = typeof window !== "undefined" ? window.event?.type : void 0;
14200
+ if (eventType === void 0) return r;
14201
+ return getEventPriority(eventType);
14869
14202
  },
14870
14203
  resetFormInstance() {
14871
14204
  },
@@ -14914,11 +14247,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14914
14247
  cloneMutableTextInstance(textInstance) {
14915
14248
  return textInstance;
14916
14249
  },
14250
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14251
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14252
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14253
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14254
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14255
+ // Guarded by a test asserting a full render + unmount never reaches them.
14917
14256
  cloneRootViewTransitionContainer(_rootContainer) {
14918
- throw new Error("Not implemented.");
14919
14257
  },
14920
14258
  removeRootViewTransitionClone(_rootContainer, _clone) {
14921
- throw new Error("Not implemented.");
14922
14259
  },
14923
14260
  // https://github.com/facebook/react/pull/32465
14924
14261
  createFragmentInstance: (_fiber) => null,
@@ -15003,6 +14340,7 @@ function createRoot(canvas) {
15003
14340
  const lastConfiguredProps = {};
15004
14341
  let configured = false;
15005
14342
  let pending = null;
14343
+ let rendererSetup = null;
15006
14344
  return {
15007
14345
  async configure(props = {}) {
15008
14346
  let resolve;
@@ -15018,7 +14356,6 @@ function createRoot(canvas) {
15018
14356
  events,
15019
14357
  onCreated: onCreatedCallback,
15020
14358
  shadows = false,
15021
- textureColorSpace = three.SRGBColorSpace,
15022
14359
  orthographic = false,
15023
14360
  frameloop = "always",
15024
14361
  dpr = [1, 2],
@@ -15033,7 +14370,8 @@ function createRoot(canvas) {
15033
14370
  _sizeProps,
15034
14371
  forceEven
15035
14372
  } = props;
15036
- const state = store.getState();
14373
+ const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || three.SRGBColorSpace;
14374
+ let state = store.getState();
15037
14375
  const defaultGLProps = {
15038
14376
  canvas,
15039
14377
  powerPreference: "high-performance",
@@ -15061,9 +14399,21 @@ function createRoot(canvas) {
15061
14399
  );
15062
14400
  }
15063
14401
  if (!state.internal.actualRenderer) {
15064
- renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
15065
- state.internal.actualRenderer = renderer;
15066
- state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
14402
+ if (!rendererSetup) {
14403
+ rendererSetup = (async () => {
14404
+ {
14405
+ renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
14406
+ state.internal.actualRenderer = renderer;
14407
+ state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
14408
+ }
14409
+ })().catch((err) => {
14410
+ rendererSetup = null;
14411
+ throw err;
14412
+ });
14413
+ }
14414
+ await rendererSetup;
14415
+ state = store.getState();
14416
+ renderer = state.internal.actualRenderer;
15067
14417
  }
15068
14418
  let raycaster = state.raycaster;
15069
14419
  if (!raycaster) state.set({ raycaster: raycaster = new three.Raycaster() });
@@ -15156,7 +14506,7 @@ function createRoot(canvas) {
15156
14506
  lastConfiguredProps.performance = performance;
15157
14507
  }
15158
14508
  if (!state.xr) {
15159
- const handleXRFrame = (timestamp, frame) => {
14509
+ const handleXRFrame = (timestamp, _frame) => {
15160
14510
  const state2 = store.getState();
15161
14511
  if (state2.frameloop === "never") return;
15162
14512
  advance(timestamp);
@@ -15192,15 +14542,22 @@ function createRoot(canvas) {
15192
14542
  const oldType = renderer.shadowMap.type;
15193
14543
  renderer.shadowMap.enabled = !!shadows;
15194
14544
  if (is.boo(shadows)) {
15195
- renderer.shadowMap.type = three.PCFSoftShadowMap;
14545
+ renderer.shadowMap.type = three.PCFShadowMap;
15196
14546
  } else if (is.str(shadows)) {
14547
+ if (shadows === "soft") {
14548
+ notifyDepreciated({
14549
+ heading: 'shadows="soft" is deprecated',
14550
+ body: "Three has depreciated soft and improved basic PCFShadows, we converted for you.",
14551
+ link: "https://github.com/mrdoob/three.js/wiki/Migration-Guide?utm_source=chatgpt.com#181--182"
14552
+ });
14553
+ }
15197
14554
  const types = {
15198
14555
  basic: three.BasicShadowMap,
15199
14556
  percentage: three.PCFShadowMap,
15200
- soft: three.PCFSoftShadowMap,
14557
+ soft: three.PCFShadowMap,
15201
14558
  variance: three.VSMShadowMap
15202
14559
  };
15203
- renderer.shadowMap.type = types[shadows] ?? three.PCFSoftShadowMap;
14560
+ renderer.shadowMap.type = types[shadows] ?? three.PCFShadowMap;
15204
14561
  } else if (is.obj(shadows)) {
15205
14562
  Object.assign(renderer.shadowMap, shadows);
15206
14563
  }
@@ -15216,24 +14573,35 @@ function createRoot(canvas) {
15216
14573
  if (state.textureColorSpace !== textureColorSpace) state.set(() => ({ textureColorSpace }));
15217
14574
  lastConfiguredProps.textureColorSpace = textureColorSpace;
15218
14575
  }
14576
+ const r3fProps = ["textureColorSpace"];
14577
+ const constructorOnlyProps = ["samples", "antialias", "alpha", "canvas", "powerPreference"];
14578
+ const nonApplyProps = [...r3fProps, ...constructorOnlyProps];
15219
14579
  if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose)) {
15220
- applyProps(renderer, glConfig);
14580
+ const glProps = {};
14581
+ for (const key in glConfig) {
14582
+ if (!nonApplyProps.includes(key)) glProps[key] = glConfig[key];
14583
+ }
14584
+ applyProps(renderer, glProps);
15221
14585
  }
15222
14586
  if (rendererConfig && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && state.renderer) {
15223
14587
  const currentRenderer = state.renderer;
15224
14588
  if (!is.equ(rendererConfig, currentRenderer, shallowLoose)) {
15225
- applyProps(currentRenderer, rendererConfig);
14589
+ const rendererProps = {};
14590
+ for (const key in rendererConfig) {
14591
+ if (!nonApplyProps.includes(key)) rendererProps[key] = rendererConfig[key];
14592
+ }
14593
+ applyProps(currentRenderer, rendererProps);
15226
14594
  }
15227
14595
  }
15228
- const scheduler = getScheduler();
14596
+ const scheduler$1 = scheduler.getScheduler();
15229
14597
  const rootId = state.internal.rootId;
15230
14598
  if (!rootId) {
15231
- const newRootId = canvasId || scheduler.generateRootId();
15232
- const unregisterRoot = scheduler.registerRoot(newRootId, {
14599
+ const newRootId = canvasId || scheduler$1.generateRootId();
14600
+ const unregisterRoot = scheduler$1.registerRoot(newRootId, {
15233
14601
  getState: () => store.getState(),
15234
14602
  onError: (err) => store.getState().setError(err)
15235
14603
  });
15236
- const unregisterCanvasTarget = scheduler.register(
14604
+ const unregisterCanvasTarget = scheduler$1.register(
15237
14605
  () => {
15238
14606
  const state2 = store.getState();
15239
14607
  if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
@@ -15248,7 +14616,19 @@ function createRoot(canvas) {
15248
14616
  system: true
15249
14617
  }
15250
14618
  );
15251
- const unregisterFrustum = scheduler.register(
14619
+ const unregisterEventsFlush = scheduler$1.register(
14620
+ () => {
14621
+ const state2 = store.getState();
14622
+ state2.events.flush?.();
14623
+ },
14624
+ {
14625
+ id: `${newRootId}_events`,
14626
+ rootId: newRootId,
14627
+ phase: "input",
14628
+ system: true
14629
+ }
14630
+ );
14631
+ const unregisterFrustum = scheduler$1.register(
15252
14632
  () => {
15253
14633
  const state2 = store.getState();
15254
14634
  if (state2.autoUpdateFrustum && state2.camera) {
@@ -15258,11 +14638,11 @@ function createRoot(canvas) {
15258
14638
  {
15259
14639
  id: `${newRootId}_frustum`,
15260
14640
  rootId: newRootId,
15261
- phase: "preRender",
14641
+ before: "render",
15262
14642
  system: true
15263
14643
  }
15264
14644
  );
15265
- const unregisterVisibility = scheduler.register(
14645
+ const unregisterVisibility = scheduler$1.register(
15266
14646
  () => {
15267
14647
  const state2 = store.getState();
15268
14648
  checkVisibility(state2);
@@ -15270,19 +14650,19 @@ function createRoot(canvas) {
15270
14650
  {
15271
14651
  id: `${newRootId}_visibility`,
15272
14652
  rootId: newRootId,
15273
- phase: "preRender",
14653
+ before: "render",
15274
14654
  system: true,
15275
14655
  after: `${newRootId}_frustum`
15276
14656
  }
15277
14657
  );
15278
- const unregisterRender = scheduler.register(
14658
+ const unregisterRender = scheduler$1.register(
15279
14659
  () => {
15280
14660
  const state2 = store.getState();
15281
14661
  const renderer2 = state2.internal.actualRenderer;
15282
- const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
14662
+ const userHandlesRender = scheduler$1.hasUserJobsInPhase("render", newRootId);
15283
14663
  if (userHandlesRender || state2.internal.priority) return;
15284
14664
  try {
15285
- if (state2.postProcessing?.render) state2.postProcessing.render();
14665
+ if (state2.renderPipeline?.render) state2.renderPipeline.render();
15286
14666
  else if (renderer2?.render) renderer2.render(state2.scene, state2.camera);
15287
14667
  } catch (error) {
15288
14668
  state2.setError(error instanceof Error ? error : new Error(String(error)));
@@ -15307,15 +14687,16 @@ function createRoot(canvas) {
15307
14687
  unregisterRoot: () => {
15308
14688
  unregisterRoot();
15309
14689
  unregisterCanvasTarget();
14690
+ unregisterEventsFlush();
15310
14691
  unregisterFrustum();
15311
14692
  unregisterVisibility();
15312
14693
  unregisterRender();
15313
14694
  },
15314
- scheduler
14695
+ scheduler: scheduler$1
15315
14696
  }
15316
14697
  }));
15317
14698
  }
15318
- scheduler.frameloop = frameloop;
14699
+ scheduler$1.frameloop = frameloop;
15319
14700
  onCreated = onCreatedCallback;
15320
14701
  configured = true;
15321
14702
  resolve();
@@ -15382,7 +14763,8 @@ function unmountComponentAtNode(canvas, callback) {
15382
14763
  dispose(state.scene);
15383
14764
  _roots.delete(canvas);
15384
14765
  if (callback) callback(canvas);
15385
- } catch {
14766
+ } catch (error) {
14767
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15386
14768
  }
15387
14769
  }, 500);
15388
14770
  }
@@ -15445,6 +14827,7 @@ function PortalInner({ state = {}, children, container }) {
15445
14827
  viewport = rootState.viewport.getCurrentViewport(camera, new three.Vector3(), resolvedSize);
15446
14828
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15447
14829
  }
14830
+ const set = injectState.set;
15448
14831
  return {
15449
14832
  // The intersect consists of the previous root state
15450
14833
  ...rootState,
@@ -15463,7 +14846,7 @@ function PortalInner({ state = {}, children, container }) {
15463
14846
  size: resolvedSize,
15464
14847
  viewport: { ...rootState.viewport, ...viewport },
15465
14848
  // Layers are allowed to override events
15466
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14849
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15467
14850
  // Container for child attachment - the portalScene (injected or container itself)
15468
14851
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15469
14852
  };
@@ -15472,9 +14855,13 @@ function PortalInner({ state = {}, children, container }) {
15472
14855
  const store = traditional.createWithEqualityFn((set, get) => ({ ...rest, set, get }));
15473
14856
  const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
15474
14857
  onMutate(previousRoot.getState());
15475
- previousRoot.subscribe(onMutate);
15476
14858
  return store;
15477
14859
  }, [previousRoot, container]);
14860
+ useIsomorphicLayoutEffect(() => {
14861
+ const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
14862
+ const unsubscribe = previousRoot.subscribe(onMutate);
14863
+ return unsubscribe;
14864
+ }, [previousRoot, usePortalStore]);
15478
14865
  return (
15479
14866
  // @ts-ignore, reconciler types are not maintained
15480
14867
  /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: reconciler.createPortal(
@@ -15488,6 +14875,81 @@ function flushSync(fn) {
15488
14875
  return reconciler.flushSyncFromReconciler(fn);
15489
14876
  }
15490
14877
 
14878
+ function parseBackground(background) {
14879
+ if (!background) return null;
14880
+ if (typeof background === "object" && !background.isColor) {
14881
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14882
+ return {
14883
+ ...rest,
14884
+ preset,
14885
+ files: envMap || files,
14886
+ backgroundFiles: backgroundMap,
14887
+ background: true
14888
+ };
14889
+ }
14890
+ if (typeof background === "number") {
14891
+ return { color: background, background: true };
14892
+ }
14893
+ if (typeof background === "string") {
14894
+ if (background in presetsObj) {
14895
+ return { preset: background, background: true };
14896
+ }
14897
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14898
+ return { files: background, background: true };
14899
+ }
14900
+ return { color: background, background: true };
14901
+ }
14902
+ if (background.isColor) {
14903
+ return { color: background, background: true };
14904
+ }
14905
+ return null;
14906
+ }
14907
+
14908
+ function parseRendererConfig(rendererProp) {
14909
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14910
+ if (isRendererConfig) {
14911
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14912
+ return {
14913
+ primaryCanvas: pc,
14914
+ scheduler: sc,
14915
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14916
+ };
14917
+ }
14918
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14919
+ }
14920
+
14921
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14922
+ const registries = /* @__PURE__ */ new WeakMap();
14923
+ function getKindRegistry(store, kind) {
14924
+ let registry = registries.get(store);
14925
+ if (!registry) {
14926
+ registry = {
14927
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14928
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14929
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14930
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14931
+ };
14932
+ registries.set(store, registry);
14933
+ }
14934
+ return registry[kind];
14935
+ }
14936
+ function invalidateResource(store, kind, scopeKey) {
14937
+ const registry = getKindRegistry(store, kind);
14938
+ {
14939
+ registry.valid.clear();
14940
+ registry.staged.clear();
14941
+ }
14942
+ }
14943
+ function invalidateAllResources(store) {
14944
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
14945
+ }
14946
+
14947
+ function clearHmrCaches(store) {
14948
+ const primary = store.getState().primaryStore ?? store;
14949
+ invalidateAllResources(primary);
14950
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14951
+ }
14952
+
15491
14953
  function CanvasImpl({
15492
14954
  ref,
15493
14955
  children,
@@ -15508,6 +14970,8 @@ function CanvasImpl({
15508
14970
  raycaster,
15509
14971
  camera,
15510
14972
  scene,
14973
+ autoUpdateFrustum,
14974
+ occlusion,
15511
14975
  onPointerMissed,
15512
14976
  onDragOverMissed,
15513
14977
  onDropMissed,
@@ -15519,39 +14983,10 @@ function CanvasImpl({
15519
14983
  forceEven,
15520
14984
  ...props
15521
14985
  }) {
15522
- const { primaryCanvas, scheduler, ...rendererConfig } = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp) ? rendererProp : { primaryCanvas: void 0, scheduler: void 0 };
15523
- const renderer = Object.keys(rendererConfig).length > 0 ? rendererConfig : rendererProp;
14986
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15524
14987
  React__namespace.useMemo(() => extend(THREE), []);
15525
14988
  const Bridge = useBridge();
15526
- const backgroundProps = React__namespace.useMemo(() => {
15527
- if (!background) return null;
15528
- if (typeof background === "object" && !background.isColor) {
15529
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15530
- return {
15531
- ...rest,
15532
- preset,
15533
- files: envMap || files,
15534
- backgroundFiles: backgroundMap,
15535
- background: true
15536
- };
15537
- }
15538
- if (typeof background === "number") {
15539
- return { color: background, background: true };
15540
- }
15541
- if (typeof background === "string") {
15542
- if (background in presetsObj) {
15543
- return { preset: background, background: true };
15544
- }
15545
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15546
- return { files: background, background: true };
15547
- }
15548
- return { color: background, background: true };
15549
- }
15550
- if (background.isColor) {
15551
- return { color: background, background: true };
15552
- }
15553
- return null;
15554
- }, [background]);
14989
+ const backgroundProps = React__namespace.useMemo(() => parseBackground(background), [background]);
15555
14990
  const hasInitialSizeRef = React__namespace.useRef(false);
15556
14991
  const measureConfig = React__namespace.useMemo(() => {
15557
14992
  if (!hasInitialSizeRef.current) {
@@ -15593,6 +15028,7 @@ function CanvasImpl({
15593
15028
  const handleDropMissed = useMutableCallback(onDropMissed);
15594
15029
  const [block, setBlock] = React__namespace.useState(false);
15595
15030
  const [error, setError] = React__namespace.useState(false);
15031
+ const [fallbackVisible, setFallbackVisible] = React__namespace.useState(false);
15596
15032
  if (block) throw block;
15597
15033
  if (error) throw error;
15598
15034
  const root = React__namespace.useRef(null);
@@ -15600,6 +15036,7 @@ function CanvasImpl({
15600
15036
  const unsubscribeErrorRef = React__namespace.useRef(null);
15601
15037
  useIsomorphicLayoutEffect(() => {
15602
15038
  effectActiveRef.current = true;
15039
+ if (fallbackVisible) return;
15603
15040
  const canvas = canvasRef.current;
15604
15041
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15605
15042
  if (!root.current) {
@@ -15620,7 +15057,7 @@ function CanvasImpl({
15620
15057
  }
15621
15058
  async function run() {
15622
15059
  if (!effectActiveRef.current || !root.current) return;
15623
- await root.current.configure({
15060
+ const configured = await root.current.configure({
15624
15061
  id,
15625
15062
  primaryCanvas,
15626
15063
  scheduler,
@@ -15635,6 +15072,8 @@ function CanvasImpl({
15635
15072
  performance,
15636
15073
  raycaster,
15637
15074
  camera,
15075
+ autoUpdateFrustum,
15076
+ occlusion,
15638
15077
  size: effectiveSize,
15639
15078
  // Store size props for reset functionality
15640
15079
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15659,8 +15098,20 @@ function CanvasImpl({
15659
15098
  }
15660
15099
  onCreated?.(state);
15661
15100
  }
15662
- });
15663
- if (!effectActiveRef.current || !root.current) return;
15101
+ }).then(
15102
+ () => true,
15103
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
15104
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
15105
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
15106
+ (setupError) => {
15107
+ if (effectActiveRef.current) {
15108
+ if (fallback != null) setFallbackVisible(true);
15109
+ else setError(setupError);
15110
+ }
15111
+ return false;
15112
+ }
15113
+ );
15114
+ if (!configured || !effectActiveRef.current || !root.current) return;
15664
15115
  root.current.render(
15665
15116
  /* @__PURE__ */ jsxRuntime.jsx(Bridge, { children: /* @__PURE__ */ jsxRuntime.jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxRuntime.jsxs(React__namespace.Suspense, { fallback: /* @__PURE__ */ jsxRuntime.jsx(Block, { set: setBlock }), children: [
15666
15117
  backgroundProps && /* @__PURE__ */ jsxRuntime.jsx(Environment, { ...backgroundProps }),
@@ -15694,20 +15145,13 @@ function CanvasImpl({
15694
15145
  const handleHMR = () => {
15695
15146
  queueMicrotask(() => {
15696
15147
  const rootEntry = _roots.get(canvas);
15697
- if (rootEntry?.store) {
15698
- rootEntry.store.setState((state) => ({
15699
- nodes: {},
15700
- uniforms: {},
15701
- _hmrVersion: state._hmrVersion + 1
15702
- }));
15703
- }
15148
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15704
15149
  });
15705
15150
  };
15706
15151
  if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('legacy.cjs', document.baseURI).href)) }) !== "undefined" && undefined) {
15707
15152
  const hot = undefined;
15708
15153
  hot.on("vite:afterUpdate", handleHMR);
15709
- return () => hot.dispose?.(() => {
15710
- });
15154
+ return () => hot.off?.("vite:afterUpdate", handleHMR);
15711
15155
  }
15712
15156
  if (typeof module !== "undefined" && module.hot) {
15713
15157
  const hot = module.hot;
@@ -15730,7 +15174,20 @@ function CanvasImpl({
15730
15174
  ...style
15731
15175
  },
15732
15176
  ...props,
15733
- children: /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx("canvas", { ref: canvasRef, id, className: "r3f-canvas", style: { display: "block" }, children: fallback }) })
15177
+ children: fallbackVisible ? (
15178
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15179
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15180
+ fallback
15181
+ ) : /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
15182
+ "canvas",
15183
+ {
15184
+ ref: canvasRef,
15185
+ id,
15186
+ className: "r3f-canvas",
15187
+ style: { display: "block", width: "100%", height: "100%" },
15188
+ children: fallback
15189
+ }
15190
+ ) })
15734
15191
  }
15735
15192
  );
15736
15193
  }
@@ -15740,6 +15197,8 @@ function Canvas(props) {
15740
15197
 
15741
15198
  extend(THREE);
15742
15199
 
15200
+ exports.Scheduler = scheduler.Scheduler;
15201
+ exports.getScheduler = scheduler.getScheduler;
15743
15202
  exports.Block = Block;
15744
15203
  exports.Canvas = Canvas;
15745
15204
  exports.Environment = Environment;
@@ -15755,10 +15214,8 @@ exports.R3F_BUILD_LEGACY = R3F_BUILD_LEGACY;
15755
15214
  exports.R3F_BUILD_WEBGPU = R3F_BUILD_WEBGPU;
15756
15215
  exports.REACT_INTERNAL_PROPS = REACT_INTERNAL_PROPS;
15757
15216
  exports.RESERVED_PROPS = RESERVED_PROPS;
15758
- exports.Scheduler = Scheduler;
15759
15217
  exports.Texture = Texture;
15760
15218
  exports._roots = _roots;
15761
- exports.act = act;
15762
15219
  exports.addAfterEffect = addAfterEffect;
15763
15220
  exports.addEffect = addEffect;
15764
15221
  exports.addTail = addTail;
@@ -15785,7 +15242,6 @@ exports.getInstanceProps = getInstanceProps;
15785
15242
  exports.getPrimary = getPrimary;
15786
15243
  exports.getPrimaryIds = getPrimaryIds;
15787
15244
  exports.getRootState = getRootState;
15788
- exports.getScheduler = getScheduler;
15789
15245
  exports.getUuidPrefix = getUuidPrefix;
15790
15246
  exports.hasConstructor = hasConstructor;
15791
15247
  exports.hasPrimary = hasPrimary;
@@ -15809,6 +15265,7 @@ exports.reconciler = reconciler;
15809
15265
  exports.registerPrimary = registerPrimary;
15810
15266
  exports.removeInteractivity = removeInteractivity;
15811
15267
  exports.resolve = resolve;
15268
+ exports.swapInteractivity = swapInteractivity;
15812
15269
  exports.unmountComponentAtNode = unmountComponentAtNode;
15813
15270
  exports.unregisterPrimary = unregisterPrimary;
15814
15271
  exports.updateCamera = updateCamera;