-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
mesh.ts
5499 lines (4796 loc) · 235 KB
/
mesh.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
/* eslint-disable jsdoc/require-returns-check */
import type { Observer } from "../Misc/observable";
import { Observable } from "../Misc/observable";
import { Tools, AsyncLoop } from "../Misc/tools";
import type { IAnimatable } from "../Animations/animatable.interface";
import { DeepCopier } from "../Misc/deepCopier";
import { Tags } from "../Misc/tags";
import type { Coroutine } from "../Misc/coroutine";
import { runCoroutineSync, runCoroutineAsync, createYieldingScheduler } from "../Misc/coroutine";
import type { Nullable, FloatArray, IndicesArray } from "../types";
import { Camera } from "../Cameras/camera";
import type { Scene } from "../scene";
import { ScenePerformancePriority } from "../scene";
import type { Vector4 } from "../Maths/math.vector";
import { Quaternion, Matrix, Vector3, Vector2 } from "../Maths/math.vector";
import type { Color4 } from "../Maths/math.color";
import { Color3 } from "../Maths/math.color";
import { Node } from "../node";
import { VertexBuffer, Buffer } from "../Buffers/buffer";
import type { IGetSetVerticesData } from "./mesh.vertexData";
import { VertexData } from "./mesh.vertexData";
import { Geometry } from "./geometry";
import type { IMeshDataOptions } from "./abstractMesh";
import { AbstractMesh } from "./abstractMesh";
import { SubMesh } from "./subMesh";
import type { BoundingSphere } from "../Culling/boundingSphere";
import type { Effect } from "../Materials/effect";
import { Material } from "../Materials/material";
import { MultiMaterial } from "../Materials/multiMaterial";
import { SceneLoaderFlags } from "../Loading/sceneLoaderFlags";
import type { Skeleton } from "../Bones/skeleton";
import { Constants } from "../Engines/constants";
import { SerializationHelper } from "../Misc/decorators.serialization";
import { Logger } from "../Misc/logger";
import { GetClass, RegisterClass } from "../Misc/typeStore";
import { _WarnImport } from "../Misc/devTools";
import { SceneComponentConstants } from "../sceneComponent";
import { MeshLODLevel } from "./meshLODLevel";
import type { Path3D } from "../Maths/math.path";
import type { Plane } from "../Maths/math.plane";
import type { TransformNode } from "./transformNode";
import type { DrawWrapper } from "../Materials/drawWrapper";
import type { PhysicsEngine as PhysicsEngineV1 } from "../Physics/v1/physicsEngine";
import type { GoldbergMesh } from "./goldbergMesh";
import type { InstancedMesh } from "./instancedMesh";
import type { IPhysicsEnabledObject, PhysicsImpostor } from "../Physics/v1/physicsImpostor";
import type { ICreateCapsuleOptions } from "./Builders/capsuleBuilder";
import type { LinesMesh } from "./linesMesh";
import type { GroundMesh } from "./groundMesh";
import type { DataBuffer } from "core/Buffers/dataBuffer";
import type { AbstractEngine } from "core/Engines/abstractEngine";
/**
* @internal
**/
export class _CreationDataStorage {
public closePath?: boolean;
public closeArray?: boolean;
public idx: number[];
public dashSize: number;
public gapSize: number;
public path3D: Path3D;
public pathArray: Vector3[][];
public arc: number;
public radius: number;
public cap: number;
public tessellation: number;
}
/**
* @internal
**/
class _InstanceDataStorage {
public visibleInstances: any = {};
public batchCache = new _InstancesBatch();
public batchCacheReplacementModeInFrozenMode = new _InstancesBatch();
public instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
public instancesBuffer: Nullable<Buffer>;
public instancesPreviousBuffer: Nullable<Buffer>;
public instancesData: Float32Array;
public instancesPreviousData: Float32Array;
public overridenInstanceCount: number;
public isFrozen: boolean;
public forceMatrixUpdates: boolean;
public previousBatch: Nullable<_InstancesBatch>;
public hardwareInstancedRendering: boolean;
public sideOrientation: number;
public manualUpdate: boolean;
public previousManualUpdate: boolean;
public previousRenderId: number;
public masterMeshPreviousWorldMatrix: Nullable<Matrix>;
}
/**
* @internal
**/
export class _InstancesBatch {
public mustReturn = false;
public visibleInstances = new Array<Nullable<Array<InstancedMesh>>>();
public renderSelf: boolean[] = [];
public hardwareInstancedRendering: boolean[] = [];
}
/**
* @internal
**/
class _ThinInstanceDataStorage {
public instancesCount: number = 0;
public matrixBuffer: Nullable<Buffer> = null;
public previousMatrixBuffer: Nullable<Buffer> = null;
public matrixBufferSize = 32 * 16; // let's start with a maximum of 32 thin instances
public matrixData: Nullable<Float32Array> = null;
public previousMatrixData: Nullable<Float32Array>;
public boundingVectors: Array<Vector3> = [];
public worldMatrices: Nullable<Matrix[]> = null;
public masterMeshPreviousWorldMatrix: Nullable<Matrix>;
}
/**
* @internal
**/
class _InternalMeshDataInfo {
// Events
public _onBeforeRenderObservable: Nullable<Observable<Mesh>>;
public _onBeforeBindObservable: Nullable<Observable<Mesh>>;
public _onAfterRenderObservable: Nullable<Observable<Mesh>>;
public _onBeforeDrawObservable: Nullable<Observable<Mesh>>;
public _onBetweenPassObservable: Nullable<Observable<SubMesh>>;
public _areNormalsFrozen: boolean = false; // Will be used by ribbons mainly
public _sourcePositions: Nullable<Float32Array>; // Will be used to save original positions when using software skinning
public _sourceNormals: Nullable<Float32Array>; // Will be used to save original normals when using software skinning
// Will be used to save a source mesh reference, If any
public _source: Nullable<Mesh> = null;
// Will be used to for fast cloned mesh lookup
public meshMap: Nullable<{ [id: string]: Mesh | undefined }> = null;
public _preActivateId: number = -1;
// eslint-disable-next-line @typescript-eslint/naming-convention
public _LODLevels = new Array<MeshLODLevel>();
/** Alternative definition of LOD level, using screen coverage instead of distance */
public _useLODScreenCoverage: boolean = false;
public _checkReadinessObserver: Nullable<Observer<Scene>>;
public _onMeshReadyObserverAdded: (observer: Observer<Mesh>) => void;
public _effectiveMaterial: Nullable<Material> = null;
public _forcedInstanceCount: number = 0;
public _overrideRenderingFillMode: Nullable<number> = null;
public _sideOrientation: number;
}
/**
* Class used to represent renderable models
*/
export class Mesh extends AbstractMesh implements IGetSetVerticesData {
// Consts
/**
* Mesh side orientation : usually the external or front surface
*/
public static readonly FRONTSIDE = VertexData.FRONTSIDE;
/**
* Mesh side orientation : usually the internal or back surface
*/
public static readonly BACKSIDE = VertexData.BACKSIDE;
/**
* Mesh side orientation : both internal and external or front and back surfaces
*/
public static readonly DOUBLESIDE = VertexData.DOUBLESIDE;
/**
* Mesh side orientation : by default, `FRONTSIDE`
*/
public static readonly DEFAULTSIDE = VertexData.DEFAULTSIDE;
/**
* Mesh cap setting : no cap
*/
public static readonly NO_CAP = 0;
/**
* Mesh cap setting : one cap at the beginning of the mesh
*/
public static readonly CAP_START = 1;
/**
* Mesh cap setting : one cap at the end of the mesh
*/
public static readonly CAP_END = 2;
/**
* Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
*/
public static readonly CAP_ALL = 3;
/**
* Mesh pattern setting : no flip or rotate
*/
public static readonly NO_FLIP = 0;
/**
* Mesh pattern setting : flip (reflect in y axis) alternate tiles on each row or column
*/
public static readonly FLIP_TILE = 1;
/**
* Mesh pattern setting : rotate (180degs) alternate tiles on each row or column
*/
public static readonly ROTATE_TILE = 2;
/**
* Mesh pattern setting : flip (reflect in y axis) all tiles on alternate rows
*/
public static readonly FLIP_ROW = 3;
/**
* Mesh pattern setting : rotate (180degs) all tiles on alternate rows
*/
public static readonly ROTATE_ROW = 4;
/**
* Mesh pattern setting : flip and rotate alternate tiles on each row or column
*/
public static readonly FLIP_N_ROTATE_TILE = 5;
/**
* Mesh pattern setting : rotate pattern and rotate
*/
public static readonly FLIP_N_ROTATE_ROW = 6;
/**
* Mesh tile positioning : part tiles same on left/right or top/bottom
*/
public static readonly CENTER = 0;
/**
* Mesh tile positioning : part tiles on left
*/
public static readonly LEFT = 1;
/**
* Mesh tile positioning : part tiles on right
*/
public static readonly RIGHT = 2;
/**
* Mesh tile positioning : part tiles on top
*/
public static readonly TOP = 3;
/**
* Mesh tile positioning : part tiles on bottom
*/
public static readonly BOTTOM = 4;
/**
* Indicates that the instanced meshes should be sorted from back to front before rendering if their material is transparent
*/
public static INSTANCEDMESH_SORT_TRANSPARENT = false;
/**
* Gets the default side orientation.
* @param orientation the orientation to value to attempt to get
* @returns the default orientation
* @internal
*/
public static _GetDefaultSideOrientation(orientation?: number): number {
return orientation || Mesh.FRONTSIDE; // works as Mesh.FRONTSIDE is 0
}
// Internal data
private _internalMeshDataInfo = new _InternalMeshDataInfo();
/**
* Determines if the LOD levels are intended to be calculated using screen coverage (surface area ratio) instead of distance.
*/
public get useLODScreenCoverage() {
return this._internalMeshDataInfo._useLODScreenCoverage;
}
public set useLODScreenCoverage(value: boolean) {
this._internalMeshDataInfo._useLODScreenCoverage = value;
this._sortLODLevels();
}
/**
* Will notify when the mesh is completely ready, including materials.
* Observers added to this observable will be removed once triggered
*/
public onMeshReadyObservable: Observable<Mesh>;
public override get computeBonesUsingShaders(): boolean {
return this._internalAbstractMeshDataInfo._computeBonesUsingShaders;
}
public override set computeBonesUsingShaders(value: boolean) {
if (this._internalAbstractMeshDataInfo._computeBonesUsingShaders === value) {
return;
}
if (value && this._internalMeshDataInfo._sourcePositions) {
// switch from software to GPU computation: we need to reset the vertex and normal buffers that have been updated by the software process
this.setVerticesData(VertexBuffer.PositionKind, this._internalMeshDataInfo._sourcePositions, true);
if (this._internalMeshDataInfo._sourceNormals) {
this.setVerticesData(VertexBuffer.NormalKind, this._internalMeshDataInfo._sourceNormals, true);
}
this._internalMeshDataInfo._sourcePositions = null;
this._internalMeshDataInfo._sourceNormals = null;
}
this._internalAbstractMeshDataInfo._computeBonesUsingShaders = value;
this._markSubMeshesAsAttributesDirty();
}
/**
* An event triggered before rendering the mesh
*/
public get onBeforeRenderObservable(): Observable<Mesh> {
if (!this._internalMeshDataInfo._onBeforeRenderObservable) {
this._internalMeshDataInfo._onBeforeRenderObservable = new Observable<Mesh>();
}
return this._internalMeshDataInfo._onBeforeRenderObservable;
}
/**
* An event triggered before binding the mesh
*/
public get onBeforeBindObservable(): Observable<Mesh> {
if (!this._internalMeshDataInfo._onBeforeBindObservable) {
this._internalMeshDataInfo._onBeforeBindObservable = new Observable<Mesh>();
}
return this._internalMeshDataInfo._onBeforeBindObservable;
}
/**
* An event triggered after rendering the mesh
*/
public get onAfterRenderObservable(): Observable<Mesh> {
if (!this._internalMeshDataInfo._onAfterRenderObservable) {
this._internalMeshDataInfo._onAfterRenderObservable = new Observable<Mesh>();
}
return this._internalMeshDataInfo._onAfterRenderObservable;
}
/**
* An event triggeredbetween rendering pass when using separateCullingPass = true
*/
public get onBetweenPassObservable(): Observable<SubMesh> {
if (!this._internalMeshDataInfo._onBetweenPassObservable) {
this._internalMeshDataInfo._onBetweenPassObservable = new Observable<SubMesh>();
}
return this._internalMeshDataInfo._onBetweenPassObservable;
}
/**
* An event triggered before drawing the mesh
*/
public get onBeforeDrawObservable(): Observable<Mesh> {
if (!this._internalMeshDataInfo._onBeforeDrawObservable) {
this._internalMeshDataInfo._onBeforeDrawObservable = new Observable<Mesh>();
}
return this._internalMeshDataInfo._onBeforeDrawObservable;
}
private _onBeforeDrawObserver: Nullable<Observer<Mesh>>;
/**
* Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
*/
public set onBeforeDraw(callback: () => void) {
if (this._onBeforeDrawObserver) {
this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
}
this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
}
public override get hasInstances(): boolean {
return this.instances.length > 0;
}
public override get hasThinInstances(): boolean {
return (this.forcedInstanceCount || this._thinInstanceDataStorage.instancesCount || 0) > 0;
}
// Members
/**
* Gets the delay loading state of the mesh (when delay loading is turned on)
* @see https://doc.babylonjs.com/features/featuresDeepDive/importers/incrementalLoading
*/
public delayLoadState = Constants.DELAYLOADSTATE_NONE;
/**
* Gets the list of instances created from this mesh
* it is not supposed to be modified manually.
* Note also that the order of the InstancedMesh wihin the array is not significant and might change.
* @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances
*/
public instances: InstancedMesh[] = [];
/**
* Gets the file containing delay loading data for this mesh
*/
public delayLoadingFile: string;
/** @internal */
public _binaryInfo: any;
/**
* User defined function used to change how LOD level selection is done
* @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD
*/
public onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Nullable<Mesh>) => void;
// Private
/** @internal */
public _creationDataStorage: Nullable<_CreationDataStorage> = null;
/** @internal */
public _geometry: Nullable<Geometry> = null;
/** @internal */
public _delayInfo: Array<string>;
/** @internal */
public _delayLoadingFunction: (any: any, mesh: Mesh) => void;
/**
* Gets or sets the forced number of instances to display.
* If 0 (default value), the number of instances is not forced and depends on the draw type
* (regular / instance / thin instances mesh)
*/
public get forcedInstanceCount(): number {
return this._internalMeshDataInfo._forcedInstanceCount;
}
public set forcedInstanceCount(count: number) {
this._internalMeshDataInfo._forcedInstanceCount = count;
}
/** @internal */
public _instanceDataStorage = new _InstanceDataStorage();
/** @internal */
public _thinInstanceDataStorage = new _ThinInstanceDataStorage();
/** @internal */
public _shouldGenerateFlatShading: boolean = false;
// Use by builder only to know what orientation were the mesh build in.
/** @internal */
public _originalBuilderSideOrientation: number = Mesh.DEFAULTSIDE;
/**
* Use this property to change the original side orientation defined at construction time
* Material.sideOrientation will override this value if set
* User will still be able to change the material sideOrientation afterwards if they really need it
*/
public get sideOrientation(): number {
return this._internalMeshDataInfo._sideOrientation;
}
public set sideOrientation(value: number) {
this._internalMeshDataInfo._sideOrientation = value;
this._internalAbstractMeshDataInfo._sideOrientationHint =
(this._scene.useRightHandedSystem && value === Constants.MATERIAL_CounterClockWiseSideOrientation) ||
(!this._scene.useRightHandedSystem && value === Constants.MATERIAL_ClockWiseSideOrientation);
}
/**
* @deprecated Please use sideOrientation instead.
* @see https://doc.babylonjs.com/breaking-changes#7110
*/
public get overrideMaterialSideOrientation() {
return this.sideOrientation;
}
public set overrideMaterialSideOrientation(value: number) {
this.sideOrientation = value;
if (this.material) {
this.material.sideOrientation = null;
}
}
/**
* Use this property to override the Material's fillMode value
*/
public get overrideRenderingFillMode(): Nullable<number> {
return this._internalMeshDataInfo._overrideRenderingFillMode;
}
public set overrideRenderingFillMode(fillMode: Nullable<number>) {
this._internalMeshDataInfo._overrideRenderingFillMode = fillMode;
}
public override get material(): Nullable<Material> {
return this._internalAbstractMeshDataInfo._material;
}
public override set material(value: Nullable<Material>) {
if (value && ((this.material && this.material.sideOrientation === null) || this._internalAbstractMeshDataInfo._sideOrientationHint)) {
value.sideOrientation = null;
}
this._setMaterial(value);
}
/**
* Gets or sets a boolean indicating whether to render ignoring the active camera's max z setting. (false by default)
* You should not mix meshes that have this property set to true with meshes that have it set to false if they all write
* to the depth buffer, because the z-values are not comparable in the two cases and you will get rendering artifacts if you do.
* You can set the property to true for meshes that do not write to the depth buffer, or set the same value (either false or true) otherwise.
* Note this will reduce performance when set to true.
*/
public ignoreCameraMaxZ = false;
/**
* Gets the source mesh (the one used to clone this one from)
*/
public get source(): Nullable<Mesh> {
return this._internalMeshDataInfo._source;
}
/**
* Gets the list of clones of this mesh
* The scene must have been constructed with useClonedMeshMap=true for this to work!
* Note that useClonedMeshMap=true is the default setting
*/
public get cloneMeshMap(): Nullable<{ [id: string]: Mesh | undefined }> {
return this._internalMeshDataInfo.meshMap;
}
/**
* Gets or sets a boolean indicating that this mesh does not use index buffer
*/
public get isUnIndexed(): boolean {
return this._unIndexed;
}
public set isUnIndexed(value: boolean) {
if (this._unIndexed !== value) {
this._unIndexed = value;
this._markSubMeshesAsAttributesDirty();
}
}
/** Gets the array buffer used to store the instanced buffer used for instances' world matrices */
public get worldMatrixInstancedBuffer() {
return this._instanceDataStorage.instancesData;
}
/** Gets the array buffer used to store the instanced buffer used for instances' previous world matrices */
public get previousWorldMatrixInstancedBuffer() {
return this._instanceDataStorage.instancesPreviousData;
}
/** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices is manual */
public get manualUpdateOfWorldMatrixInstancedBuffer() {
return this._instanceDataStorage.manualUpdate;
}
public set manualUpdateOfWorldMatrixInstancedBuffer(value: boolean) {
this._instanceDataStorage.manualUpdate = value;
}
/** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices is manual */
public get manualUpdateOfPreviousWorldMatrixInstancedBuffer() {
return this._instanceDataStorage.previousManualUpdate;
}
public set manualUpdateOfPreviousWorldMatrixInstancedBuffer(value: boolean) {
this._instanceDataStorage.previousManualUpdate = value;
}
/** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices must be performed in all cases (and notably even in frozen mode) */
public get forceWorldMatrixInstancedBufferUpdate() {
return this._instanceDataStorage.forceMatrixUpdates;
}
public set forceWorldMatrixInstancedBufferUpdate(value: boolean) {
this._instanceDataStorage.forceMatrixUpdates = value;
}
protected _copySource(source: Mesh, doNotCloneChildren?: boolean, clonePhysicsImpostor: boolean = true) {
const scene = this.getScene();
// Geometry
if (source._geometry) {
source._geometry.applyToMesh(this);
}
// Deep copy
DeepCopier.DeepCopy(
source,
this,
[
"name",
"material",
"skeleton",
"instances",
"parent",
"uniqueId",
"source",
"metadata",
"morphTargetManager",
"hasInstances",
"worldMatrixInstancedBuffer",
"previousWorldMatrixInstancedBuffer",
"hasLODLevels",
"geometry",
"isBlocked",
"areNormalsFrozen",
"facetNb",
"isFacetDataEnabled",
"lightSources",
"useBones",
"isAnInstance",
"collider",
"edgesRenderer",
"forward",
"up",
"right",
"absolutePosition",
"absoluteScaling",
"absoluteRotationQuaternion",
"isWorldMatrixFrozen",
"nonUniformScaling",
"behaviors",
"worldMatrixFromCache",
"hasThinInstances",
"cloneMeshMap",
"hasBoundingInfo",
"physicsBody",
"physicsImpostor",
],
["_poseMatrix"]
);
// Source mesh
this._internalMeshDataInfo._source = source;
if (scene.useClonedMeshMap) {
if (!source._internalMeshDataInfo.meshMap) {
source._internalMeshDataInfo.meshMap = {};
}
source._internalMeshDataInfo.meshMap[this.uniqueId] = this;
}
// Construction Params
// Clone parameters allowing mesh to be updated in case of parametric shapes.
this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
this._creationDataStorage = source._creationDataStorage;
// Animation ranges
if (source._ranges) {
const ranges = source._ranges;
for (const name in ranges) {
if (!Object.prototype.hasOwnProperty.call(ranges, name)) {
continue;
}
if (!ranges[name]) {
continue;
}
this.createAnimationRange(name, ranges[name]!.from, ranges[name]!.to);
}
}
// Metadata
if (source.metadata && source.metadata.clone) {
this.metadata = source.metadata.clone();
} else {
this.metadata = source.metadata;
}
this._internalMetadata = source._internalMetadata;
// Tags
if (Tags && Tags.HasTags(source)) {
Tags.AddTagsTo(this, Tags.GetTags(source, true));
}
// Enabled. We shouldn't need to check the source's ancestors, as this mesh
// will have the same ones.
this.setEnabled(source.isEnabled(false));
// Parent
this.parent = source.parent;
// Pivot
this.setPivotMatrix(source.getPivotMatrix(), this._postMultiplyPivotMatrix);
this.id = this.name + "." + source.id;
// Material
this.material = source.material;
if (!doNotCloneChildren) {
// Children
const directDescendants = source.getDescendants(true);
for (let index = 0; index < directDescendants.length; index++) {
const child = directDescendants[index];
if ((<any>child).clone) {
(<any>child).clone(this.name + "." + child.name, this);
}
}
}
// Morphs
if (source.morphTargetManager) {
this.morphTargetManager = source.morphTargetManager;
}
// Physics clone
if (scene.getPhysicsEngine) {
const physicsEngine = scene.getPhysicsEngine();
if (clonePhysicsImpostor && physicsEngine) {
if (physicsEngine.getPluginVersion() === 1) {
const impostor = (physicsEngine as PhysicsEngineV1).getImpostorForPhysicsObject(source);
if (impostor) {
this.physicsImpostor = impostor.clone(this);
}
} else if (physicsEngine.getPluginVersion() === 2) {
if (source.physicsBody) {
source.physicsBody.clone(this);
}
}
}
}
// Particles
for (let index = 0; index < scene.particleSystems.length; index++) {
const system = scene.particleSystems[index];
if (system.emitter === source) {
system.clone(system.name, this);
}
}
// Skeleton
this.skeleton = source.skeleton;
this.refreshBoundingInfo(true, true);
this.computeWorldMatrix(true);
}
/**
* Constructor
* @param name The value used by scene.getMeshByName() to do a lookup.
* @param scene The scene to add this mesh to.
* @param parent The parent of this mesh, if it has one
* @param source An optional Mesh from which geometry is shared, cloned.
* @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
* When false, achieved by calling a clone(), also passing False.
* This will make creation of children, recursive.
* @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
*/
constructor(
name: string,
scene: Nullable<Scene> = null,
parent: Nullable<Node> = null,
source: Nullable<Mesh> = null,
doNotCloneChildren?: boolean,
clonePhysicsImpostor: boolean = true
) {
super(name, scene);
scene = this.getScene();
if (this._scene.useRightHandedSystem) {
this.sideOrientation = Constants.MATERIAL_ClockWiseSideOrientation;
} else {
this.sideOrientation = Constants.MATERIAL_CounterClockWiseSideOrientation;
}
this._onBeforeDraw = (isInstance: boolean, world: Matrix, effectiveMaterial?: Material) => {
if (isInstance && effectiveMaterial) {
if (this._uniformBuffer) {
this.transferToEffect(world);
} else {
effectiveMaterial.bindOnlyWorldMatrix(world);
}
}
};
if (source) {
this._copySource(source, doNotCloneChildren, clonePhysicsImpostor);
}
// Parent
if (parent !== null) {
this.parent = parent;
}
this._instanceDataStorage.hardwareInstancedRendering = this.getEngine().getCaps().instancedArrays;
this._internalMeshDataInfo._onMeshReadyObserverAdded = (observer: Observer<Mesh>) => {
// only notify once! then unregister the observer
observer.unregisterOnNextCall = true;
if (this.isReady(true)) {
this.onMeshReadyObservable.notifyObservers(this);
} else {
if (!this._internalMeshDataInfo._checkReadinessObserver) {
this._internalMeshDataInfo._checkReadinessObserver = this._scene.onBeforeRenderObservable.add(() => {
// check for complete readiness
if (this.isReady(true)) {
this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver);
this._internalMeshDataInfo._checkReadinessObserver = null;
this.onMeshReadyObservable.notifyObservers(this);
}
});
}
}
};
this.onMeshReadyObservable = new Observable(this._internalMeshDataInfo._onMeshReadyObserverAdded);
if (source) {
source.onClonedObservable.notifyObservers(this);
}
}
public override instantiateHierarchy(
newParent: Nullable<TransformNode> = null,
options?: { doNotInstantiate: boolean | ((node: TransformNode) => boolean) },
onNewNodeCreated?: (source: TransformNode, clone: TransformNode) => void
): Nullable<TransformNode> {
const instance =
this.getTotalVertices() === 0 || (options && options.doNotInstantiate && (options.doNotInstantiate === true || options.doNotInstantiate(this)))
? this.clone("Clone of " + (this.name || this.id), newParent || this.parent, true)
: this.createInstance("instance of " + (this.name || this.id));
instance.parent = newParent || this.parent;
instance.position = this.position.clone();
instance.scaling = this.scaling.clone();
if (this.rotationQuaternion) {
instance.rotationQuaternion = this.rotationQuaternion.clone();
} else {
instance.rotation = this.rotation.clone();
}
if (onNewNodeCreated) {
onNewNodeCreated(this, instance);
}
for (const child of this.getChildTransformNodes(true)) {
// instancedMesh should have a different sourced mesh
if (child.getClassName() === "InstancedMesh" && instance.getClassName() === "Mesh" && (child as InstancedMesh).sourceMesh === this) {
(child as InstancedMesh).instantiateHierarchy(
instance,
{
doNotInstantiate: (options && options.doNotInstantiate) || false,
newSourcedMesh: instance as Mesh,
},
onNewNodeCreated
);
} else {
child.instantiateHierarchy(instance, options, onNewNodeCreated);
}
}
return instance;
}
/**
* Gets the class name
* @returns the string "Mesh".
*/
public override getClassName(): string {
return "Mesh";
}
/** @internal */
public get _isMesh() {
return true;
}
/**
* Returns a description of this mesh
* @param fullDetails define if full details about this mesh must be used
* @returns a descriptive string representing this mesh
*/
public override toString(fullDetails?: boolean): string {
let ret = super.toString(fullDetails);
ret += ", n vertices: " + this.getTotalVertices();
ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : this.parent ? this.parent.name : "NONE");
if (this.animations) {
for (let i = 0; i < this.animations.length; i++) {
ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
}
}
if (fullDetails) {
if (this._geometry) {
const ib = this.getIndices();
const vb = this.getVerticesData(VertexBuffer.PositionKind);
if (vb && ib) {
ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
}
} else {
ret += ", flat shading: UNKNOWN";
}
}
return ret;
}
/** @internal */
public override _unBindEffect() {
super._unBindEffect();
for (const instance of this.instances) {
instance._unBindEffect();
}
}
/**
* Gets a boolean indicating if this mesh has LOD
*/
public get hasLODLevels(): boolean {
return this._internalMeshDataInfo._LODLevels.length > 0;
}
/**
* Gets the list of MeshLODLevel associated with the current mesh
* @returns an array of MeshLODLevel
*/
public getLODLevels(): MeshLODLevel[] {
return this._internalMeshDataInfo._LODLevels;
}
private _sortLODLevels(): void {
const sortingOrderFactor = this._internalMeshDataInfo._useLODScreenCoverage ? -1 : 1;
this._internalMeshDataInfo._LODLevels.sort((a, b) => {
if (a.distanceOrScreenCoverage < b.distanceOrScreenCoverage) {
return sortingOrderFactor;
}
if (a.distanceOrScreenCoverage > b.distanceOrScreenCoverage) {
return -sortingOrderFactor;
}
return 0;
});
}
/**
* Add a mesh as LOD level triggered at the given distance.
* @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD
* @param distanceOrScreenCoverage Either distance from the center of the object to show this level or the screen coverage if `useScreenCoverage` is set to `true`.
* If screen coverage, value is a fraction of the screen's total surface, between 0 and 1.
* Example Playground for distance https://playground.babylonjs.com/#QE7KM#197
* Example Playground for screen coverage https://playground.babylonjs.com/#QE7KM#196
* @param mesh The mesh to be added as LOD level (can be null)
* @returns This mesh (for chaining)
*/
public addLODLevel(distanceOrScreenCoverage: number, mesh: Nullable<Mesh>): Mesh {
if (mesh && mesh._masterMesh) {
Logger.Warn("You cannot use a mesh as LOD level twice");
return this;
}
const level = new MeshLODLevel(distanceOrScreenCoverage, mesh);
this._internalMeshDataInfo._LODLevels.push(level);
if (mesh) {
mesh._masterMesh = this;
}
this._sortLODLevels();
return this;
}
/**
* Returns the LOD level mesh at the passed distance or null if not found.
* @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD
* @param distance The distance from the center of the object to show this level
* @returns a Mesh or `null`
*/
public getLODLevelAtDistance(distance: number): Nullable<Mesh> {
const internalDataInfo = this._internalMeshDataInfo;
for (let index = 0; index < internalDataInfo._LODLevels.length; index++) {
const level = internalDataInfo._LODLevels[index];
if (level.distanceOrScreenCoverage === distance) {
return level.mesh;
}
}
return null;
}
/**
* Remove a mesh from the LOD array
* @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD
* @param mesh defines the mesh to be removed
* @returns This mesh (for chaining)
*/
public removeLODLevel(mesh: Nullable<Mesh>): Mesh {
const internalDataInfo = this._internalMeshDataInfo;
for (let index = 0; index < internalDataInfo._LODLevels.length; index++) {
if (internalDataInfo._LODLevels[index].mesh === mesh) {
internalDataInfo._LODLevels.splice(index, 1);
if (mesh) {
mesh._masterMesh = null;
}
}