forked from harlyq/aframe-sprite-particles-component
-
Notifications
You must be signed in to change notification settings - Fork 1
/
aframe-sprite-particles-component.js
1869 lines (1536 loc) · 70 KB
/
aframe-sprite-particles-component.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 harlyq
// License MIT
(function() {
const TIME_PARAM = 0 // [0].x
const ID_PARAM = 1 // [0].y
const RADIAL_X_PARAM = 2 // [0].z
const DURATION_PARAM = 3 // [0].w
const SPAWN_TYPE_PARAM = 4 // [1].x
const SPAWN_RATE_PARAM = 5 // [1].y
const SEED_PARAM = 6 // [1].z
const VERTEX_COUNT_PARAM = 7 // [1].w
const PARTICLE_SIZE_PARAM = 8 // [2].x
const USE_PERSPECTIVE_PARAM = 9 // [2].y
const DIRECTION_PARAM = 10 // [2].z
const DRAG_PARAM = 11 // [2].w
const TRAIL_INTERVAL_PARAM = 12 // [3].x
const PARTICLE_COUNT_PARAM = 13 // [3].y
const TRAIL_COUNT_PARAM = 14 // [3].z
const SCREEN_DEPTH_OFFSET_PARAM = 15 // [3].w
const RIBBON_WIDTH_PARAM = 16 // [4].x
const RIBBON_UV_MULTIPLIER_PARAM = 17 // [4].y
const RIBBON_UV_TYPE_PARAM = 18 // [4].z
const RADIAL_Y_PARAM = 19 // [4].w
const PARAMS_LENGTH = 5 // 0..4
const MODEL_MESH = "mesh"
const VERTS_PER_RIBBON = 2
const RANDOM_REPEAT_COUNT = 131072 // random numbers will start repeating after this number of particles
const degToRad = THREE.Math.degToRad
const ATTR_TO_DEFINES = {
acceleration: "USE_PARTICLE_ACCELERATION",
angularAcceleration: "USE_PARTICLE_ANGULAR_ACCELERATION",
angularVelocity: "USE_PARTICLE_ANGULAR_VELOCITY",
color: "USE_PARTICLE_COLOR",
textureFrame: "USE_PARTICLE_FRAMES",
textureCount: "USE_PARTICLE_FRAMES",
textureLoop: "USE_PARTICLE_FRAMES",
position: "USE_PARTICLE_OFFSET",
opacity: "USE_PARTICLE_OPACITY",
radialAcceleration: "USE_PARTICLE_RADIAL_ACCELERATION",
radialPosition: "USE_PARTICLE_RADIAL_OFFSET",
radialVelocity: "USE_PARTICLE_RADIAL_VELOCITY",
scale: "USE_PARTICLE_SCALE",
velocity: "USE_PARTICLE_VELOCITY",
orbitalVelocity: "USE_PARTICLE_ORBITAL",
orbitalAcceleration: "USE_PARTICLE_ORBITAL",
drag: "USE_PARTICLE_DRAG",
destinationWeight: "USE_PARTICLE_DESTINATION",
screenDepthOffset: "USE_PARTICLE_SCREEN_DEPTH_OFFSET",
source: "USE_PARTICLE_SOURCE",
model: "USE_PARTICLE_SOURCE",
}
const UV_TYPE_STRINGS = ["overtime", "interval"]
const PARTICLE_ORDER_STRINGS = ["newest", "oldest", "original"]
const AXES_NAMES = ["x", "y", "z"]
// Bring all sub-array elements into a single array e.g. [[1,2],[[3],4],5] => [1,2,3,4,5]
const flattenDeep = arr1 => arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), [])
// Convert a vector range string into an array of elements. def defines the default elements for each vector
const parseVecRange = (str, def) => {
let parts = str.split("..").map(a => a.trim().split(" ").map(b => {
const num = Number(b)
return isNaN(num) ? undefined : num
}))
if (parts.length === 1) parts[1] = parts[0] // if there is no second part then copy the first part
parts.length = 2
return flattenDeep( parts.map(a => def.map((x,i) => typeof a[i] === "undefined" ? x : a[i])) )
}
// parse a ("," separated) list of vector range elements
const parseVecRangeArray = (str, def) => {
return flattenDeep( str.split(",").map(a => parseVecRange(a, def)) )
}
// parse a ("," separated) list of color range elements
const parseColorRangeArray = (str) => {
return flattenDeep( str.split(",").map(a => {
let parts = a.split("..")
if (parts.length === 1) parts[1] = parts[0] // if there is no second part then copy the first part
parts.length = 2
return parts.map(b => new THREE.Color(b.trim()))
}) )
}
const toLowerCase = x => x.toLowerCase()
// console.assert(AFRAME.utils.deepEqual(parseVecRange("", [1,2,3]), [1,2,3,1,2,3]))
// console.assert(AFRAME.utils.deepEqual(parseVecRange("5", [1,2,3]), [5,2,3,5,2,3]))
// console.assert(AFRAME.utils.deepEqual(parseVecRange("5 6", [1,2,3]), [5,6,3,5,6,3]))
// console.assert(AFRAME.utils.deepEqual(parseVecRange("5 6 7 8", [1,2,3]), [5,6,7,5,6,7]))
// console.assert(AFRAME.utils.deepEqual(parseVecRange("8 9..10", [1,2,3]), [8,9,3,10,2,3]))
// console.assert(AFRAME.utils.deepEqual(parseVecRange("..5 6 7", [1,2,3]), [1,2,3,5,6,7]))
// console.assert(AFRAME.utils.deepEqual(parseVecRange("2 3 4..5 6 7", [1,2,3]), [2,3,4,5,6,7]))
// console.assert(AFRAME.utils.deepEqual(parseVecRange("5 6 7..", [1,2,3]), [5,6,7,1,2,3]))
// console.assert(AFRAME.utils.deepEqual(parseVecRangeArray("5 6 7..,9..10 11 12", [1,2,3]), [5,6,7,1,2,3,9,2,3,10,11,12]))
// console.assert(AFRAME.utils.deepEqual(parseVecRangeArray("1,2,,,3", [10]), [1,1,2,2,10,10,10,10,3,3]))
// console.assert(AFRAME.utils.deepEqual(parseColorRangeArray("black..red,blue,,#ff0..#00ffaa").map(a => a.getHexString()), ["000000","ff0000","0000ff","0000ff","ffffff","ffffff","ffff00","00ffaa"]))
let WHITE_TEXTURE = new THREE.DataTexture(new Uint8Array(4).fill(255), 1, 1, THREE.RGBAFormat)
WHITE_TEXTURE.needsUpdate = true
const BLENDING_MAP = {
"none": THREE.NoBlending,
"normal": THREE.NormalBlending,
"additive": THREE.AdditiveBlending,
"subtractive": THREE.SubtractiveBlending,
"multiply": THREE.MultiplyBlending,
}
const SIDE_MAP = {
"double": THREE.DoubleSide,
"front": THREE.FrontSide,
"back": THREE.BackSide,
}
AFRAME.registerComponent("sprite-particles", {
schema: {
enableInEditor: { default: false },
texture: { type: "map" },
delay: { default: 0 },
duration: { default: -1 },
spawnType: { default: "continuous", oneOf: ["continuous", "burst"], parse: toLowerCase },
spawnRate: { default: 10 },
source: { type: "selector" },
textureFrame: { type: "vec2", default: {x: 1, y: 1} },
textureCount: { type: "int", default: 0 },
textureLoop: { default: 1 },
randomizeFrames: { default: false },
trailInterval: { default: 0 },
trailLifeTime: { default: "0" },
trailType: { default: "particle", oneOf: ["particle", "ribbon", "ribbon3d"] },
ribbonWidth: { default: 1, },
ribbonShape: { default: "flat", oneOf: ["flat", "taperin", "taperout", "taper"], parse: toLowerCase },
ribbonUVType: { default: "overtime", oneOf: UV_TYPE_STRINGS, parse: toLowerCase },
emitterColor: { type: "color" },
lifeTime: { default: "1" },
position: { default: "0 0 0" },
velocity: { default: "0 0 0" },
acceleration: { default: "0 0 0" },
radialType: { default: "circle", oneOf: ["circle", "sphere", "circlexy", "circlexz"], parse: toLowerCase },
radialPosition: { default: "0" },
radialVelocity: { default: "0" },
radialAcceleration: { default: "0" },
angularVelocity: { default: "0 0 0" },
angularAcceleration: { default: "0 0 0" },
orbitalVelocity: { default: "0" },
orbitalAcceleration: { default: "0" },
scale: { default: "1" },
color: { default: "white", parse: toLowerCase },
rotation: { default: "0" }, // if rotating textureFrames important to have enough space so overlapping parts of frames are blank (circle of sqrt(2) around the center of the frame will be viewable while rotating)
opacity: { default: "1" },
velocityScale: { default: 0 },
velocityScaleMinMax: { type: "vec2", default: {x: 0, y: 3} },
drag: { default: 0 },
destination: { type: "selector" },
destinationOffset: { default: "0 0 0" },
destinationWeight: { default: "0" },
enable: { default: true },
emitterTime: { default: 0 },
model: { type: "selector" },
modelFill: { default: "triangle", oneOf: ["triangle", "edge", "vertex"], parse: toLowerCase },
direction: { default: "forward", oneOf: ["forward", "backward"], parse: toLowerCase },
particleOrder: { default: "original", oneOf: PARTICLE_ORDER_STRINGS },
ribbonUVMultiplier: { default: 1 },
materialSide: { default: "front", oneOf: ["double", "front", "back"], parse: toLowerCase },
screenDepthOffset: { default: 0 },
alphaTest: { default: 0 },
fog: { default: true },
depthWrite: { default: false },
depthTest: { default: true },
blending: { default: "normal", oneOf: ["none", "normal", "additive", "subtractive", "multiply"], parse: toLowerCase },
transparent: { default: true },
particleSize: { default: 100 },
usePerspective: { default: true },
seed: { type: "number", default: -1 },
overTimeSlots: { type: "int", default: 5 },
frustumCulled: { default: true },
editorObject: { default: true },
},
multiple: true,
help: "https://github.com/harlyq/aframe-sprite-particles-component",
init() {
this.pauseTick = this.pauseTick.bind(this)
this.handleObject3DSet = this.handleObject3DSet.bind(this)
this.count = 0
this.trailCount = 0
this.overTimeArrayLength = 0
this.emitterTime = 0
this.delayTime = 0
this.lifeTime = [1,1]
this.trailLifeTime = [0,0] // if 0, then use this.lifeTime
// this.useTransparent = false
this.textureFrames = new Float32Array(4) // xy is TextureFrame, z is TextureCount, w is TextureLoop
this.offset = new Float32Array(2*4).fill(0) // xyz is position, w is radialPosition
this.velocity = new Float32Array(2*4).fill(0) // xyz is velocity, w is radialVelocity
this.acceleration = new Float32Array(2*4).fill(0) // xyz is acceleration, w is radialAcceleration
this.angularVelocity = new Float32Array(2*4).fill(0) // xyz is angularVelocity, w is lifeTime
this.angularAcceleration = new Float32Array(2*4).fill(0) // xyz is angularAcceleration
this.orbital = new Float32Array(2*2).fill(0) // x is orbitalVelocity, y is orbitalAcceleration
this.colorOverTime // color is xyz and opacity is w. created in update()
this.rotationScaleOverTime // x is rotation, y is scale. created in update()
this.params = new Float32Array(5*4).fill(0) // see ..._PARAM constants
this.velocityScale = new Float32Array(3).fill(0) // x is velocityScale, y is velocityScaleMinMax.x and z is velocityScaleMinMax.y
this.emitterColor = new THREE.Vector3() // use vec3 for color
this.destination = new Float32Array(2*4).fill(0) // range value, xyz is destinationEntity.position + destinationOffset, w is destinationWeight
this.destinationOffset // parsed value for destinationOffset, this will be blended into destination
this.destinationWeight // parsed value for destinationWeight
this.nextID = 0
this.nextTime = 0
this.numDisabled = 0
this.numEnabled = 0
this.startDisabled = !this.data.enable // if we start disabled then the tick is disabled, until the component is enabled
this.manageIDs = false
this.params[ID_PARAM] = -1 // unmanaged IDs
},
remove() {
if (this.mesh) {
this.el.removeObject3D(this.mesh.name)
}
if (data.model) {
data.model.removeEventListener("object3dset", this.handleObject3DSet)
}
},
update(oldData) {
const data = this.data
let boundsDirty = data.particleSize !== oldData.particleSize
let overTimeDirty = false
// can only change overTimeSlots while paused, as it will rebuild the shader (see updateDefines())
if (data.overTimeSlots !== oldData.overTimeSlots && !this.isPlaying) {
this.overTimeArrayLength = this.data.overTimeSlots*2 + 1 // each slot represents 2 glsl array elements pluse one element for the length info
this.colorOverTime = new Float32Array(4*this.overTimeArrayLength).fill(0) // color is xyz and opacity is w
this.rotationScaleOverTime = new Float32Array(2*this.overTimeArrayLength).fill(0) // x is rotation, y is scale
overTimeDirty = true
}
this.params[PARTICLE_SIZE_PARAM] = data.particleSize
this.params[USE_PERSPECTIVE_PARAM] = data.usePerspective ? 1 : 0
this.params[DIRECTION_PARAM] = data.direction === "forward" ? 0 : 1
this.params[DRAG_PARAM] = THREE.Math.clamp(data.drag, 0, 1)
this.params[SCREEN_DEPTH_OFFSET_PARAM] = data.screenDepthOffset*1e-5
this.params[RIBBON_WIDTH_PARAM] = data.ribbonWidth
this.params[RIBBON_UV_MULTIPLIER_PARAM] = data.ribbonUVMultiplier
this.textureFrames[0] = data.textureFrame.x
this.textureFrames[1] = data.textureFrame.y
this.textureFrames[2] = data.textureCount > 0 ? data.textureCount : data.textureFrame.x * data.textureFrame.y
this.textureFrames[3] = data.textureLoop
this.velocityScale[0] = data.velocityScale
this.velocityScale[1] = data.velocityScaleMinMax.x
this.velocityScale[2] = data.velocityScaleMinMax.y
if (this.material) {
this.material.alphaTest = data.alphaTest
this.material.depthTest = data.depthTest
this.material.depthWrite = data.depthWrite
this.material.blending = BLENDING_MAP[data.blending]
this.material.fog = data.fog
}
if (data.seed !== oldData.seed) {
this.seed = data.seed
this.params[SEED_PARAM] = data.seed >= 0 ? data.seed : Math.random()
}
if (data.ribbonUVType !== oldData.ribbonUVType) {
this.params[RIBBON_UV_TYPE_PARAM] = UV_TYPE_STRINGS.indexOf(data.ribbonUVType) === -1 ? 0 : UV_TYPE_STRINGS.indexOf(data.ribbonUVType)
}
if (data.radialType !== oldData.radialType) {
this.params[RADIAL_X_PARAM] = ["sphere", "circlexy", "circle"].includes(data.radialType) ? 1 : 0
this.params[RADIAL_Y_PARAM] = ["sphere", "circlexz"].includes(data.radialType) ? 1 : 0
}
if (this.mesh && data.frustumCulled !== oldData.frustumCulled) {
this.mesh.frustumCulled = data.frustumCulled
}
if (data.emitterColor !== oldData.emitterColor) {
const col = new THREE.Color(data.emitterColor)
this.emitterColor.set(col.r, col.g, col.b)
}
if (data.position !== oldData.position || data.radialPosition !== oldData.radialPosition) {
this.updateVec4XYZRange(data.position, "offset")
this.updateVec4WRange(data.radialPosition, [0], "offset")
boundsDirty = true
}
if (data.velocity !== oldData.velocity || data.radialVelocity !== oldData.radialVelocity) {
this.updateVec4XYZRange(data.velocity, "velocity")
this.updateVec4WRange(data.radialVelocity, [0], "velocity")
boundsDirty = true
}
if (data.acceleration !== oldData.acceleration || data.radialAcceleration !== oldData.radialAcceleration) {
this.updateVec4XYZRange(data.acceleration, "acceleration")
this.updateVec4WRange(data.radialAcceleration, [0], "acceleration")
boundsDirty = true
}
if (data.rotation !== oldData.rotation || data.scale !== oldData.scale || overTimeDirty) {
this.updateRotationScaleOverTime()
boundsDirty = true
}
if (data.color !== oldData.color || data.opacity !== oldData.opacity || overTimeDirty) {
this.updateColorOverTime()
}
if (data.lifeTime !== oldData.lifeTime) {
this.lifeTime = this.updateVec4WRange(data.lifeTime, [1], "angularVelocity")
}
if (data.angularVelocity !== oldData.angularVelocity) {
this.updateAngularVec4XYZRange(data.angularVelocity, "angularVelocity")
}
if (data.trailLifeTime !== oldData.trailLifeTime) {
// if trailLifeTime is 0 then use the lifeTime values, and always ensure that trailLifeTime never exceeds the lifeTime
this.trailLifeTime = parseVecRange(data.trailLifeTime, [0]).map((x,i) => x > 0 ? x : this.lifeTime[i])
this["angularAcceleration"][3] = this.trailLifeTime[0] // angularAcceleration[0].w
this["angularAcceleration"][7] = this.trailLifeTime[1] // angularAcceleration[1].w
}
if (data.angularAcceleration !== oldData.angularAcceleration) {
this.updateAngularVec4XYZRange(data.angularAcceleration, "angularAcceleration")
}
if (data.orbitalVelocity !== oldData.orbitalVelocity) {
this.updateAngularVec2PartRange(data.orbitalVelocity, [0], "orbital", 0) // x part
}
if (data.orbitalAcceleration !== oldData.orbitalAcceleration) {
this.updateAngularVec2PartRange(data.orbitalAcceleration, [0], "orbital", 1) // y part
}
if (data.destinationOffset !== oldData.destinationOffset) {
this.destinationOffset = this.updateVec4XYZRange(data.destinationOffset, "destination")
}
if (data.destinationWeight !== oldData.destinationWeight) {
this.destinationWeight = this.updateVec4WRange(data.destinationWeight, [0], "destination")
}
if (data.duration !== oldData.duration || data.delay !== oldData.delay || data.emitterTime !== oldData.emitterTime) {
// restart the particles
this.params[DURATION_PARAM] = data.duration
this.emitterTime = data.emitterTime
this.delayTime = data.delay
}
if (data.spawnType !== oldData.spawnType || data.spawnRate !== oldData.spawnRate || data.lifeTime !== oldData.lifeTime || data.trailInterval !== oldData.trailInterval) {
const maxParticleLifeTime = this.lifeTime[1]
const maxTrailLifeTime = data.trailInterval > 0 ? this.trailLifeTime[1] : 0
const maxAge = maxParticleLifeTime + maxTrailLifeTime
const particleCount = Math.max( 1, Math.ceil(maxAge*data.spawnRate) )
this.trailCount = 1 + ( data.trailInterval > 0 ? Math.ceil( Math.min(maxTrailLifeTime, maxParticleLifeTime)/data.trailInterval ) : 0 ) // +1 because the trail includes the lead particle
if (this.isRibbon()) {
this.trailCount++ // short ribbons will need an extra vert so they can bend around an interval, but why the extra vert for long ribbons?
this.count = particleCount * this.trailCount * VERTS_PER_RIBBON
} else {
this.count = particleCount * this.trailCount
}
this.params[SPAWN_TYPE_PARAM] = data.spawnType === "burst" ? 0 : 1
this.params[SPAWN_RATE_PARAM] = data.spawnRate
this.params[VERTEX_COUNT_PARAM] = this.count
this.params[PARTICLE_COUNT_PARAM] = particleCount
this.params[TRAIL_INTERVAL_PARAM] = data.trailInterval
this.params[TRAIL_COUNT_PARAM] = this.trailCount
this.updateAttributes()
}
if (data.enableInEditor !== oldData.enableInEditor) {
this.enablePauseTick(data.enableInEditor)
}
if (data.enable && this.startDisabled) {
this.startDisabled = false
}
if (data.model !== oldData.model && data.model && "getObject3D" in data.model) {
if (oldData.model) { oldData.model.removeEventListener("object3dset", this.handleObject3DSet) }
this.updateModelMesh(data.model.getObject3D(MODEL_MESH))
if (data.model) { data.model.addEventListener("object3dset", this.handleObject3DSet) }
}
if (data.particleOrder !== "original" && data.source) {
console.warn(`changing particleOrder to 'original' (was '${data.particleOrder}'), because particles use a source`)
}
if (!this.mesh) {
this.createMesh()
} else {
this.updateDefines()
}
if (data.materialSide !== oldData.materialSide) {
this.material.side = SIDE_MAP[data.materialSide]
}
if (boundsDirty) {
this.updateBounds() // call after createMesh()
}
if (this.paused && data.editorObject !== oldData.editorObject) {
this.enableEditorObject(data.editorObject)
}
// for managedIDs the CPU defines the ID - and we want to avoid this if at all possible
// once managed, always managed
this.manageIDs = this.manageIDs || !data.enable || data.source || typeof this.el.getDOMAttribute(this.attrName).enable !== "undefined" || data.model || data.delay > 0
// call loadTexture() after createMesh() to ensure that the material is available to accept the texture
if (data.texture !== oldData.texture) {
this.loadTexture(data.texture)
}
},
tick(time, deltaTime) {
const data = this.data
if (this.startDisabled) { return }
if (deltaTime > 100) deltaTime = 100 // ignore long pauses
const dt = deltaTime/1000 // dt is in seconds
if (data.enable) { this.delayTime -= dt }
if (this.delayTime >= 0) { return }
if (!data.model || this.modelVertices) {
this.emitterTime += dt
this.params[TIME_PARAM] = this.emitterTime
if (this.geometry && this.manageIDs) {
this.updateWorldTransform(this.emitterTime)
} else {
this.params[ID_PARAM] = -1
}
if (data.destination && data.destination.object3D && (this.destinationWeight[0] > 0 || this.destinationWeight[1] > 0)) {
this.updateDestinationEntity()
}
}
},
pause() {
this.paused = true
this.enablePauseTick(this.data.enableInEditor)
this.enableEditorObject(this.data.editorObject)
},
play() {
this.paused = false
this.enableEditorObject(false)
this.enablePauseTick(false)
},
enablePauseTick(enable) {
if (enable) {
this.pauseRAF = requestAnimationFrame(this.pauseTick)
} else {
cancelAnimationFrame(this.pauseRAF)
}
},
pauseTick() {
this.tick(0, 16) // time is not used
this.enablePauseTick(true)
},
handleObject3DSet(event) {
if (event.target === this.data.model && event.detail.type === MODEL_MESH) {
this.updateModelMesh(this.data.model.getObject3D(MODEL_MESH))
}
},
loadTexture(filename) {
if (filename) {
let materialSystem = this.el.sceneEl.systems["material"]
materialSystem.loadTexture(filename, {src: filename}, (texture) => {
if (this.isRibbon()) {
texture.wrapS = THREE.RepeatWrapping // needed by ribbonUVMultipler
}
this.material.uniforms.map.value = texture
})
} else {
this.material.uniforms.map.value = WHITE_TEXTURE
}
},
isRibbon() {
return this.data.trailInterval > 0 && this.data.trailType !== "particle"
},
createMesh() {
const data = this.data
this.geometry = new THREE.BufferGeometry()
this.updateAttributes()
this.material = new THREE.ShaderMaterial({
uniforms: {
map: { type: "t", value: WHITE_TEXTURE },
textureFrames: { value: this.textureFrames },
params: { value: this.params },
offset: { value: this.offset },
velocity: { value: this.velocity },
acceleration: { value: this.acceleration },
angularVelocity: { value: this.angularVelocity },
angularAcceleration: { value: this.angularAcceleration },
orbital: { value: this.orbital },
colorOverTime: { value: this.colorOverTime },
rotationScaleOverTime: { value: this.rotationScaleOverTime },
velocityScale: { value: this.velocityScale },
emitterColor: { value: this.emitterColor },
destination: { value: this.destination },
fogDensity: { value: 0.00025 },
fogNear: { value: 1 },
fogFar: { value: 2000 },
fogColor: { value: new THREE.Color( 0xffffff ) }
},
fragmentShader: particleFragmentShader,
vertexShader: particleVertexShader,
transparent: data.transparent,
alphaTest: data.alphaTest,
blending: BLENDING_MAP[data.blending],
fog: data.fog,
depthWrite: data.depthWrite,
depthTest: data.depthTest,
defines: {}, // updated in updateDefines()
})
this.updateDefines()
if (this.isRibbon()) {
// // this.material.side = THREE.DoubleSide
// this.material.side = THREE.FrontSide
this.mesh = new THREE.Mesh(this.geometry, [this.material]) // geometry groups need an array of materials
// this.mesh.drawMode = THREE.TriangleStripDrawMode
} else {
this.mesh = new THREE.Points(this.geometry, this.material)
}
this.mesh.frustumCulled = data.frustumCulled
this.mesh.name = this.attrName
this.material.name = this.mesh.name
this.el.setObject3D(this.mesh.name, this.mesh)
},
updateColorOverTime() {
let color = parseColorRangeArray(this.data.color)
let opacity = parseVecRangeArray(this.data.opacity, [1])
const maxSlots = this.data.overTimeSlots
if (color.length > maxSlots*2) color.length = maxSlots*2
if (opacity.length > maxSlots*2) opacity.length = maxSlots*2
this.colorOverTime.fill(0)
// first colorOverTime block contains length information
// divide by 2 because each array contains min and max values
this.colorOverTime[0] = color.length/2 // glsl colorOverTime[0].x
this.colorOverTime[1] = opacity.length/2 // glsl colorOverTime[0].y
// set k to 4 because the first vec4 of colorOverTime is use for the length params
let n = color.length
for (let i = 0, k = 4; i < n; i++, k += 4) {
let col = color[i]
this.colorOverTime[k] = col.r // glsl colorOverTime[1..].x
this.colorOverTime[k+1] = col.g // glsl colorOverTime[1..].y
this.colorOverTime[k+2] = col.b // glsl colorOverTime[1..].z
}
n = opacity.length
for (let i = 0, k = 4; i < n; i++, k += 4) {
let alpha = opacity[i]
this.colorOverTime[k+3] = alpha // glsl colorOverTime[1..].w
// this.useTransparent = this.useTransparent || alpha < 1
}
},
updateRotationScaleOverTime() {
const maxSlots = this.data.overTimeSlots
let rotation = parseVecRangeArray(this.data.rotation, [0])
let scale = parseVecRangeArray(this.data.scale, [1])
if (rotation.length > maxSlots*2) rotation.length = maxSlots*2 // 2 rotations per range
if (scale.length > maxSlots*2) scale.length = maxSlots*2 // 2 scales per range
// first vec4 contains the lengths of the rotation and scale vectors
this.rotationScaleOverTime.fill(0)
this.rotationScaleOverTime[0] = rotation.length/2
this.rotationScaleOverTime[1] = scale.length/2
// set k to 2 because the first vec2 of rotationScaleOverTime is use for the length params
// update i by 1 becase rotation is 1 numbers per vector, and k by 2 because rotationScaleOverTime is 2 numbers per vector
let n = rotation.length
for (let i = 0, k = 2; i < n; i ++, k += 2) {
this.rotationScaleOverTime[k] = degToRad(rotation[i]) // glsl rotationScaleOverTime[1..].x
}
n = scale.length
for (let i = 0, k = 2; i < n; i++, k += 2) {
this.rotationScaleOverTime[k+1] = scale[i] // glsl rotationScaleOverTime[1..].y
}
},
updateVec4XYZRange(vecData, uniformAttr) {
const vecRange = parseVecRange(vecData, [0,0,0])
for (let i = 0, j = 0; i < vecRange.length; ) {
this[uniformAttr][j++] = vecRange[i++] // x
this[uniformAttr][j++] = vecRange[i++] // y
this[uniformAttr][j++] = vecRange[i++] // z
j++ // skip the w
}
return vecRange
},
updateAngularVec4XYZRange(vecData, uniformAttr) {
const vecRange = parseVecRange(vecData, [0,0,0])
for (let i = 0, j = 0; i < vecRange.length; ) {
this[uniformAttr][j++] = degToRad(vecRange[i++]) // x
this[uniformAttr][j++] = degToRad(vecRange[i++]) // y
this[uniformAttr][j++] = degToRad(vecRange[i++]) // z
j++ // skip the w
}
},
updateAngularVec2PartRange(vecData, def, uniformAttr, part) {
const vecRange = parseVecRange(vecData, def)
this[uniformAttr][part] = degToRad(vecRange[0])
this[uniformAttr][part + 2] = degToRad(vecRange[1])
},
// update just the w component
updateVec4WRange(floatData, def, uniformAttr) {
let floatRange = parseVecRange(floatData, def)
this[uniformAttr][3] = floatRange[0] // floatData value is packed into the 4th part of each vec4
this[uniformAttr][7] = floatRange[1]
return floatRange
},
updateBounds() {
const data = this.data
let maxAge = Math.max(this.lifeTime[0], this.lifeTime[1])
const STRIDE = 4
let extent = [new Array(STRIDE), new Array(STRIDE)] // extent[0] = min values, extent[1] = max values
if (data.drag > 0) {
maxAge = maxAge*(1 - .5*data.drag)
}
// Use offset, velocity and acceleration to determine the extents for the particles
for (let j = 0; j < 2; j++) { // index for extent
const compare = j === 0 ? Math.min: Math.max
for (let i = 0; i < STRIDE; i++) { // 0 = x, 1 = y, 2 = z, 3 = radial
const offset = compare(this.offset[i], this.offset[i + STRIDE])
const velocity = compare(this.velocity[i], this.velocity[i + STRIDE])
const acceleration = compare(this.acceleration[i], this.acceleration[i + STRIDE])
// extent at time tmax
extent[j][i] = offset + (velocity + 0.5 * acceleration * maxAge) * maxAge
// extent at time t0
extent[j][i] = compare(extent[j][i], offset)
// extent at turning point
const turningPoint = -velocity/acceleration
if (turningPoint > 0 && turningPoint < maxAge) {
extent[j][i] = compare(extent[j][i], offset - 0.5*velocity*velocity/acceleration)
}
}
}
// include the bounds the base model
if (this.modelBounds) {
extent[0][0] += this.modelBounds.min.x
extent[0][1] += this.modelBounds.min.y
extent[0][2] += this.modelBounds.min.z
extent[1][0] += this.modelBounds.max.x
extent[1][1] += this.modelBounds.max.y
extent[1][2] += this.modelBounds.max.z
}
// apply the radial extents to the XYZ extents
const domAttrs = this.el.getDOMAttribute(this.attrName)
const maxScale = this.rotationScaleOverTime.reduce((max, x, i) => (i & 1) ? Math.max(max, x) : max, 0) // scale is every second number
const maxRadial = Math.max(Math.abs(extent[0][3]), Math.abs(extent[1][3])) + data.particleSize*0.00045*maxScale
const isSphere = data.radialType === "sphere" || domAttrs.angularVelocity || domAttrs.angularAcceleration || domAttrs.orbitalVelocity || domAttrs.orbitalAcceleration
extent[0][0] -= maxRadial
extent[0][1] -= maxRadial
extent[0][2] -= isSphere ? maxRadial : 0
extent[1][0] += maxRadial
extent[1][1] += maxRadial
extent[1][2] += isSphere ? maxRadial : 0
// discard the radial element
extent[0].length = 3
extent[0].length = 3
// TODO include destination
const maxR = Math.max(...extent[0].map(Math.abs), ...extent[1].map(Math.abs))
if (!this.geometry.boundingSphere) {
this.geometry.boundingSphere = new THREE.Sphere()
}
this.geometry.boundingSphere.radius = maxR
if (!this.geometry.boundingBox) {
this.geometry.boundingBox = new THREE.Box3()
}
this.geometry.boundingBox.min.set(...extent[0])
this.geometry.boundingBox.max.set(...extent[1])
const existingMesh = this.el.getObject3D("mesh")
// update any bounding boxes to the new bounds
if (existingMesh && existingMesh.isParticlesEditorObject) {
this.enableEditorObject(true)
}
},
updateDestinationEntity: (function() {
let dest = new THREE.Vector3()
let selfPos = new THREE.Vector3()
return function updateDestinationEntity() {
const data = this.data
data.destination.object3D.getWorldPosition(dest)
this.el.object3D.getWorldPosition(selfPos)
dest.sub(selfPos)
// this.destination is a vec4, this.destinationOffset is a vec3
for (let i = 0, n = AXES_NAMES.length; i < n; i++) {
this.destination[i] = dest[AXES_NAMES[i]] + this.destinationOffset[i] // min part of range
this.destination[i + 4] = dest[AXES_NAMES[i]] + this.destinationOffset[i + 3] // max part of range
}
}
})(),
enableEditorObject(enable) {
const existingMesh = this.el.getObject3D("mesh")
if (enable && (!existingMesh || existingMesh.isParticlesEditorObject)) {
const BOX_SIZE = 0.25
const maxBound = new THREE.Vector3(BOX_SIZE, BOX_SIZE, BOX_SIZE).max(this.geometry.boundingBox.max)
const minBound = new THREE.Vector3(-BOX_SIZE, -BOX_SIZE, -BOX_SIZE).min(this.geometry.boundingBox.min)
let box3 = new THREE.Box3(minBound, maxBound)
let box3Mesh = new THREE.Box3Helper(box3, 0x808000)
box3Mesh.isParticlesEditorObject = true
box3Mesh.visible = false
this.el.setObject3D("mesh", box3Mesh) // the inspector puts a bounding box around the "mesh" object
} else if (!enable && existingMesh && existingMesh.isParticlesEditorObject) {
this.el.removeObject3D("mesh")
}
},
updateAttributes() {
if (this.geometry) {
const n = this.count
let vertexIDs = new Float32Array(n)
if (this.startDisabled || this.data.delay > 0 || this.data.model) {
vertexIDs.fill(-1)
this.numEnabled = 0
this.numDisabled = n
} else {
for (let i = 0; i < n; i++) {
vertexIDs[i] = i
}
this.numEnabled = n
this.numDisabled = 0
}
this.geometry.setAttribute("vertexID", new THREE.Float32BufferAttribute(vertexIDs, 1)) // gl_VertexID is not supported, so make our own id
this.geometry.setAttribute("position", new THREE.Float32BufferAttribute(new Float32Array(n*3).fill(0), 3))
if (this.data.source) {
this.geometry.setAttribute("quaternion", new THREE.Float32BufferAttribute(new Float32Array(n*4).fill(0), 4))
}
// the ribbons are presented as triangle strips, so each vert pairs with it's two previous verts to
// form a triangle. To ensure each particle ribbon is not connected to other ribbons we place each
// one in a group containing only the verts for that ribbon
if (this.isRibbon()) {
this.geometry.clearGroups()
const m = this.trailCount * VERTS_PER_RIBBON
for (let i = 0; i < n; i += m) {
this.geometry.addGroup(i, m, 0)
}
}
}
},
// to get the fastest shader possible we remove unused glsl code via #if defined(USE_...) clauses,
// with each clause matching to one or more component attributes. updateDefines() maps each
// attribute to its equivalent USE_... define, and determines if any defines have changed.
// If a define has changed and we are playing we generate an error, otherwise (i.e. in the Inspector)
// we update the material and rebuild the shader program
updateDefines() {
const data = this.data
const domAttrs = Object.keys(this.el.getDOMAttribute(this.attrName))
const domDefines = domAttrs.map(a => ATTR_TO_DEFINES[a]).filter(b => b)
let defines = {
PARAMS_LENGTH,
OVER_TIME_ARRAY_LENGTH: this.overTimeArrayLength,
RANDOM_REPEAT_COUNT,
USE_MAP: true,
}
for (key of domDefines) {
defines[key] = true
}
if (data.velocityScale > 0) {
defines.USE_PARTICLE_VELOCITY_SCALE = true
}
if (data.trailInterval > 0) {
if (this.isRibbon()) {
if (data.trailType === "ribbon") {
defines.USE_RIBBON_TRAILS = true
} else {
defines.USE_RIBBON_3D_TRAILS = true
}
}
else {
defines.USE_PARTICLE_TRAILS = true
}
}
if (data.randomizeFrames) {
defines.USE_PARTICLE_RANDOMIZE_FRAMES = true
}
if (domAttrs.includes("rotation")) {
if (this.isRibbon()) {
defines.USE_RIBBON_ROTATION = true
} else {
defines.USE_PARTICLE_ROTATION = true
}
}
let ribbonShapeFunction = "1."
if (data.ribbonShape === "taperout") {
ribbonShapeFunction = "1. - p"
} else if (data.ribbonShape === "taperin") {
ribbonShapeFunction = "p"
} else if (data.ribbonShape === "taper") {
ribbonShapeFunction = "2. * ( p < .5 ? p : 1. - p )"
} else if (data.ribbonShape[0] === "=") {
ribbonShapeFunction = data.ribbonShape.slice(1)
}
defines.RIBBON_SHAPE_FUNCTION = ribbonShapeFunction
if (data.source) {
defines.PARTICLE_ORDER = 2
} else {
defines.PARTICLE_ORDER = PARTICLE_ORDER_STRINGS.indexOf(data.particleOrder)
}
defines.PARTICLE_TRAIL_ORDER = PARTICLE_ORDER_STRINGS.indexOf(data.particleOrder)
const extraDefines = Object.keys(defines).filter(b => this.material.defines[b] !== defines[b])
if (extraDefines.length > 0) {
if (this.isPlaying) {
const extraAttrs = domAttrs.filter(a => {
const b = ATTR_TO_DEFINES[a]
return b && !this.material.defines[b]
})
console.error(`cannot add attributes (${extraAttrs.join(",")}) at run-time`)
} else {
this.material.defines = defines
this.material.needsUpdate = true
}
}
},
updateModelMesh(mesh) {
if (!mesh) { return }
this.modelBounds = new THREE.Box3()
this.modelVertices
let offset = 0
let numFloats = 0
let stage = 0
const parseModel = (obj3D) => {
if (!obj3D.geometry) { return }
let positions = obj3D.geometry.getAttribute("position")
if (positions && positions.itemSize !== 3) { return } // some text geometry uses 2D positions
if (stage == 0) {
numFloats += positions.array.length
} else {
this.modelVertices.set(positions.array, offset)
offset += positions.array.length
}
}
stage = 0
mesh.traverse(parseModel)
if (numFloats > 0) {
stage = 1
this.modelVertices = new Float32Array(numFloats)
mesh.traverse(parseModel)
applyScale(this.modelVertices, mesh.el.object3D.scale)
this.modelBounds.setFromArray(this.modelVertices)
this.updateBounds()
}
},
updateWorldTransform: (function() {
let position = new THREE.Vector3()
let quaternion = new THREE.Quaternion()
let scale = new THREE.Vector3()
let modelPosition = new THREE.Vector3()
let m4 = new THREE.Matrix4()
return function(emitterTime) {
const data = this.data
const n = this.count
// for particles using a source the CPU sets the instancePosition and instanceQuaternion
// of the new particles to the current object3D position/orientation, and tells the GPU
// the ID of last emitted particle (this.params[ID_PARAM])
const spawnRate = this.data.spawnRate
const isBurst = data.spawnType === "burst"
const spawnDelta = isBurst ? 0 : 1/spawnRate // for burst particles spawn everything at once
const isEnableDisable = data.enable ? this.numEnabled < n : this.numDisabled < n
const hasSource = data.source && data.source.object3D != null
const isUsingModel = this.modelVertices && this.modelVertices.length
const isRibbon = this.isRibbon()
const isIDUnique = isUsingModel || hasSource
let particleVertexID = this.geometry.getAttribute("vertexID")
let particlePosition = this.geometry.getAttribute("position")
let particleQuaternion = this.geometry.getAttribute("quaternion")
if (hasSource) {
this.el.object3D.updateMatrixWorld()
data.source.object3D.updateMatrixWorld()
// get source matrix in our local space
m4.copy( this.el.object3D.matrixWorld ).invert();
m4.multiply(data.source.object3D.matrixWorld)
m4.decompose(position, quaternion, scale)
this.geometry.boundingSphere.center.copy(position)
}
let startIndex = this.nextID % n
let numSpawned = 0 // number of particles and/or trails
let index = startIndex
let id = this.nextID
modelFillFn = randomPointInTriangle
switch (data.modelFill) {
case "edge": modelFillFn = randomPointOnTriangleEdge; break
case "vertex": modelFillFn = randomVertex; break
}