forked from BabylonJS/Babylon.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgpuParticleSystem.ts
More file actions
1847 lines (1534 loc) · 68 KB
/
Copy pathgpuParticleSystem.ts
File metadata and controls
1847 lines (1534 loc) · 68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
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 { Nullable, float, DataArray } from "../types";
import { FactorGradient, ColorGradient, Color3Gradient, IValueGradient, GradientHelper } from "../Misc/gradients";
import { Observable } from "../Misc/observable";
import { Vector3, Matrix, TmpVectors } from "../Maths/math.vector";
import { Color4, Color3, TmpColors } from "../Maths/math.color";
import { Scalar } from "../Maths/math.scalar";
import { VertexBuffer } from "../Buffers/buffer";
import { Buffer } from "../Buffers/buffer";
import { IParticleSystem } from "./IParticleSystem";
import { BaseParticleSystem } from "./baseParticleSystem";
import { ParticleSystem } from "./particleSystem";
import { BoxParticleEmitter } from "../Particles/EmitterTypes/boxParticleEmitter";
import { IDisposable } from "../scene";
import { Effect } from "../Materials/effect";
import { MaterialHelper } from "../Materials/materialHelper";
import { ImageProcessingConfiguration } from "../Materials/imageProcessingConfiguration";
import { RawTexture } from "../Materials/Textures/rawTexture";
import { Constants } from "../Engines/constants";
import { EngineStore } from "../Engines/engineStore";
import { IAnimatable } from "../Animations/animatable.interface";
import { CustomParticleEmitter } from "./EmitterTypes/customParticleEmitter";
import { ThinEngine } from "../Engines/thinEngine";
import { DataBuffer } from "../Buffers/dataBuffer";
import { DrawWrapper } from "../Materials/drawWrapper";
import { UniformBufferEffectCommonAccessor } from "../Materials/uniformBufferEffectCommonAccessor";
import { IGPUParticleSystemPlatform } from "./IGPUParticleSystemPlatform";
declare type Scene = import("../scene").Scene;
declare type Engine = import("../Engines/engine").Engine;
declare type AbstractMesh = import("../Meshes/abstractMesh").AbstractMesh;
import "../Shaders/gpuRenderParticles.fragment";
import "../Shaders/gpuRenderParticles.vertex";
import { GetClass } from "../Misc/typeStore";
/**
* This represents a GPU particle system in Babylon
* This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
* @see https://www.babylonjs-playground.com/#PU4WYI#4
*/
export class GPUParticleSystem extends BaseParticleSystem implements IDisposable, IParticleSystem, IAnimatable {
/**
* The layer mask we are rendering the particles through.
*/
public layerMask: number = 0x0fffffff;
private _capacity: number;
private _activeCount: number;
private _currentActiveCount: number;
private _accumulatedCount = 0;
private _updateBuffer: UniformBufferEffectCommonAccessor;
private _buffer0: Buffer;
private _buffer1: Buffer;
private _spriteBuffer: Buffer;
private _targetIndex = 0;
private _sourceBuffer: Buffer;
private _targetBuffer: Buffer;
private _currentRenderId = -1;
private _currentRenderingCameraUniqueId = -1;
private _started = false;
private _stopped = false;
private _timeDelta = 0;
/** @hidden */
public _randomTexture: RawTexture;
/** @hidden */
public _randomTexture2: RawTexture;
private _attributesStrideSize: number;
private _cachedUpdateDefines: string;
private _randomTextureSize: number;
private _actualFrame = 0;
private _drawWrappers: { [blendMode: number]: DrawWrapper };
private _customWrappers: { [blendMode: number]: Nullable<DrawWrapper> };
private readonly _rawTextureWidth = 256;
private _platform: IGPUParticleSystemPlatform;
/**
* Gets a boolean indicating if the GPU particles can be rendered on current browser
*/
public static get IsSupported(): boolean {
if (!EngineStore.LastCreatedEngine) {
return false;
}
return (EngineStore.LastCreatedEngine.name === "WebGL" && EngineStore.LastCreatedEngine.version > 1) || EngineStore.LastCreatedEngine.getCaps().supportComputeShaders;
}
/**
* An event triggered when the system is disposed.
*/
public onDisposeObservable = new Observable<IParticleSystem>();
/**
* An event triggered when the system is stopped
*/
public onStoppedObservable = new Observable<IParticleSystem>();
/**
* Gets the maximum number of particles active at the same time.
* @returns The max number of active particles.
*/
public getCapacity(): number {
return this._capacity;
}
/**
* Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
* to override the particles.
*/
public forceDepthWrite = false;
/**
* Gets or set the number of active particles
*/
public get activeParticleCount(): number {
return this._activeCount;
}
public set activeParticleCount(value: number) {
this._activeCount = Math.min(value, this._capacity);
}
private _preWarmDone = false;
/**
* Specifies if the particles are updated in emitter local space or world space.
*/
public isLocal = false;
/** Gets or sets a matrix to use to compute projection */
public defaultProjectionMatrix: Matrix;
/**
* Is this system ready to be used/rendered
* @return true if the system is ready
*/
public isReady(): boolean {
if (!this.emitter || this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
return false;
}
if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
if (!this._getWrapper(this.blendMode).effect!.isReady()) {
return false;
}
} else {
if (!this._getWrapper(ParticleSystem.BLENDMODE_MULTIPLY).effect!.isReady()) {
return false;
}
if (!this._getWrapper(ParticleSystem.BLENDMODE_ADD).effect!.isReady()) {
return false;
}
}
if (!this._platform.isUpdateBufferCreated()) {
this._recreateUpdateEffect();
return false;
}
return this._platform.isUpdateBufferReady();
}
/**
* Gets if the system has been started. (Note: this will still be true after stop is called)
* @returns True if it has been started, otherwise false.
*/
public isStarted(): boolean {
return this._started;
}
/**
* Gets if the system has been stopped. (Note: rendering is still happening but the system is frozen)
* @returns True if it has been stopped, otherwise false.
*/
public isStopped(): boolean {
return this._stopped;
}
/**
* Gets a boolean indicating that the system is stopping
* @returns true if the system is currently stopping
*/
public isStopping() {
return false; // Stop is immediate on GPU
}
/**
* Gets the number of particles active at the same time.
* @returns The number of active particles.
*/
public getActiveCount() {
return this._currentActiveCount;
}
/**
* Starts the particle system and begins to emit
* @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
*/
public start(delay = this.startDelay): void {
if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
}
if (delay) {
setTimeout(() => {
this.start(0);
}, delay);
return;
}
this._started = true;
this._stopped = false;
this._preWarmDone = false;
// Animations
if (this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene) {
this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
}
}
/**
* Stops the particle system.
*/
public stop(): void {
if (this._stopped) {
return;
}
this._stopped = true;
}
/**
* Remove all active particles
*/
public reset(): void {
this._releaseBuffers();
this._platform.releaseVertexBuffers();
this._currentActiveCount = 0;
this._targetIndex = 0;
}
/**
* Returns the string "GPUParticleSystem"
* @returns a string containing the class name
*/
public getClassName(): string {
return "GPUParticleSystem";
}
/**
* Gets the custom effect used to render the particles
* @param blendMode Blend mode for which the effect should be retrieved
* @returns The effect
*/
public getCustomEffect(blendMode: number = 0): Nullable<Effect> {
return this._customWrappers[blendMode]?.effect ?? this._customWrappers[0]!.effect;
}
private _getCustomDrawWrapper(blendMode: number = 0): Nullable<DrawWrapper> {
return this._customWrappers[blendMode] ?? this._customWrappers[0];
}
/**
* Sets the custom effect used to render the particles
* @param effect The effect to set
* @param blendMode Blend mode for which the effect should be set
*/
public setCustomEffect(effect: Nullable<Effect>, blendMode: number = 0) {
this._customWrappers[blendMode] = new DrawWrapper(this._engine);
this._customWrappers[blendMode]!.effect = effect;
}
/** @hidden */
protected _onBeforeDrawParticlesObservable: Nullable<Observable<Nullable<Effect>>> = null;
/**
* Observable that will be called just before the particles are drawn
*/
public get onBeforeDrawParticlesObservable(): Observable<Nullable<Effect>> {
if (!this._onBeforeDrawParticlesObservable) {
this._onBeforeDrawParticlesObservable = new Observable<Nullable<Effect>>();
}
return this._onBeforeDrawParticlesObservable;
}
/**
* Gets the name of the particle vertex shader
*/
public get vertexShaderName(): string {
return "gpuRenderParticles";
}
/** @hidden */
public _colorGradientsTexture: RawTexture;
protected _removeGradientAndTexture(gradient: number, gradients: Nullable<IValueGradient[]>, texture: RawTexture): BaseParticleSystem {
super._removeGradientAndTexture(gradient, gradients, texture);
this._releaseBuffers();
return this;
}
/**
* Adds a new color gradient
* @param gradient defines the gradient to use (between 0 and 1)
* @param color1 defines the color to affect to the specified gradient
* @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
* @returns the current particle system
*/
public addColorGradient(gradient: number, color1: Color4, color2?: Color4): GPUParticleSystem {
if (!this._colorGradients) {
this._colorGradients = [];
}
let colorGradient = new ColorGradient(gradient, color1);
this._colorGradients.push(colorGradient);
this._refreshColorGradient(true);
this._releaseBuffers();
return this;
}
private _refreshColorGradient(reorder = false) {
if (this._colorGradients) {
if (reorder) {
this._colorGradients.sort((a, b) => {
if (a.gradient < b.gradient) {
return -1;
} else if (a.gradient > b.gradient) {
return 1;
}
return 0;
});
}
if (this._colorGradientsTexture) {
this._colorGradientsTexture.dispose();
(<any>this._colorGradientsTexture) = null;
}
}
}
/** Force the system to rebuild all gradients that need to be resync */
public forceRefreshGradients() {
this._refreshColorGradient();
this._refreshFactorGradient(this._sizeGradients, "_sizeGradientsTexture");
this._refreshFactorGradient(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
this._refreshFactorGradient(this._velocityGradients, "_velocityGradientsTexture");
this._refreshFactorGradient(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
this._refreshFactorGradient(this._dragGradients, "_dragGradientsTexture");
this.reset();
}
/**
* Remove a specific color gradient
* @param gradient defines the gradient to remove
* @returns the current particle system
*/
public removeColorGradient(gradient: number): GPUParticleSystem {
this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
(<any>this._colorGradientsTexture) = null;
return this;
}
/**
* Resets the draw wrappers cache
*/
public resetDrawCache(): void {
for (const blendMode in this._drawWrappers) {
const drawWrapper = this._drawWrappers[blendMode];
drawWrapper.drawContext?.reset();
}
}
/** @hidden */
public _angularSpeedGradientsTexture: RawTexture;
/** @hidden */
public _sizeGradientsTexture: RawTexture;
/** @hidden */
public _velocityGradientsTexture: RawTexture;
/** @hidden */
public _limitVelocityGradientsTexture: RawTexture;
/** @hidden */
public _dragGradientsTexture: RawTexture;
private _addFactorGradient(factorGradients: FactorGradient[], gradient: number, factor: number) {
let valueGradient = new FactorGradient(gradient, factor);
factorGradients.push(valueGradient);
this._releaseBuffers();
}
/**
* Adds a new size gradient
* @param gradient defines the gradient to use (between 0 and 1)
* @param factor defines the size factor to affect to the specified gradient
* @returns the current particle system
*/
public addSizeGradient(gradient: number, factor: number): GPUParticleSystem {
if (!this._sizeGradients) {
this._sizeGradients = [];
}
this._addFactorGradient(this._sizeGradients, gradient, factor);
this._refreshFactorGradient(this._sizeGradients, "_sizeGradientsTexture", true);
this._releaseBuffers();
return this;
}
/**
* Remove a specific size gradient
* @param gradient defines the gradient to remove
* @returns the current particle system
*/
public removeSizeGradient(gradient: number): GPUParticleSystem {
this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
(<any>this._sizeGradientsTexture) = null;
return this;
}
private _refreshFactorGradient(factorGradients: Nullable<FactorGradient[]>, textureName: string, reorder = false) {
if (!factorGradients) {
return;
}
if (reorder) {
factorGradients.sort((a, b) => {
if (a.gradient < b.gradient) {
return -1;
} else if (a.gradient > b.gradient) {
return 1;
}
return 0;
});
}
let that = this as any;
if (that[textureName]) {
that[textureName].dispose();
that[textureName] = null;
}
}
/**
* Adds a new angular speed gradient
* @param gradient defines the gradient to use (between 0 and 1)
* @param factor defines the angular speed to affect to the specified gradient
* @returns the current particle system
*/
public addAngularSpeedGradient(gradient: number, factor: number): GPUParticleSystem {
if (!this._angularSpeedGradients) {
this._angularSpeedGradients = [];
}
this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
this._refreshFactorGradient(this._angularSpeedGradients, "_angularSpeedGradientsTexture", true);
this._releaseBuffers();
return this;
}
/**
* Remove a specific angular speed gradient
* @param gradient defines the gradient to remove
* @returns the current particle system
*/
public removeAngularSpeedGradient(gradient: number): GPUParticleSystem {
this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
(<any>this._angularSpeedGradientsTexture) = null;
return this;
}
/**
* Adds a new velocity gradient
* @param gradient defines the gradient to use (between 0 and 1)
* @param factor defines the velocity to affect to the specified gradient
* @returns the current particle system
*/
public addVelocityGradient(gradient: number, factor: number): GPUParticleSystem {
if (!this._velocityGradients) {
this._velocityGradients = [];
}
this._addFactorGradient(this._velocityGradients, gradient, factor);
this._refreshFactorGradient(this._velocityGradients, "_velocityGradientsTexture", true);
this._releaseBuffers();
return this;
}
/**
* Remove a specific velocity gradient
* @param gradient defines the gradient to remove
* @returns the current particle system
*/
public removeVelocityGradient(gradient: number): GPUParticleSystem {
this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
(<any>this._velocityGradientsTexture) = null;
return this;
}
/**
* Adds a new limit velocity gradient
* @param gradient defines the gradient to use (between 0 and 1)
* @param factor defines the limit velocity value to affect to the specified gradient
* @returns the current particle system
*/
public addLimitVelocityGradient(gradient: number, factor: number): GPUParticleSystem {
if (!this._limitVelocityGradients) {
this._limitVelocityGradients = [];
}
this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
this._refreshFactorGradient(this._limitVelocityGradients, "_limitVelocityGradientsTexture", true);
this._releaseBuffers();
return this;
}
/**
* Remove a specific limit velocity gradient
* @param gradient defines the gradient to remove
* @returns the current particle system
*/
public removeLimitVelocityGradient(gradient: number): GPUParticleSystem {
this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
(<any>this._limitVelocityGradientsTexture) = null;
return this;
}
/**
* Adds a new drag gradient
* @param gradient defines the gradient to use (between 0 and 1)
* @param factor defines the drag value to affect to the specified gradient
* @returns the current particle system
*/
public addDragGradient(gradient: number, factor: number): GPUParticleSystem {
if (!this._dragGradients) {
this._dragGradients = [];
}
this._addFactorGradient(this._dragGradients, gradient, factor);
this._refreshFactorGradient(this._dragGradients, "_dragGradientsTexture", true);
this._releaseBuffers();
return this;
}
/**
* Remove a specific drag gradient
* @param gradient defines the gradient to remove
* @returns the current particle system
*/
public removeDragGradient(gradient: number): GPUParticleSystem {
this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
(<any>this._dragGradientsTexture) = null;
return this;
}
/**
* Not supported by GPUParticleSystem
* @param gradient defines the gradient to use (between 0 and 1)
* @param factor defines the emit rate value to affect to the specified gradient
* @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
* @returns the current particle system
*/
public addEmitRateGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
// Do nothing as emit rate is not supported by GPUParticleSystem
return this;
}
/**
* Not supported by GPUParticleSystem
* @param gradient defines the gradient to remove
* @returns the current particle system
*/
public removeEmitRateGradient(gradient: number): IParticleSystem {
// Do nothing as emit rate is not supported by GPUParticleSystem
return this;
}
/**
* Not supported by GPUParticleSystem
* @param gradient defines the gradient to use (between 0 and 1)
* @param factor defines the start size value to affect to the specified gradient
* @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
* @returns the current particle system
*/
public addStartSizeGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
// Do nothing as start size is not supported by GPUParticleSystem
return this;
}
/**
* Not supported by GPUParticleSystem
* @param gradient defines the gradient to remove
* @returns the current particle system
*/
public removeStartSizeGradient(gradient: number): IParticleSystem {
// Do nothing as start size is not supported by GPUParticleSystem
return this;
}
/**
* Not supported by GPUParticleSystem
* @param gradient defines the gradient to use (between 0 and 1)
* @param min defines the color remap minimal range
* @param max defines the color remap maximal range
* @returns the current particle system
*/
public addColorRemapGradient(gradient: number, min: number, max: number): IParticleSystem {
// Do nothing as start size is not supported by GPUParticleSystem
return this;
}
/**
* Not supported by GPUParticleSystem
* @param gradient defines the gradient to remove
* @returns the current particle system
*/
public removeColorRemapGradient(): IParticleSystem {
// Do nothing as start size is not supported by GPUParticleSystem
return this;
}
/**
* Not supported by GPUParticleSystem
* @param gradient defines the gradient to use (between 0 and 1)
* @param min defines the alpha remap minimal range
* @param max defines the alpha remap maximal range
* @returns the current particle system
*/
public addAlphaRemapGradient(gradient: number, min: number, max: number): IParticleSystem {
// Do nothing as start size is not supported by GPUParticleSystem
return this;
}
/**
* Not supported by GPUParticleSystem
* @param gradient defines the gradient to remove
* @returns the current particle system
*/
public removeAlphaRemapGradient(): IParticleSystem {
// Do nothing as start size is not supported by GPUParticleSystem
return this;
}
/**
* Not supported by GPUParticleSystem
* @param gradient defines the gradient to use (between 0 and 1)
* @param color defines the color to affect to the specified gradient
* @returns the current particle system
*/
public addRampGradient(gradient: number, color: Color3): IParticleSystem {
//Not supported by GPUParticleSystem
return this;
}
/**
* Not supported by GPUParticleSystem
* @param gradient defines the gradient to remove
* @returns the current particle system
*/
public removeRampGradient(): IParticleSystem {
//Not supported by GPUParticleSystem
return this;
}
/**
* Not supported by GPUParticleSystem
* @returns the list of ramp gradients
*/
public getRampGradients(): Nullable<Array<Color3Gradient>> {
return null;
}
/**
* Not supported by GPUParticleSystem
* Gets or sets a boolean indicating that ramp gradients must be used
* @see https://doc.babylonjs.com/babylon101/particles#ramp-gradients
*/
public get useRampGradients(): boolean {
//Not supported by GPUParticleSystem
return false;
}
public set useRampGradients(value: boolean) {
//Not supported by GPUParticleSystem
}
/**
* Not supported by GPUParticleSystem
* @param gradient defines the gradient to use (between 0 and 1)
* @param factor defines the life time factor to affect to the specified gradient
* @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
* @returns the current particle system
*/
public addLifeTimeGradient(gradient: number, factor: number, factor2?: number): IParticleSystem {
//Not supported by GPUParticleSystem
return this;
}
/**
* Not supported by GPUParticleSystem
* @param gradient defines the gradient to remove
* @returns the current particle system
*/
public removeLifeTimeGradient(gradient: number): IParticleSystem {
//Not supported by GPUParticleSystem
return this;
}
/**
* Instantiates a GPU particle system.
* Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
* @param name The name of the particle system
* @param options The options used to create the system
* @param sceneOrEngine The scene the particle system belongs to or the engine to use if no scene
* @param customEffect a custom effect used to change the way particles are rendered by default
* @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
*/
constructor(
name: string,
options: Partial<{
capacity: number;
randomTextureSize: number;
}>,
sceneOrEngine: Scene | ThinEngine,
customEffect: Nullable<Effect> = null,
isAnimationSheetEnabled: boolean = false
) {
super(name);
if (!sceneOrEngine || sceneOrEngine.getClassName() === "Scene") {
this._scene = (sceneOrEngine as Scene) || EngineStore.LastCreatedScene;
this._engine = this._scene.getEngine();
this.uniqueId = this._scene.getUniqueId();
this._scene.particleSystems.push(this);
} else {
this._engine = sceneOrEngine as ThinEngine;
this.defaultProjectionMatrix = Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100, this._engine.isNDCHalfZRange);
}
if (this._engine.getCaps().supportComputeShaders) {
if (!GetClass("BABYLON.ComputeShaderParticleSystem")) {
throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");
}
this._platform = new (GetClass("BABYLON.ComputeShaderParticleSystem") as any)(this, this._engine);
} else {
if (!GetClass("BABYLON.WebGL2ParticleSystem")) {
throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");
}
this._platform = new (GetClass("BABYLON.WebGL2ParticleSystem") as any)(this, this._engine);
}
this._customWrappers = { 0: new DrawWrapper(this._engine) };
this._customWrappers[0]!.effect = customEffect;
this._drawWrappers = { 0: new DrawWrapper(this._engine) };
if (this._drawWrappers[0].drawContext) {
this._drawWrappers[0].drawContext.useInstancing = true;
}
// Setup the default processing configuration to the scene.
this._attachImageProcessingConfiguration(null);
options = options ?? {};
if (!options.randomTextureSize) {
delete options.randomTextureSize;
}
let fullOptions = {
capacity: 50000,
randomTextureSize: this._engine.getCaps().maxTextureSize,
...options,
};
var optionsAsNumber = <number>options;
if (isFinite(optionsAsNumber)) {
fullOptions.capacity = optionsAsNumber;
}
this._capacity = fullOptions.capacity;
this._activeCount = fullOptions.capacity;
this._currentActiveCount = 0;
this._isAnimationSheetEnabled = isAnimationSheetEnabled;
this.particleEmitterType = new BoxParticleEmitter();
// Random data
var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
var d = [];
for (var i = 0; i < maxTextureSize; ++i) {
d.push(Math.random());
d.push(Math.random());
d.push(Math.random());
d.push(Math.random());
}
this._randomTexture = new RawTexture(new Float32Array(d), maxTextureSize, 1, Constants.TEXTUREFORMAT_RGBA, sceneOrEngine, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE, Constants.TEXTURETYPE_FLOAT);
this._randomTexture.name = "GPUParticleSystem_random1";
this._randomTexture.wrapU = Constants.TEXTURE_WRAP_ADDRESSMODE;
this._randomTexture.wrapV = Constants.TEXTURE_WRAP_ADDRESSMODE;
d = [];
for (var i = 0; i < maxTextureSize; ++i) {
d.push(Math.random());
d.push(Math.random());
d.push(Math.random());
d.push(Math.random());
}
this._randomTexture2 = new RawTexture(new Float32Array(d), maxTextureSize, 1, Constants.TEXTUREFORMAT_RGBA, sceneOrEngine, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE, Constants.TEXTURETYPE_FLOAT);
this._randomTexture2.name = "GPUParticleSystem_random2";
this._randomTexture2.wrapU = Constants.TEXTURE_WRAP_ADDRESSMODE;
this._randomTexture2.wrapV = Constants.TEXTURE_WRAP_ADDRESSMODE;
this._randomTextureSize = maxTextureSize;
}
protected _reset() {
this._releaseBuffers();
}
private _createVertexBuffers(updateBuffer: Buffer, renderBuffer: Buffer, spriteSource: Buffer): void {
let renderVertexBuffers: { [key: string]: VertexBuffer } = {};
renderVertexBuffers["position"] = renderBuffer.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
let offset = 3;
renderVertexBuffers["age"] = renderBuffer.createVertexBuffer("age", offset, 1, this._attributesStrideSize, true);
offset += 1;
renderVertexBuffers["size"] = renderBuffer.createVertexBuffer("size", offset, 3, this._attributesStrideSize, true);
offset += 3;
renderVertexBuffers["life"] = renderBuffer.createVertexBuffer("life", offset, 1, this._attributesStrideSize, true);
offset += 1;
offset += 4; // seed
if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
renderVertexBuffers["direction"] = renderBuffer.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
}
offset += 3; // direction
if (this._platform.alignDataInBuffer) {
offset += 1;
}
if (this.particleEmitterType instanceof CustomParticleEmitter) {
offset += 3;
if (this._platform.alignDataInBuffer) {
offset += 1;
}
}
if (!this._colorGradientsTexture) {
renderVertexBuffers["color"] = renderBuffer.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
offset += 4;
}
if (!this._isBillboardBased) {
renderVertexBuffers["initialDirection"] = renderBuffer.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
offset += 3;
if (this._platform.alignDataInBuffer) {
offset += 1;
}
}
if (this.noiseTexture) {
renderVertexBuffers["noiseCoordinates1"] = renderBuffer.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
offset += 3;
if (this._platform.alignDataInBuffer) {
offset += 1;
}
renderVertexBuffers["noiseCoordinates2"] = renderBuffer.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
offset += 3;
if (this._platform.alignDataInBuffer) {
offset += 1;
}
}
renderVertexBuffers["angle"] = renderBuffer.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
if (this._angularSpeedGradientsTexture) {
offset++;
} else {
offset += 2;
}
if (this._isAnimationSheetEnabled) {
renderVertexBuffers["cellIndex"] = renderBuffer.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
offset += 1;
if (this.spriteRandomStartCell) {
renderVertexBuffers["cellStartOffset"] = renderBuffer.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
offset += 1;
}
}
renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
this._platform.createVertexBuffers(updateBuffer, renderVertexBuffers);
this.resetDrawCache();
}
private _initialize(force = false): void {
if (this._buffer0 && !force) {
return;
}
let engine = this._engine;
var data = new Array<float>();
this._attributesStrideSize = 21;
this._targetIndex = 0;
if (this._platform.alignDataInBuffer) {
this._attributesStrideSize += 1;
}
if (this.particleEmitterType instanceof CustomParticleEmitter) {
this._attributesStrideSize += 3;
if (this._platform.alignDataInBuffer) {
this._attributesStrideSize += 1;
}
}
if (!this.isBillboardBased) {
this._attributesStrideSize += 3;
if (this._platform.alignDataInBuffer) {
this._attributesStrideSize += 1;
}
}
if (this._colorGradientsTexture) {
this._attributesStrideSize -= 4;
}
if (this._angularSpeedGradientsTexture) {
this._attributesStrideSize -= 1;
}
if (this._isAnimationSheetEnabled) {
this._attributesStrideSize += 1;
if (this.spriteRandomStartCell) {
this._attributesStrideSize += 1;
}
}
if (this.noiseTexture) {
this._attributesStrideSize += 6;
if (this._platform.alignDataInBuffer) {
this._attributesStrideSize += 2;
}
}
if (this._platform.alignDataInBuffer) {
this._attributesStrideSize += 3 - ((this._attributesStrideSize + 3) & 3); // round to multiple of 4
}
const usingCustomEmitter = this.particleEmitterType instanceof CustomParticleEmitter;
const tmpVector = TmpVectors.Vector3[0];
let offset = 0;
for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
// position
data.push(0.0);
data.push(0.0);
data.push(0.0);
// Age
data.push(0.0); // create the particle as a dead one to create a new one at start
// Size
data.push(0.0);
data.push(0.0);