-
-
Notifications
You must be signed in to change notification settings - Fork 35.7k
/
Copy pathBatchedMesh.js
1652 lines (1155 loc) · 46.1 KB
/
BatchedMesh.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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { BufferAttribute } from '../core/BufferAttribute.js';
import { BufferGeometry } from '../core/BufferGeometry.js';
import { DataTexture } from '../textures/DataTexture.js';
import { FloatType, RedIntegerFormat, UnsignedIntType, RGBAFormat } from '../constants.js';
import { Matrix4 } from '../math/Matrix4.js';
import { Mesh } from './Mesh.js';
import { ColorManagement } from '../math/ColorManagement.js';
import { Box3 } from '../math/Box3.js';
import { Sphere } from '../math/Sphere.js';
import { Frustum } from '../math/Frustum.js';
import { Vector3 } from '../math/Vector3.js';
import { Color } from '../math/Color.js';
import { FrustumArray } from '../math/FrustumArray.js';
function ascIdSort( a, b ) {
return a - b;
}
function sortOpaque( a, b ) {
return a.z - b.z;
}
function sortTransparent( a, b ) {
return b.z - a.z;
}
class MultiDrawRenderList {
constructor() {
this.index = 0;
this.pool = [];
this.list = [];
}
push( start, count, z, index ) {
const pool = this.pool;
const list = this.list;
if ( this.index >= pool.length ) {
pool.push( {
start: - 1,
count: - 1,
z: - 1,
index: - 1,
} );
}
const item = pool[ this.index ];
list.push( item );
this.index ++;
item.start = start;
item.count = count;
item.z = z;
item.index = index;
}
reset() {
this.list.length = 0;
this.index = 0;
}
}
const _matrix = /*@__PURE__*/ new Matrix4();
const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
const _frustum = /*@__PURE__*/ new Frustum();
const _frustumArray = /*@__PURE__*/ new FrustumArray();
const _box = /*@__PURE__*/ new Box3();
const _sphere = /*@__PURE__*/ new Sphere();
const _vector = /*@__PURE__*/ new Vector3();
const _forward = /*@__PURE__*/ new Vector3();
const _temp = /*@__PURE__*/ new Vector3();
const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
const _mesh = /*@__PURE__*/ new Mesh();
const _batchIntersects = [];
// copies data from attribute "src" into "target" starting at "targetOffset"
function copyAttributeData( src, target, targetOffset = 0 ) {
const itemSize = target.itemSize;
if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
// use the component getters and setters if the array data cannot
// be copied directly
const vertexCount = src.count;
for ( let i = 0; i < vertexCount; i ++ ) {
for ( let c = 0; c < itemSize; c ++ ) {
target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
}
}
} else {
// faster copy approach using typed array set function
target.array.set( src.array, targetOffset * itemSize );
}
target.needsUpdate = true;
}
// safely copies array contents to a potentially smaller array
function copyArrayContents( src, target ) {
if ( src.constructor !== target.constructor ) {
// if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
const len = Math.min( src.length, target.length );
for ( let i = 0; i < len; i ++ ) {
target[ i ] = src[ i ];
}
} else {
// if the arrays use the same data layout we can use a fast block copy
const len = Math.min( src.length, target.length );
target.set( new src.constructor( src.buffer, 0, len ) );
}
}
/**
* A special version of a mesh with multi draw batch rendering support. Use
* this class if you have to render a large number of objects with the same
* material but with different geometries or world transformations. The usage of
* `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
* rendering performance in your application.
*
* ```js
* const box = new THREE.BoxGeometry( 1, 1, 1 );
* const sphere = new THREE.SphereGeometry( 1, 12, 12 );
* const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
*
* // initialize and add geometries into the batched mesh
* const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
* const boxGeometryId = batchedMesh.addGeometry( box );
* const sphereGeometryId = batchedMesh.addGeometry( sphere );
*
* // create instances of those geometries
* const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
* const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
*
* const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
* const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
*
* // position the geometries
* batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
* batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
*
* batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
* batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
*
* scene.add( batchedMesh );
* ```
*
* @augments Mesh
*/
class BatchedMesh extends Mesh {
/**
* Constructs a new batched mesh.
*
* @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
* @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
* @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
* @param {Material|Array<Material>} [material] - The mesh material.
*/
constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
super( new BufferGeometry(), material );
/**
* This flag can be used for type testing.
*
* @type {boolean}
* @readonly
* @default true
*/
this.isBatchedMesh = true;
/**
* When set ot `true`, the individual objects of a batch are frustum culled.
*
* @type {boolean}
* @default true
*/
this.perObjectFrustumCulled = true;
/**
* When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
* If the material is marked as "transparent" objects are rendered back to front and if not then they are
* rendered front to back.
*
* @type {boolean}
* @default true
*/
this.sortObjects = true;
/**
* The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
*
* @type {?Box3}
* @default null
*/
this.boundingBox = null;
/**
* The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
*
* @type {?Sphere}
* @default null
*/
this.boundingSphere = null;
/**
* Takes a sort a function that is run before render. The function takes a list of instances to
* sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
* sort with.
*
* @type {?Function}
* @default null
*/
this.customSort = null;
// stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
this._instanceInfo = [];
this._geometryInfo = [];
// instance, geometry ids that have been set as inactive, and are available to be overwritten
this._availableInstanceIds = [];
this._availableGeometryIds = [];
// used to track where the next point is that geometry should be inserted
this._nextIndexStart = 0;
this._nextVertexStart = 0;
this._geometryCount = 0;
// flags
this._visibilityChanged = true;
this._geometryInitialized = false;
// cached user options
this._maxInstanceCount = maxInstanceCount;
this._maxVertexCount = maxVertexCount;
this._maxIndexCount = maxIndexCount;
// buffers for multi draw
this._multiDrawCounts = new Int32Array( maxInstanceCount );
this._multiDrawStarts = new Int32Array( maxInstanceCount );
this._multiDrawCount = 0;
this._multiDrawInstances = null;
// Local matrix per geometry by using data texture
this._matricesTexture = null;
this._indirectTexture = null;
this._colorsTexture = null;
this._initMatricesTexture();
this._initIndirectTexture();
}
/**
* The maximum number of individual instances that can be stored in the batch.
*
* @type {number}
* @readonly
*/
get maxInstanceCount() {
return this._maxInstanceCount;
}
/**
* The instance count.
*
* @type {number}
* @readonly
*/
get instanceCount() {
return this._instanceInfo.length - this._availableInstanceIds.length;
}
/**
* The number of unused vertices.
*
* @type {number}
* @readonly
*/
get unusedVertexCount() {
return this._maxVertexCount - this._nextVertexStart;
}
/**
* The number of unused indices.
*
* @type {number}
* @readonly
*/
get unusedIndexCount() {
return this._maxIndexCount - this._nextIndexStart;
}
_initMatricesTexture() {
// layout (1 matrix = 4 pixels)
// RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
// with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
// 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
// 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
// 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
size = Math.ceil( size / 4 ) * 4;
size = Math.max( size, 4 );
const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
this._matricesTexture = matricesTexture;
}
_initIndirectTexture() {
let size = Math.sqrt( this._maxInstanceCount );
size = Math.ceil( size );
const indirectArray = new Uint32Array( size * size );
const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
this._indirectTexture = indirectTexture;
}
_initColorsTexture() {
let size = Math.sqrt( this._maxInstanceCount );
size = Math.ceil( size );
// 4 floats per RGBA pixel initialized to white
const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
colorsTexture.colorSpace = ColorManagement.workingColorSpace;
this._colorsTexture = colorsTexture;
}
_initializeGeometry( reference ) {
const geometry = this.geometry;
const maxVertexCount = this._maxVertexCount;
const maxIndexCount = this._maxIndexCount;
if ( this._geometryInitialized === false ) {
for ( const attributeName in reference.attributes ) {
const srcAttribute = reference.getAttribute( attributeName );
const { array, itemSize, normalized } = srcAttribute;
const dstArray = new array.constructor( maxVertexCount * itemSize );
const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
geometry.setAttribute( attributeName, dstAttribute );
}
if ( reference.getIndex() !== null ) {
// Reserve last u16 index for primitive restart.
const indexArray = maxVertexCount > 65535
? new Uint32Array( maxIndexCount )
: new Uint16Array( maxIndexCount );
geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
}
this._geometryInitialized = true;
}
}
// Make sure the geometry is compatible with the existing combined geometry attributes
_validateGeometry( geometry ) {
// check to ensure the geometries are using consistent attributes and indices
const batchGeometry = this.geometry;
if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
}
for ( const attributeName in batchGeometry.attributes ) {
if ( ! geometry.hasAttribute( attributeName ) ) {
throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
}
const srcAttribute = geometry.getAttribute( attributeName );
const dstAttribute = batchGeometry.getAttribute( attributeName );
if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
}
}
}
/**
* Validates the instance defined by the given ID.
*
* @param {number} instanceId - The instance to validate.
*/
validateInstanceId( instanceId ) {
const instanceInfo = this._instanceInfo;
if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
}
}
/**
* Validates the geometry defined by the given ID.
*
* @param {number} geometryId - The geometry to validate.
*/
validateGeometryId( geometryId ) {
const geometryInfoList = this._geometryInfo;
if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
}
}
/**
* Takes a sort a function that is run before render. The function takes a list of instances to
* sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
*
* @param {Function} func - The custom sort function.
* @return {BatchedMesh} A reference to this batched mesh.
*/
setCustomSort( func ) {
this.customSort = func;
return this;
}
/**
* Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
* Bounding boxes aren't computed by default. They need to be explicitly computed,
* otherwise they are `null`.
*/
computeBoundingBox() {
if ( this.boundingBox === null ) {
this.boundingBox = new Box3();
}
const boundingBox = this.boundingBox;
const instanceInfo = this._instanceInfo;
boundingBox.makeEmpty();
for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
if ( instanceInfo[ i ].active === false ) continue;
const geometryId = instanceInfo[ i ].geometryIndex;
this.getMatrixAt( i, _matrix );
this.getBoundingBoxAt( geometryId, _box ).applyMatrix4( _matrix );
boundingBox.union( _box );
}
}
/**
* Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
* Bounding spheres aren't computed by default. They need to be explicitly computed,
* otherwise they are `null`.
*/
computeBoundingSphere() {
if ( this.boundingSphere === null ) {
this.boundingSphere = new Sphere();
}
const boundingSphere = this.boundingSphere;
const instanceInfo = this._instanceInfo;
boundingSphere.makeEmpty();
for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
if ( instanceInfo[ i ].active === false ) continue;
const geometryId = instanceInfo[ i ].geometryIndex;
this.getMatrixAt( i, _matrix );
this.getBoundingSphereAt( geometryId, _sphere ).applyMatrix4( _matrix );
boundingSphere.union( _sphere );
}
}
/**
* Adds a new instance to the batch using the geometry of the given ID and returns
* a new id referring to the new instance to be used by other functions.
*
* @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
* @return {number} The instance ID.
*/
addInstance( geometryId ) {
const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
// ensure we're not over geometry
if ( atCapacity && this._availableInstanceIds.length === 0 ) {
throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
}
const instanceInfo = {
visible: true,
active: true,
geometryIndex: geometryId,
};
let drawId = null;
// Prioritize using previously freed instance ids
if ( this._availableInstanceIds.length > 0 ) {
this._availableInstanceIds.sort( ascIdSort );
drawId = this._availableInstanceIds.shift();
this._instanceInfo[ drawId ] = instanceInfo;
} else {
drawId = this._instanceInfo.length;
this._instanceInfo.push( instanceInfo );
}
const matricesTexture = this._matricesTexture;
_matrix.identity().toArray( matricesTexture.image.data, drawId * 16 );
matricesTexture.needsUpdate = true;
const colorsTexture = this._colorsTexture;
if ( colorsTexture ) {
_whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
colorsTexture.needsUpdate = true;
}
this._visibilityChanged = true;
return drawId;
}
/**
* Adds the given geometry to the batch and returns the associated
* geometry id referring to it to be used in other functions.
*
* @param {BufferGeometry} geometry - The geometry to add.
* @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
* vertex buffer space to reserve for the added geometry. This is necessary if it is planned
* to set a new geometry at this index at a later time that is larger than the original geometry.
* Defaults to the length of the given geometry vertex buffer.
* @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
* buffer space to reserve for the added geometry. This is necessary if it is planned to set a
* new geometry at this index at a later time that is larger than the original geometry. Defaults to
* the length of the given geometry index buffer.
* @return {number} The geometry ID.
*/
addGeometry( geometry, reservedVertexCount = - 1, reservedIndexCount = - 1 ) {
this._initializeGeometry( geometry );
this._validateGeometry( geometry );
const geometryInfo = {
// geometry information
vertexStart: - 1,
vertexCount: - 1,
reservedVertexCount: - 1,
indexStart: - 1,
indexCount: - 1,
reservedIndexCount: - 1,
// draw range information
start: - 1,
count: - 1,
// state
boundingBox: null,
boundingSphere: null,
active: true,
};
const geometryInfoList = this._geometryInfo;
geometryInfo.vertexStart = this._nextVertexStart;
geometryInfo.reservedVertexCount = reservedVertexCount === - 1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
const index = geometry.getIndex();
const hasIndex = index !== null;
if ( hasIndex ) {
geometryInfo.indexStart = this._nextIndexStart;
geometryInfo.reservedIndexCount = reservedIndexCount === - 1 ? index.count : reservedIndexCount;
}
if (
geometryInfo.indexStart !== - 1 &&
geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
) {
throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
}
// update id
let geometryId;
if ( this._availableGeometryIds.length > 0 ) {
this._availableGeometryIds.sort( ascIdSort );
geometryId = this._availableGeometryIds.shift();
geometryInfoList[ geometryId ] = geometryInfo;
} else {
geometryId = this._geometryCount;
this._geometryCount ++;
geometryInfoList.push( geometryInfo );
}
// update the geometry
this.setGeometryAt( geometryId, geometry );
// increment the next geometry position
this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
return geometryId;
}
/**
* Replaces the geometry at the given ID with the provided geometry. Throws an error if there
* is not enough space reserved for geometry. Calling this will change all instances that are
* rendering that geometry.
*
* @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
* @param {BufferGeometry} geometry - The new geometry.
* @return {number} The geometry ID.
*/
setGeometryAt( geometryId, geometry ) {
if ( geometryId >= this._geometryCount ) {
throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
}
this._validateGeometry( geometry );
const batchGeometry = this.geometry;
const hasIndex = batchGeometry.getIndex() !== null;
const dstIndex = batchGeometry.getIndex();
const srcIndex = geometry.getIndex();
const geometryInfo = this._geometryInfo[ geometryId ];
if (
hasIndex &&
srcIndex.count > geometryInfo.reservedIndexCount ||
geometry.attributes.position.count > geometryInfo.reservedVertexCount
) {
throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
}
// copy geometry buffer data over
const vertexStart = geometryInfo.vertexStart;
const reservedVertexCount = geometryInfo.reservedVertexCount;
geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
for ( const attributeName in batchGeometry.attributes ) {
// copy attribute data
const srcAttribute = geometry.getAttribute( attributeName );
const dstAttribute = batchGeometry.getAttribute( attributeName );
copyAttributeData( srcAttribute, dstAttribute, vertexStart );
// fill the rest in with zeroes
const itemSize = srcAttribute.itemSize;
for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
const index = vertexStart + i;
for ( let c = 0; c < itemSize; c ++ ) {
dstAttribute.setComponent( index, c, 0 );
}
}
dstAttribute.needsUpdate = true;
dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
}
// copy index
if ( hasIndex ) {
const indexStart = geometryInfo.indexStart;
const reservedIndexCount = geometryInfo.reservedIndexCount;
geometryInfo.indexCount = geometry.getIndex().count;
// copy index data over
for ( let i = 0; i < srcIndex.count; i ++ ) {
dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
}
// fill the rest in with zeroes
for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
dstIndex.setX( indexStart + i, vertexStart );
}
dstIndex.needsUpdate = true;
dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
}
// update the draw range
geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
// store the bounding boxes
geometryInfo.boundingBox = null;
if ( geometry.boundingBox !== null ) {
geometryInfo.boundingBox = geometry.boundingBox.clone();
}
geometryInfo.boundingSphere = null;
if ( geometry.boundingSphere !== null ) {
geometryInfo.boundingSphere = geometry.boundingSphere.clone();
}
this._visibilityChanged = true;
return geometryId;
}
/**
* Deletes the geometry defined by the given ID from this batch. Any instances referencing
* this geometry will also be removed as a side effect.
*
* @param {number} geometryId - The ID of the geometry to remove from the batch.
* @return {BatchedMesh} A reference to this batched mesh.
*/
deleteGeometry( geometryId ) {
const geometryInfoList = this._geometryInfo;
if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
return this;
}
// delete any instances associated with this geometry
const instanceInfo = this._instanceInfo;
for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
this.deleteInstance( i );
}
}
geometryInfoList[ geometryId ].active = false;
this._availableGeometryIds.push( geometryId );
this._visibilityChanged = true;
return this;
}
/**
* Deletes an existing instance from the batch using the given ID.
*
* @param {number} instanceId - The ID of the instance to remove from the batch.
* @return {BatchedMesh} A reference to this batched mesh.
*/
deleteInstance( instanceId ) {
this.validateInstanceId( instanceId );
this._instanceInfo[ instanceId ].active = false;
this._availableInstanceIds.push( instanceId );
this._visibilityChanged = true;
return this;
}
/**
* Repacks the sub geometries in [name] to remove any unused space remaining from
* previously deleted geometry, freeing up space to add new geometry.
*
* @param {number} instanceId - The ID of the instance to remove from the batch.
* @return {BatchedMesh} A reference to this batched mesh.
*/
optimize() {
// track the next indices to copy data to
let nextVertexStart = 0;
let nextIndexStart = 0;
// Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
// in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
const geometryInfoList = this._geometryInfo;
const indices = geometryInfoList
.map( ( e, i ) => i )
.sort( ( a, b ) => {
return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
} );
const geometry = this.geometry;
for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
// if a geometry range is inactive then don't copy anything
const index = indices[ i ];
const geometryInfo = geometryInfoList[ index ];
if ( geometryInfo.active === false ) {
continue;
}
// if a geometry contains an index buffer then shift it, as well
if ( geometry.index !== null ) {
if ( geometryInfo.indexStart !== nextIndexStart ) {
const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
const index = geometry.index;
const array = index.array;
// shift the index pointers based on how the vertex data will shift
// adjusting the index must happen first so the original vertex start value is available
const elementDelta = nextVertexStart - vertexStart;
for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
array[ j ] = array[ j ] + elementDelta;
}
index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
index.addUpdateRange( nextIndexStart, reservedIndexCount );
geometryInfo.indexStart = nextIndexStart;
}
nextIndexStart += geometryInfo.reservedIndexCount;
}
// if a geometry needs to be moved then copy attribute data to overwrite unused space
if ( geometryInfo.vertexStart !== nextVertexStart ) {
const { vertexStart, reservedVertexCount } = geometryInfo;
const attributes = geometry.attributes;
for ( const key in attributes ) {
const attribute = attributes[ key ];
const { array, itemSize } = attribute;
array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
}
geometryInfo.vertexStart = nextVertexStart;
}
nextVertexStart += geometryInfo.reservedVertexCount;
geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
// step the next geometry points to the shifted position
this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
}
return this;
}
/**
* Returns the bounding box for the given geometry.
*
* @param {number} geometryId - The ID of the geometry to return the bounding box for.
* @param {Box3} target - The target object that is used to store the method's result.
* @return {Box3|null} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
*/
getBoundingBoxAt( geometryId, target ) {
if ( geometryId >= this._geometryCount ) {
return null;
}
// compute bounding box
const geometry = this.geometry;
const geometryInfo = this._geometryInfo[ geometryId ];
if ( geometryInfo.boundingBox === null ) {
const box = new Box3();
const index = geometry.index;
const position = geometry.attributes.position;
for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
let iv = i;
if ( index ) {
iv = index.getX( iv );
}