-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparticles.js
More file actions
343 lines (293 loc) · 11.1 KB
/
particles.js
File metadata and controls
343 lines (293 loc) · 11.1 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
import {debug, Entity, Component, System, DeleteComponent, TransformComponent, Game} from './engine.js';
import {CollisionComponent} from './collision.js';
import { RenderComponent } from './graphics.js';
import {Vector} from './vector.js';
import {KDTree} from './kdtree.js';
export class ParticleTypeComponent extends Component {
constructor(id, updateFn, render, particle) {
super("particleType");
this.id = id;
this.updateFn = updateFn || this.defaultUpdate;
this.particles = [];
this.particle = particle;
this.render = render;
this.activeParticles = 0;
this.rollingAverage = 0;
}
update(dt, tree) {
let active = 0;
// Iterate over the particles in this type
for (const particle of this.particles) {
if(particle.markedForDeletion){
continue;
}
active++;
// Update the particle using the callback function
this.updateFn(particle, dt);
// Check for collisions with the interactors
const queryMin = [particle.position.x - particle.radius, particle.position.y - particle.radius];
const queryMax = [particle.position.x + particle.radius, particle.position.y + particle.radius];
const interactors = tree.query(queryMin, queryMax);
for (const entity of interactors) {
const interactor = entity.getComponent("interactor");
interactor.process(entity, particle);
}
// Decrement the particle's lifetime
particle.lifetime -= dt;
// If the particle has reached the end of its lifetime, mark it for removal
if (particle.lifetime <= 0) {
particle.markedForDeletion = true;
}
this.rollingAverage = (this.rollingAverage*127+active)/128;
this.activeParticles = active;
if(this.particles.length > this.rollingAverage*20){
let i = this.particles.length-1
for(;this.particles[i].markedForDeletion&& i > this.activeParticles; i--);
this.particles.splice(i+1);
}
}
}
defaultUpdate(particle, dt) {
// Update the particle's position based on its velocity and acceleration
particle.position.x += particle.velocity.x * dt;
particle.position.y += particle.velocity.y * dt;
particle.velocity.x += particle.acceleration.x * dt;
particle.velocity.y += particle.acceleration.y * dt;
}
draw(ctx, transfom){
for (let particle of this.particles) {
if (!particle.markedForDeletion){
if(!this.render){
ctx.beginPath();
ctx.fillStyle = `rgba(${particle.color.r}, ${particle.color.g}, ${particle.color.b}, ${particle.color.a})`;
ctx.arc(particle.position.x, particle.position.y, particle.radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
else{
this.render.draw(ctx, particle.position.add(transfom));
}
}
}
}
}
function getRandomPointInPolygon(polygon) {
// Get the bounding box of the polygon
const minX = Math.min(...polygon.map(point => point.x));
const maxX = Math.max(...polygon.map(point => point.x));
const minY = Math.min(...polygon.map(point => point.y));
const maxY = Math.max(...polygon.map(point => point.y));
// Generate a random point within the bounding box
const x = Math.random() * (maxX - minX) + minX;
const y = Math.random() * (maxY - minY) + minY;
// Check if the point is inside the polygon
const isInside = rayCasting(polygon, { x, y });
// If the point is inside the polygon, return it; otherwise, try again
return isInside ? { x, y } : getRandomPointInPolygon(polygon);
}
function rayCasting(polygon, point) {
let isInside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const xi = polygon[i].x;
const yi = polygon[i].y;
const xj = polygon[j].x;
const yj = polygon[j].y;
const intersect = ((yi > point.y) !== (yj > point.y))
&& (point.x < (xj - xi) * (point.y - yi) / (yj - yi) + xi);
if (intersect) isInside = !isInside;
}
return isInside;
}
//constructor(position, velocity, acceleration, direction, color, size, lifetime, type, radius)
export class ParticleEmitterComponent extends Component {
constructor(emissionRate, particleTypeId, origin, particle) {
super("particleEmitter");
this.emissionRate = emissionRate;
this.particleType = particleTypeId;
this.origin = origin || { x: 0, y: 0 };
this.lifetime = 1000;
this.particle = particle;
}
emit(dt) {
const particles = [];
// Calculate the probability of emitting a particle based on the dt
// and the emission rate
const probability = this.emissionRate * dt;
for (let i = 0; i < probability; i++){
if (Math.random() < probability) {
// Emit a particle
const particle = new Particle(
// Position the particle at the origin of the emitter
new Vector({ x: this.origin.x, y: this.origin.y }),
// Give the particle a random velocity
new Vector({ x: (Math.random() * 2 - 1)*.2, y: (Math.random() * 2 - 1)*.2 }),
// Set the particle's acceleration to 0
new Vector({ x: 0, y: 0 }),
// Set the particle's direction to 0
0,
// Set the particle's color to white
{ r: 120+Math.random()*50, g: 90+Math.random()*50, b:Math.random()*160, a:.3},
// Set the particle's size to 1
.1,
// Set the particle's lifetime to 1 second
this.lifetime,
// Set the particle's type
this.particleType,
// Set the particle's radius to 1
5
);
particles.push(particle);
}
}
return particles;
}
}
function defaultParticleGenerator(origin, polygon, lifetime, particleType){
const particle = new Particle(
// Position the particle at the origin of the emitter
new Vector({ x: origin.x, y: origin.y }),
// Give the particle a random velocity
new Vector({ x: (Math.random() * 2 - 1)*.2, y: (Math.random() * 2 - 1)*.2 }),
// Set the particle's acceleration to 0
new Vector({ x: 0, y: 0 }),
// Set the particle's direction to 0
0,
// Set the particle's color to white
{ r: 120+Math.random()*50, g: 90+Math.random()*50, b:Math.random()*160, a:.3},
// Set the particle's size to 1
.1,
// Set the particle's lifetime to 1 second
lifetime,
// Set the particle's type
particleType,
// Set the particle's radius to 1
5
);
return particle;
}
export class ParticleBurstComponent extends Component {
constructor(quantity, particleTypeId, origin, polygon, particleGenerator) {
super("particleBurst");
super("particleEmitter");
this.emissionRate = emissionRate;
this.particleType = particleTypeId;
this.origin = origin || { x: 0, y: 0 };
this.lifetime = 1000;
this.particle = particle;
}
emit(dt) {
const particles = [];
for (let i = 0; i < quantity; i++){
particles.push(particleGenerator(origin, polygon, lifetime, particleType));
}
return particles;
}
}
export class Particle {
constructor(position, velocity, acceleration, direction, color, size, lifetime, type, radius) {
this.position = position || new Vector({x:0,y:0});
this.velocity = velocity || new Vector({x:0,y:0})
this.acceleration = acceleration|| new Vector({x:0,y:0})
this.direction = direction|| new Vector({x:0,y:0})
this.color = color || {r: 185, g:128, b:0, a:1};
this.size = size || 2;
this.lifetime = lifetime || 151200;
this.type = type;
this.radius = radius || 40;
this.markedForDeletion = false;
}
}
export class ParticleInteractorComponent extends Component {
constructor(onCollisionFn, checkCollisionFn) {
super("particleInteractor");
this.checkCollision = checkCollisionFn || this.defaultCheckCollision;
this.onCollision = onCollisionFn;
}
process(entity, particle) {
if (this.checkCollision(entity, particle)) {
this.onCollision(entity, particle);
}
}
defaultCheckCollision(entity, particle){
const transform = entity.getComponent("transform");
const collision = entity.getComponent("collision");
const minX = transform.x;
const minY = transform.y;
const maxX = transform.x + collision.width;
const maxY = transform.y + collision.height;
return particle.x >= minX && particle.x <= maxX && particle.y >= minY && particle.y <= maxY;
};
}
function makeParticleBounce(entity, particle) {
// Get the collision component of the entity
const collision = entity.getComponent("collision");
const transform = entity.getComponent("transform");
// Calculate the particle's new velocity based on the surface normal
// of the collision component
const surfaceNormal = collision.getSurfaceNormal(particle.position);
particle.velocity = {
x: -particle.velocity.x,
y: -particle.velocity.y
};
// Move the particle out of the collision
particle.position = collision.getDisplacement(particle.position);
}
function deleteParticle(entity, particle) {
// Remove the particle from the particle type's list of particles
particle.type.particles = particle.type.particles.filter(
p => p !== particle
);
}
export class ParticleSystem extends System{
constructor() {
super("particle")
this.particleTypes = [];//we need to get rid of this
this.interactors = [];
this.tree = new KDTree();
}
update(entities, dt) {
// Update the arrays of particle types and interactors
this.particleTypes = [];
this.interactors = [];
for (const entity of entities) {
if (entity.hasComponent("particleType")) {
this.particleTypes.push(entity.getComponent("particleType"));
}
if (entity.hasComponent("interactor")) {
this.interactors.push(entity);
}
}
// Insert the interactors into the k-d tree
for (const entity of this.interactors) {
const interactor = entity.getComponent("interactor");
const transform = entity.getComponent("transform");
const collision = entity.getComponent("collision");
const min = [transform.x, transform.y];
const max = [transform.x + collision.width, transform.y + collision.height];
this.tree.insert(interactor, min, max);
}
// Process any particle emitters
for (const entity of entities) {
if (entity.hasComponent("particleEmitter")) {
const emitter = entity.getComponent("particleEmitter");
const transform = entity.getComponent("transform");
const emittedParticles = emitter.emit(dt);
const particleType = this.particleTypes.find(type => type.id === emitter.particleType);
const particlePool = particleType.particles;
let p = 0;
for (let particle of emittedParticles) {
// Offset the particle position by the transform of the entity
particle.position.x += transform.x;
particle.position.y += transform.y;
// Add the particle to the appropriate particle type's particles array
for(;p<particlePool.length && !particlePool[p].markedForDeletion;p++);
particlePool[p] = particle;
}
}
}
// Update the particle types
for (const particleType of this.particleTypes) {
particleType.update(dt, this.tree);
}
}
}