-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
utils.ts
402 lines (359 loc) Β· 15.1 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import * as THREE from 'three'
import * as React from 'react'
import { UseBoundStore } from 'zustand'
import { EventHandlers } from './events'
import { AttachType, Instance, InstanceProps, LocalState } from './renderer'
import { Dpr, RootState, Size } from './store'
export type Camera = THREE.OrthographicCamera | THREE.PerspectiveCamera
export const isOrthographicCamera = (def: Camera): def is THREE.OrthographicCamera =>
def && (def as THREE.OrthographicCamera).isOrthographicCamera
export const isRef = (obj: any): obj is React.MutableRefObject<unknown> => obj && obj.hasOwnProperty('current')
/**
* An SSR-friendly useLayoutEffect.
*
* React currently throws a warning when using useLayoutEffect on the server.
* To get around it, we can conditionally useEffect on the server (no-op) and
* useLayoutEffect elsewhere.
*
* @see https://github.com/facebook/react/issues/14927
*/
export const useIsomorphicLayoutEffect =
typeof window !== 'undefined' && (window.document?.createElement || window.navigator?.product === 'ReactNative')
? React.useLayoutEffect
: React.useEffect
export function useMutableCallback<T>(fn: T) {
const ref = React.useRef<T>(fn)
useIsomorphicLayoutEffect(() => void (ref.current = fn), [fn])
return ref
}
export type SetBlock = false | Promise<null> | null
export type UnblockProps = { set: React.Dispatch<React.SetStateAction<SetBlock>>; children: React.ReactNode }
export function Block({ set }: Omit<UnblockProps, 'children'>) {
useIsomorphicLayoutEffect(() => {
set(new Promise(() => null))
return () => set(false)
}, [set])
return null
}
export class ErrorBoundary extends React.Component<
{ set: React.Dispatch<Error | undefined>; children: React.ReactNode },
{ error: boolean }
> {
state = { error: false }
static getDerivedStateFromError = () => ({ error: true })
componentDidCatch(err: Error) {
this.props.set(err)
}
render() {
return this.state.error ? null : this.props.children
}
}
export const DEFAULT = '__default'
export type DiffSet = {
memoized: { [key: string]: any }
changes: [key: string, value: unknown, isEvent: boolean, keys: string[]][]
}
export const isDiffSet = (def: any): def is DiffSet => def && !!(def as DiffSet).memoized && !!(def as DiffSet).changes
export type ClassConstructor = { new (): void }
export type ObjectMap = {
nodes: { [name: string]: THREE.Object3D }
materials: { [name: string]: THREE.Material }
}
export function calculateDpr(dpr: Dpr) {
const target = typeof window !== 'undefined' ? window.devicePixelRatio : 1
return Array.isArray(dpr) ? Math.min(Math.max(dpr[0], target), dpr[1]) : dpr
}
/**
* Returns instance root state
*/
export const getRootState = (obj: THREE.Object3D): RootState | undefined =>
(obj as unknown as Instance).__r3f?.root.getState()
export type EquConfig = {
/** Compare arrays by reference equality a === b (default), or by shallow equality */
arrays?: 'reference' | 'shallow'
/** Compare objects by reference equality a === b (default), or by shallow equality */
objects?: 'reference' | 'shallow'
/** If true the keys in both a and b must match 1:1 (default), if false a's keys must intersect b's */
strict?: boolean
}
// A collection of compare functions
export const is = {
obj: (a: any) => a === Object(a) && !is.arr(a) && typeof a !== 'function',
fun: (a: any): a is Function => typeof a === 'function',
str: (a: any): a is string => typeof a === 'string',
num: (a: any): a is number => typeof a === 'number',
boo: (a: any): a is boolean => typeof a === 'boolean',
und: (a: any) => a === void 0,
arr: (a: any) => Array.isArray(a),
equ(a: any, b: any, { arrays = 'shallow', objects = 'reference', strict = true }: EquConfig = {}) {
// Wrong type or one of the two undefined, doesn't match
if (typeof a !== typeof b || !!a !== !!b) return false
// Atomic, just compare a against b
if (is.str(a) || is.num(a)) return a === b
const isObj = is.obj(a)
if (isObj && objects === 'reference') return a === b
const isArr = is.arr(a)
if (isArr && arrays === 'reference') return a === b
// Array or Object, shallow compare first to see if it's a match
if ((isArr || isObj) && a === b) return true
// Last resort, go through keys
let i
for (i in a) if (!(i in b)) return false
for (i in strict ? b : a) if (a[i] !== b[i]) return false
if (is.und(i)) {
if (isArr && a.length === 0 && b.length === 0) return true
if (isObj && Object.keys(a).length === 0 && Object.keys(b).length === 0) return true
if (a !== b) return false
}
return true
},
}
// Collects nodes and materials from a THREE.Object3D
export function buildGraph(object: THREE.Object3D) {
const data: ObjectMap = { nodes: {}, materials: {} }
if (object) {
object.traverse((obj: any) => {
if (obj.name) data.nodes[obj.name] = obj
if (obj.material && !data.materials[obj.material.name]) data.materials[obj.material.name] = obj.material
})
}
return data
}
// Disposes an object and all its properties
export function dispose<TObj extends { dispose?: () => void; type?: string; [key: string]: any }>(obj: TObj) {
if (obj.dispose && obj.type !== 'Scene') obj.dispose()
for (const p in obj) {
;(p as any).dispose?.()
delete obj[p]
}
}
// Each object in the scene carries a small LocalState descriptor
export function prepare<T = THREE.Object3D>(object: T, state?: Partial<LocalState>) {
const instance = object as unknown as Instance
if (state?.primitive || !instance.__r3f) {
instance.__r3f = {
type: '',
root: null as unknown as UseBoundStore<RootState>,
previousAttach: null,
memoizedProps: {},
eventCount: 0,
handlers: {},
objects: [],
parent: null,
...state,
}
}
return object
}
function resolve(instance: Instance, key: string) {
let target = instance
if (key.includes('-')) {
const entries = key.split('-')
const last = entries.pop() as string
target = entries.reduce((acc, key) => acc[key], instance)
return { target, key: last }
} else return { target, key }
}
// Checks if a dash-cased string ends with an integer
const INDEX_REGEX = /-\d+$/
export function attach(parent: Instance, child: Instance, type: AttachType) {
if (is.str(type)) {
// If attaching into an array (foo-0), create one
if (INDEX_REGEX.test(type)) {
const root = type.replace(INDEX_REGEX, '')
const { target, key } = resolve(parent, root)
if (!Array.isArray(target[key])) target[key] = []
}
const { target, key } = resolve(parent, type)
child.__r3f.previousAttach = target[key]
target[key] = child
} else child.__r3f.previousAttach = type(parent, child)
}
export function detach(parent: Instance, child: Instance, type: AttachType) {
if (is.str(type)) {
const { target, key } = resolve(parent, type)
const previous = child.__r3f.previousAttach
// When the previous value was undefined, it means the value was never set to begin with
if (previous === undefined) delete target[key]
// Otherwise set the previous value
else target[key] = previous
} else child.__r3f?.previousAttach?.(parent, child)
delete child.__r3f?.previousAttach
}
// This function prepares a set of changes to be applied to the instance
export function diffProps(
instance: Instance,
{ children: cN, key: kN, ref: rN, ...props }: InstanceProps,
{ children: cP, key: kP, ref: rP, ...previous }: InstanceProps = {},
remove = false,
): DiffSet {
const localState = (instance?.__r3f ?? {}) as LocalState
const entries = Object.entries(props)
const changes: [key: string, value: unknown, isEvent: boolean, keys: string[]][] = []
// Catch removed props, prepend them so they can be reset or removed
if (remove) {
const previousKeys = Object.keys(previous)
for (let i = 0; i < previousKeys.length; i++) {
if (!props.hasOwnProperty(previousKeys[i])) entries.unshift([previousKeys[i], DEFAULT + 'remove'])
}
}
entries.forEach(([key, value]) => {
// Bail out on primitive object
if (instance.__r3f?.primitive && key === 'object') return
// When props match bail out
if (is.equ(value, previous[key])) return
// Collect handlers and bail out
if (/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/.test(key)) return changes.push([key, value, true, []])
// Split dashed props
let entries: string[] = []
if (key.includes('-')) entries = key.split('-')
changes.push([key, value, false, entries])
// Reset pierced props
for (const prop in props) {
const value = props[prop]
if (prop.startsWith(`${key}-`)) changes.push([prop, value, false, prop.split('-')])
}
})
const memoized: { [key: string]: any } = { ...props }
if (localState.memoizedProps && localState.memoizedProps.args) memoized.args = localState.memoizedProps.args
if (localState.memoizedProps && localState.memoizedProps.attach) memoized.attach = localState.memoizedProps.attach
return { memoized, changes }
}
// This function applies a set of changes to the instance
export function applyProps(instance: Instance, data: InstanceProps | DiffSet) {
// Filter equals, events and reserved props
const localState = (instance.__r3f ?? {}) as LocalState
const root = localState.root
const rootState = root?.getState?.() ?? {}
const { memoized, changes } = isDiffSet(data) ? data : diffProps(instance, data)
const prevHandlers = localState.eventCount
// Prepare memoized props
if (instance.__r3f) instance.__r3f.memoizedProps = memoized
for (let i = 0; i < changes.length; i++) {
let [key, value, isEvent, keys] = changes[i]
let currentInstance = instance
let targetProp = currentInstance[key]
// Revolve dashed props
if (keys.length) {
targetProp = keys.reduce((acc, key) => acc[key], instance)
// If the target is atomic, it forces us to switch the root
if (!(targetProp && targetProp.set)) {
const [name, ...reverseEntries] = keys.reverse()
currentInstance = reverseEntries.reverse().reduce((acc, key) => acc[key], instance)
key = name
}
}
// https://github.com/mrdoob/three.js/issues/21209
// HMR/fast-refresh relies on the ability to cancel out props, but threejs
// has no means to do this. Hence we curate a small collection of value-classes
// with their respective constructor/set arguments
// For removed props, try to set default values, if possible
if (value === DEFAULT + 'remove') {
if (targetProp && targetProp.constructor) {
// use the prop constructor to find the default it should be
value = new targetProp.constructor(...(memoized.args ?? []))
} else if (currentInstance.constructor) {
// create a blank slate of the instance and copy the particular parameter.
// @ts-ignore
const defaultClassCall = new currentInstance.constructor(...(currentInstance.__r3f.memoizedProps.args ?? []))
value = defaultClassCall[targetProp]
// destory the instance
if (defaultClassCall.dispose) defaultClassCall.dispose()
// instance does not have constructor, just set it to 0
} else {
value = 0
}
}
// Deal with pointer events ...
if (isEvent) {
if (value) localState.handlers[key as keyof EventHandlers] = value as any
else delete localState.handlers[key as keyof EventHandlers]
localState.eventCount = Object.keys(localState.handlers).length
}
// Special treatment for objects with support for set/copy, and layers
else if (targetProp && targetProp.set && (targetProp.copy || targetProp instanceof THREE.Layers)) {
// If value is an array
if (Array.isArray(value)) {
if (targetProp.fromArray) targetProp.fromArray(value)
else targetProp.set(...value)
}
// Test again target.copy(class) next ...
else if (
targetProp.copy &&
value &&
(value as ClassConstructor).constructor &&
targetProp.constructor.name === (value as ClassConstructor).constructor.name
) {
targetProp.copy(value)
}
// If nothing else fits, just set the single value, ignore undefined
// https://github.com/pmndrs/react-three-fiber/issues/274
else if (value !== undefined) {
const isColor = targetProp instanceof THREE.Color
// Allow setting array scalars
if (!isColor && targetProp.setScalar) targetProp.setScalar(value)
// Layers have no copy function, we must therefore copy the mask property
else if (targetProp instanceof THREE.Layers && value instanceof THREE.Layers) targetProp.mask = value.mask
// Otherwise just set ...
else targetProp.set(value)
// For versions of three which don't support THREE.ColorManagement,
// Auto-convert sRGB colors
// https://github.com/pmndrs/react-three-fiber/issues/344
const supportsColorManagement = 'ColorManagement' in THREE
if (!supportsColorManagement && !rootState.linear && isColor) targetProp.convertSRGBToLinear()
}
// Else, just overwrite the value
} else {
currentInstance[key] = value
// Auto-convert sRGB textures, for now ...
// https://github.com/pmndrs/react-three-fiber/issues/344
if (!rootState.linear && currentInstance[key] instanceof THREE.Texture) {
currentInstance[key].encoding = THREE.sRGBEncoding
}
}
invalidateInstance(instance)
}
if (localState.parent && rootState.internal && instance.raycast && prevHandlers !== localState.eventCount) {
// Pre-emptively remove the instance from the interaction manager
const index = rootState.internal.interaction.indexOf(instance as unknown as THREE.Object3D)
if (index > -1) rootState.internal.interaction.splice(index, 1)
// Add the instance to the interaction manager only when it has handlers
if (localState.eventCount) rootState.internal.interaction.push(instance as unknown as THREE.Object3D)
}
// Call the update lifecycle when it is being updated, but only when it is part of the scene
if (changes.length && instance.__r3f?.parent) updateInstance(instance)
return instance
}
export function invalidateInstance(instance: Instance) {
const state = instance.__r3f?.root?.getState?.()
if (state && state.internal.frames === 0) state.invalidate()
}
export function updateInstance(instance: Instance) {
instance.onUpdate?.(instance)
}
export function updateCamera(camera: Camera & { manual?: boolean }, size: Size) {
// https://github.com/pmndrs/react-three-fiber/issues/92
// Do not mess with the camera if it belongs to the user
if (!camera.manual) {
if (isOrthographicCamera(camera)) {
camera.left = size.width / -2
camera.right = size.width / 2
camera.top = size.height / 2
camera.bottom = size.height / -2
} else {
camera.aspect = size.width / size.height
}
camera.updateProjectionMatrix()
// https://github.com/pmndrs/react-three-fiber/issues/178
// Update matrix world since the renderer is a frame late
camera.updateMatrixWorld()
}
}
/**
* Safely sets a deeply-nested value on an object.
*/
export function setDeep(obj: any, value: any, keys: string[]) {
const key = keys.pop()!
const target = keys.reduce((acc, key) => acc[key], obj)
return (target[key] = value)
}