Repository navigation
Expand file tree
/
Copy pathutils.js
More file actions
493 lines (360 loc) · 12.2 KB
/
Copy pathutils.js
File metadata and controls
493 lines (360 loc) · 12.2 KB
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
import { AlwaysDepth, EqualDepth, GreaterDepth, GreaterEqualDepth, LessDepth, LessEqualDepth, NeverDepth, NotEqualDepth } from './constants.js';
/**
* Finds the minimum value in an array.
*
* @private
* @param {Array<number>} array - The array to search for the minimum value.
* @return {number} The minimum value in the array, or Infinity if the array is empty.
*/
function arrayMin( array ) {
if ( array.length === 0 ) return Infinity;
let min = array[ 0 ];
for ( let i = 1, l = array.length; i < l; ++ i ) {
if ( array[ i ] < min ) min = array[ i ];
}
return min;
}
/**
* Finds the maximum value in an array.
*
* @private
* @param {Array<number>} array - The array to search for the maximum value.
* @return {number} The maximum value in the array, or -Infinity if the array is empty.
*/
function arrayMax( array ) {
if ( array.length === 0 ) return - Infinity;
let max = array[ 0 ];
for ( let i = 1, l = array.length; i < l; ++ i ) {
if ( array[ i ] > max ) max = array[ i ];
}
return max;
}
/**
* Checks if an array contains values that require Uint32 representation.
*
* This function determines whether the array contains any values >= 65535,
* which would require a Uint32Array rather than a Uint16Array for proper storage.
* The function iterates from the end of the array, assuming larger values are
* typically located at the end.
*
* @private
* @param {Array<number>} array - The array to check.
* @return {boolean} True if the array contains values >= 65535, false otherwise.
*/
function arrayNeedsUint32( array ) {
// assumes larger values usually on last
for ( let i = array.length - 1; i >= 0; -- i ) {
if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
}
return false;
}
/**
* Map of typed array constructor names to their constructors.
* This mapping enables dynamic creation of typed arrays based on string type names.
*
* @private
* @constant
* @type {Object<string, TypedArrayConstructor>}
*/
const TYPED_ARRAYS = {
Int8Array: Int8Array,
Uint8Array: Uint8Array,
Uint8ClampedArray: Uint8ClampedArray,
Int16Array: Int16Array,
Uint16Array: Uint16Array,
Int32Array: Int32Array,
Uint32Array: Uint32Array,
Float32Array: Float32Array,
Float64Array: Float64Array
};
/**
* Creates a typed array of the specified type from the given buffer.
*
* @private
* @param {string} type - The name of the typed array type (e.g., 'Float32Array', 'Uint16Array').
* @param {ArrayBuffer} buffer - The buffer to create the typed array from.
* @return {TypedArray} A new typed array of the specified type.
*/
function getTypedArray( type, buffer ) {
return new TYPED_ARRAYS[ type ]( buffer );
}
/**
* Returns `true` if the given object is a typed array.
*
* @param {any} array - The object to check.
* @return {boolean} Whether the given object is a typed array.
*/
function isTypedArray( array ) {
return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
}
/**
* Creates an XHTML element with the specified tag name.
*
* This function uses the XHTML namespace to create DOM elements,
* ensuring proper element creation in XML-based contexts.
*
* @private
* @param {string} name - The tag name of the element to create (e.g., 'canvas', 'div').
* @return {HTMLElement} The created XHTML element.
*/
function createElementNS( name ) {
return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
}
/**
* Creates a canvas element configured for block display.
*
* This is a convenience function that creates a canvas element with
* display style set to 'block', which is commonly used in three.js
* rendering contexts to avoid inline element spacing issues.
*
* @return {HTMLCanvasElement} A canvas element with display set to 'block'.
*/
function createCanvasElement() {
const canvas = createElementNS( 'canvas' );
canvas.style.display = 'block';
return canvas;
}
/**
* Internal cache for tracking warning messages to prevent duplicate warnings.
*
* @private
* @type {Object<string, boolean>}
*/
const _cache = {};
/**
* Custom console function handler for intercepting log, warn, and error calls.
*
* @private
* @type {Function|null}
*/
let _setConsoleFunction = null;
/**
* Sets a custom function to handle console output.
*
* This allows external code to intercept and handle console.log, console.warn,
* and console.error calls made by three.js, which is useful for custom logging,
* testing, or debugging workflows.
*
* @param {Function} fn - The function to handle console output. Should accept
* (type, message, ...params) where type is 'log', 'warn', or 'error'.
*/
function setConsoleFunction( fn ) {
_setConsoleFunction = fn;
}
/**
* Gets the currently set custom console function.
*
* @return {Function|null} The custom console function, or null if not set.
*/
function getConsoleFunction() {
return _setConsoleFunction;
}
/**
* Logs an informational message with the 'THREE.' prefix.
*
* If a custom console function is set via setConsoleFunction(), it will be used
* instead of the native console.log. The first parameter is treated as the
* method name and is automatically prefixed with 'THREE.'.
*
* @param {...any} params - The message components. The first param is used as
* the method name and prefixed with 'THREE.'.
*/
function log( ...params ) {
const message = 'THREE.' + params.shift();
if ( _setConsoleFunction ) {
_setConsoleFunction( 'log', message, ...params );
} else {
console.log( message, ...params );
}
}
/**
* Enhances log/warn/error messages related to TSL.
*
* @param {Array<any>} params - The original message parameters.
* @returns {Array<any>} The filtered and enhanced message parameters.
*/
function enhanceLogMessage( params ) {
const message = params[ 0 ];
if ( typeof message === 'string' && message.startsWith( 'TSL:' ) ) {
const stackTrace = params[ 1 ];
if ( stackTrace && stackTrace.isStackTrace ) {
params[ 0 ] += ' ' + stackTrace.getLocation();
} else {
params[ 1 ] = 'Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.';
}
}
return params;
}
/**
* Logs a warning message with the 'THREE.' prefix.
*
* If a custom console function is set via setConsoleFunction(), it will be used
* instead of the native console.warn. The first parameter is treated as the
* method name and is automatically prefixed with 'THREE.'.
*
* @param {...any} params - The message components. The first param is used as
* the method name and prefixed with 'THREE.'.
*/
function warn( ...params ) {
params = enhanceLogMessage( params );
const message = 'THREE.' + params.shift();
if ( _setConsoleFunction ) {
_setConsoleFunction( 'warn', message, ...params );
} else {
const stackTrace = params[ 0 ];
if ( stackTrace && stackTrace.isStackTrace ) {
console.warn( stackTrace.getError( message ) );
} else {
console.warn( message, ...params );
}
}
}
/**
* Logs an error message with the 'THREE.' prefix.
*
* If a custom console function is set via setConsoleFunction(), it will be used
* instead of the native console.error. The first parameter is treated as the
* method name and is automatically prefixed with 'THREE.'.
*
* @param {...any} params - The message components. The first param is used as
* the method name and prefixed with 'THREE.'.
*/
function error( ...params ) {
params = enhanceLogMessage( params );
const message = 'THREE.' + params.shift();
if ( _setConsoleFunction ) {
_setConsoleFunction( 'error', message, ...params );
} else {
const stackTrace = params[ 0 ];
if ( stackTrace && stackTrace.isStackTrace ) {
console.error( stackTrace.getError( message ) );
} else {
console.error( message, ...params );
}
}
}
/**
* Logs a warning message only once, preventing duplicate warnings.
*
* This function maintains an internal cache of warning messages and will only
* output each unique warning message once. Useful for warnings that may be
* triggered repeatedly but should only be shown to the user once.
*
* @param {...any} params - The warning message components.
*/
function warnOnce( ...params ) {
const message = params.join( ' ' );
if ( message in _cache ) return;
_cache[ message ] = true;
warn( ...params );
}
/**
* Yields execution to the main thread to allow rendering and other tasks.
* Uses scheduler.yield() when available (Chrome 115+), falls back to requestAnimationFrame.
*
* @return {Promise<void>}
*/
function yieldToMain() {
if ( typeof self !== 'undefined' && typeof self.scheduler !== 'undefined' && typeof self.scheduler.yield !== 'undefined' ) {
return self.scheduler.yield();
}
return new Promise( resolve => {
requestAnimationFrame( resolve );
} );
}
/**
* Asynchronously probes for WebGL sync object completion.
*
* This function creates a promise that resolves when the WebGL sync object
* signals completion or rejects if the sync operation fails. It uses polling
* at the specified interval to check the sync status without blocking the
* main thread. This is useful for GPU-CPU synchronization in WebGL contexts.
*
* @private
* @param {WebGL2RenderingContext} gl - The WebGL rendering context.
* @param {WebGLSync} sync - The WebGL sync object to wait for.
* @param {number} interval - The polling interval in milliseconds.
* @return {Promise<void>} A promise that resolves when the sync completes or rejects if it fails.
*/
function probeAsync( gl, sync, interval ) {
return new Promise( function ( resolve, reject ) {
function probe() {
switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
case gl.WAIT_FAILED:
reject();
break;
case gl.TIMEOUT_EXPIRED:
setTimeout( probe, interval );
break;
default:
resolve();
}
}
setTimeout( probe, interval );
} );
}
/**
* Converts a projection matrix from normalized device coordinates (NDC)
* range [-1, 1] to [0, 1].
*
* This conversion is commonly needed when working with depth textures or
* render targets that expect depth values in the [0, 1] range rather than
* the standard OpenGL NDC range of [-1, 1]. The function modifies the
* projection matrix in place.
*
* @private
* @param {Matrix4} projectionMatrix - The projection matrix to convert (modified in place).
*/
function toNormalizedProjectionMatrix( projectionMatrix ) {
const m = projectionMatrix.elements;
// Convert [-1, 1] to [0, 1] projection matrix
m[ 2 ] = 0.5 * m[ 2 ] + 0.5 * m[ 3 ];
m[ 6 ] = 0.5 * m[ 6 ] + 0.5 * m[ 7 ];
m[ 10 ] = 0.5 * m[ 10 ] + 0.5 * m[ 11 ];
m[ 14 ] = 0.5 * m[ 14 ] + 0.5 * m[ 15 ];
}
/**
* Reverses the depth range of a projection matrix.
*
* This function inverts the depth mapping of a projection matrix, which is
* useful for reversed-Z depth buffer techniques that can improve depth
* precision. The function handles both perspective and orthographic projection
* matrices differently and modifies the matrix in place.
*
* For perspective matrices (where m[11] === -1), the depth mapping is
* reversed with an offset. For orthographic matrices, a simpler reversal
* is applied.
*
* @private
* @param {Matrix4} projectionMatrix - The projection matrix to reverse (modified in place).
*/
function toReversedProjectionMatrix( projectionMatrix ) {
const m = projectionMatrix.elements;
const isPerspectiveMatrix = m[ 11 ] === - 1;
// Reverse [0, 1] projection matrix
if ( isPerspectiveMatrix ) {
m[ 10 ] = - m[ 10 ] - 1;
m[ 14 ] = - m[ 14 ];
} else {
m[ 10 ] = - m[ 10 ];
m[ 14 ] = - m[ 14 ] + 1;
}
}
/**
* Used to select the correct depth functions
* when reversed depth buffer is used.
*
* @private
* @type {Object}
*/
const ReversedDepthFuncs = {
[ NeverDepth ]: AlwaysDepth,
[ LessDepth ]: GreaterDepth,
[ EqualDepth ]: NotEqualDepth,
[ LessEqualDepth ]: GreaterEqualDepth,
[ AlwaysDepth ]: NeverDepth,
[ GreaterDepth ]: LessDepth,
[ NotEqualDepth ]: EqualDepth,
[ GreaterEqualDepth ]: LessEqualDepth,
};
export { arrayMin, arrayMax, arrayNeedsUint32, getTypedArray, createElementNS, createCanvasElement, setConsoleFunction, getConsoleFunction, log, warn, error, warnOnce, probeAsync, yieldToMain, toNormalizedProjectionMatrix, toReversedProjectionMatrix, isTypedArray, ReversedDepthFuncs };