Source

love / src / modules / graphics / opengl / ParticleSystem.cpp

Full commit
  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
/**
 * Copyright (c) 2006-2013 LOVE Development Team
 *
 * This software is provided 'as-is', without any express or implied
 * warranty.  In no event will the authors be held liable for any damages
 * arising from the use of this software.
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 *    claim that you wrote the original software. If you use this software
 *    in a product, an acknowledgment in the product documentation would be
 *    appreciated but is not required.
 * 2. Altered source versions must be plainly marked as such, and must not be
 *    misrepresented as being the original software.
 * 3. This notice may not be removed or altered from any source distribution.
 **/

#include "ParticleSystem.h"

#include "common/math.h"

#include "OpenGL.h"
#include <cmath>
#include <cstdlib>

namespace love
{
namespace graphics
{
namespace opengl
{

namespace
{
Colorf colorToFloat(const Color &c)
{
	return Colorf((GLfloat)c.r/255.0f, (GLfloat)c.g/255.0f, (GLfloat)c.b/255.0f, (GLfloat)c.a/255.0f);
}
}

float calculate_variation(float inner, float outer, float var)
{
	float low = inner - (outer/2.0f)*var;
	float high = inner + (outer/2.0f)*var;
	float r = random();
	return low*(1-r)+high*r;
}

StringMap<ParticleSystem::AreaSpreadDistribution, ParticleSystem::DISTRIBUTION_MAX_ENUM>::Entry ParticleSystem::distributionsEntries[] = {
	{ "none",     ParticleSystem::DISTRIBUTION_NONE },
	{ "uniform",  ParticleSystem::DISTRIBUTION_UNIFORM },
	{ "normal",   ParticleSystem::DISTRIBUTION_NORMAL },
};

StringMap<ParticleSystem::AreaSpreadDistribution, ParticleSystem::DISTRIBUTION_MAX_ENUM> ParticleSystem::distributions(ParticleSystem::distributionsEntries, sizeof(ParticleSystem::distributionsEntries));


ParticleSystem::ParticleSystem(Image *sprite, unsigned int buffer)
	: pStart(0)
	, pLast(0)
	, pEnd(0)
	, particleVerts(0)
	, active(true)
	, emissionRate(0)
	, emitCounter(0)
	, areaSpreadDistribution(DISTRIBUTION_NONE)
	, lifetime(-1)
	, life(0)
	, particleLifeMin(0)
	, particleLifeMax(0)
	, direction(0)
	, spread(0)
	, relative(false)
	, speedMin(0)
	, speedMax(0)
	, gravityMin(0)
	, gravityMax(0)
	, radialAccelerationMin(0)
	, radialAccelerationMax(0)
	, tangentialAccelerationMin(0)
	, tangentialAccelerationMax(0)
	, sizeVariation(0)
	, rotationMin(0)
	, rotationMax(0)
	, spinStart(0)
	, spinEnd(0)
	, spinVariation(0)
	, offsetX(sprite->getWidth()*0.5f)
	, offsetY(sprite->getHeight()*0.5f)
{
	this->sprite = sprite;
	sprite->retain();
	sizes.push_back(1.0f);
	colors.push_back(Colorf(1.0f, 1.0f, 1.0f, 1.0f));
	setBufferSize(buffer);
}

ParticleSystem::~ParticleSystem()
{
	if (this->sprite != 0)
		this->sprite->release();

	if (pStart != 0)
		delete [] pStart;

	if (particleVerts != 0)
		delete [] particleVerts;
}

void ParticleSystem::add()
{
	if (isFull()) return;

	float min,max;

	min = particleLifeMin;
	max = particleLifeMax;
	if (min == max)
		pLast->life = min;
	else
		pLast->life = random(min, max);
	pLast->lifetime = pLast->life;

	pLast->position[0] = position.getX();
	pLast->position[1] = position.getY();

	switch (areaSpreadDistribution)
	{
		case DISTRIBUTION_UNIFORM:
			pLast->position[0] += random(-areaSpread.getX(), areaSpread.getX());
			pLast->position[1] += random(-areaSpread.getY(), areaSpread.getY());
			break;
		case DISTRIBUTION_NORMAL:
			pLast->position[0] += random_normal(areaSpread.getX());
			pLast->position[1] += random_normal(areaSpread.getY());
			break;
		case DISTRIBUTION_NONE:
		default:
			break;
	}

	min = direction - spread/2.0f;
	max = direction + spread/2.0f;
	pLast->direction = random(min, max);

	pLast->origin = position;

	min = speedMin;
	max = speedMax;
	float speed = random(min, max);
	pLast->speed = love::Vector(cos(pLast->direction), sin(pLast->direction));
	pLast->speed *= speed;

	min = gravityMin;
	max = gravityMax;
	pLast->gravity = random(min, max);

	min = radialAccelerationMin;
	max = radialAccelerationMax;
	pLast->radialAcceleration = random(min, max);

	min = tangentialAccelerationMin;
	max = tangentialAccelerationMax;
	pLast->tangentialAcceleration = random(min, max);

	pLast->sizeOffset       = random(sizeVariation); // time offset for size change
	pLast->sizeIntervalSize = (1.0f - random(sizeVariation)) - pLast->sizeOffset;
	pLast->size = sizes[(size_t)(pLast->sizeOffset - .5f) * (sizes.size() - 1)];

	min = rotationMin;
	max = rotationMax;
	pLast->spinStart = calculate_variation(spinStart, spinEnd, spinVariation);
	pLast->spinEnd = calculate_variation(spinEnd, spinStart, spinVariation);
	pLast->rotation = random(min, max);

	pLast->color = colors[0];

	pLast++;
}

void ParticleSystem::remove(particle *p)
{
	if (!isEmpty())
	{
		 *p = *(--pLast);
	}
}

void ParticleSystem::setSprite(Image *image)
{
	if (sprite != 0)
		sprite->release();

	sprite = image;
	sprite->retain();
}

void ParticleSystem::setBufferSize(unsigned int size)
{
	// delete previous data
	if (pStart != 0)
		delete [] pStart;

	pLast = pStart = new particle[size];

	pEnd = pStart + size;

	if (particleVerts != 0)
		delete [] particleVerts;

	// each particle has 4 vertices
	particleVerts = new vertex[size*4];
}

void ParticleSystem::setEmissionRate(int rate)
{
	emissionRate = rate;
}

void ParticleSystem::setLifetime(float life)
{
	this->life = lifetime = life;
}

void ParticleSystem::setParticleLife(float min, float max)
{
	particleLifeMin = min;
	if (max == 0)
		particleLifeMax = min;
	else
		particleLifeMax = max;
}

void ParticleSystem::setPosition(float x, float y)
{
	position = love::Vector(x, y);
}


void ParticleSystem::setAreaSpread(AreaSpreadDistribution distribution, float x, float y)
{
	areaSpread = love::Vector(x, y);
	areaSpreadDistribution = distribution;
}

void ParticleSystem::setDirection(float direction)
{
	this->direction = direction;
}

void ParticleSystem::setSpread(float spread)
{
	this->spread = spread;
}

void ParticleSystem::setRelativeDirection(bool relative)
{
	this->relative = relative;
}

void ParticleSystem::setSpeed(float speed)
{
	speedMin = speedMax = speed;
}

void ParticleSystem::setSpeed(float min, float max)
{
	speedMin = min;
	speedMax = max;
}

void ParticleSystem::setGravity(float gravity)
{
	gravityMin = gravityMax = gravity;
}

void ParticleSystem::setGravity(float min, float max)
{
	gravityMin = min;
	gravityMax = max;
}

void ParticleSystem::setRadialAcceleration(float acceleration)
{
	radialAccelerationMin = radialAccelerationMax = acceleration;
}

void ParticleSystem::setRadialAcceleration(float min, float max)
{
	radialAccelerationMin = min;
	radialAccelerationMax = max;
}

void ParticleSystem::setTangentialAcceleration(float acceleration)
{
	tangentialAccelerationMin = tangentialAccelerationMax = acceleration;
}

void ParticleSystem::setTangentialAcceleration(float min, float max)
{
	tangentialAccelerationMin = min;
	tangentialAccelerationMax = max;
}

void ParticleSystem::setSize(float size)
{
	sizes.resize(1);
	sizes[0] = size;
}

void ParticleSystem::setSize(const std::vector<float> &newSizes, float variation)
{
	sizes = newSizes;
	sizeVariation = variation;
}

void ParticleSystem::setSizeVariation(float variation)
{
	sizeVariation = variation;
}

void ParticleSystem::setRotation(float rotation)
{
	rotationMin = rotationMax = rotation;
}

void ParticleSystem::setRotation(float min, float max)
{
	rotationMin = min;
	rotationMax = max;
}

void ParticleSystem::setSpin(float spin)
{
	spinStart = spin;
	spinEnd = spin;
}

void ParticleSystem::setSpin(float start, float end)
{
	spinStart = start;
	spinEnd = end;
}

void ParticleSystem::setSpin(float start, float end, float variation)
{
	spinStart = start;
	spinEnd = end;
	spinVariation = variation;
}

void ParticleSystem::setSpinVariation(float variation)
{
	spinVariation = variation;
}

void ParticleSystem::setColor(const Color &color)
{
	colors.resize(1);
	colors[0] = colorToFloat(color);
}

void ParticleSystem::setColor(const std::vector<Color> &newColors)
{
	colors.resize(newColors.size());
	for (size_t i = 0; i < newColors.size(); ++i)
		colors[i] = colorToFloat(newColors[i]);
}

void ParticleSystem::setOffset(float x, float y)
{
	offsetX = x;
	offsetY = y;
}

float ParticleSystem::getX() const
{
	return position.getX();
}

float ParticleSystem::getY() const
{
	return position.getY();
}

const love::Vector &ParticleSystem::getPosition() const
{
	return position;
}

ParticleSystem::AreaSpreadDistribution ParticleSystem::getAreaSpreadDistribution() const
{
	return areaSpreadDistribution;
}

const love::Vector &ParticleSystem::getAreaSpreadParameters() const
{
	return areaSpread;
}

float ParticleSystem::getDirection() const
{
	return direction;
}

float ParticleSystem::getSpread() const
{
	return spread;
}

float ParticleSystem::getOffsetX() const
{
	return offsetX;
}

float ParticleSystem::getOffsetY() const
{
	return offsetY;
}

int ParticleSystem::count() const
{
	return (int)(pLast - pStart);
}

void ParticleSystem::start()
{
	active = true;
}

void ParticleSystem::stop()
{
	active = false;
	life = lifetime;
	emitCounter = 0;
}

void ParticleSystem::pause()
{
	active = false;
}

void ParticleSystem::reset()
{
	pLast = pStart;
	life = lifetime;
	emitCounter = 0;
}

bool ParticleSystem::isActive() const
{
	return active;
}

bool ParticleSystem::isEmpty() const
{
	return pStart == pLast;
}

bool ParticleSystem::isFull() const
{
	return pLast == pEnd;
}

void ParticleSystem::draw(float x, float y, float angle, float sx, float sy, float ox, float oy, float kx, float ky) const
{
	if (sprite == 0) return;  // just in case of failure

	int numParticles = count();
	if (numParticles == 0) return; // don't bother if there's nothing to do

	glPushMatrix();
	glPushAttrib(GL_CURRENT_BIT);

	static Matrix t;
	t.setTransformation(x, y, angle, sx, sy, ox, oy, kx, ky);
	glMultMatrixf((const GLfloat *)t.getElements());

	const vertex * imageVerts = sprite->getVertices();

	// set the vertex data for each particle (transformation, texcoords, color)
	for (int i = 0; i < numParticles; i++)
	{
		particle * p = pStart + i;

		// particle vertices are sprite vertices transformed by particle information 
		t.setTransformation(p->position[0], p->position[1], p->rotation, p->size, p->size, offsetX, offsetY, 0.0f, 0.0f);
		t.transform(&particleVerts[i*4], &imageVerts[0], 4);

		// set the texture coordinate and color data for particle vertices
		for (int v = 0; v < 4; v++)
		{
			int vi = (i * 4) + v; // current vertex index for particle

			particleVerts[vi].s = imageVerts[v].s;
			particleVerts[vi].t = imageVerts[v].t;

			// particle colors are stored as floats (0-1) but vertex colors are stored as unsigned bytes (0-255)
			particleVerts[vi].r = p->color.r*255;
			particleVerts[vi].g = p->color.g*255;
			particleVerts[vi].b = p->color.b*255;
			particleVerts[vi].a = p->color.a*255;
		}
	}

	sprite->bind();

	glEnableClientState(GL_COLOR_ARRAY);
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);

	glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(vertex), (GLvoid *)&particleVerts[0].r);
	glVertexPointer(2, GL_FLOAT, sizeof(vertex), (GLvoid *)&particleVerts[0].x);
	glTexCoordPointer(2, GL_FLOAT, sizeof(vertex), (GLvoid *)&particleVerts[0].s);

	glDrawArrays(GL_QUADS, 0, numParticles*4);

	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_COLOR_ARRAY);

	glPopAttrib();
	glPopMatrix();
}

void ParticleSystem::update(float dt)
{
	// Traverse all particles and update.
	particle *p = pStart;

	// Make some more particles.
	if (active)
	{
		float rate = 1.0f / emissionRate; // the amount of time between each particle emit
		emitCounter += dt;
		while (emitCounter > rate)
		{
			add();
			emitCounter -= rate;
		}
		/*int particles = (int)(emissionRate * dt);
		for (int i = 0; i != particles; i++)
			add();*/

		life -= dt;
		if (lifetime != -1 && life < 0)
			stop();
	}

	while (p != pLast)
	{
		// Decrease lifespan.
		p->life -= dt;

		if (p->life > 0)
		{

			// Temp variables.
			love::Vector radial, tangential, gravity(0, p->gravity);
			love::Vector ppos(p->position[0], p->position[1]);

			// Get vector from particle center to particle.
			radial = ppos - p->origin;
			radial.normalize();
			tangential = radial;

			// Resize radial acceleration.
			radial *= p->radialAcceleration;

			// Calculate tangential acceleration.
			{
				float a = tangential.getX();
				tangential.setX(-tangential.getY());
				tangential.setY(a);
			}

			// Resize tangential.
			tangential *= p->tangentialAcceleration;

			// Update position.
			p->speed += (radial+tangential+gravity)*dt;

			// Modify position.
			ppos += p->speed * dt;

			p->position[0] = ppos.getX();
			p->position[1] = ppos.getY();

			const float t = 1.0f - p->life / p->lifetime;

			// Rotate.
			p->rotation += (p->spinStart * (1.0f - t) + p->spinEnd * t)*dt;

			// Change size according to given intervals:
			// i = 0       1       2      3          n-1
			//     |-------|-------|------|--- ... ---|
			// t = 0    1/(n-1)        3/(n-1)        1
			//
			// `s' is the interpolation variable scaled to the current
			// interval width, e.g. if n = 5 and t = 0.3, then the current
			// indices are 1,2 and s = 0.3 - 0.25 = 0.05
			float s = p->sizeOffset + t * p->sizeIntervalSize; // size variation
			s *= (float)(sizes.size() - 1); // 0 <= s < sizes.size()
			size_t i = (size_t)s;
			size_t k = (i == sizes.size() - 1) ? i : i + 1; // boundary check (prevents failing on t = 1.0f)
			s -= (float)i; // transpose s to be in interval [0:1]: i <= s < i + 1 ~> 0 <= s < 1
			p->size = sizes[i] * (1.0f - s) + sizes[k] * s;

			// Update color according to given intervals (as above)
			s = t * (float)(colors.size() - 1);
			i = (size_t)s;
			k = (i == colors.size() - 1) ? i : i + 1;
			s -= (float)i;                            // 0 <= s <= 1
			p->color = colors[i] * (1.0f - s) + colors[k] * s;

			// Next particle.
			p++;
		}
		else
		{
			remove(p);

			if (p >= pLast)
				return;
		} // else
	} // while
}

bool ParticleSystem::getConstant(const char *in, AreaSpreadDistribution &out)
{
	return distributions.find(in, out);
}

bool ParticleSystem::getConstant(AreaSpreadDistribution in, const char *&out)
{
	return distributions.find(in, out);
}

} // opengl
} // graphics
} // love