@react-three/fiber 8.0.0-alpha.0 → 8.0.0-beta-01
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/CHANGELOG.md +67 -0
- package/dist/declarations/src/core/events.d.ts +63 -59
- package/dist/declarations/src/core/hooks.d.ts +21 -29
- package/dist/declarations/src/core/loop.d.ts +12 -12
- package/dist/declarations/src/core/renderer.d.ts +50 -52
- package/dist/declarations/src/core/store.d.ts +111 -106
- package/dist/declarations/src/core/utils.d.ts +43 -0
- package/dist/declarations/src/index.d.ts +7 -7
- package/dist/declarations/src/native/Canvas.d.ts +16 -0
- package/dist/declarations/src/native/events.d.ts +6 -0
- package/dist/declarations/src/native/hooks.d.ts +9 -0
- package/dist/declarations/src/native/index.d.ts +37 -0
- package/dist/declarations/src/native.d.ts +7 -0
- package/dist/declarations/src/three-types.d.ts +320 -320
- package/dist/declarations/src/web/Canvas.d.ts +13 -13
- package/dist/declarations/src/web/events.d.ts +5 -4
- package/dist/declarations/src/web/index.d.ts +34 -30
- package/dist/hooks-c89a6f88.esm.js +1455 -0
- package/dist/hooks-dd693347.cjs.dev.js +1501 -0
- package/dist/hooks-e01f12ec.cjs.prod.js +1501 -0
- package/dist/react-three-fiber.cjs.dev.js +142 -1551
- package/dist/react-three-fiber.cjs.prod.js +142 -1551
- package/dist/react-three-fiber.esm.js +123 -1529
- package/native/dist/react-three-fiber-native.cjs.d.ts +1 -0
- package/native/dist/react-three-fiber-native.cjs.dev.js +590 -0
- package/native/dist/react-three-fiber-native.cjs.js +7 -0
- package/native/dist/react-three-fiber-native.cjs.prod.js +590 -0
- package/native/dist/react-three-fiber-native.esm.js +538 -0
- package/native/package.json +5 -0
- package/package.json +16 -6
- package/__mocks__/react-use-measure/index.ts +0 -22
- package/dist/declarations/src/core/is.d.ts +0 -9
|
@@ -0,0 +1,1455 @@
|
|
|
1
|
+
import * as THREE from 'three';
|
|
2
|
+
import Reconciler from 'react-reconciler';
|
|
3
|
+
import { DefaultEventPriority, IdleEventPriority } from 'react-reconciler/constants';
|
|
4
|
+
import * as React from 'react';
|
|
5
|
+
import { suspend, preload, clear } from 'suspend-react';
|
|
6
|
+
import create from 'zustand';
|
|
7
|
+
|
|
8
|
+
var threeTypes = /*#__PURE__*/Object.freeze({
|
|
9
|
+
__proto__: null
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
const DEFAULT = '__default';
|
|
13
|
+
const isDiffSet = def => def && !!def.memoized && !!def.changes;
|
|
14
|
+
function calculateDpr(dpr) {
|
|
15
|
+
return Array.isArray(dpr) ? Math.min(Math.max(dpr[0], window.devicePixelRatio), dpr[1]) : dpr;
|
|
16
|
+
} // A collection of compare functions
|
|
17
|
+
|
|
18
|
+
const is = {
|
|
19
|
+
obj: a => a === Object(a) && !is.arr(a) && typeof a !== 'function',
|
|
20
|
+
fun: a => typeof a === 'function',
|
|
21
|
+
str: a => typeof a === 'string',
|
|
22
|
+
num: a => typeof a === 'number',
|
|
23
|
+
und: a => a === void 0,
|
|
24
|
+
arr: a => Array.isArray(a),
|
|
25
|
+
|
|
26
|
+
equ(a, b) {
|
|
27
|
+
// Wrong type or one of the two undefined, doesn't match
|
|
28
|
+
if (typeof a !== typeof b || !!a !== !!b) return false; // Atomic, just compare a against b
|
|
29
|
+
|
|
30
|
+
if (is.str(a) || is.num(a) || is.obj(a)) return a === b; // Array, shallow compare first to see if it's a match
|
|
31
|
+
|
|
32
|
+
if (is.arr(a) && a == b) return true; // Last resort, go through keys
|
|
33
|
+
|
|
34
|
+
let i;
|
|
35
|
+
|
|
36
|
+
for (i in a) if (!(i in b)) return false;
|
|
37
|
+
|
|
38
|
+
for (i in b) if (a[i] !== b[i]) return false;
|
|
39
|
+
|
|
40
|
+
return is.und(i) ? a === b : true;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
}; // Collects nodes and materials from a THREE.Object3D
|
|
44
|
+
|
|
45
|
+
function buildGraph(object) {
|
|
46
|
+
const data = {
|
|
47
|
+
nodes: {},
|
|
48
|
+
materials: {}
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
if (object) {
|
|
52
|
+
object.traverse(obj => {
|
|
53
|
+
if (obj.name) data.nodes[obj.name] = obj;
|
|
54
|
+
if (obj.material && !data.materials[obj.material.name]) data.materials[obj.material.name] = obj.material;
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return data;
|
|
59
|
+
} // Disposes an object and all its properties
|
|
60
|
+
|
|
61
|
+
function dispose(obj) {
|
|
62
|
+
if (obj.dispose && obj.type !== 'Scene') obj.dispose();
|
|
63
|
+
|
|
64
|
+
for (const p in obj) {
|
|
65
|
+
var _dispose, _ref;
|
|
66
|
+
(_dispose = (_ref = p).dispose) == null ? void 0 : _dispose.call(_ref);
|
|
67
|
+
delete obj[p];
|
|
68
|
+
}
|
|
69
|
+
} // Each object in the scene carries a small LocalState descriptor
|
|
70
|
+
|
|
71
|
+
function prepare(object, state) {
|
|
72
|
+
const instance = object;
|
|
73
|
+
|
|
74
|
+
if (state != null && state.primitive || !instance.__r3f) {
|
|
75
|
+
instance.__r3f = {
|
|
76
|
+
root: null,
|
|
77
|
+
memoizedProps: {},
|
|
78
|
+
eventCount: 0,
|
|
79
|
+
handlers: {},
|
|
80
|
+
objects: [],
|
|
81
|
+
parent: null,
|
|
82
|
+
...state
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return object;
|
|
87
|
+
} // Shallow check arrays, but check objects atomically
|
|
88
|
+
|
|
89
|
+
function checkShallow(a, b) {
|
|
90
|
+
if (is.arr(a) && is.equ(a, b)) return true;
|
|
91
|
+
if (a === b) return true;
|
|
92
|
+
return false;
|
|
93
|
+
} // This function prepares a set of changes to be applied to the instance
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
function diffProps(instance, {
|
|
97
|
+
children: cN,
|
|
98
|
+
key: kN,
|
|
99
|
+
ref: rN,
|
|
100
|
+
...props
|
|
101
|
+
}, {
|
|
102
|
+
children: cP,
|
|
103
|
+
key: kP,
|
|
104
|
+
ref: rP,
|
|
105
|
+
...previous
|
|
106
|
+
} = {}, remove = false) {
|
|
107
|
+
var _instance$__r3f;
|
|
108
|
+
|
|
109
|
+
const localState = (_instance$__r3f = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f : {};
|
|
110
|
+
const entries = Object.entries(props);
|
|
111
|
+
const changes = []; // Catch removed props, prepend them so they can be reset or removed
|
|
112
|
+
|
|
113
|
+
if (remove) {
|
|
114
|
+
const previousKeys = Object.keys(previous);
|
|
115
|
+
|
|
116
|
+
for (let i = 0; i < previousKeys.length; i++) if (!props.hasOwnProperty(previousKeys[i])) entries.unshift([previousKeys[i], DEFAULT + 'remove']);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
entries.forEach(([key, value]) => {
|
|
120
|
+
var _instance$__r3f2;
|
|
121
|
+
|
|
122
|
+
// Bail out on primitive object
|
|
123
|
+
if ((_instance$__r3f2 = instance.__r3f) != null && _instance$__r3f2.primitive && key === 'object') return; // When props match bail out
|
|
124
|
+
|
|
125
|
+
if (checkShallow(value, previous[key])) return; // Collect handlers and bail out
|
|
126
|
+
|
|
127
|
+
if (/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/.test(key)) return changes.push([key, value, true, []]); // Split dashed props
|
|
128
|
+
|
|
129
|
+
let entries = [];
|
|
130
|
+
if (key.includes('-')) entries = key.split('-');
|
|
131
|
+
changes.push([key, value, false, entries]);
|
|
132
|
+
});
|
|
133
|
+
const memoized = { ...props
|
|
134
|
+
};
|
|
135
|
+
if (localState.memoizedProps && localState.memoizedProps.args) memoized.args = localState.memoizedProps.args;
|
|
136
|
+
if (localState.memoizedProps && localState.memoizedProps.attach) memoized.attach = localState.memoizedProps.attach;
|
|
137
|
+
return {
|
|
138
|
+
memoized,
|
|
139
|
+
changes
|
|
140
|
+
};
|
|
141
|
+
} // This function applies a set of changes to the instance
|
|
142
|
+
|
|
143
|
+
function applyProps(instance, data) {
|
|
144
|
+
var _instance$__r3f3, _root$getState;
|
|
145
|
+
|
|
146
|
+
// Filter equals, events and reserved props
|
|
147
|
+
const localState = (_instance$__r3f3 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f3 : {};
|
|
148
|
+
const root = localState.root;
|
|
149
|
+
const rootState = (_root$getState = root == null ? void 0 : root.getState == null ? void 0 : root.getState()) != null ? _root$getState : {};
|
|
150
|
+
const {
|
|
151
|
+
memoized,
|
|
152
|
+
changes
|
|
153
|
+
} = isDiffSet(data) ? data : diffProps(instance, data);
|
|
154
|
+
const prevHandlers = localState.eventCount; // Prepare memoized props
|
|
155
|
+
|
|
156
|
+
if (instance.__r3f) instance.__r3f.memoizedProps = memoized;
|
|
157
|
+
changes.forEach(([key, value, isEvent, keys]) => {
|
|
158
|
+
let currentInstance = instance;
|
|
159
|
+
let targetProp = currentInstance[key]; // Revolve dashed props
|
|
160
|
+
|
|
161
|
+
if (keys.length) {
|
|
162
|
+
targetProp = keys.reduce((acc, key) => acc[key], instance); // If the target is atomic, it forces us to switch the root
|
|
163
|
+
|
|
164
|
+
if (!(targetProp && targetProp.set)) {
|
|
165
|
+
const [name, ...reverseEntries] = keys.reverse();
|
|
166
|
+
currentInstance = reverseEntries.reverse().reduce((acc, key) => acc[key], instance);
|
|
167
|
+
key = name;
|
|
168
|
+
}
|
|
169
|
+
} // https://github.com/mrdoob/three.js/issues/21209
|
|
170
|
+
// HMR/fast-refresh relies on the ability to cancel out props, but threejs
|
|
171
|
+
// has no means to do this. Hence we curate a small collection of value-classes
|
|
172
|
+
// with their respective constructor/set arguments
|
|
173
|
+
// For removed props, try to set default values, if possible
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
if (value === DEFAULT + 'remove') {
|
|
177
|
+
if (targetProp && targetProp.constructor) {
|
|
178
|
+
// use the prop constructor to find the default it should be
|
|
179
|
+
value = new targetProp.constructor(memoized.args);
|
|
180
|
+
} else if (currentInstance.constructor) {
|
|
181
|
+
// create a blank slate of the instance and copy the particular parameter.
|
|
182
|
+
// @ts-ignore
|
|
183
|
+
const defaultClassCall = new currentInstance.constructor(currentInstance.__r3f.memoizedProps.args);
|
|
184
|
+
value = defaultClassCall[targetProp]; // destory the instance
|
|
185
|
+
|
|
186
|
+
if (defaultClassCall.dispose) defaultClassCall.dispose(); // instance does not have constructor, just set it to 0
|
|
187
|
+
} else value = 0;
|
|
188
|
+
} // Deal with pointer events ...
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
if (isEvent) {
|
|
192
|
+
if (value) localState.handlers[key] = value;else delete localState.handlers[key];
|
|
193
|
+
localState.eventCount = Object.keys(localState.handlers).length;
|
|
194
|
+
} // Special treatment for objects with support for set/copy, and layers
|
|
195
|
+
else if (targetProp && targetProp.set && (targetProp.copy || targetProp instanceof THREE.Layers)) {
|
|
196
|
+
// If value is an array
|
|
197
|
+
if (Array.isArray(value)) {
|
|
198
|
+
if (targetProp.fromArray) targetProp.fromArray(value);else targetProp.set(...value);
|
|
199
|
+
} // Test again target.copy(class) next ...
|
|
200
|
+
else if (targetProp.copy && value && value.constructor && targetProp.constructor.name === value.constructor.name) targetProp.copy(value); // If nothing else fits, just set the single value, ignore undefined
|
|
201
|
+
// https://github.com/react-spring/react-three-fiber/issues/274
|
|
202
|
+
else if (value !== undefined) {
|
|
203
|
+
const isColor = targetProp instanceof THREE.Color; // Allow setting array scalars
|
|
204
|
+
|
|
205
|
+
if (!isColor && targetProp.setScalar) targetProp.setScalar(value); // Layers have no copy function, we must therefore copy the mask property
|
|
206
|
+
else if (targetProp instanceof THREE.Layers && value instanceof THREE.Layers) targetProp.mask = value.mask; // Otherwise just set ...
|
|
207
|
+
else targetProp.set(value); // Auto-convert sRGB colors, for now ...
|
|
208
|
+
// https://github.com/react-spring/react-three-fiber/issues/344
|
|
209
|
+
|
|
210
|
+
if (!rootState.linear && isColor) targetProp.convertSRGBToLinear();
|
|
211
|
+
} // Else, just overwrite the value
|
|
212
|
+
|
|
213
|
+
} else {
|
|
214
|
+
currentInstance[key] = value; // Auto-convert sRGB textures, for now ...
|
|
215
|
+
// https://github.com/react-spring/react-three-fiber/issues/344
|
|
216
|
+
|
|
217
|
+
if (!rootState.linear && currentInstance[key] instanceof THREE.Texture) currentInstance[key].encoding = THREE.sRGBEncoding;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
invalidateInstance(instance);
|
|
221
|
+
return instance;
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
if (rootState.internal && instance.raycast && prevHandlers !== localState.eventCount) {
|
|
225
|
+
// Pre-emptively remove the instance from the interaction manager
|
|
226
|
+
const index = rootState.internal.interaction.indexOf(instance);
|
|
227
|
+
if (index > -1) rootState.internal.interaction.splice(index, 1); // Add the instance to the interaction manager only when it has handlers
|
|
228
|
+
|
|
229
|
+
if (localState.eventCount) rootState.internal.interaction.push(instance);
|
|
230
|
+
} // Call the update lifecycle when it is being updated, but only when it is part of the scene
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
if (changes.length && instance.parent) updateInstance(instance);
|
|
234
|
+
}
|
|
235
|
+
function invalidateInstance(instance) {
|
|
236
|
+
var _instance$__r3f4, _instance$__r3f4$root;
|
|
237
|
+
|
|
238
|
+
const state = (_instance$__r3f4 = instance.__r3f) == null ? void 0 : (_instance$__r3f4$root = _instance$__r3f4.root) == null ? void 0 : _instance$__r3f4$root.getState == null ? void 0 : _instance$__r3f4$root.getState();
|
|
239
|
+
if (state && state.internal.frames === 0) state.invalidate();
|
|
240
|
+
}
|
|
241
|
+
function updateInstance(instance) {
|
|
242
|
+
instance.onUpdate == null ? void 0 : instance.onUpdate(instance);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function makeId(event) {
|
|
246
|
+
return (event.eventObject || event.object).uuid + '/' + event.index + event.instanceId;
|
|
247
|
+
}
|
|
248
|
+
/** Release pointer captures.
|
|
249
|
+
* This is called by releasePointerCapture in the API, and when an object is removed.
|
|
250
|
+
*/
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
|
|
254
|
+
const captureData = captures.get(obj);
|
|
255
|
+
|
|
256
|
+
if (captureData) {
|
|
257
|
+
captures.delete(obj); // If this was the last capturing object for this pointer
|
|
258
|
+
|
|
259
|
+
if (captures.size === 0) {
|
|
260
|
+
capturedMap.delete(pointerId);
|
|
261
|
+
captureData.target.releasePointerCapture(pointerId);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function removeInteractivity(store, object) {
|
|
267
|
+
const {
|
|
268
|
+
internal
|
|
269
|
+
} = store.getState(); // Removes every trace of an object from the data store
|
|
270
|
+
|
|
271
|
+
internal.interaction = internal.interaction.filter(o => o !== object);
|
|
272
|
+
internal.initialHits = internal.initialHits.filter(o => o !== object);
|
|
273
|
+
internal.hovered.forEach((value, key) => {
|
|
274
|
+
if (value.eventObject === object || value.object === object) {
|
|
275
|
+
internal.hovered.delete(key);
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
internal.capturedMap.forEach((captures, pointerId) => {
|
|
279
|
+
releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
function createEvents(store) {
|
|
283
|
+
const temp = new THREE.Vector3();
|
|
284
|
+
/** Sets up defaultRaycaster */
|
|
285
|
+
|
|
286
|
+
function prepareRay(event) {
|
|
287
|
+
var _raycaster$computeOff;
|
|
288
|
+
|
|
289
|
+
const state = store.getState();
|
|
290
|
+
const {
|
|
291
|
+
raycaster,
|
|
292
|
+
mouse,
|
|
293
|
+
camera,
|
|
294
|
+
size
|
|
295
|
+
} = state; // https://github.com/pmndrs/react-three-fiber/pull/782
|
|
296
|
+
// Events trigger outside of canvas when moved
|
|
297
|
+
|
|
298
|
+
const {
|
|
299
|
+
offsetX,
|
|
300
|
+
offsetY
|
|
301
|
+
} = (_raycaster$computeOff = raycaster.computeOffsets == null ? void 0 : raycaster.computeOffsets(event, state)) != null ? _raycaster$computeOff : event;
|
|
302
|
+
const {
|
|
303
|
+
width,
|
|
304
|
+
height
|
|
305
|
+
} = size;
|
|
306
|
+
mouse.set(offsetX / width * 2 - 1, -(offsetY / height) * 2 + 1);
|
|
307
|
+
raycaster.setFromCamera(mouse, camera);
|
|
308
|
+
}
|
|
309
|
+
/** Calculates delta */
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
function calculateDistance(event) {
|
|
313
|
+
const {
|
|
314
|
+
internal
|
|
315
|
+
} = store.getState();
|
|
316
|
+
const dx = event.offsetX - internal.initialClick[0];
|
|
317
|
+
const dy = event.offsetY - internal.initialClick[1];
|
|
318
|
+
return Math.round(Math.sqrt(dx * dx + dy * dy));
|
|
319
|
+
}
|
|
320
|
+
/** Returns true if an instance has a valid pointer-event registered, this excludes scroll, clicks etc */
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
function filterPointerEvents(objects) {
|
|
324
|
+
return objects.filter(obj => ['Move', 'Over', 'Enter', 'Out', 'Leave'].some(name => {
|
|
325
|
+
var _r3f;
|
|
326
|
+
|
|
327
|
+
return (_r3f = obj.__r3f) == null ? void 0 : _r3f.handlers['onPointer' + name];
|
|
328
|
+
}));
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function intersect(filter) {
|
|
332
|
+
const state = store.getState();
|
|
333
|
+
const {
|
|
334
|
+
raycaster,
|
|
335
|
+
internal
|
|
336
|
+
} = state; // Skip event handling when noEvents is set
|
|
337
|
+
|
|
338
|
+
if (!raycaster.enabled) return [];
|
|
339
|
+
const seen = new Set();
|
|
340
|
+
const intersections = []; // Allow callers to eliminate event objects
|
|
341
|
+
|
|
342
|
+
const eventsObjects = filter ? filter(internal.interaction) : internal.interaction; // Intersect known handler objects and filter against duplicates
|
|
343
|
+
|
|
344
|
+
let intersects = raycaster.intersectObjects(eventsObjects, true).filter(item => {
|
|
345
|
+
const id = makeId(item);
|
|
346
|
+
if (seen.has(id)) return false;
|
|
347
|
+
seen.add(id);
|
|
348
|
+
return true;
|
|
349
|
+
}); // https://github.com/mrdoob/three.js/issues/16031
|
|
350
|
+
// Allow custom userland intersect sort order
|
|
351
|
+
|
|
352
|
+
if (raycaster.filter) intersects = raycaster.filter(intersects, state);
|
|
353
|
+
|
|
354
|
+
for (const intersect of intersects) {
|
|
355
|
+
let eventObject = intersect.object; // Bubble event up
|
|
356
|
+
|
|
357
|
+
while (eventObject) {
|
|
358
|
+
var _r3f2;
|
|
359
|
+
|
|
360
|
+
if ((_r3f2 = eventObject.__r3f) != null && _r3f2.eventCount) intersections.push({ ...intersect,
|
|
361
|
+
eventObject
|
|
362
|
+
});
|
|
363
|
+
eventObject = eventObject.parent;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
return intersections;
|
|
368
|
+
}
|
|
369
|
+
/** Creates filtered intersects and returns an array of positive hits */
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
function patchIntersects(intersections, event) {
|
|
373
|
+
const {
|
|
374
|
+
internal
|
|
375
|
+
} = store.getState(); // If the interaction is captured, make all capturing targets part of the
|
|
376
|
+
// intersect.
|
|
377
|
+
|
|
378
|
+
if ('pointerId' in event && internal.capturedMap.has(event.pointerId)) {
|
|
379
|
+
for (let captureData of internal.capturedMap.get(event.pointerId).values()) {
|
|
380
|
+
intersections.push(captureData.intersection);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
return intersections;
|
|
385
|
+
}
|
|
386
|
+
/** Handles intersections by forwarding them to handlers */
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
function handleIntersects(intersections, event, delta, callback) {
|
|
390
|
+
const {
|
|
391
|
+
raycaster,
|
|
392
|
+
mouse,
|
|
393
|
+
camera,
|
|
394
|
+
internal
|
|
395
|
+
} = store.getState(); // If anything has been found, forward it to the event listeners
|
|
396
|
+
|
|
397
|
+
if (intersections.length) {
|
|
398
|
+
const unprojectedPoint = temp.set(mouse.x, mouse.y, 0).unproject(camera);
|
|
399
|
+
const localState = {
|
|
400
|
+
stopped: false
|
|
401
|
+
};
|
|
402
|
+
|
|
403
|
+
for (const hit of intersections) {
|
|
404
|
+
const hasPointerCapture = id => {
|
|
405
|
+
var _internal$capturedMap, _internal$capturedMap2;
|
|
406
|
+
|
|
407
|
+
return (_internal$capturedMap = (_internal$capturedMap2 = internal.capturedMap.get(id)) == null ? void 0 : _internal$capturedMap2.has(hit.eventObject)) != null ? _internal$capturedMap : false;
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
const setPointerCapture = id => {
|
|
411
|
+
const captureData = {
|
|
412
|
+
intersection: hit,
|
|
413
|
+
target: event.target
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
if (internal.capturedMap.has(id)) {
|
|
417
|
+
// if the pointerId was previously captured, we add the hit to the
|
|
418
|
+
// event capturedMap.
|
|
419
|
+
internal.capturedMap.get(id).set(hit.eventObject, captureData);
|
|
420
|
+
} else {
|
|
421
|
+
// if the pointerId was not previously captured, we create a map
|
|
422
|
+
// containing the hitObject, and the hit. hitObject is used for
|
|
423
|
+
// faster access.
|
|
424
|
+
internal.capturedMap.set(id, new Map([[hit.eventObject, captureData]]));
|
|
425
|
+
} // Call the original event now
|
|
426
|
+
event.target.setPointerCapture(id);
|
|
427
|
+
};
|
|
428
|
+
|
|
429
|
+
const releasePointerCapture = id => {
|
|
430
|
+
const captures = internal.capturedMap.get(id);
|
|
431
|
+
|
|
432
|
+
if (captures) {
|
|
433
|
+
releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
|
|
434
|
+
}
|
|
435
|
+
}; // Add native event props
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
let extractEventProps = {}; // This iterates over the event's properties including the inherited ones. Native PointerEvents have most of their props as getters which are inherited, but polyfilled PointerEvents have them all as their own properties (i.e. not inherited). We can't use Object.keys() or Object.entries() as they only return "own" properties; nor Object.getPrototypeOf(event) as that *doesn't* return "own" properties, only inherited ones.
|
|
439
|
+
|
|
440
|
+
for (let prop in event) {
|
|
441
|
+
let property = event[prop]; // Only copy over atomics, leave functions alone as these should be
|
|
442
|
+
// called as event.nativeEvent.fn()
|
|
443
|
+
|
|
444
|
+
if (typeof property !== 'function') extractEventProps[prop] = property;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
let raycastEvent = { ...hit,
|
|
448
|
+
...extractEventProps,
|
|
449
|
+
spaceX: mouse.x,
|
|
450
|
+
spaceY: mouse.y,
|
|
451
|
+
intersections,
|
|
452
|
+
stopped: localState.stopped,
|
|
453
|
+
delta,
|
|
454
|
+
unprojectedPoint,
|
|
455
|
+
ray: raycaster.ray,
|
|
456
|
+
camera: camera,
|
|
457
|
+
// Hijack stopPropagation, which just sets a flag
|
|
458
|
+
stopPropagation: () => {
|
|
459
|
+
// https://github.com/pmndrs/react-three-fiber/issues/596
|
|
460
|
+
// Events are not allowed to stop propagation if the pointer has been captured
|
|
461
|
+
const capturesForPointer = 'pointerId' in event && internal.capturedMap.get(event.pointerId); // We only authorize stopPropagation...
|
|
462
|
+
|
|
463
|
+
if ( // ...if this pointer hasn't been captured
|
|
464
|
+
!capturesForPointer || // ... or if the hit object is capturing the pointer
|
|
465
|
+
capturesForPointer.has(hit.eventObject)) {
|
|
466
|
+
raycastEvent.stopped = localState.stopped = true; // Propagation is stopped, remove all other hover records
|
|
467
|
+
// An event handler is only allowed to flush other handlers if it is hovered itself
|
|
468
|
+
|
|
469
|
+
if (internal.hovered.size && Array.from(internal.hovered.values()).find(i => i.eventObject === hit.eventObject)) {
|
|
470
|
+
// Objects cannot flush out higher up objects that have already caught the event
|
|
471
|
+
const higher = intersections.slice(0, intersections.indexOf(hit));
|
|
472
|
+
cancelPointer([...higher, hit]);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
},
|
|
476
|
+
// there should be a distinction between target and currentTarget
|
|
477
|
+
target: {
|
|
478
|
+
hasPointerCapture,
|
|
479
|
+
setPointerCapture,
|
|
480
|
+
releasePointerCapture
|
|
481
|
+
},
|
|
482
|
+
currentTarget: {
|
|
483
|
+
hasPointerCapture,
|
|
484
|
+
setPointerCapture,
|
|
485
|
+
releasePointerCapture
|
|
486
|
+
},
|
|
487
|
+
sourceEvent: event,
|
|
488
|
+
// deprecated
|
|
489
|
+
nativeEvent: event
|
|
490
|
+
}; // Call subscribers
|
|
491
|
+
|
|
492
|
+
callback(raycastEvent); // Event bubbling may be interrupted by stopPropagation
|
|
493
|
+
|
|
494
|
+
if (localState.stopped === true) break;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
return intersections;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function cancelPointer(hits) {
|
|
502
|
+
const {
|
|
503
|
+
internal
|
|
504
|
+
} = store.getState();
|
|
505
|
+
Array.from(internal.hovered.values()).forEach(hoveredObj => {
|
|
506
|
+
// When no objects were hit or the the hovered object wasn't found underneath the cursor
|
|
507
|
+
// we call onPointerOut and delete the object from the hovered-elements map
|
|
508
|
+
if (!hits.length || !hits.find(hit => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId)) {
|
|
509
|
+
const eventObject = hoveredObj.eventObject;
|
|
510
|
+
const instance = eventObject.__r3f;
|
|
511
|
+
const handlers = instance == null ? void 0 : instance.handlers;
|
|
512
|
+
internal.hovered.delete(makeId(hoveredObj));
|
|
513
|
+
|
|
514
|
+
if (instance != null && instance.eventCount) {
|
|
515
|
+
// Clear out intersects, they are outdated by now
|
|
516
|
+
const data = { ...hoveredObj,
|
|
517
|
+
intersections: hits || []
|
|
518
|
+
};
|
|
519
|
+
handlers.onPointerOut == null ? void 0 : handlers.onPointerOut(data);
|
|
520
|
+
handlers.onPointerLeave == null ? void 0 : handlers.onPointerLeave(data);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
const handlePointer = name => {
|
|
527
|
+
// Deal with cancelation
|
|
528
|
+
switch (name) {
|
|
529
|
+
case 'onPointerLeave':
|
|
530
|
+
case 'onPointerCancel':
|
|
531
|
+
return () => cancelPointer([]);
|
|
532
|
+
|
|
533
|
+
case 'onLostPointerCapture':
|
|
534
|
+
return event => {
|
|
535
|
+
if ('pointerId' in event) {
|
|
536
|
+
// If the object event interface had onLostPointerCapture, we'd call it here on every
|
|
537
|
+
// object that's getting removed.
|
|
538
|
+
store.getState().internal.capturedMap.delete(event.pointerId);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
cancelPointer([]);
|
|
542
|
+
};
|
|
543
|
+
} // Any other pointer goes here ...
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
return event => {
|
|
547
|
+
const {
|
|
548
|
+
onPointerMissed,
|
|
549
|
+
internal
|
|
550
|
+
} = store.getState();
|
|
551
|
+
prepareRay(event); // Get fresh intersects
|
|
552
|
+
|
|
553
|
+
const isPointerMove = name === 'onPointerMove';
|
|
554
|
+
const isClickEvent = name === 'onClick' || name === 'onContextMenu' || name === 'onDoubleClick';
|
|
555
|
+
const filter = isPointerMove ? filterPointerEvents : undefined;
|
|
556
|
+
const hits = patchIntersects(intersect(filter), event);
|
|
557
|
+
const delta = isClickEvent ? calculateDistance(event) : 0; // Save initial coordinates on pointer-down
|
|
558
|
+
|
|
559
|
+
if (name === 'onPointerDown') {
|
|
560
|
+
internal.initialClick = [event.offsetX, event.offsetY];
|
|
561
|
+
internal.initialHits = hits.map(hit => hit.eventObject);
|
|
562
|
+
} // If a click yields no results, pass it back to the user as a miss
|
|
563
|
+
// Missed events have to come first in order to establish user-land side-effect clean up
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
if (isClickEvent && !hits.length) {
|
|
567
|
+
if (delta <= 2) {
|
|
568
|
+
pointerMissed(event, internal.interaction);
|
|
569
|
+
if (onPointerMissed) onPointerMissed(event);
|
|
570
|
+
}
|
|
571
|
+
} // Take care of unhover
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
if (isPointerMove) cancelPointer(hits);
|
|
575
|
+
handleIntersects(hits, event, delta, data => {
|
|
576
|
+
const eventObject = data.eventObject;
|
|
577
|
+
const instance = eventObject.__r3f;
|
|
578
|
+
const handlers = instance == null ? void 0 : instance.handlers; // Check presence of handlers
|
|
579
|
+
|
|
580
|
+
if (!(instance != null && instance.eventCount)) return;
|
|
581
|
+
|
|
582
|
+
if (isPointerMove) {
|
|
583
|
+
// Move event ...
|
|
584
|
+
if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
|
|
585
|
+
// When enter or out is present take care of hover-state
|
|
586
|
+
const id = makeId(data);
|
|
587
|
+
const hoveredItem = internal.hovered.get(id);
|
|
588
|
+
|
|
589
|
+
if (!hoveredItem) {
|
|
590
|
+
// If the object wasn't previously hovered, book it and call its handler
|
|
591
|
+
internal.hovered.set(id, data);
|
|
592
|
+
handlers.onPointerOver == null ? void 0 : handlers.onPointerOver(data);
|
|
593
|
+
handlers.onPointerEnter == null ? void 0 : handlers.onPointerEnter(data);
|
|
594
|
+
} else if (hoveredItem.stopped) {
|
|
595
|
+
// If the object was previously hovered and stopped, we shouldn't allow other items to proceed
|
|
596
|
+
data.stopPropagation();
|
|
597
|
+
}
|
|
598
|
+
} // Call mouse move
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
handlers.onPointerMove == null ? void 0 : handlers.onPointerMove(data);
|
|
602
|
+
} else {
|
|
603
|
+
// All other events ...
|
|
604
|
+
const handler = handlers[name];
|
|
605
|
+
|
|
606
|
+
if (handler) {
|
|
607
|
+
// Forward all events back to their respective handlers with the exception of click events,
|
|
608
|
+
// which must use the initial target
|
|
609
|
+
if (name !== 'onClick' && name !== 'onContextMenu' && name !== 'onDoubleClick' || internal.initialHits.includes(eventObject)) {
|
|
610
|
+
// Missed events have to come first
|
|
611
|
+
pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object))); // Now call the handler
|
|
612
|
+
|
|
613
|
+
handler(data);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
});
|
|
618
|
+
};
|
|
619
|
+
};
|
|
620
|
+
|
|
621
|
+
function pointerMissed(event, objects) {
|
|
622
|
+
objects.forEach(object => {
|
|
623
|
+
var _r3f3;
|
|
624
|
+
|
|
625
|
+
return (_r3f3 = object.__r3f) == null ? void 0 : _r3f3.handlers.onPointerMissed == null ? void 0 : _r3f3.handlers.onPointerMissed(event);
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
return {
|
|
630
|
+
handlePointer
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// Type guard to tell a store from a portal
|
|
635
|
+
const isStore = def => def && !!def.getState;
|
|
636
|
+
|
|
637
|
+
const getContainer = (container, child) => {
|
|
638
|
+
var _container$__r3f$root, _container$__r3f;
|
|
639
|
+
|
|
640
|
+
return {
|
|
641
|
+
// If the container is not a root-store then it must be a THREE.Object3D into which part of the
|
|
642
|
+
// scene is portalled into. Now there can be two variants of this, either that object is part of
|
|
643
|
+
// the regular jsx tree, in which case it already has __r3f with a valid root attached, or it lies
|
|
644
|
+
// outside react, in which case we must take the root of the child that is about to be attached to it.
|
|
645
|
+
root: isStore(container) ? container : (_container$__r3f$root = (_container$__r3f = container.__r3f) == null ? void 0 : _container$__r3f.root) != null ? _container$__r3f$root : child.__r3f.root,
|
|
646
|
+
// The container is the eventual target into which objects are mounted, it has to be a THREE.Object3D
|
|
647
|
+
container: isStore(container) ? container.getState().scene : container
|
|
648
|
+
};
|
|
649
|
+
};
|
|
650
|
+
|
|
651
|
+
let catalogue = {};
|
|
652
|
+
|
|
653
|
+
let extend = objects => void (catalogue = { ...catalogue,
|
|
654
|
+
...objects
|
|
655
|
+
});
|
|
656
|
+
|
|
657
|
+
function createRenderer(roots, getEventPriority) {
|
|
658
|
+
function createInstance(type, {
|
|
659
|
+
args = [],
|
|
660
|
+
...props
|
|
661
|
+
}, root, hostContext, internalInstanceHandle) {
|
|
662
|
+
let name = `${type[0].toUpperCase()}${type.slice(1)}`;
|
|
663
|
+
let instance; // https://github.com/facebook/react/issues/17147
|
|
664
|
+
// Portals do not give us a root, they are themselves treated as a root by the reconciler
|
|
665
|
+
// In order to figure out the actual root we have to climb through fiber internals :(
|
|
666
|
+
|
|
667
|
+
if (!isStore(root) && internalInstanceHandle) {
|
|
668
|
+
const fn = node => {
|
|
669
|
+
if (!node.return) return node.stateNode && node.stateNode.containerInfo;else return fn(node.return);
|
|
670
|
+
};
|
|
671
|
+
|
|
672
|
+
root = fn(internalInstanceHandle);
|
|
673
|
+
} // Assert that by now we have a valid root
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
if (!root || !isStore(root)) throw `No valid root for ${name}!`;
|
|
677
|
+
|
|
678
|
+
if (type === 'primitive') {
|
|
679
|
+
if (props.object === undefined) throw `Primitives without 'object' are invalid!`;
|
|
680
|
+
const object = props.object;
|
|
681
|
+
instance = prepare(object, {
|
|
682
|
+
root,
|
|
683
|
+
primitive: true
|
|
684
|
+
});
|
|
685
|
+
} else {
|
|
686
|
+
const target = catalogue[name] || THREE[name];
|
|
687
|
+
if (!target) throw `${name} is not part of the THREE namespace! Did you forget to extend? See: https://github.com/pmndrs/react-three-fiber/blob/master/markdown/api.md#using-3rd-party-objects-declaratively`; // Instanciate new object, link it to the root
|
|
688
|
+
// Append memoized props with args so it's not forgotten
|
|
689
|
+
|
|
690
|
+
instance = prepare(new target(...args), {
|
|
691
|
+
root,
|
|
692
|
+
memoizedProps: {
|
|
693
|
+
args: args.length === 0 ? null : args
|
|
694
|
+
}
|
|
695
|
+
});
|
|
696
|
+
} // Auto-attach geometries and materials
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
if (!('attachFns' in props)) {
|
|
700
|
+
if (name.endsWith('Geometry')) {
|
|
701
|
+
props = {
|
|
702
|
+
attach: 'geometry',
|
|
703
|
+
...props
|
|
704
|
+
};
|
|
705
|
+
} else if (name.endsWith('Material')) {
|
|
706
|
+
props = {
|
|
707
|
+
attach: 'material',
|
|
708
|
+
...props
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
} // It should NOT call onUpdate on object instanciation, because it hasn't been added to the
|
|
712
|
+
// view yet. If the callback relies on references for instance, they won't be ready yet, this is
|
|
713
|
+
// why it passes "true" here
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
applyProps(instance, props);
|
|
717
|
+
return instance;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
function appendChild(parentInstance, child) {
|
|
721
|
+
let addedAsChild = false;
|
|
722
|
+
|
|
723
|
+
if (child) {
|
|
724
|
+
// The attach attribute implies that the object attaches itself on the parent
|
|
725
|
+
if (child.attachArray) {
|
|
726
|
+
if (!is.arr(parentInstance[child.attachArray])) parentInstance[child.attachArray] = [];
|
|
727
|
+
parentInstance[child.attachArray].push(child);
|
|
728
|
+
} else if (child.attachObject) {
|
|
729
|
+
if (!is.obj(parentInstance[child.attachObject[0]])) parentInstance[child.attachObject[0]] = {};
|
|
730
|
+
parentInstance[child.attachObject[0]][child.attachObject[1]] = child;
|
|
731
|
+
} else if (child.attach && !is.fun(child.attach)) {
|
|
732
|
+
parentInstance[child.attach] = child;
|
|
733
|
+
} else if (is.arr(child.attachFns)) {
|
|
734
|
+
const [attachFn] = child.attachFns;
|
|
735
|
+
|
|
736
|
+
if (is.str(attachFn) && is.fun(parentInstance[attachFn])) {
|
|
737
|
+
parentInstance[attachFn](child);
|
|
738
|
+
} else if (is.fun(attachFn)) {
|
|
739
|
+
attachFn(child, parentInstance);
|
|
740
|
+
}
|
|
741
|
+
} else if (child.isObject3D && parentInstance.isObject3D) {
|
|
742
|
+
// add in the usual parent-child way
|
|
743
|
+
parentInstance.add(child);
|
|
744
|
+
addedAsChild = true;
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
if (!addedAsChild) {
|
|
748
|
+
// This is for anything that used attach, and for non-Object3Ds that don't get attached to props;
|
|
749
|
+
// that is, anything that's a child in React but not a child in the scenegraph.
|
|
750
|
+
parentInstance.__r3f.objects.push(child);
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
if (!child.__r3f) {
|
|
754
|
+
prepare(child, {});
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
child.__r3f.parent = parentInstance;
|
|
758
|
+
updateInstance(child);
|
|
759
|
+
invalidateInstance(child);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
function insertBefore(parentInstance, child, beforeChild) {
|
|
764
|
+
let added = false;
|
|
765
|
+
|
|
766
|
+
if (child) {
|
|
767
|
+
if (child.attachArray) {
|
|
768
|
+
const array = parentInstance[child.attachArray];
|
|
769
|
+
if (!is.arr(array)) parentInstance[child.attachArray] = [];
|
|
770
|
+
array.splice(array.indexOf(beforeChild), 0, child);
|
|
771
|
+
} else if (child.attachObject || child.attach && !is.fun(child.attach)) {
|
|
772
|
+
// attach and attachObject don't have an order anyway, so just append
|
|
773
|
+
return appendChild(parentInstance, child);
|
|
774
|
+
} else if (child.isObject3D && parentInstance.isObject3D) {
|
|
775
|
+
child.parent = parentInstance;
|
|
776
|
+
child.dispatchEvent({
|
|
777
|
+
type: 'added'
|
|
778
|
+
});
|
|
779
|
+
const restSiblings = parentInstance.children.filter(sibling => sibling !== child);
|
|
780
|
+
const index = restSiblings.indexOf(beforeChild);
|
|
781
|
+
parentInstance.children = [...restSiblings.slice(0, index), child, ...restSiblings.slice(index)];
|
|
782
|
+
added = true;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
if (!added) {
|
|
786
|
+
parentInstance.__r3f.objects.push(child);
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
if (!child.__r3f) {
|
|
790
|
+
prepare(child, {});
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
child.__r3f.parent = parentInstance;
|
|
794
|
+
updateInstance(child);
|
|
795
|
+
invalidateInstance(child);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
function removeRecursive(array, parent, dispose = false) {
|
|
800
|
+
if (array) [...array].forEach(child => removeChild(parent, child, dispose));
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
function removeChild(parentInstance, child, dispose) {
|
|
804
|
+
if (child) {
|
|
805
|
+
var _parentInstance$__r3f, _child$__r3f2;
|
|
806
|
+
|
|
807
|
+
if (child.__r3f) {
|
|
808
|
+
child.__r3f.parent = null;
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
if ((_parentInstance$__r3f = parentInstance.__r3f) != null && _parentInstance$__r3f.objects) {
|
|
812
|
+
parentInstance.__r3f.objects = parentInstance.__r3f.objects.filter(x => x !== child);
|
|
813
|
+
} // Remove attachment
|
|
814
|
+
|
|
815
|
+
|
|
816
|
+
if (child.attachArray) {
|
|
817
|
+
parentInstance[child.attachArray] = parentInstance[child.attachArray].filter(x => x !== child);
|
|
818
|
+
} else if (child.attachObject) {
|
|
819
|
+
delete parentInstance[child.attachObject[0]][child.attachObject[1]];
|
|
820
|
+
} else if (child.attach && !is.fun(child.attach)) {
|
|
821
|
+
parentInstance[child.attach] = null;
|
|
822
|
+
} else if (is.arr(child.attachFns)) {
|
|
823
|
+
const [, detachFn] = child.attachFns;
|
|
824
|
+
|
|
825
|
+
if (is.str(detachFn) && is.fun(parentInstance[detachFn])) {
|
|
826
|
+
parentInstance[detachFn](child);
|
|
827
|
+
} else if (is.fun(detachFn)) {
|
|
828
|
+
detachFn(child, parentInstance);
|
|
829
|
+
}
|
|
830
|
+
} else if (child.isObject3D && parentInstance.isObject3D) {
|
|
831
|
+
var _child$__r3f;
|
|
832
|
+
|
|
833
|
+
parentInstance.remove(child); // Remove interactivity
|
|
834
|
+
|
|
835
|
+
if ((_child$__r3f = child.__r3f) != null && _child$__r3f.root) {
|
|
836
|
+
removeInteractivity(child.__r3f.root, child);
|
|
837
|
+
}
|
|
838
|
+
} // Allow objects to bail out of recursive dispose alltogether by passing dispose={null}
|
|
839
|
+
// Never dispose of primitives because their state may be kept outside of React!
|
|
840
|
+
// In order for an object to be able to dispose it has to have
|
|
841
|
+
// - a dispose method,
|
|
842
|
+
// - it cannot be a <primitive object={...} />
|
|
843
|
+
// - it cannot be a THREE.Scene, because three has broken it's own api
|
|
844
|
+
//
|
|
845
|
+
// Since disposal is recursive, we can check the optional dispose arg, which will be undefined
|
|
846
|
+
// when the reconciler calls it, but then carry our own check recursively
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
const isPrimitive = (_child$__r3f2 = child.__r3f) == null ? void 0 : _child$__r3f2.primitive;
|
|
850
|
+
const shouldDispose = dispose === undefined ? child.dispose !== null && !isPrimitive : dispose; // Remove nested child objects. Primitives should not have objects and children that are
|
|
851
|
+
// attached to them declaratively ...
|
|
852
|
+
|
|
853
|
+
if (!isPrimitive) {
|
|
854
|
+
var _child$__r3f3;
|
|
855
|
+
|
|
856
|
+
removeRecursive((_child$__r3f3 = child.__r3f) == null ? void 0 : _child$__r3f3.objects, child, shouldDispose);
|
|
857
|
+
removeRecursive(child.children, child, shouldDispose);
|
|
858
|
+
} // Remove references
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
if (child.__r3f) {
|
|
862
|
+
delete child.__r3f.root;
|
|
863
|
+
delete child.__r3f.objects;
|
|
864
|
+
delete child.__r3f.handlers;
|
|
865
|
+
delete child.__r3f.memoizedProps;
|
|
866
|
+
if (!isPrimitive) delete child.__r3f;
|
|
867
|
+
} // Dispose item whenever the reconciler feels like it
|
|
868
|
+
|
|
869
|
+
|
|
870
|
+
if (shouldDispose && child.dispose && child.type !== 'Scene') {
|
|
871
|
+
reconciler.runWithPriority(IdleEventPriority, () => {
|
|
872
|
+
try {
|
|
873
|
+
child.dispose();
|
|
874
|
+
} catch (e) {
|
|
875
|
+
/* ... */
|
|
876
|
+
}
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
invalidateInstance(parentInstance);
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
function switchInstance(instance, type, newProps, fiber) {
|
|
885
|
+
var _instance$__r3f;
|
|
886
|
+
|
|
887
|
+
const parent = (_instance$__r3f = instance.__r3f) == null ? void 0 : _instance$__r3f.parent;
|
|
888
|
+
if (!parent) return;
|
|
889
|
+
const newInstance = createInstance(type, newProps, instance.__r3f.root); // https://github.com/pmndrs/react-three-fiber/issues/1348
|
|
890
|
+
// When args change the instance has to be re-constructed, which then
|
|
891
|
+
// forces r3f to re-parent the children and non-scene objects
|
|
892
|
+
// This can not include primitives, which should not have declarative children
|
|
893
|
+
|
|
894
|
+
if (type !== 'primitive' && instance.children) {
|
|
895
|
+
instance.children.forEach(child => appendChild(newInstance, child));
|
|
896
|
+
instance.children = [];
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
instance.__r3f.objects.forEach(child => appendChild(newInstance, child));
|
|
900
|
+
|
|
901
|
+
instance.__r3f.objects = [];
|
|
902
|
+
removeChild(parent, instance);
|
|
903
|
+
appendChild(parent, newInstance) // This evil hack switches the react-internal fiber node
|
|
904
|
+
// https://github.com/facebook/react/issues/14983
|
|
905
|
+
// https://github.com/facebook/react/pull/15021
|
|
906
|
+
;
|
|
907
|
+
[fiber, fiber.alternate].forEach(fiber => {
|
|
908
|
+
if (fiber !== null) {
|
|
909
|
+
fiber.stateNode = newInstance;
|
|
910
|
+
|
|
911
|
+
if (fiber.ref) {
|
|
912
|
+
if (typeof fiber.ref === 'function') fiber.ref(newInstance);else fiber.ref.current = newInstance;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
});
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
const reconciler = Reconciler({
|
|
919
|
+
appendChildToContainer: (parentInstance, child) => {
|
|
920
|
+
const {
|
|
921
|
+
container,
|
|
922
|
+
root
|
|
923
|
+
} = getContainer(parentInstance, child); // Link current root to the default scene
|
|
924
|
+
|
|
925
|
+
container.__r3f.root = root;
|
|
926
|
+
appendChild(container, child);
|
|
927
|
+
},
|
|
928
|
+
removeChildFromContainer: (parentInstance, child) => removeChild(getContainer(parentInstance, child).container, child),
|
|
929
|
+
insertInContainerBefore: (parentInstance, child, beforeChild) => insertBefore(getContainer(parentInstance, child).container, child, beforeChild),
|
|
930
|
+
|
|
931
|
+
prepareUpdate(instance, type, oldProps, newProps) {
|
|
932
|
+
if (instance.__r3f.primitive && newProps.object && newProps.object !== instance) return [true];else {
|
|
933
|
+
// This is a data object, let's extract critical information about it
|
|
934
|
+
const {
|
|
935
|
+
args: argsNew = [],
|
|
936
|
+
children: cN,
|
|
937
|
+
...restNew
|
|
938
|
+
} = newProps;
|
|
939
|
+
const {
|
|
940
|
+
args: argsOld = [],
|
|
941
|
+
children: cO,
|
|
942
|
+
...restOld
|
|
943
|
+
} = oldProps; // If it has new props or arguments, then it needs to be re-instanciated
|
|
944
|
+
|
|
945
|
+
if (argsNew.some((value, index) => value !== argsOld[index])) return [true]; // Create a diff-set, flag if there are any changes
|
|
946
|
+
|
|
947
|
+
const diff = diffProps(instance, restNew, restOld, true);
|
|
948
|
+
if (diff.changes.length) return [false, diff]; // Otherwise do not touch the instance
|
|
949
|
+
|
|
950
|
+
return null;
|
|
951
|
+
}
|
|
952
|
+
},
|
|
953
|
+
|
|
954
|
+
commitUpdate(instance, [reconstruct, diff], type, oldProps, newProps, fiber) {
|
|
955
|
+
// Reconstruct when args or <primitive object={...} have changes
|
|
956
|
+
if (reconstruct) switchInstance(instance, type, newProps, fiber); // Otherwise just overwrite props
|
|
957
|
+
else applyProps(instance, diff);
|
|
958
|
+
},
|
|
959
|
+
|
|
960
|
+
hideInstance(instance) {
|
|
961
|
+
if (instance.isObject3D) {
|
|
962
|
+
instance.visible = false;
|
|
963
|
+
invalidateInstance(instance);
|
|
964
|
+
}
|
|
965
|
+
},
|
|
966
|
+
|
|
967
|
+
unhideInstance(instance, props) {
|
|
968
|
+
if (instance.isObject3D && props.visible == null || props.visible) {
|
|
969
|
+
instance.visible = true;
|
|
970
|
+
invalidateInstance(instance);
|
|
971
|
+
}
|
|
972
|
+
},
|
|
973
|
+
|
|
974
|
+
createInstance,
|
|
975
|
+
removeChild,
|
|
976
|
+
appendChild,
|
|
977
|
+
appendInitialChild: appendChild,
|
|
978
|
+
insertBefore,
|
|
979
|
+
warnsIfNotActing: true,
|
|
980
|
+
supportsMutation: true,
|
|
981
|
+
isPrimaryRenderer: false,
|
|
982
|
+
getCurrentEventPriority: () => getEventPriority ? getEventPriority() : DefaultEventPriority,
|
|
983
|
+
// @ts-ignore
|
|
984
|
+
now: is.fun(performance.now) ? performance.now : is.fun(Date.now) ? Date.now : undefined,
|
|
985
|
+
// @ts-ignore
|
|
986
|
+
scheduleTimeout: is.fun(setTimeout) ? setTimeout : undefined,
|
|
987
|
+
// @ts-ignore
|
|
988
|
+
cancelTimeout: is.fun(clearTimeout) ? clearTimeout : undefined,
|
|
989
|
+
setTimeout: is.fun(setTimeout) ? setTimeout : undefined,
|
|
990
|
+
clearTimeout: is.fun(clearTimeout) ? clearTimeout : undefined,
|
|
991
|
+
noTimeout: -1,
|
|
992
|
+
hideTextInstance: () => {
|
|
993
|
+
throw new Error('Text is not allowed in the R3F tree.');
|
|
994
|
+
},
|
|
995
|
+
// prettier-ignore
|
|
996
|
+
getPublicInstance: instance => instance,
|
|
997
|
+
getRootHostContext: () => null,
|
|
998
|
+
getChildHostContext: parentHostContext => parentHostContext,
|
|
999
|
+
createTextInstance: () => {},
|
|
1000
|
+
finalizeInitialChildren: () => false,
|
|
1001
|
+
commitMount: () => {},
|
|
1002
|
+
shouldDeprioritizeSubtree: () => false,
|
|
1003
|
+
prepareForCommit: () => null,
|
|
1004
|
+
preparePortalMount: containerInfo => prepare(containerInfo),
|
|
1005
|
+
resetAfterCommit: () => {},
|
|
1006
|
+
shouldSetTextContent: () => false,
|
|
1007
|
+
clearContainer: () => false,
|
|
1008
|
+
detachDeletedInstance: () => {}
|
|
1009
|
+
});
|
|
1010
|
+
return {
|
|
1011
|
+
reconciler,
|
|
1012
|
+
applyProps
|
|
1013
|
+
};
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
const isRenderer = def => !!(def != null && def.render);
|
|
1017
|
+
const isOrthographicCamera = def => def && def.isOrthographicCamera;
|
|
1018
|
+
const context = /*#__PURE__*/React.createContext(null);
|
|
1019
|
+
|
|
1020
|
+
const createStore = (applyProps, invalidate, advance, props) => {
|
|
1021
|
+
const {
|
|
1022
|
+
gl,
|
|
1023
|
+
size,
|
|
1024
|
+
shadows = false,
|
|
1025
|
+
linear = false,
|
|
1026
|
+
flat = false,
|
|
1027
|
+
orthographic = false,
|
|
1028
|
+
frameloop = 'always',
|
|
1029
|
+
dpr = [1, 2],
|
|
1030
|
+
performance,
|
|
1031
|
+
clock = new THREE.Clock(),
|
|
1032
|
+
raycaster: raycastOptions,
|
|
1033
|
+
camera: cameraOptions,
|
|
1034
|
+
onPointerMissed
|
|
1035
|
+
} = props; // Set shadowmap
|
|
1036
|
+
|
|
1037
|
+
if (shadows) {
|
|
1038
|
+
gl.shadowMap.enabled = true;
|
|
1039
|
+
if (typeof shadows === 'object') Object.assign(gl.shadowMap, shadows);else gl.shadowMap.type = THREE.PCFSoftShadowMap;
|
|
1040
|
+
} // Set color preferences
|
|
1041
|
+
|
|
1042
|
+
|
|
1043
|
+
if (linear) gl.outputEncoding = THREE.LinearEncoding;
|
|
1044
|
+
if (flat) gl.toneMapping = THREE.NoToneMapping; // clock.elapsedTime is updated using advance(timestamp)
|
|
1045
|
+
|
|
1046
|
+
if (frameloop === 'never') {
|
|
1047
|
+
clock.stop();
|
|
1048
|
+
clock.elapsedTime = 0;
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
const rootState = create((set, get) => {
|
|
1052
|
+
// Create custom raycaster
|
|
1053
|
+
const raycaster = new THREE.Raycaster();
|
|
1054
|
+
const {
|
|
1055
|
+
params,
|
|
1056
|
+
...options
|
|
1057
|
+
} = raycastOptions || {};
|
|
1058
|
+
applyProps(raycaster, {
|
|
1059
|
+
enabled: true,
|
|
1060
|
+
...options,
|
|
1061
|
+
params: { ...raycaster.params,
|
|
1062
|
+
...params
|
|
1063
|
+
}
|
|
1064
|
+
}); // Create default camera
|
|
1065
|
+
|
|
1066
|
+
const isCamera = cameraOptions instanceof THREE.Camera;
|
|
1067
|
+
const camera = isCamera ? cameraOptions : orthographic ? new THREE.OrthographicCamera(0, 0, 0, 0, 0.1, 1000) : new THREE.PerspectiveCamera(75, 0, 0.1, 1000);
|
|
1068
|
+
|
|
1069
|
+
if (!isCamera) {
|
|
1070
|
+
camera.position.z = 5;
|
|
1071
|
+
if (cameraOptions) applyProps(camera, cameraOptions); // Always look at center by default
|
|
1072
|
+
|
|
1073
|
+
if (!(cameraOptions != null && cameraOptions.rotation)) camera.lookAt(0, 0, 0);
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
const initialDpr = calculateDpr(dpr);
|
|
1077
|
+
const position = new THREE.Vector3();
|
|
1078
|
+
const defaultTarget = new THREE.Vector3();
|
|
1079
|
+
const tempTarget = new THREE.Vector3();
|
|
1080
|
+
|
|
1081
|
+
function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
|
|
1082
|
+
const {
|
|
1083
|
+
width,
|
|
1084
|
+
height
|
|
1085
|
+
} = size;
|
|
1086
|
+
const aspect = width / height;
|
|
1087
|
+
if (target instanceof THREE.Vector3) tempTarget.copy(target);else tempTarget.set(...target);
|
|
1088
|
+
const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
|
|
1089
|
+
|
|
1090
|
+
if (isOrthographicCamera(camera)) {
|
|
1091
|
+
return {
|
|
1092
|
+
width: width / camera.zoom,
|
|
1093
|
+
height: height / camera.zoom,
|
|
1094
|
+
factor: 1,
|
|
1095
|
+
distance,
|
|
1096
|
+
aspect
|
|
1097
|
+
};
|
|
1098
|
+
} else {
|
|
1099
|
+
const fov = camera.fov * Math.PI / 180; // convert vertical fov to radians
|
|
1100
|
+
|
|
1101
|
+
const h = 2 * Math.tan(fov / 2) * distance; // visible height
|
|
1102
|
+
|
|
1103
|
+
const w = h * (width / height);
|
|
1104
|
+
return {
|
|
1105
|
+
width: w,
|
|
1106
|
+
height: h,
|
|
1107
|
+
factor: width / w,
|
|
1108
|
+
distance,
|
|
1109
|
+
aspect
|
|
1110
|
+
};
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
let performanceTimeout = undefined;
|
|
1115
|
+
|
|
1116
|
+
const setPerformanceCurrent = current => set(state => ({
|
|
1117
|
+
performance: { ...state.performance,
|
|
1118
|
+
current
|
|
1119
|
+
}
|
|
1120
|
+
})); // Handle frame behavior in WebXR
|
|
1121
|
+
|
|
1122
|
+
|
|
1123
|
+
const handleXRFrame = timestamp => {
|
|
1124
|
+
const state = get();
|
|
1125
|
+
if (state.frameloop === 'never') return;
|
|
1126
|
+
advance(timestamp, true);
|
|
1127
|
+
}; // Toggle render switching on session
|
|
1128
|
+
|
|
1129
|
+
|
|
1130
|
+
const handleSessionChange = () => {
|
|
1131
|
+
gl.xr.enabled = gl.xr.isPresenting;
|
|
1132
|
+
gl.setAnimationLoop(gl.xr.isPresenting ? handleXRFrame : null); // If exiting session, request frame
|
|
1133
|
+
|
|
1134
|
+
if (!gl.xr.isPresenting) invalidate(get());
|
|
1135
|
+
}; // WebXR session manager
|
|
1136
|
+
|
|
1137
|
+
|
|
1138
|
+
const xr = {
|
|
1139
|
+
connect() {
|
|
1140
|
+
gl.xr.addEventListener('sessionstart', handleSessionChange);
|
|
1141
|
+
gl.xr.addEventListener('sessionend', handleSessionChange);
|
|
1142
|
+
},
|
|
1143
|
+
|
|
1144
|
+
disconnect() {
|
|
1145
|
+
gl.xr.removeEventListener('sessionstart', handleSessionChange);
|
|
1146
|
+
gl.xr.removeEventListener('sessionend', handleSessionChange);
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
}; // Subscribe to WebXR session events
|
|
1150
|
+
|
|
1151
|
+
if (gl.xr) xr.connect();
|
|
1152
|
+
return {
|
|
1153
|
+
gl,
|
|
1154
|
+
set,
|
|
1155
|
+
get,
|
|
1156
|
+
invalidate: () => invalidate(get()),
|
|
1157
|
+
advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
|
|
1158
|
+
linear,
|
|
1159
|
+
flat,
|
|
1160
|
+
scene: prepare(new THREE.Scene()),
|
|
1161
|
+
camera,
|
|
1162
|
+
controls: null,
|
|
1163
|
+
raycaster,
|
|
1164
|
+
clock,
|
|
1165
|
+
mouse: new THREE.Vector2(),
|
|
1166
|
+
frameloop,
|
|
1167
|
+
onPointerMissed,
|
|
1168
|
+
performance: {
|
|
1169
|
+
current: 1,
|
|
1170
|
+
min: 0.5,
|
|
1171
|
+
max: 1,
|
|
1172
|
+
debounce: 200,
|
|
1173
|
+
...performance,
|
|
1174
|
+
regress: () => {
|
|
1175
|
+
const state = get(); // Clear timeout
|
|
1176
|
+
|
|
1177
|
+
if (performanceTimeout) clearTimeout(performanceTimeout); // Set lower bound performance
|
|
1178
|
+
|
|
1179
|
+
if (state.performance.current !== state.performance.min) setPerformanceCurrent(state.performance.min); // Go back to upper bound performance after a while unless something regresses meanwhile
|
|
1180
|
+
|
|
1181
|
+
performanceTimeout = setTimeout(() => setPerformanceCurrent(get().performance.max), state.performance.debounce);
|
|
1182
|
+
}
|
|
1183
|
+
},
|
|
1184
|
+
size: {
|
|
1185
|
+
width: 0,
|
|
1186
|
+
height: 0
|
|
1187
|
+
},
|
|
1188
|
+
viewport: {
|
|
1189
|
+
initialDpr,
|
|
1190
|
+
dpr: initialDpr,
|
|
1191
|
+
width: 0,
|
|
1192
|
+
height: 0,
|
|
1193
|
+
aspect: 0,
|
|
1194
|
+
distance: 0,
|
|
1195
|
+
factor: 0,
|
|
1196
|
+
getCurrentViewport
|
|
1197
|
+
},
|
|
1198
|
+
setSize: (width, height) => {
|
|
1199
|
+
const size = {
|
|
1200
|
+
width,
|
|
1201
|
+
height
|
|
1202
|
+
};
|
|
1203
|
+
set(state => ({
|
|
1204
|
+
size,
|
|
1205
|
+
viewport: { ...state.viewport,
|
|
1206
|
+
...getCurrentViewport(camera, defaultTarget, size)
|
|
1207
|
+
}
|
|
1208
|
+
}));
|
|
1209
|
+
},
|
|
1210
|
+
setDpr: dpr => set(state => ({
|
|
1211
|
+
viewport: { ...state.viewport,
|
|
1212
|
+
dpr: calculateDpr(dpr)
|
|
1213
|
+
}
|
|
1214
|
+
})),
|
|
1215
|
+
events: {
|
|
1216
|
+
connected: false
|
|
1217
|
+
},
|
|
1218
|
+
internal: {
|
|
1219
|
+
active: false,
|
|
1220
|
+
priority: 0,
|
|
1221
|
+
frames: 0,
|
|
1222
|
+
lastProps: props,
|
|
1223
|
+
interaction: [],
|
|
1224
|
+
hovered: new Map(),
|
|
1225
|
+
subscribers: [],
|
|
1226
|
+
initialClick: [0, 0],
|
|
1227
|
+
initialHits: [],
|
|
1228
|
+
capturedMap: new Map(),
|
|
1229
|
+
xr,
|
|
1230
|
+
subscribe: (ref, priority = 0) => {
|
|
1231
|
+
set(({
|
|
1232
|
+
internal
|
|
1233
|
+
}) => ({
|
|
1234
|
+
internal: { ...internal,
|
|
1235
|
+
// If this subscription was given a priority, it takes rendering into its own hands
|
|
1236
|
+
// For that reason we switch off automatic rendering and increase the manual flag
|
|
1237
|
+
// As long as this flag is positive there can be no internal rendering at all
|
|
1238
|
+
// because there could be multiple render subscriptions
|
|
1239
|
+
priority: internal.priority + (priority > 0 ? 1 : 0),
|
|
1240
|
+
// Register subscriber and sort layers from lowest to highest, meaning,
|
|
1241
|
+
// highest priority renders last (on top of the other frames)
|
|
1242
|
+
subscribers: [...internal.subscribers, {
|
|
1243
|
+
ref,
|
|
1244
|
+
priority
|
|
1245
|
+
}].sort((a, b) => a.priority - b.priority)
|
|
1246
|
+
}
|
|
1247
|
+
}));
|
|
1248
|
+
return () => {
|
|
1249
|
+
set(({
|
|
1250
|
+
internal
|
|
1251
|
+
}) => ({
|
|
1252
|
+
internal: { ...internal,
|
|
1253
|
+
// Decrease manual flag if this subscription had a priority
|
|
1254
|
+
priority: internal.priority - (priority > 0 ? 1 : 0),
|
|
1255
|
+
// Remove subscriber from list
|
|
1256
|
+
subscribers: internal.subscribers.filter(s => s.ref !== ref)
|
|
1257
|
+
}
|
|
1258
|
+
}));
|
|
1259
|
+
};
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
};
|
|
1263
|
+
});
|
|
1264
|
+
const state = rootState.getState(); // Resize camera and renderer on changes to size and pixelratio
|
|
1265
|
+
|
|
1266
|
+
let oldSize = state.size;
|
|
1267
|
+
let oldDpr = state.viewport.dpr;
|
|
1268
|
+
rootState.subscribe(() => {
|
|
1269
|
+
const {
|
|
1270
|
+
camera,
|
|
1271
|
+
size,
|
|
1272
|
+
viewport,
|
|
1273
|
+
internal
|
|
1274
|
+
} = rootState.getState();
|
|
1275
|
+
|
|
1276
|
+
if (size !== oldSize || viewport.dpr !== oldDpr) {
|
|
1277
|
+
// https://github.com/pmndrs/react-three-fiber/issues/92
|
|
1278
|
+
// Do not mess with the camera if it belongs to the user
|
|
1279
|
+
if (!(internal.lastProps.camera instanceof THREE.Camera)) {
|
|
1280
|
+
if (isOrthographicCamera(camera)) {
|
|
1281
|
+
camera.left = size.width / -2;
|
|
1282
|
+
camera.right = size.width / 2;
|
|
1283
|
+
camera.top = size.height / 2;
|
|
1284
|
+
camera.bottom = size.height / -2;
|
|
1285
|
+
} else {
|
|
1286
|
+
camera.aspect = size.width / size.height;
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
camera.updateProjectionMatrix(); // https://github.com/pmndrs/react-three-fiber/issues/178
|
|
1290
|
+
// Update matrix world since the renderer is a frame late
|
|
1291
|
+
|
|
1292
|
+
camera.updateMatrixWorld();
|
|
1293
|
+
} // Update renderer
|
|
1294
|
+
|
|
1295
|
+
|
|
1296
|
+
gl.setPixelRatio(viewport.dpr);
|
|
1297
|
+
gl.setSize(size.width, size.height);
|
|
1298
|
+
oldSize = size;
|
|
1299
|
+
oldDpr = viewport.dpr;
|
|
1300
|
+
}
|
|
1301
|
+
}); // Update size
|
|
1302
|
+
|
|
1303
|
+
if (size) state.setSize(size.width, size.height); // Invalidate on any change
|
|
1304
|
+
|
|
1305
|
+
rootState.subscribe(state => invalidate(state)); // Return root state
|
|
1306
|
+
|
|
1307
|
+
return rootState;
|
|
1308
|
+
};
|
|
1309
|
+
|
|
1310
|
+
function createSubs(callback, subs) {
|
|
1311
|
+
const index = subs.length;
|
|
1312
|
+
subs.push(callback);
|
|
1313
|
+
return () => void subs.splice(index, 1);
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
let i;
|
|
1317
|
+
let globalEffects = [];
|
|
1318
|
+
let globalAfterEffects = [];
|
|
1319
|
+
let globalTailEffects = [];
|
|
1320
|
+
const addEffect = callback => createSubs(callback, globalEffects);
|
|
1321
|
+
const addAfterEffect = callback => createSubs(callback, globalAfterEffects);
|
|
1322
|
+
const addTail = callback => createSubs(callback, globalTailEffects);
|
|
1323
|
+
|
|
1324
|
+
function run(effects, timestamp) {
|
|
1325
|
+
for (i = 0; i < effects.length; i++) effects[i](timestamp);
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
function render(timestamp, state) {
|
|
1329
|
+
// Run local effects
|
|
1330
|
+
let delta = state.clock.getDelta(); // In frameloop='never' mode, clock times are updated using the provided timestamp
|
|
1331
|
+
|
|
1332
|
+
if (state.frameloop === 'never' && typeof timestamp === 'number') {
|
|
1333
|
+
delta = timestamp - state.clock.elapsedTime;
|
|
1334
|
+
state.clock.oldTime = state.clock.elapsedTime;
|
|
1335
|
+
state.clock.elapsedTime = timestamp;
|
|
1336
|
+
} // Call subscribers (useFrame)
|
|
1337
|
+
|
|
1338
|
+
|
|
1339
|
+
for (i = 0; i < state.internal.subscribers.length; i++) state.internal.subscribers[i].ref.current(state, delta); // Render content
|
|
1340
|
+
|
|
1341
|
+
|
|
1342
|
+
if (!state.internal.priority && state.gl.render) state.gl.render(state.scene, state.camera); // Decrease frame count
|
|
1343
|
+
|
|
1344
|
+
state.internal.frames = Math.max(0, state.internal.frames - 1);
|
|
1345
|
+
return state.frameloop === 'always' ? 1 : state.internal.frames;
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
function createLoop(roots) {
|
|
1349
|
+
let running = false;
|
|
1350
|
+
let repeat;
|
|
1351
|
+
|
|
1352
|
+
function loop(timestamp) {
|
|
1353
|
+
running = true;
|
|
1354
|
+
repeat = 0; // Run effects
|
|
1355
|
+
|
|
1356
|
+
run(globalEffects, timestamp); // Render all roots
|
|
1357
|
+
|
|
1358
|
+
roots.forEach(root => {
|
|
1359
|
+
var _state$gl$xr;
|
|
1360
|
+
|
|
1361
|
+
const state = root.store.getState(); // If the frameloop is invalidated, do not run another frame
|
|
1362
|
+
|
|
1363
|
+
if (state.internal.active && (state.frameloop === 'always' || state.internal.frames > 0) && !((_state$gl$xr = state.gl.xr) != null && _state$gl$xr.isPresenting)) repeat += render(timestamp, state);
|
|
1364
|
+
}); // Run after-effects
|
|
1365
|
+
|
|
1366
|
+
run(globalAfterEffects, timestamp); // Keep on looping if anything invalidates the frameloop
|
|
1367
|
+
|
|
1368
|
+
if (repeat > 0) return requestAnimationFrame(loop); // Tail call effects, they are called when rendering stops
|
|
1369
|
+
else run(globalTailEffects, timestamp); // Flag end of operation
|
|
1370
|
+
|
|
1371
|
+
running = false;
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
function invalidate(state) {
|
|
1375
|
+
var _state$gl$xr2;
|
|
1376
|
+
|
|
1377
|
+
if (!state) return roots.forEach(root => invalidate(root.store.getState()));
|
|
1378
|
+
if ((_state$gl$xr2 = state.gl.xr) != null && _state$gl$xr2.isPresenting || !state.internal.active || state.frameloop === 'never') return; // Increase frames, do not go higher than 60
|
|
1379
|
+
|
|
1380
|
+
state.internal.frames = Math.min(60, state.internal.frames + 1); // If the render-loop isn't active, start it
|
|
1381
|
+
|
|
1382
|
+
if (!running) {
|
|
1383
|
+
running = true;
|
|
1384
|
+
requestAnimationFrame(loop);
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
function advance(timestamp, runGlobalEffects = true, state) {
|
|
1389
|
+
if (runGlobalEffects) run(globalEffects, timestamp);
|
|
1390
|
+
if (!state) roots.forEach(root => render(timestamp, root.store.getState()));else render(timestamp, state);
|
|
1391
|
+
if (runGlobalEffects) run(globalAfterEffects, timestamp);
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
return {
|
|
1395
|
+
loop,
|
|
1396
|
+
invalidate,
|
|
1397
|
+
advance
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
function useStore() {
|
|
1402
|
+
const store = React.useContext(context);
|
|
1403
|
+
if (!store) throw `R3F hooks can only be used within the Canvas component!`;
|
|
1404
|
+
return store;
|
|
1405
|
+
}
|
|
1406
|
+
function useThree(selector = state => state, equalityFn) {
|
|
1407
|
+
return useStore()(selector, equalityFn);
|
|
1408
|
+
}
|
|
1409
|
+
function useFrame(callback, renderPriority = 0) {
|
|
1410
|
+
const subscribe = useStore().getState().internal.subscribe; // Update ref
|
|
1411
|
+
|
|
1412
|
+
const ref = React.useRef(callback);
|
|
1413
|
+
React.useLayoutEffect(() => void (ref.current = callback), [callback]); // Subscribe on mount, unsubscribe on unmount
|
|
1414
|
+
|
|
1415
|
+
React.useLayoutEffect(() => subscribe(ref, renderPriority), [renderPriority, subscribe]);
|
|
1416
|
+
return null;
|
|
1417
|
+
}
|
|
1418
|
+
function useGraph(object) {
|
|
1419
|
+
return React.useMemo(() => buildGraph(object), [object]);
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
function loadingFn(extensions, onProgress) {
|
|
1423
|
+
return function (Proto, ...input) {
|
|
1424
|
+
// Construct new loader and run extensions
|
|
1425
|
+
const loader = new Proto();
|
|
1426
|
+
if (extensions) extensions(loader); // Go through the urls and load them
|
|
1427
|
+
|
|
1428
|
+
return Promise.all(input.map(input => new Promise((res, reject) => loader.load(input, data => {
|
|
1429
|
+
if (data.scene) Object.assign(data, buildGraph(data.scene));
|
|
1430
|
+
res(data);
|
|
1431
|
+
}, onProgress, error => reject(`Could not load ${input}: ${error.message}`)))));
|
|
1432
|
+
};
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
function useLoader(Proto, input, extensions, onProgress) {
|
|
1436
|
+
// Use suspense to load async assets
|
|
1437
|
+
const keys = Array.isArray(input) ? input : [input];
|
|
1438
|
+
const results = suspend(loadingFn(extensions, onProgress), [Proto, ...keys], {
|
|
1439
|
+
equal: is.equ
|
|
1440
|
+
}); // Return the object/s
|
|
1441
|
+
|
|
1442
|
+
return Array.isArray(input) ? results : results[0];
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
useLoader.preload = function (Proto, input, extensions) {
|
|
1446
|
+
const keys = Array.isArray(input) ? input : [input];
|
|
1447
|
+
return preload(loadingFn(extensions), [Proto, ...keys]);
|
|
1448
|
+
};
|
|
1449
|
+
|
|
1450
|
+
useLoader.clear = function (Proto, input) {
|
|
1451
|
+
const keys = Array.isArray(input) ? input : [input];
|
|
1452
|
+
return clear([Proto, ...keys]);
|
|
1453
|
+
};
|
|
1454
|
+
|
|
1455
|
+
export { createLoop as a, createRenderer as b, createEvents as c, calculateDpr as d, createStore as e, context as f, dispose as g, extend as h, isRenderer as i, addEffect as j, addAfterEffect as k, addTail as l, useThree as m, useFrame as n, useGraph as o, useLoader as p, buildGraph as q, is as r, threeTypes as t, useStore as u };
|