-
-
Notifications
You must be signed in to change notification settings - Fork 91
/
BVH.js
662 lines (426 loc) · 12.9 KB
/
BVH.js
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
import { AABB } from './AABB.js';
import { Vector3 } from './Vector3.js';
const v1 = new Vector3();
const v2 = new Vector3();
const v3 = new Vector3();
const xAxis = new Vector3( 1, 0, 0 );
const yAxis = new Vector3( 0, 1, 0 );
const zAxis = new Vector3( 0, 0, 1 );
const triangle = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
const intersection = new Vector3();
const intersections = new Array();
/**
* Class representing a bounding volume hierarchy. The current implementation
* represents single BVH nodes as AABBs. It accepts arbitrary branching factors
* and can subdivide the given geometry until a defined hierarchy depth has been reached.
* Besides, the hierarchy construction is performed top-down and the algorithm only
* performs splits along the cardinal axes.
*
* Reference: Bounding Volume Hierarchies in Real-Time Collision Detection
* by Christer Ericson (chapter 6).
*
* @author {@link https://github.com/robp94|robp94}
* @author {@link https://github.com/Mugen87|Mugen87}
*/
class BVH {
/**
* Constructs a new BVH.
*
* @param {Number} branchingFactor - The branching factor.
* @param {Number} primitivesPerNode - The minimum amount of primitives per BVH node.
* @param {Number} depth - The maximum hierarchical depth.
*/
constructor( branchingFactor = 2, primitivesPerNode = 1, depth = 10 ) {
/**
* The branching factor (how many nodes per level).
* @type {Number}
* @default 2
*/
this.branchingFactor = branchingFactor;
/**
* The minimum amount of primitives per BVH node.
* @type {Number}
* @default 10
*/
this.primitivesPerNode = primitivesPerNode;
/**
* The maximum hierarchical depth.
* @type {Number}
* @default 10
*/
this.depth = depth;
/**
* The root BVH node.
* @type {BVHNode}
* @default null
*/
this.root = null;
}
/**
* Computes a BVH for the given mesh geometry.
*
* @param {MeshGeometry} geometry - The mesh geometry.
* @return {BVH} A reference to this BVH.
*/
fromMeshGeometry( geometry ) {
this.root = new BVHNode();
// primitives
if ( geometry.indices !== null ) geometry = geometry.toTriangleSoup();
const vertices = geometry.vertices;
for ( let i = 0, l = vertices.length; i < l; i ++ ) {
this.root.primitives.push( vertices[ i ] );
}
// centroids
const primitives = this.root.primitives;
for ( let i = 0, l = primitives.length; i < l; i += 9 ) {
v1.fromArray( primitives, i );
v2.fromArray( primitives, i + 3 );
v3.fromArray( primitives, i + 6 );
v1.add( v2 ).add( v3 ).divideScalar( 3 );
this.root.centroids.push( v1.x, v1.y, v1.z );
}
// build
this.root.build( this.branchingFactor, this.primitivesPerNode, this.depth, 1 );
return this;
}
/**
* Executes the given callback for each node of the BVH.
*
* @param {Function} callback - The callback to execute.
* @return {BVH} A reference to this BVH.
*/
traverse( callback ) {
this.root.traverse( callback );
return this;
}
}
/**
* A single node in a bounding volume hierarchy (BVH).
*
* @author {@link https://github.com/robp94|robp94}
* @author {@link https://github.com/Mugen87|Mugen87}
*/
class BVHNode {
/**
* Constructs a BVH node.
*/
constructor() {
/**
* The parent BVH node.
* @type {BVHNode}
* @default null
*/
this.parent = null;
/**
* The child BVH nodes.
* @type {Array<BVHNode>}
*/
this.children = new Array();
/**
* The bounding volume of this BVH node.
* @type {AABB}
*/
this.boundingVolume = new AABB();
/**
* The primitives (triangles) of this BVH node.
* Only filled for leaf nodes.
* @type {Array<Number>}
*/
this.primitives = new Array();
/**
* The centroids of the node's triangles.
* Only filled for leaf nodes.
* @type {Array<Number>}
*/
this.centroids = new Array();
}
/**
* Returns true if this BVH node is a root node.
*
* @return {Boolean} Whether this BVH node is a root node or not.
*/
root() {
return this.parent === null;
}
/**
* Returns true if this BVH node is a leaf node.
*
* @return {Boolean} Whether this BVH node is a leaf node or not.
*/
leaf() {
return this.children.length === 0;
}
/**
* Returns the depth of this BVH node in its hierarchy.
*
* @return {Number} The hierarchical depth of this BVH node.
*/
getDepth() {
let depth = 0;
let parent = this.parent;
while ( parent !== null ) {
parent = parent.parent;
depth ++;
}
return depth;
}
/**
* Executes the given callback for this BVH node and its ancestors.
*
* @param {Function} callback - The callback to execute.
* @return {BVHNode} A reference to this BVH node.
*/
traverse( callback ) {
callback( this );
for ( let i = 0, l = this.children.length; i < l; i ++ ) {
this.children[ i ].traverse( callback );
}
return this;
}
/**
* Builds this BVH node. That means the respective bounding volume
* is computed and the node's primitives are distributed under new child nodes.
* This only happens if the maximum hierarchical depth is not yet reached and
* the node does contain enough primitives required for a split.
*
* @param {Number} branchingFactor - The branching factor.
* @param {Number} primitivesPerNode - The minimum amount of primitives per BVH node.
* @param {Number} maxDepth - The maximum hierarchical depth.
* @param {Number} currentDepth - The current hierarchical depth.
* @return {BVHNode} A reference to this BVH node.
*/
build( branchingFactor, primitivesPerNode, maxDepth, currentDepth ) {
this.computeBoundingVolume();
// check depth and primitive count
const primitiveCount = this.primitives.length / 9;
const newPrimitiveCount = Math.floor( primitiveCount / branchingFactor );
if ( ( currentDepth <= maxDepth ) && ( newPrimitiveCount >= primitivesPerNode ) ) {
// split (distribute primitives on new child BVH nodes)
this.split( branchingFactor );
// proceed with build on the next hierarchy level
for ( let i = 0; i < branchingFactor; i ++ ) {
this.children[ i ].build( branchingFactor, primitivesPerNode, maxDepth, currentDepth + 1 );
}
}
return this;
}
/**
* Computes the AABB for this BVH node.
*
* @return {BVHNode} A reference to this BVH node.
*/
computeBoundingVolume() {
const primitives = this.primitives;
const aabb = this.boundingVolume;
// compute AABB
aabb.min.set( Infinity, Infinity, Infinity );
aabb.max.set( - Infinity, - Infinity, - Infinity );
for ( let i = 0, l = primitives.length; i < l; i += 3 ) {
v1.x = primitives[ i ];
v1.y = primitives[ i + 1 ];
v1.z = primitives[ i + 2 ];
aabb.expand( v1 );
}
return this;
}
/**
* Computes the split axis. Right now, only the cardinal axes
* are potential split axes.
*
* @return {Vector3} The split axis.
*/
computeSplitAxis() {
let maxX, maxY, maxZ = maxY = maxX = - Infinity;
let minX, minY, minZ = minY = minX = Infinity;
const centroids = this.centroids;
for ( let i = 0, l = centroids.length; i < l; i += 3 ) {
const x = centroids[ i ];
const y = centroids[ i + 1 ];
const z = centroids[ i + 2 ];
if ( x > maxX ) {
maxX = x;
}
if ( y > maxY ) {
maxY = y;
}
if ( z > maxZ ) {
maxZ = z;
}
if ( x < minX ) {
minX = x;
}
if ( y < minY ) {
minY = y;
}
if ( z < minZ ) {
minZ = z;
}
}
const rangeX = maxX - minX;
const rangeY = maxY - minY;
const rangeZ = maxZ - minZ;
if ( rangeX > rangeY && rangeX > rangeZ ) {
return xAxis;
} else if ( rangeY > rangeZ ) {
return yAxis;
} else {
return zAxis;
}
}
/**
* Splits the node and distributes node's primitives over new child nodes.
*
* @param {Number} branchingFactor - The branching factor.
* @return {BVHNode} A reference to this BVH node.
*/
split( branchingFactor ) {
const centroids = this.centroids;
const primitives = this.primitives;
// create (empty) child BVH nodes
for ( let i = 0; i < branchingFactor; i ++ ) {
this.children[ i ] = new BVHNode();
this.children[ i ].parent = this;
}
// sort primitives along split axis
const axis = this.computeSplitAxis();
const sortedPrimitiveIndices = new Array();
for ( let i = 0, l = centroids.length; i < l; i += 3 ) {
v1.fromArray( centroids, i );
// the result from the dot product is our sort criterion.
// it represents the projection of the centroid on the split axis
const p = v1.dot( axis );
const primitiveIndex = i / 3;
sortedPrimitiveIndices.push( { index: primitiveIndex, p: p } );
}
sortedPrimitiveIndices.sort( sortPrimitives );
// distribute data
const primitveCount = sortedPrimitiveIndices.length;
const primitivesPerChild = Math.floor( primitveCount / branchingFactor );
var childIndex = 0;
var primitivesIndex = 0;
for ( let i = 0; i < primitveCount; i ++ ) {
// selected child
primitivesIndex ++;
// check if we try to add more primitives to a child than "primitivesPerChild" defines.
// move primitives to the next child
if ( primitivesIndex > primitivesPerChild ) {
// ensure "childIndex" does not overflow (meaning the last child takes all remaining primitives)
if ( childIndex < ( branchingFactor - 1 ) ) {
primitivesIndex = 1; // reset primitive index
childIndex ++; // raise child index
}
}
const child = this.children[ childIndex ];
// move data to the next level
// 1. primitives
const primitiveIndex = sortedPrimitiveIndices[ i ].index;
const stride = primitiveIndex * 9; // remember the "primitives" array holds raw vertex data defining triangles
v1.fromArray( primitives, stride );
v2.fromArray( primitives, stride + 3 );
v3.fromArray( primitives, stride + 6 );
child.primitives.push( v1.x, v1.y, v1.z );
child.primitives.push( v2.x, v2.y, v2.z );
child.primitives.push( v3.x, v3.y, v3.z );
// 2. centroid
v1.fromArray( centroids, primitiveIndex * 3 );
child.centroids.push( v1.x, v1.y, v1.z );
}
// remove centroids/primitives after split from this node
this.centroids.length = 0;
this.primitives.length = 0;
return this;
}
/**
* Performs a ray/BVH node intersection test and stores the closest intersection point
* to the given 3D vector. If no intersection is detected, *null* is returned.
*
* @param {Ray} ray - The ray.
* @param {Vector3} result - The result vector.
* @return {Vector3} The result vector.
*/
intersectRay( ray, result ) {
// gather all intersection points along the hierarchy
if ( ray.intersectAABB( this.boundingVolume, result ) !== null ) {
if ( this.leaf() === true ) {
const vertices = this.primitives;
for ( let i = 0, l = vertices.length; i < l; i += 9 ) {
// remember: we assume primitives are triangles
triangle.a.fromArray( vertices, i );
triangle.b.fromArray( vertices, i + 3 );
triangle.c.fromArray( vertices, i + 6 );
if ( ray.intersectTriangle( triangle, true, result ) !== null ) {
intersections.push( result.clone() );
}
}
} else {
// process childs
for ( let i = 0, l = this.children.length; i < l; i ++ ) {
this.children[ i ].intersectRay( ray, result );
}
}
}
// determine the closest intersection point in the root node (so after
// the hierarchy was processed)
if ( this.root() === true ) {
if ( intersections.length > 0 ) {
let minDistance = Infinity;
for ( let i = 0, l = intersections.length; i < l; i ++ ) {
const squaredDistance = ray.origin.squaredDistanceTo( intersections[ i ] );
if ( squaredDistance < minDistance ) {
minDistance = squaredDistance;
result.copy( intersections[ i ] );
}
}
// reset array
intersections.length = 0;
// return closest intersection point
return result;
} else {
// no intersection detected
return null;
}
} else {
// always return null for non-root nodes
return null;
}
}
/**
* Performs a ray/BVH node intersection test. Returns either true or false if
* there is a intersection or not.
*
* @param {Ray} ray - The ray.
* @return {boolean} Whether there is an intersection or not.
*/
intersectsRay( ray ) {
if ( ray.intersectAABB( this.boundingVolume, intersection ) !== null ) {
if ( this.leaf() === true ) {
const vertices = this.primitives;
for ( let i = 0, l = vertices.length; i < l; i += 9 ) {
// remember: we assume primitives are triangles
triangle.a.fromArray( vertices, i );
triangle.b.fromArray( vertices, i + 3 );
triangle.c.fromArray( vertices, i + 6 );
if ( ray.intersectTriangle( triangle, true, intersection ) !== null ) {
return true;
}
}
return false;
} else {
// process child BVH nodes
for ( let i = 0, l = this.children.length; i < l; i ++ ) {
if ( this.children[ i ].intersectsRay( ray ) === true ) {
return true;
}
}
return false;
}
} else {
return false;
}
}
}
//
function sortPrimitives( a, b ) {
return a.p - b.p;
}
export { BVH, BVHNode };