forked from BabylonJS/Babylon.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
geometry.ts
1604 lines (1360 loc) · 60.8 KB
/
geometry.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
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 type { Nullable, FloatArray, DataArray, IndicesArray } from "../types";
import type { Scene } from "../scene";
import type { Vector2 } from "../Maths/math.vector";
import { Vector3 } from "../Maths/math.vector";
import { Color4 } from "../Maths/math.color";
import type { Engine } from "../Engines/engine";
import type { IGetSetVerticesData } from "../Meshes/mesh.vertexData";
import { VertexData } from "../Meshes/mesh.vertexData";
import { VertexBuffer } from "../Buffers/buffer";
import { SubMesh } from "../Meshes/subMesh";
import type { AbstractMesh } from "../Meshes/abstractMesh";
import type { Effect } from "../Materials/effect";
import { SceneLoaderFlags } from "../Loading/sceneLoaderFlags";
import { BoundingInfo } from "../Culling/boundingInfo";
import { Constants } from "../Engines/constants";
import { Tools } from "../Misc/tools";
import { Tags } from "../Misc/tags";
import type { DataBuffer } from "../Buffers/dataBuffer";
import { extractMinAndMax } from "../Maths/math.functions";
import type { AbstractScene } from "../abstractScene";
import { EngineStore } from "../Engines/engineStore";
import { CompatibilityOptions } from "../Compat/compatibilityOptions";
declare type Mesh = import("../Meshes/mesh").Mesh;
/**
* Class used to store geometry data (vertex buffers + index buffer)
*/
export class Geometry implements IGetSetVerticesData {
// Members
/**
* Gets or sets the ID of the geometry
*/
public id: string;
/**
* Gets or sets the unique ID of the geometry
*/
public uniqueId: number;
/**
* Gets the delay loading state of the geometry (none by default which means not delayed)
*/
public delayLoadState = Constants.DELAYLOADSTATE_NONE;
/**
* Gets the file containing the data to load when running in delay load state
*/
public delayLoadingFile: Nullable<string>;
/**
* Callback called when the geometry is updated
*/
public onGeometryUpdated: (geometry: Geometry, kind?: string) => void;
// Private
private _scene: Scene;
private _engine: Engine;
private _meshes: Mesh[];
private _totalVertices = 0;
/** @hidden */
public _loadedUniqueId: string;
/** @hidden */
public _indices: IndicesArray;
/** @hidden */
public _vertexBuffers: { [key: string]: VertexBuffer };
private _isDisposed = false;
private _extend: { minimum: Vector3; maximum: Vector3 };
private _boundingBias: Vector2;
/** @hidden */
public _delayInfo: Array<string>;
private _indexBuffer: Nullable<DataBuffer>;
private _indexBufferIsUpdatable = false;
/** @hidden */
public _boundingInfo: Nullable<BoundingInfo>;
/** @hidden */
public _delayLoadingFunction: Nullable<(any: any, geometry: Geometry) => void>;
/** @hidden */
public _softwareSkinningFrameId: number;
private _vertexArrayObjects: { [key: string]: WebGLVertexArrayObject };
private _updatable: boolean;
// Cache
/** @hidden */
public _positions: Nullable<Vector3[]>;
private _positionsCache: Vector3[] = [];
/** @hidden */
public _parentContainer: Nullable<AbstractScene> = null;
/**
* Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
*/
public get boundingBias(): Vector2 {
return this._boundingBias;
}
/**
* Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
*/
public set boundingBias(value: Vector2) {
if (this._boundingBias) {
this._boundingBias.copyFrom(value);
} else {
this._boundingBias = value.clone();
}
this._updateBoundingInfo(true, null);
}
/**
* Static function used to attach a new empty geometry to a mesh
* @param mesh defines the mesh to attach the geometry to
* @returns the new Geometry
*/
public static CreateGeometryForMesh(mesh: Mesh): Geometry {
const geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
geometry.applyToMesh(mesh);
return geometry;
}
/** Get the list of meshes using this geometry */
public get meshes(): Mesh[] {
return this._meshes;
}
/**
* If set to true (false by default), the bounding info applied to the meshes sharing this geometry will be the bounding info defined at the class level
* and won't be computed based on the vertex positions (which is what we get when useBoundingInfoFromGeometry = false)
*/
public useBoundingInfoFromGeometry = false;
/**
* Creates a new geometry
* @param id defines the unique ID
* @param scene defines the hosting scene
* @param vertexData defines the VertexData used to get geometry data
* @param updatable defines if geometry must be updatable (false by default)
* @param mesh defines the mesh that will be associated with the geometry
*/
constructor(id: string, scene?: Scene, vertexData?: VertexData, updatable: boolean = false, mesh: Nullable<Mesh> = null) {
this._scene = scene || <Scene>EngineStore.LastCreatedScene;
if (!this._scene) {
return;
}
this.id = id;
this.uniqueId = this._scene.getUniqueId();
this._engine = this._scene.getEngine();
this._meshes = [];
//Init vertex buffer cache
this._vertexBuffers = {};
this._indices = [];
this._updatable = updatable;
// vertexData
if (vertexData) {
this.setAllVerticesData(vertexData, updatable);
} else {
this._totalVertices = 0;
this._indices = [];
}
if (this._engine.getCaps().vertexArrayObject) {
this._vertexArrayObjects = {};
}
// applyToMesh
if (mesh) {
this.applyToMesh(mesh);
mesh.computeWorldMatrix(true);
}
}
/**
* Gets the current extend of the geometry
*/
public get extend(): { minimum: Vector3; maximum: Vector3 } {
return this._extend;
}
/**
* Gets the hosting scene
* @returns the hosting Scene
*/
public getScene(): Scene {
return this._scene;
}
/**
* Gets the hosting engine
* @returns the hosting Engine
*/
public getEngine(): Engine {
return this._engine;
}
/**
* Defines if the geometry is ready to use
* @returns true if the geometry is ready to be used
*/
public isReady(): boolean {
return this.delayLoadState === Constants.DELAYLOADSTATE_LOADED || this.delayLoadState === Constants.DELAYLOADSTATE_NONE;
}
/**
* Gets a value indicating that the geometry should not be serialized
*/
public get doNotSerialize(): boolean {
for (let index = 0; index < this._meshes.length; index++) {
if (!this._meshes[index].doNotSerialize) {
return false;
}
}
return true;
}
/** @hidden */
public _rebuild(): void {
if (this._vertexArrayObjects) {
this._vertexArrayObjects = {};
}
// Index buffer
if (this._meshes.length !== 0 && this._indices) {
this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable);
}
// Vertex buffers
for (const key in this._vertexBuffers) {
const vertexBuffer = <VertexBuffer>this._vertexBuffers[key];
vertexBuffer._rebuild();
}
}
/**
* Affects all geometry data in one call
* @param vertexData defines the geometry data
* @param updatable defines if the geometry must be flagged as updatable (false as default)
*/
public setAllVerticesData(vertexData: VertexData, updatable?: boolean): void {
vertexData.applyToGeometry(this, updatable);
this._notifyUpdate();
}
/**
* Set specific vertex data
* @param kind defines the data kind (Position, normal, etc...)
* @param data defines the vertex data to use
* @param updatable defines if the vertex must be flagged as updatable (false as default)
* @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
*/
public setVerticesData(kind: string, data: FloatArray, updatable: boolean = false, stride?: number): void {
if (updatable && Array.isArray(data)) {
// to avoid converting to Float32Array at each draw call in engine.updateDynamicVertexBuffer, we make the conversion a single time here
data = new Float32Array(data);
}
const buffer = new VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
this.setVerticesBuffer(buffer);
}
/**
* Removes a specific vertex data
* @param kind defines the data kind (Position, normal, etc...)
*/
public removeVerticesData(kind: string) {
if (this._vertexBuffers[kind]) {
this._vertexBuffers[kind].dispose();
delete this._vertexBuffers[kind];
}
if (this._vertexArrayObjects) {
this._disposeVertexArrayObjects();
}
}
/**
* Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
* @param buffer defines the vertex buffer to use
* @param totalVertices defines the total number of vertices for position kind (could be null)
* @param disposeExistingBuffer disposes the existing buffer, if any (default: true)
*/
public setVerticesBuffer(buffer: VertexBuffer, totalVertices: Nullable<number> = null, disposeExistingBuffer = true): void {
const kind = buffer.getKind();
if (this._vertexBuffers[kind] && disposeExistingBuffer) {
this._vertexBuffers[kind].dispose();
}
if (buffer._buffer) {
buffer._buffer._increaseReferences();
}
this._vertexBuffers[kind] = buffer;
const meshes = this._meshes;
const numOfMeshes = meshes.length;
if (kind === VertexBuffer.PositionKind) {
const data = <FloatArray>buffer.getData();
if (totalVertices != null) {
this._totalVertices = totalVertices;
} else {
if (data != null) {
this._totalVertices = data.length / (buffer.type === VertexBuffer.BYTE ? buffer.byteStride : buffer.byteStride / 4);
}
}
this._updateExtend(data);
this._resetPointsArrayCache();
for (let index = 0; index < numOfMeshes; index++) {
const mesh = meshes[index];
mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum);
mesh._createGlobalSubMesh(mesh.isUnIndexed);
mesh.computeWorldMatrix(true);
mesh.synchronizeInstances();
}
}
this._notifyUpdate(kind);
}
/**
* Update a specific vertex buffer
* This function will directly update the underlying DataBuffer according to the passed numeric array or Float32Array
* It will do nothing if the buffer is not updatable
* @param kind defines the data kind (Position, normal, etc...)
* @param data defines the data to use
* @param offset defines the offset in the target buffer where to store the data
* @param useBytes set to true if the offset is in bytes
*/
public updateVerticesDataDirectly(kind: string, data: DataArray, offset: number, useBytes: boolean = false): void {
const vertexBuffer = this.getVertexBuffer(kind);
if (!vertexBuffer) {
return;
}
vertexBuffer.updateDirectly(data, offset, useBytes);
this._notifyUpdate(kind);
}
/**
* Update a specific vertex buffer
* This function will create a new buffer if the current one is not updatable
* @param kind defines the data kind (Position, normal, etc...)
* @param data defines the data to use
* @param updateExtends defines if the geometry extends must be recomputed (false by default)
*/
public updateVerticesData(kind: string, data: FloatArray, updateExtends: boolean = false): void {
const vertexBuffer = this.getVertexBuffer(kind);
if (!vertexBuffer) {
return;
}
vertexBuffer.update(data);
if (kind === VertexBuffer.PositionKind) {
this._updateBoundingInfo(updateExtends, data);
}
this._notifyUpdate(kind);
}
private _updateBoundingInfo(updateExtends: boolean, data: Nullable<FloatArray>) {
if (updateExtends) {
this._updateExtend(data);
}
this._resetPointsArrayCache();
if (updateExtends) {
const meshes = this._meshes;
for (const mesh of meshes) {
if (mesh.hasBoundingInfo) {
mesh.getBoundingInfo().reConstruct(this._extend.minimum, this._extend.maximum);
} else {
mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum);
}
const subMeshes = mesh.subMeshes;
for (const subMesh of subMeshes) {
subMesh.refreshBoundingInfo();
}
}
}
}
/**
* @param effect
* @param indexToBind
* @hidden
*/
public _bind(
effect: Nullable<Effect>,
indexToBind?: Nullable<DataBuffer>,
overrideVertexBuffers?: { [kind: string]: Nullable<VertexBuffer> },
overrideVertexArrayObjects?: { [key: string]: WebGLVertexArrayObject }
): void {
if (!effect) {
return;
}
if (indexToBind === undefined) {
indexToBind = this._indexBuffer;
}
const vbs = this.getVertexBuffers();
if (!vbs) {
return;
}
if (indexToBind != this._indexBuffer || (!this._vertexArrayObjects && !overrideVertexArrayObjects)) {
this._engine.bindBuffers(vbs, indexToBind, effect, overrideVertexBuffers);
return;
}
const vaos = overrideVertexArrayObjects ? overrideVertexArrayObjects : this._vertexArrayObjects;
// Using VAO
if (!vaos[effect.key]) {
vaos[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect, overrideVertexBuffers);
}
this._engine.bindVertexArrayObject(vaos[effect.key], indexToBind);
}
/**
* Gets total number of vertices
* @returns the total number of vertices
*/
public getTotalVertices(): number {
if (!this.isReady()) {
return 0;
}
return this._totalVertices;
}
/**
* Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
* @param kind defines the data kind (Position, normal, etc...)
* @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
* @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
* @returns a float array containing vertex data
*/
public getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable<FloatArray> {
const vertexBuffer = this.getVertexBuffer(kind);
if (!vertexBuffer) {
return null;
}
return vertexBuffer.getFloatData(this._totalVertices, forceCopy || (copyWhenShared && this._meshes.length !== 1));
}
/**
* Returns a boolean defining if the vertex data for the requested `kind` is updatable
* @param kind defines the data kind (Position, normal, etc...)
* @returns true if the vertex buffer with the specified kind is updatable
*/
public isVertexBufferUpdatable(kind: string): boolean {
const vb = this._vertexBuffers[kind];
if (!vb) {
return false;
}
return vb.isUpdatable();
}
/**
* Gets a specific vertex buffer
* @param kind defines the data kind (Position, normal, etc...)
* @returns a VertexBuffer
*/
public getVertexBuffer(kind: string): Nullable<VertexBuffer> {
if (!this.isReady()) {
return null;
}
return this._vertexBuffers[kind];
}
/**
* Returns all vertex buffers
* @return an object holding all vertex buffers indexed by kind
*/
public getVertexBuffers(): Nullable<{ [key: string]: VertexBuffer }> {
if (!this.isReady()) {
return null;
}
return this._vertexBuffers;
}
/**
* Gets a boolean indicating if specific vertex buffer is present
* @param kind defines the data kind (Position, normal, etc...)
* @returns true if data is present
*/
public isVerticesDataPresent(kind: string): boolean {
if (!this._vertexBuffers) {
if (this._delayInfo) {
return this._delayInfo.indexOf(kind) !== -1;
}
return false;
}
return this._vertexBuffers[kind] !== undefined;
}
/**
* Gets a list of all attached data kinds (Position, normal, etc...)
* @returns a list of string containing all kinds
*/
public getVerticesDataKinds(): string[] {
const result = [];
let kind;
if (!this._vertexBuffers && this._delayInfo) {
for (kind in this._delayInfo) {
result.push(kind);
}
} else {
for (kind in this._vertexBuffers) {
result.push(kind);
}
}
return result;
}
/**
* Update index buffer
* @param indices defines the indices to store in the index buffer
* @param offset defines the offset in the target buffer where to store the data
* @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default)
*/
public updateIndices(indices: IndicesArray, offset?: number, gpuMemoryOnly = false): void {
if (!this._indexBuffer) {
return;
}
if (!this._indexBufferIsUpdatable) {
this.setIndices(indices, null, true);
} else {
const needToUpdateSubMeshes = indices.length !== this._indices.length;
if (!gpuMemoryOnly) {
this._indices = indices.slice();
}
this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
if (needToUpdateSubMeshes) {
for (const mesh of this._meshes) {
mesh._createGlobalSubMesh(true);
}
}
}
}
/**
* Creates a new index buffer
* @param indices defines the indices to store in the index buffer
* @param totalVertices defines the total number of vertices (could be null)
* @param updatable defines if the index buffer must be flagged as updatable (false by default)
*/
public setIndices(indices: IndicesArray, totalVertices: Nullable<number> = null, updatable: boolean = false): void {
if (this._indexBuffer) {
this._engine._releaseBuffer(this._indexBuffer);
}
this._indices = indices;
this._indexBufferIsUpdatable = updatable;
if (this._meshes.length !== 0 && this._indices) {
this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
}
if (totalVertices != undefined) {
// including null and undefined
this._totalVertices = totalVertices;
}
for (const mesh of this._meshes) {
mesh._createGlobalSubMesh(true);
mesh.synchronizeInstances();
}
this._notifyUpdate();
}
/**
* Return the total number of indices
* @returns the total number of indices
*/
public getTotalIndices(): number {
if (!this.isReady()) {
return 0;
}
return this._indices.length;
}
/**
* Gets the index buffer array
* @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
* @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
* @returns the index buffer array
*/
public getIndices(copyWhenShared?: boolean, forceCopy?: boolean): Nullable<IndicesArray> {
if (!this.isReady()) {
return null;
}
const orig = this._indices;
if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
return orig;
} else {
return orig.slice();
}
}
/**
* Gets the index buffer
* @return the index buffer
*/
public getIndexBuffer(): Nullable<DataBuffer> {
if (!this.isReady()) {
return null;
}
return this._indexBuffer;
}
/**
* @param effect
* @hidden
*/
public _releaseVertexArrayObject(effect: Nullable<Effect> = null) {
if (!effect || !this._vertexArrayObjects) {
return;
}
if (this._vertexArrayObjects[effect.key]) {
this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
delete this._vertexArrayObjects[effect.key];
}
}
/**
* Release the associated resources for a specific mesh
* @param mesh defines the source mesh
* @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
*/
public releaseForMesh(mesh: Mesh, shouldDispose?: boolean): void {
const meshes = this._meshes;
const index = meshes.indexOf(mesh);
if (index === -1) {
return;
}
meshes.splice(index, 1);
if (this._vertexArrayObjects) {
mesh._invalidateInstanceVertexArrayObject();
}
mesh._geometry = null;
if (meshes.length === 0 && shouldDispose) {
this.dispose();
}
}
/**
* Apply current geometry to a given mesh
* @param mesh defines the mesh to apply geometry to
*/
public applyToMesh(mesh: Mesh): void {
if (mesh._geometry === this) {
return;
}
const previousGeometry = mesh._geometry;
if (previousGeometry) {
previousGeometry.releaseForMesh(mesh);
}
if (this._vertexArrayObjects) {
mesh._invalidateInstanceVertexArrayObject();
}
const meshes = this._meshes;
// must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
mesh._geometry = this;
mesh._internalAbstractMeshDataInfo._positions = null;
this._scene.pushGeometry(this);
meshes.push(mesh);
if (this.isReady()) {
this._applyToMesh(mesh);
} else if (this._boundingInfo) {
mesh.setBoundingInfo(this._boundingInfo);
}
}
private _updateExtend(data: Nullable<FloatArray> = null) {
if (this.useBoundingInfoFromGeometry && this._boundingInfo) {
this._extend = {
minimum: this._boundingInfo.minimum.clone(),
maximum: this._boundingInfo.maximum.clone(),
};
} else {
if (!data) {
data = this.getVerticesData(VertexBuffer.PositionKind)!;
// This can happen if the buffer comes from a Hardware Buffer where
// The data have not been uploaded by Babylon. (ex: Compute Shaders and Storage Buffers)
if (!data) {
return;
}
}
this._extend = extractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
}
}
private _applyToMesh(mesh: Mesh): void {
const numOfMeshes = this._meshes.length;
// vertexBuffers
for (const kind in this._vertexBuffers) {
if (numOfMeshes === 1) {
this._vertexBuffers[kind].create();
}
if (kind === VertexBuffer.PositionKind) {
if (!this._extend) {
this._updateExtend();
}
mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum);
mesh._createGlobalSubMesh(mesh.isUnIndexed);
//bounding info was just created again, world matrix should be applied again.
mesh._updateBoundingInfo();
}
}
// indexBuffer
if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable);
}
// morphTargets
mesh._syncGeometryWithMorphTargetManager();
// instances
mesh.synchronizeInstances();
}
private _notifyUpdate(kind?: string) {
if (this.onGeometryUpdated) {
this.onGeometryUpdated(this, kind);
}
if (this._vertexArrayObjects) {
this._disposeVertexArrayObjects();
}
for (const mesh of this._meshes) {
mesh._markSubMeshesAsAttributesDirty();
}
}
/**
* Load the geometry if it was flagged as delay loaded
* @param scene defines the hosting scene
* @param onLoaded defines a callback called when the geometry is loaded
*/
public load(scene: Scene, onLoaded?: () => void): void {
if (this.delayLoadState === Constants.DELAYLOADSTATE_LOADING) {
return;
}
if (this.isReady()) {
if (onLoaded) {
onLoaded();
}
return;
}
this.delayLoadState = Constants.DELAYLOADSTATE_LOADING;
this._queueLoad(scene, onLoaded);
}
private _queueLoad(scene: Scene, onLoaded?: () => void): void {
if (!this.delayLoadingFile) {
return;
}
scene._addPendingData(this);
scene._loadFile(
this.delayLoadingFile,
(data) => {
if (!this._delayLoadingFunction) {
return;
}
this._delayLoadingFunction(JSON.parse(data as string), this);
this.delayLoadState = Constants.DELAYLOADSTATE_LOADED;
this._delayInfo = [];
scene._removePendingData(this);
const meshes = this._meshes;
const numOfMeshes = meshes.length;
for (let index = 0; index < numOfMeshes; index++) {
this._applyToMesh(meshes[index]);
}
if (onLoaded) {
onLoaded();
}
},
undefined,
true
);
}
/**
* Invert the geometry to move from a right handed system to a left handed one.
*/
public toLeftHanded(): void {
// Flip faces
const tIndices = this.getIndices(false);
if (tIndices != null && tIndices.length > 0) {
for (let i = 0; i < tIndices.length; i += 3) {
const tTemp = tIndices[i + 0];
tIndices[i + 0] = tIndices[i + 2];
tIndices[i + 2] = tTemp;
}
this.setIndices(tIndices);
}
// Negate position.z
const tPositions = this.getVerticesData(VertexBuffer.PositionKind, false);
if (tPositions != null && tPositions.length > 0) {
for (let i = 0; i < tPositions.length; i += 3) {
tPositions[i + 2] = -tPositions[i + 2];
}
this.setVerticesData(VertexBuffer.PositionKind, tPositions, false);
}
// Negate normal.z
const tNormals = this.getVerticesData(VertexBuffer.NormalKind, false);
if (tNormals != null && tNormals.length > 0) {
for (let i = 0; i < tNormals.length; i += 3) {
tNormals[i + 2] = -tNormals[i + 2];
}
this.setVerticesData(VertexBuffer.NormalKind, tNormals, false);
}
}
// Cache
/** @hidden */
public _resetPointsArrayCache(): void {
this._positions = null;
}
/** @hidden */
public _generatePointsArray(): boolean {
if (this._positions) {
return true;
}
const data = this.getVerticesData(VertexBuffer.PositionKind);
if (!data || data.length === 0) {
return false;
}
for (let index = this._positionsCache.length * 3, arrayIdx = this._positionsCache.length; index < data.length; index += 3, ++arrayIdx) {
this._positionsCache[arrayIdx] = Vector3.FromArray(data, index);
}
for (let index = 0, arrayIdx = 0; index < data.length; index += 3, ++arrayIdx) {
this._positionsCache[arrayIdx].set(data[0 + index], data[1 + index], data[2 + index]);
}
// just in case the number of positions was reduced, splice the array
this._positionsCache.length = data.length / 3;
this._positions = this._positionsCache;
return true;
}
/**
* Gets a value indicating if the geometry is disposed
* @returns true if the geometry was disposed
*/
public isDisposed(): boolean {
return this._isDisposed;
}
private _disposeVertexArrayObjects(): void {
if (this._vertexArrayObjects) {
for (const kind in this._vertexArrayObjects) {
this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
}
this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
const meshes = this._meshes;
const numOfMeshes = meshes.length;
for (let index = 0; index < numOfMeshes; index++) {
meshes[index]._invalidateInstanceVertexArrayObject();
}
}
}
/**
* Free all associated resources
*/
public dispose(): void {
const meshes = this._meshes;
const numOfMeshes = meshes.length;
let index: number;
for (index = 0; index < numOfMeshes; index++) {
this.releaseForMesh(meshes[index]);
}
this._meshes = [];
this._disposeVertexArrayObjects();
for (const kind in this._vertexBuffers) {
this._vertexBuffers[kind].dispose();
}
this._vertexBuffers = {};
this._totalVertices = 0;
if (this._indexBuffer) {
this._engine._releaseBuffer(this._indexBuffer);
}
this._indexBuffer = null;
this._indices = [];
this.delayLoadState = Constants.DELAYLOADSTATE_NONE;
this.delayLoadingFile = null;
this._delayLoadingFunction = null;
this._delayInfo = [];
this._boundingInfo = null;
this._scene.removeGeometry(this);
if (this._parentContainer) {
const index = this._parentContainer.geometries.indexOf(this);
if (index > -1) {
this._parentContainer.geometries.splice(index, 1);
}
this._parentContainer = null;
}
this._isDisposed = true;
}
/**
* Clone the current geometry into a new geometry
* @param id defines the unique ID of the new geometry
* @returns a new geometry object
*/
public copy(id: string): Geometry {
const vertexData = new VertexData();
vertexData.indices = [];
const indices = this.getIndices();
if (indices) {
for (let index = 0; index < indices.length; index++) {
(<number[]>vertexData.indices).push(indices[index]);
}
}
let updatable = false;
let stopChecking = false;
let kind;
for (kind in this._vertexBuffers) {
// using slice() to make a copy of the array and not just reference it
const data = this.getVerticesData(kind);
if (data) {
if (data instanceof Float32Array) {
vertexData.set(new Float32Array(<Float32Array>data), kind);
} else {
vertexData.set((<number[]>data).slice(0), kind);
}
if (!stopChecking) {
const vb = this.getVertexBuffer(kind);
if (vb) {
updatable = vb.isUpdatable();
stopChecking = !updatable;
}
}
}
}