1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9 
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14 
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19 
20 #include "particles.h"
21 #include <cmath>
22 #include "client.h"
23 #include "collision.h"
24 #include "client/content_cao.h"
25 #include "client/clientevent.h"
26 #include "client/renderingengine.h"
27 #include "util/numeric.h"
28 #include "light.h"
29 #include "environment.h"
30 #include "clientmap.h"
31 #include "mapnode.h"
32 #include "nodedef.h"
33 #include "client.h"
34 #include "settings.h"
35 
36 /*
37 	Utility
38 */
39 
random_f32(f32 min,f32 max)40 static f32 random_f32(f32 min, f32 max)
41 {
42 	return rand() / (float)RAND_MAX * (max - min) + min;
43 }
44 
random_v3f(v3f min,v3f max)45 static v3f random_v3f(v3f min, v3f max)
46 {
47 	return v3f(
48 		random_f32(min.X, max.X),
49 		random_f32(min.Y, max.Y),
50 		random_f32(min.Z, max.Z));
51 }
52 
53 /*
54 	Particle
55 */
56 
Particle(IGameDef * gamedef,LocalPlayer * player,ClientEnvironment * env,const ParticleParameters & p,video::ITexture * texture,v2f texpos,v2f texsize,video::SColor color)57 Particle::Particle(
58 	IGameDef *gamedef,
59 	LocalPlayer *player,
60 	ClientEnvironment *env,
61 	const ParticleParameters &p,
62 	video::ITexture *texture,
63 	v2f texpos,
64 	v2f texsize,
65 	video::SColor color
66 ):
67 	scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(),
68 		RenderingEngine::get_scene_manager())
69 {
70 	// Misc
71 	m_gamedef = gamedef;
72 	m_env = env;
73 
74 	// Texture
75 	m_material.setFlag(video::EMF_LIGHTING, false);
76 	m_material.setFlag(video::EMF_BACK_FACE_CULLING, false);
77 	m_material.setFlag(video::EMF_BILINEAR_FILTER, false);
78 	m_material.setFlag(video::EMF_FOG_ENABLE, true);
79 	m_material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
80 	m_material.setTexture(0, texture);
81 	m_texpos = texpos;
82 	m_texsize = texsize;
83 	m_animation = p.animation;
84 
85 	// Color
86 	m_base_color = color;
87 	m_color = color;
88 
89 	// Particle related
90 	m_pos = p.pos;
91 	m_velocity = p.vel;
92 	m_acceleration = p.acc;
93 	m_expiration = p.expirationtime;
94 	m_player = player;
95 	m_size = p.size;
96 	m_collisiondetection = p.collisiondetection;
97 	m_collision_removal = p.collision_removal;
98 	m_object_collision = p.object_collision;
99 	m_vertical = p.vertical;
100 	m_glow = p.glow;
101 
102 	// Irrlicht stuff
103 	const float c = p.size / 2;
104 	m_collisionbox = aabb3f(-c, -c, -c, c, c, c);
105 	this->setAutomaticCulling(scene::EAC_OFF);
106 
107 	// Init lighting
108 	updateLight();
109 
110 	// Init model
111 	updateVertices();
112 }
113 
OnRegisterSceneNode()114 void Particle::OnRegisterSceneNode()
115 {
116 	if (IsVisible)
117 		SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT_EFFECT);
118 
119 	ISceneNode::OnRegisterSceneNode();
120 }
121 
render()122 void Particle::render()
123 {
124 	video::IVideoDriver *driver = SceneManager->getVideoDriver();
125 	driver->setMaterial(m_material);
126 	driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
127 
128 	u16 indices[] = {0,1,2, 2,3,0};
129 	driver->drawVertexPrimitiveList(m_vertices, 4,
130 			indices, 2, video::EVT_STANDARD,
131 			scene::EPT_TRIANGLES, video::EIT_16BIT);
132 }
133 
step(float dtime)134 void Particle::step(float dtime)
135 {
136 	m_time += dtime;
137 	if (m_collisiondetection) {
138 		aabb3f box = m_collisionbox;
139 		v3f p_pos = m_pos * BS;
140 		v3f p_velocity = m_velocity * BS;
141 		collisionMoveResult r = collisionMoveSimple(m_env, m_gamedef, BS * 0.5f,
142 			box, 0.0f, dtime, &p_pos, &p_velocity, m_acceleration * BS, nullptr,
143 			m_object_collision);
144 		if (m_collision_removal && r.collides) {
145 			// force expiration of the particle
146 			m_expiration = -1.0;
147 		} else {
148 			m_pos = p_pos / BS;
149 			m_velocity = p_velocity / BS;
150 		}
151 	} else {
152 		m_velocity += m_acceleration * dtime;
153 		m_pos += m_velocity * dtime;
154 	}
155 	if (m_animation.type != TAT_NONE) {
156 		m_animation_time += dtime;
157 		int frame_length_i, frame_count;
158 		m_animation.determineParams(
159 				m_material.getTexture(0)->getSize(),
160 				&frame_count, &frame_length_i, NULL);
161 		float frame_length = frame_length_i / 1000.0;
162 		while (m_animation_time > frame_length) {
163 			m_animation_frame++;
164 			m_animation_time -= frame_length;
165 		}
166 	}
167 
168 	// Update lighting
169 	updateLight();
170 
171 	// Update model
172 	updateVertices();
173 }
174 
updateLight()175 void Particle::updateLight()
176 {
177 	u8 light = 0;
178 	bool pos_ok;
179 
180 	v3s16 p = v3s16(
181 		floor(m_pos.X+0.5),
182 		floor(m_pos.Y+0.5),
183 		floor(m_pos.Z+0.5)
184 	);
185 	MapNode n = m_env->getClientMap().getNode(p, &pos_ok);
186 	if (pos_ok)
187 		light = n.getLightBlend(m_env->getDayNightRatio(), m_gamedef->ndef());
188 	else
189 		light = blend_light(m_env->getDayNightRatio(), LIGHT_SUN, 0);
190 
191 	u8 m_light = decode_light(light + m_glow);
192 	m_color.set(255,
193 		m_light * m_base_color.getRed() / 255,
194 		m_light * m_base_color.getGreen() / 255,
195 		m_light * m_base_color.getBlue() / 255);
196 }
197 
updateVertices()198 void Particle::updateVertices()
199 {
200 	f32 tx0, tx1, ty0, ty1;
201 
202 	if (m_animation.type != TAT_NONE) {
203 		const v2u32 texsize = m_material.getTexture(0)->getSize();
204 		v2f texcoord, framesize_f;
205 		v2u32 framesize;
206 		texcoord = m_animation.getTextureCoords(texsize, m_animation_frame);
207 		m_animation.determineParams(texsize, NULL, NULL, &framesize);
208 		framesize_f = v2f(framesize.X / (float) texsize.X, framesize.Y / (float) texsize.Y);
209 
210 		tx0 = m_texpos.X + texcoord.X;
211 		tx1 = m_texpos.X + texcoord.X + framesize_f.X * m_texsize.X;
212 		ty0 = m_texpos.Y + texcoord.Y;
213 		ty1 = m_texpos.Y + texcoord.Y + framesize_f.Y * m_texsize.Y;
214 	} else {
215 		tx0 = m_texpos.X;
216 		tx1 = m_texpos.X + m_texsize.X;
217 		ty0 = m_texpos.Y;
218 		ty1 = m_texpos.Y + m_texsize.Y;
219 	}
220 
221 	m_vertices[0] = video::S3DVertex(-m_size / 2, -m_size / 2,
222 		0, 0, 0, 0, m_color, tx0, ty1);
223 	m_vertices[1] = video::S3DVertex(m_size / 2, -m_size / 2,
224 		0, 0, 0, 0, m_color, tx1, ty1);
225 	m_vertices[2] = video::S3DVertex(m_size / 2, m_size / 2,
226 		0, 0, 0, 0, m_color, tx1, ty0);
227 	m_vertices[3] = video::S3DVertex(-m_size / 2, m_size / 2,
228 		0, 0, 0, 0, m_color, tx0, ty0);
229 
230 	v3s16 camera_offset = m_env->getCameraOffset();
231 	for (video::S3DVertex &vertex : m_vertices) {
232 		if (m_vertical) {
233 			v3f ppos = m_player->getPosition()/BS;
234 			vertex.Pos.rotateXZBy(std::atan2(ppos.Z - m_pos.Z, ppos.X - m_pos.X) /
235 				core::DEGTORAD + 90);
236 		} else {
237 			vertex.Pos.rotateYZBy(m_player->getPitch());
238 			vertex.Pos.rotateXZBy(m_player->getYaw());
239 		}
240 		m_box.addInternalPoint(vertex.Pos);
241 		vertex.Pos += m_pos*BS - intToFloat(camera_offset, BS);
242 	}
243 }
244 
245 /*
246 	ParticleSpawner
247 */
248 
ParticleSpawner(IGameDef * gamedef,LocalPlayer * player,const ParticleSpawnerParameters & p,u16 attached_id,video::ITexture * texture,ParticleManager * p_manager)249 ParticleSpawner::ParticleSpawner(
250 	IGameDef *gamedef,
251 	LocalPlayer *player,
252 	const ParticleSpawnerParameters &p,
253 	u16 attached_id,
254 	video::ITexture *texture,
255 	ParticleManager *p_manager
256 ):
257 	m_particlemanager(p_manager), p(p)
258 {
259 	m_gamedef = gamedef;
260 	m_player = player;
261 	m_attached_id = attached_id;
262 	m_texture = texture;
263 	m_time = 0;
264 
265 	m_spawntimes.reserve(p.amount + 1);
266 	for (u16 i = 0; i <= p.amount; i++) {
267 		float spawntime = rand() / (float)RAND_MAX * p.time;
268 		m_spawntimes.push_back(spawntime);
269 	}
270 }
271 
spawnParticle(ClientEnvironment * env,float radius,const core::matrix4 * attached_absolute_pos_rot_matrix)272 void ParticleSpawner::spawnParticle(ClientEnvironment *env, float radius,
273 	const core::matrix4 *attached_absolute_pos_rot_matrix)
274 {
275 	v3f ppos = m_player->getPosition() / BS;
276 	v3f pos = random_v3f(p.minpos, p.maxpos);
277 
278 	// Need to apply this first or the following check
279 	// will be wrong for attached spawners
280 	if (attached_absolute_pos_rot_matrix) {
281 		pos *= BS;
282 		attached_absolute_pos_rot_matrix->transformVect(pos);
283 		pos /= BS;
284 		v3s16 camera_offset = m_particlemanager->m_env->getCameraOffset();
285 		pos.X += camera_offset.X;
286 		pos.Y += camera_offset.Y;
287 		pos.Z += camera_offset.Z;
288 	}
289 
290 	if (pos.getDistanceFrom(ppos) > radius)
291 		return;
292 
293 	// Parameters for the single particle we're about to spawn
294 	ParticleParameters pp;
295 	pp.pos = pos;
296 
297 	pp.vel = random_v3f(p.minvel, p.maxvel);
298 	pp.acc = random_v3f(p.minacc, p.maxacc);
299 
300 	if (attached_absolute_pos_rot_matrix) {
301 		// Apply attachment rotation
302 		attached_absolute_pos_rot_matrix->rotateVect(pp.vel);
303 		attached_absolute_pos_rot_matrix->rotateVect(pp.acc);
304 	}
305 
306 	pp.expirationtime = random_f32(p.minexptime, p.maxexptime);
307 	p.copyCommon(pp);
308 
309 	video::ITexture *texture;
310 	v2f texpos, texsize;
311 	video::SColor color(0xFFFFFFFF);
312 
313 	if (p.node.getContent() != CONTENT_IGNORE) {
314 		const ContentFeatures &f =
315 			m_particlemanager->m_env->getGameDef()->ndef()->get(p.node);
316 		if (!ParticleManager::getNodeParticleParams(p.node, f, pp, &texture,
317 				texpos, texsize, &color, p.node_tile))
318 			return;
319 	} else {
320 		texture = m_texture;
321 		texpos = v2f(0.0f, 0.0f);
322 		texsize = v2f(1.0f, 1.0f);
323 	}
324 
325 	// Allow keeping default random size
326 	if (p.maxsize > 0.0f)
327 		pp.size = random_f32(p.minsize, p.maxsize);
328 
329 	m_particlemanager->addParticle(new Particle(
330 		m_gamedef,
331 		m_player,
332 		env,
333 		pp,
334 		texture,
335 		texpos,
336 		texsize,
337 		color
338 	));
339 }
340 
step(float dtime,ClientEnvironment * env)341 void ParticleSpawner::step(float dtime, ClientEnvironment *env)
342 {
343 	m_time += dtime;
344 
345 	static thread_local const float radius =
346 			g_settings->getS16("max_block_send_distance") * MAP_BLOCKSIZE;
347 
348 	bool unloaded = false;
349 	const core::matrix4 *attached_absolute_pos_rot_matrix = nullptr;
350 	if (m_attached_id) {
351 		if (GenericCAO *attached = dynamic_cast<GenericCAO *>(env->getActiveObject(m_attached_id))) {
352 			attached_absolute_pos_rot_matrix = attached->getAbsolutePosRotMatrix();
353 		} else {
354 			unloaded = true;
355 		}
356 	}
357 
358 	if (p.time != 0) {
359 		// Spawner exists for a predefined timespan
360 		for (auto i = m_spawntimes.begin(); i != m_spawntimes.end(); ) {
361 			if ((*i) <= m_time && p.amount > 0) {
362 				--p.amount;
363 
364 				// Pretend to, but don't actually spawn a particle if it is
365 				// attached to an unloaded object or distant from player.
366 				if (!unloaded)
367 					spawnParticle(env, radius, attached_absolute_pos_rot_matrix);
368 
369 				i = m_spawntimes.erase(i);
370 			} else {
371 				++i;
372 			}
373 		}
374 	} else {
375 		// Spawner exists for an infinity timespan, spawn on a per-second base
376 
377 		// Skip this step if attached to an unloaded object
378 		if (unloaded)
379 			return;
380 
381 		for (int i = 0; i <= p.amount; i++) {
382 			if (rand() / (float)RAND_MAX < dtime)
383 				spawnParticle(env, radius, attached_absolute_pos_rot_matrix);
384 		}
385 	}
386 }
387 
388 /*
389 	ParticleManager
390 */
391 
ParticleManager(ClientEnvironment * env)392 ParticleManager::ParticleManager(ClientEnvironment *env) :
393 	m_env(env)
394 {}
395 
~ParticleManager()396 ParticleManager::~ParticleManager()
397 {
398 	clearAll();
399 }
400 
step(float dtime)401 void ParticleManager::step(float dtime)
402 {
403 	stepParticles (dtime);
404 	stepSpawners (dtime);
405 }
406 
stepSpawners(float dtime)407 void ParticleManager::stepSpawners(float dtime)
408 {
409 	MutexAutoLock lock(m_spawner_list_lock);
410 	for (auto i = m_particle_spawners.begin(); i != m_particle_spawners.end();) {
411 		if (i->second->get_expired()) {
412 			delete i->second;
413 			m_particle_spawners.erase(i++);
414 		} else {
415 			i->second->step(dtime, m_env);
416 			++i;
417 		}
418 	}
419 }
420 
stepParticles(float dtime)421 void ParticleManager::stepParticles(float dtime)
422 {
423 	MutexAutoLock lock(m_particle_list_lock);
424 	for (auto i = m_particles.begin(); i != m_particles.end();) {
425 		if ((*i)->get_expired()) {
426 			(*i)->remove();
427 			delete *i;
428 			i = m_particles.erase(i);
429 		} else {
430 			(*i)->step(dtime);
431 			++i;
432 		}
433 	}
434 }
435 
clearAll()436 void ParticleManager::clearAll()
437 {
438 	MutexAutoLock lock(m_spawner_list_lock);
439 	MutexAutoLock lock2(m_particle_list_lock);
440 	for (auto i = m_particle_spawners.begin(); i != m_particle_spawners.end();) {
441 		delete i->second;
442 		m_particle_spawners.erase(i++);
443 	}
444 
445 	for(auto i = m_particles.begin(); i != m_particles.end();)
446 	{
447 		(*i)->remove();
448 		delete *i;
449 		i = m_particles.erase(i);
450 	}
451 }
452 
handleParticleEvent(ClientEvent * event,Client * client,LocalPlayer * player)453 void ParticleManager::handleParticleEvent(ClientEvent *event, Client *client,
454 	LocalPlayer *player)
455 {
456 	switch (event->type) {
457 		case CE_DELETE_PARTICLESPAWNER: {
458 			deleteParticleSpawner(event->delete_particlespawner.id);
459 			// no allocated memory in delete event
460 			break;
461 		}
462 		case CE_ADD_PARTICLESPAWNER: {
463 			deleteParticleSpawner(event->add_particlespawner.id);
464 
465 			const ParticleSpawnerParameters &p = *event->add_particlespawner.p;
466 
467 			video::ITexture *texture =
468 				client->tsrc()->getTextureForMesh(p.texture);
469 
470 			auto toadd = new ParticleSpawner(client, player,
471 					p,
472 					event->add_particlespawner.attached_id,
473 					texture,
474 					this);
475 
476 			addParticleSpawner(event->add_particlespawner.id, toadd);
477 
478 			delete event->add_particlespawner.p;
479 			break;
480 		}
481 		case CE_SPAWN_PARTICLE: {
482 			ParticleParameters &p = *event->spawn_particle;
483 
484 			video::ITexture *texture;
485 			v2f texpos, texsize;
486 			video::SColor color(0xFFFFFFFF);
487 
488 			f32 oldsize = p.size;
489 
490 			if (p.node.getContent() != CONTENT_IGNORE) {
491 				const ContentFeatures &f = m_env->getGameDef()->ndef()->get(p.node);
492 				if (!getNodeParticleParams(p.node, f, p, &texture, texpos,
493 						texsize, &color, p.node_tile))
494 					texture = nullptr;
495 			} else {
496 				texture = client->tsrc()->getTextureForMesh(p.texture);
497 				texpos = v2f(0.0f, 0.0f);
498 				texsize = v2f(1.0f, 1.0f);
499 			}
500 
501 			// Allow keeping default random size
502 			if (oldsize > 0.0f)
503 				p.size = oldsize;
504 
505 			if (texture) {
506 				Particle *toadd = new Particle(client, player, m_env,
507 						p, texture, texpos, texsize, color);
508 
509 				addParticle(toadd);
510 			}
511 
512 			delete event->spawn_particle;
513 			break;
514 		}
515 		default: break;
516 	}
517 }
518 
getNodeParticleParams(const MapNode & n,const ContentFeatures & f,ParticleParameters & p,video::ITexture ** texture,v2f & texpos,v2f & texsize,video::SColor * color,u8 tilenum)519 bool ParticleManager::getNodeParticleParams(const MapNode &n,
520 	const ContentFeatures &f, ParticleParameters &p, video::ITexture **texture,
521 	v2f &texpos, v2f &texsize, video::SColor *color, u8 tilenum)
522 {
523 	// No particles for "airlike" nodes
524 	if (f.drawtype == NDT_AIRLIKE)
525 		return false;
526 
527 	// Texture
528 	u8 texid;
529 	if (tilenum > 0 && tilenum <= 6)
530 		texid = tilenum - 1;
531 	else
532 		texid = rand() % 6;
533 	const TileLayer &tile = f.tiles[texid].layers[0];
534 	p.animation.type = TAT_NONE;
535 
536 	// Only use first frame of animated texture
537 	if (tile.material_flags & MATERIAL_FLAG_ANIMATION)
538 		*texture = (*tile.frames)[0].texture;
539 	else
540 		*texture = tile.texture;
541 
542 	float size = (rand() % 8) / 64.0f;
543 	p.size = BS * size;
544 	if (tile.scale)
545 		size /= tile.scale;
546 	texsize = v2f(size * 2.0f, size * 2.0f);
547 	texpos.X = (rand() % 64) / 64.0f - texsize.X;
548 	texpos.Y = (rand() % 64) / 64.0f - texsize.Y;
549 
550 	if (tile.has_color)
551 		*color = tile.color;
552 	else
553 		n.getColor(f, color);
554 
555 	return true;
556 }
557 
558 // The final burst of particles when a node is finally dug, *not* particles
559 // spawned during the digging of a node.
560 
addDiggingParticles(IGameDef * gamedef,LocalPlayer * player,v3s16 pos,const MapNode & n,const ContentFeatures & f)561 void ParticleManager::addDiggingParticles(IGameDef *gamedef,
562 	LocalPlayer *player, v3s16 pos, const MapNode &n, const ContentFeatures &f)
563 {
564 	// No particles for "airlike" nodes
565 	if (f.drawtype == NDT_AIRLIKE)
566 		return;
567 
568 	for (u16 j = 0; j < 16; j++) {
569 		addNodeParticle(gamedef, player, pos, n, f);
570 	}
571 }
572 
573 // During the digging of a node particles are spawned individually by this
574 // function, called from Game::handleDigging() in game.cpp.
575 
addNodeParticle(IGameDef * gamedef,LocalPlayer * player,v3s16 pos,const MapNode & n,const ContentFeatures & f)576 void ParticleManager::addNodeParticle(IGameDef *gamedef,
577 	LocalPlayer *player, v3s16 pos, const MapNode &n, const ContentFeatures &f)
578 {
579 	ParticleParameters p;
580 	video::ITexture *texture;
581 	v2f texpos, texsize;
582 	video::SColor color;
583 
584 	if (!getNodeParticleParams(n, f, p, &texture, texpos, texsize, &color))
585 		return;
586 
587 	p.expirationtime = (rand() % 100) / 100.0f;
588 
589 	// Physics
590 	p.vel = v3f(
591 		(rand() % 150) / 50.0f - 1.5f,
592 		(rand() % 150) / 50.0f,
593 		(rand() % 150) / 50.0f - 1.5f
594 	);
595 	p.acc = v3f(
596 		0.0f,
597 		-player->movement_gravity * player->physics_override_gravity / BS,
598 		0.0f
599 	);
600 	p.pos = v3f(
601 		(f32)pos.X + (rand() % 100) / 200.0f - 0.25f,
602 		(f32)pos.Y + (rand() % 100) / 200.0f - 0.25f,
603 		(f32)pos.Z + (rand() % 100) / 200.0f - 0.25f
604 	);
605 
606 	Particle *toadd = new Particle(
607 		gamedef,
608 		player,
609 		m_env,
610 		p,
611 		texture,
612 		texpos,
613 		texsize,
614 		color);
615 
616 	addParticle(toadd);
617 }
618 
addParticle(Particle * toadd)619 void ParticleManager::addParticle(Particle *toadd)
620 {
621 	MutexAutoLock lock(m_particle_list_lock);
622 	m_particles.push_back(toadd);
623 }
624 
625 
addParticleSpawner(u64 id,ParticleSpawner * toadd)626 void ParticleManager::addParticleSpawner(u64 id, ParticleSpawner *toadd)
627 {
628 	MutexAutoLock lock(m_spawner_list_lock);
629 	m_particle_spawners[id] = toadd;
630 }
631 
deleteParticleSpawner(u64 id)632 void ParticleManager::deleteParticleSpawner(u64 id)
633 {
634 	MutexAutoLock lock(m_spawner_list_lock);
635 	auto it = m_particle_spawners.find(id);
636 	if (it != m_particle_spawners.end()) {
637 		delete it->second;
638 		m_particle_spawners.erase(it);
639 	}
640 }
641