1/**************************************************************************/
2/* particles_storage.cpp */
3/**************************************************************************/
4/* This file is part of: */
5/* GODOT ENGINE */
6/* https://godotengine.org */
7/**************************************************************************/
8/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10/* */
11/* Permission is hereby granted, free of charge, to any person obtaining */
12/* a copy of this software and associated documentation files (the */
13/* "Software"), to deal in the Software without restriction, including */
14/* without limitation the rights to use, copy, modify, merge, publish, */
15/* distribute, sublicense, and/or sell copies of the Software, and to */
16/* permit persons to whom the Software is furnished to do so, subject to */
17/* the following conditions: */
18/* */
19/* The above copyright notice and this permission notice shall be */
20/* included in all copies or substantial portions of the Software. */
21/* */
22/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29/**************************************************************************/
30
31#include "particles_storage.h"
32
33#include "servers/rendering/renderer_rd/renderer_compositor_rd.h"
34#include "servers/rendering/rendering_server_globals.h"
35#include "texture_storage.h"
36
37using namespace RendererRD;
38
39ParticlesStorage *ParticlesStorage::singleton = nullptr;
40
41ParticlesStorage *ParticlesStorage::get_singleton() {
42 return singleton;
43}
44
45ParticlesStorage::ParticlesStorage() {
46 singleton = this;
47
48 MaterialStorage *material_storage = MaterialStorage::get_singleton();
49
50 /* Effects */
51
52 sort_effects = memnew(SortEffects);
53
54 /* Particles */
55
56 {
57 String defines = "#define SAMPLERS_BINDING_FIRST_INDEX " + itos(SAMPLERS_BINDING_FIRST_INDEX) + "\n";
58 // Initialize particles
59 Vector<String> particles_modes;
60 particles_modes.push_back("");
61 particles_shader.shader.initialize(particles_modes, defines);
62 }
63 MaterialStorage::get_singleton()->shader_set_data_request_function(MaterialStorage::SHADER_TYPE_PARTICLES, _create_particles_shader_funcs);
64 MaterialStorage::get_singleton()->material_set_data_request_function(MaterialStorage::SHADER_TYPE_PARTICLES, _create_particles_material_funcs);
65
66 {
67 ShaderCompiler::DefaultIdentifierActions actions;
68
69 actions.renames["COLOR"] = "PARTICLE.color";
70 actions.renames["VELOCITY"] = "PARTICLE.velocity";
71 //actions.renames["MASS"] = "mass"; ?
72 actions.renames["ACTIVE"] = "particle_active";
73 actions.renames["RESTART"] = "restart";
74 actions.renames["CUSTOM"] = "PARTICLE.custom";
75 for (int i = 0; i < ParticlesShader::MAX_USERDATAS; i++) {
76 String udname = "USERDATA" + itos(i + 1);
77 actions.renames[udname] = "PARTICLE.userdata" + itos(i + 1);
78 actions.usage_defines[udname] = "#define USERDATA" + itos(i + 1) + "_USED\n";
79 }
80 actions.renames["TRANSFORM"] = "PARTICLE.xform";
81 actions.renames["TIME"] = "frame_history.data[0].time";
82 actions.renames["PI"] = _MKSTR(Math_PI);
83 actions.renames["TAU"] = _MKSTR(Math_TAU);
84 actions.renames["E"] = _MKSTR(Math_E);
85 actions.renames["LIFETIME"] = "params.lifetime";
86 actions.renames["DELTA"] = "local_delta";
87 actions.renames["NUMBER"] = "particle_number";
88 actions.renames["INDEX"] = "index";
89 //actions.renames["GRAVITY"] = "current_gravity";
90 actions.renames["EMISSION_TRANSFORM"] = "FRAME.emission_transform";
91 actions.renames["RANDOM_SEED"] = "FRAME.random_seed";
92 actions.renames["FLAG_EMIT_POSITION"] = "EMISSION_FLAG_HAS_POSITION";
93 actions.renames["FLAG_EMIT_ROT_SCALE"] = "EMISSION_FLAG_HAS_ROTATION_SCALE";
94 actions.renames["FLAG_EMIT_VELOCITY"] = "EMISSION_FLAG_HAS_VELOCITY";
95 actions.renames["FLAG_EMIT_COLOR"] = "EMISSION_FLAG_HAS_COLOR";
96 actions.renames["FLAG_EMIT_CUSTOM"] = "EMISSION_FLAG_HAS_CUSTOM";
97 actions.renames["RESTART_POSITION"] = "restart_position";
98 actions.renames["RESTART_ROT_SCALE"] = "restart_rotation_scale";
99 actions.renames["RESTART_VELOCITY"] = "restart_velocity";
100 actions.renames["RESTART_COLOR"] = "restart_color";
101 actions.renames["RESTART_CUSTOM"] = "restart_custom";
102 actions.renames["emit_subparticle"] = "emit_subparticle";
103 actions.renames["COLLIDED"] = "collided";
104 actions.renames["COLLISION_NORMAL"] = "collision_normal";
105 actions.renames["COLLISION_DEPTH"] = "collision_depth";
106 actions.renames["ATTRACTOR_FORCE"] = "attractor_force";
107
108 actions.render_mode_defines["disable_force"] = "#define DISABLE_FORCE\n";
109 actions.render_mode_defines["disable_velocity"] = "#define DISABLE_VELOCITY\n";
110 actions.render_mode_defines["keep_data"] = "#define ENABLE_KEEP_DATA\n";
111 actions.render_mode_defines["collision_use_scale"] = "#define USE_COLLISION_SCALE\n";
112
113 actions.base_texture_binding_index = 1;
114 actions.texture_layout_set = 3;
115 actions.base_uniform_string = "material.";
116 actions.base_varying_index = 10;
117
118 actions.default_filter = ShaderLanguage::FILTER_LINEAR_MIPMAP;
119 actions.default_repeat = ShaderLanguage::REPEAT_ENABLE;
120 actions.global_buffer_array_variable = "global_shader_uniforms.data";
121
122 particles_shader.compiler.initialize(actions);
123 }
124
125 {
126 // default material and shader for particles shader
127 particles_shader.default_shader = material_storage->shader_allocate();
128 material_storage->shader_initialize(particles_shader.default_shader);
129 material_storage->shader_set_code(particles_shader.default_shader, R"(
130// Default particles shader.
131
132shader_type particles;
133
134void process() {
135 COLOR = vec4(1.0);
136}
137)");
138 particles_shader.default_material = material_storage->material_allocate();
139 material_storage->material_initialize(particles_shader.default_material);
140 material_storage->material_set_shader(particles_shader.default_material, particles_shader.default_shader);
141
142 ParticleProcessMaterialData *md = static_cast<ParticleProcessMaterialData *>(material_storage->material_get_data(particles_shader.default_material, MaterialStorage::SHADER_TYPE_PARTICLES));
143 particles_shader.default_shader_rd = particles_shader.shader.version_get_shader(md->shader_data->version, 0);
144
145 Vector<RD::Uniform> uniforms;
146
147 {
148 RD::Uniform u;
149 u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
150 u.binding = 2;
151 u.append_id(material_storage->global_shader_uniforms_get_storage_buffer());
152 uniforms.push_back(u);
153 }
154
155 uniforms.append_array(material_storage->get_default_sampler_uniforms(SAMPLERS_BINDING_FIRST_INDEX));
156
157 particles_shader.base_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, particles_shader.default_shader_rd, BASE_UNIFORM_SET);
158 }
159
160 {
161 Vector<String> copy_modes;
162 for (int i = 0; i <= ParticlesShader::MAX_USERDATAS; i++) {
163 if (i == 0) {
164 copy_modes.push_back("\n#define MODE_FILL_INSTANCES\n");
165 copy_modes.push_back("\n#define MODE_FILL_SORT_BUFFER\n#define USE_SORT_BUFFER\n");
166 copy_modes.push_back("\n#define MODE_FILL_INSTANCES\n#define USE_SORT_BUFFER\n");
167 } else {
168 copy_modes.push_back("\n#define MODE_FILL_INSTANCES\n#define USERDATA_COUNT " + itos(i) + "\n");
169 copy_modes.push_back("\n#define MODE_FILL_SORT_BUFFER\n#define USE_SORT_BUFFER\n#define USERDATA_COUNT " + itos(i) + "\n");
170 copy_modes.push_back("\n#define MODE_FILL_INSTANCES\n#define USE_SORT_BUFFER\n#define USERDATA_COUNT " + itos(i) + "\n");
171 }
172 }
173
174 particles_shader.copy_shader.initialize(copy_modes);
175
176 particles_shader.copy_shader_version = particles_shader.copy_shader.version_create();
177
178 for (int i = 0; i <= ParticlesShader::MAX_USERDATAS; i++) {
179 for (int j = 0; j < ParticlesShader::COPY_MODE_MAX; j++) {
180 particles_shader.copy_pipelines[i * ParticlesShader::COPY_MODE_MAX + j] = RD::get_singleton()->compute_pipeline_create(particles_shader.copy_shader.version_get_shader(particles_shader.copy_shader_version, i * ParticlesShader::COPY_MODE_MAX + j));
181 }
182 }
183 }
184}
185
186ParticlesStorage::~ParticlesStorage() {
187 MaterialStorage *material_storage = MaterialStorage::get_singleton();
188
189 particles_shader.copy_shader.version_free(particles_shader.copy_shader_version);
190
191 material_storage->material_free(particles_shader.default_material);
192 material_storage->shader_free(particles_shader.default_shader);
193
194 if (sort_effects) {
195 memdelete(sort_effects);
196 sort_effects = nullptr;
197 }
198
199 singleton = nullptr;
200}
201
202bool ParticlesStorage::free(RID p_rid) {
203 if (owns_particles(p_rid)) {
204 particles_free(p_rid);
205 return true;
206 } else if (owns_particles_collision(p_rid)) {
207 particles_collision_free(p_rid);
208 return true;
209 } else if (owns_particles_collision_instance(p_rid)) {
210 particles_collision_instance_free(p_rid);
211 return true;
212 }
213
214 return false;
215}
216
217/* PARTICLES */
218
219RID ParticlesStorage::particles_allocate() {
220 return particles_owner.allocate_rid();
221}
222
223void ParticlesStorage::particles_initialize(RID p_rid) {
224 particles_owner.initialize_rid(p_rid, Particles());
225}
226
227void ParticlesStorage::particles_free(RID p_rid) {
228 update_particles();
229 Particles *particles = particles_owner.get_or_null(p_rid);
230 particles->dependency.deleted_notify(p_rid);
231 _particles_free_data(particles);
232 particles_owner.free(p_rid);
233}
234
235void ParticlesStorage::particles_set_mode(RID p_particles, RS::ParticlesMode p_mode) {
236 Particles *particles = particles_owner.get_or_null(p_particles);
237 ERR_FAIL_COND(!particles);
238 if (particles->mode == p_mode) {
239 return;
240 }
241
242 _particles_free_data(particles);
243
244 particles->mode = p_mode;
245}
246
247void ParticlesStorage::particles_set_emitting(RID p_particles, bool p_emitting) {
248 Particles *particles = particles_owner.get_or_null(p_particles);
249 ERR_FAIL_COND(!particles);
250
251 particles->emitting = p_emitting;
252}
253
254bool ParticlesStorage::particles_get_emitting(RID p_particles) {
255 ERR_FAIL_COND_V_MSG(RSG::threaded, false, "This function should never be used with threaded rendering, as it stalls the renderer.");
256 Particles *particles = particles_owner.get_or_null(p_particles);
257 ERR_FAIL_COND_V(!particles, false);
258
259 return particles->emitting;
260}
261
262void ParticlesStorage::_particles_free_data(Particles *particles) {
263 if (particles->particle_buffer.is_valid()) {
264 RD::get_singleton()->free(particles->particle_buffer);
265 particles->particle_buffer = RID();
266 RD::get_singleton()->free(particles->particle_instance_buffer);
267 particles->particle_instance_buffer = RID();
268 }
269
270 particles->userdata_count = 0;
271
272 if (particles->frame_params_buffer.is_valid()) {
273 RD::get_singleton()->free(particles->frame_params_buffer);
274 particles->frame_params_buffer = RID();
275 }
276 particles->particles_transforms_buffer_uniform_set = RID();
277
278 if (RD::get_singleton()->uniform_set_is_valid(particles->trail_bind_pose_uniform_set)) {
279 RD::get_singleton()->free(particles->trail_bind_pose_uniform_set);
280 }
281 particles->trail_bind_pose_uniform_set = RID();
282
283 if (particles->trail_bind_pose_buffer.is_valid()) {
284 RD::get_singleton()->free(particles->trail_bind_pose_buffer);
285 particles->trail_bind_pose_buffer = RID();
286 }
287 if (RD::get_singleton()->uniform_set_is_valid(particles->collision_textures_uniform_set)) {
288 RD::get_singleton()->free(particles->collision_textures_uniform_set);
289 }
290 particles->collision_textures_uniform_set = RID();
291
292 if (particles->particles_sort_buffer.is_valid()) {
293 RD::get_singleton()->free(particles->particles_sort_buffer);
294 particles->particles_sort_buffer = RID();
295 particles->particles_sort_uniform_set = RID();
296 }
297
298 if (particles->emission_buffer != nullptr) {
299 particles->emission_buffer = nullptr;
300 particles->emission_buffer_data.clear();
301 RD::get_singleton()->free(particles->emission_storage_buffer);
302 particles->emission_storage_buffer = RID();
303 }
304
305 if (RD::get_singleton()->uniform_set_is_valid(particles->particles_material_uniform_set)) {
306 //will need to be re-created
307 RD::get_singleton()->free(particles->particles_material_uniform_set);
308 }
309 particles->particles_material_uniform_set = RID();
310}
311
312void ParticlesStorage::particles_set_amount(RID p_particles, int p_amount) {
313 Particles *particles = particles_owner.get_or_null(p_particles);
314 ERR_FAIL_COND(!particles);
315
316 if (particles->amount == p_amount) {
317 return;
318 }
319
320 _particles_free_data(particles);
321
322 particles->amount = p_amount;
323
324 particles->prev_ticks = 0;
325 particles->phase = 0;
326 particles->prev_phase = 0;
327 particles->clear = true;
328
329 particles->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_PARTICLES);
330}
331
332void ParticlesStorage::particles_set_lifetime(RID p_particles, double p_lifetime) {
333 Particles *particles = particles_owner.get_or_null(p_particles);
334 ERR_FAIL_COND(!particles);
335 particles->lifetime = p_lifetime;
336}
337
338void ParticlesStorage::particles_set_one_shot(RID p_particles, bool p_one_shot) {
339 Particles *particles = particles_owner.get_or_null(p_particles);
340 ERR_FAIL_COND(!particles);
341 particles->one_shot = p_one_shot;
342}
343
344void ParticlesStorage::particles_set_pre_process_time(RID p_particles, double p_time) {
345 Particles *particles = particles_owner.get_or_null(p_particles);
346 ERR_FAIL_COND(!particles);
347 particles->pre_process_time = p_time;
348}
349void ParticlesStorage::particles_set_explosiveness_ratio(RID p_particles, real_t p_ratio) {
350 Particles *particles = particles_owner.get_or_null(p_particles);
351 ERR_FAIL_COND(!particles);
352 particles->explosiveness = p_ratio;
353}
354void ParticlesStorage::particles_set_randomness_ratio(RID p_particles, real_t p_ratio) {
355 Particles *particles = particles_owner.get_or_null(p_particles);
356 ERR_FAIL_COND(!particles);
357 particles->randomness = p_ratio;
358}
359
360void ParticlesStorage::particles_set_custom_aabb(RID p_particles, const AABB &p_aabb) {
361 Particles *particles = particles_owner.get_or_null(p_particles);
362 ERR_FAIL_COND(!particles);
363 particles->custom_aabb = p_aabb;
364 particles->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_AABB);
365}
366
367void ParticlesStorage::particles_set_speed_scale(RID p_particles, double p_scale) {
368 Particles *particles = particles_owner.get_or_null(p_particles);
369 ERR_FAIL_COND(!particles);
370
371 particles->speed_scale = p_scale;
372}
373void ParticlesStorage::particles_set_use_local_coordinates(RID p_particles, bool p_enable) {
374 Particles *particles = particles_owner.get_or_null(p_particles);
375 ERR_FAIL_COND(!particles);
376
377 particles->use_local_coords = p_enable;
378 particles->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_PARTICLES);
379}
380
381void ParticlesStorage::particles_set_fixed_fps(RID p_particles, int p_fps) {
382 Particles *particles = particles_owner.get_or_null(p_particles);
383 ERR_FAIL_COND(!particles);
384
385 particles->fixed_fps = p_fps;
386
387 _particles_free_data(particles);
388
389 particles->prev_ticks = 0;
390 particles->phase = 0;
391 particles->prev_phase = 0;
392 particles->clear = true;
393
394 particles->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_PARTICLES);
395}
396
397void ParticlesStorage::particles_set_interpolate(RID p_particles, bool p_enable) {
398 Particles *particles = particles_owner.get_or_null(p_particles);
399 ERR_FAIL_COND(!particles);
400
401 particles->interpolate = p_enable;
402}
403
404void ParticlesStorage::particles_set_fractional_delta(RID p_particles, bool p_enable) {
405 Particles *particles = particles_owner.get_or_null(p_particles);
406 ERR_FAIL_COND(!particles);
407
408 particles->fractional_delta = p_enable;
409}
410
411void ParticlesStorage::particles_set_trails(RID p_particles, bool p_enable, double p_length) {
412 Particles *particles = particles_owner.get_or_null(p_particles);
413 ERR_FAIL_COND(!particles);
414 ERR_FAIL_COND(p_length < 0.01);
415 p_length = MIN(10.0, p_length);
416
417 particles->trails_enabled = p_enable;
418 particles->trail_lifetime = p_length;
419
420 _particles_free_data(particles);
421
422 particles->prev_ticks = 0;
423 particles->phase = 0;
424 particles->prev_phase = 0;
425 particles->clear = true;
426
427 particles->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_PARTICLES);
428}
429
430void ParticlesStorage::particles_set_trail_bind_poses(RID p_particles, const Vector<Transform3D> &p_bind_poses) {
431 Particles *particles = particles_owner.get_or_null(p_particles);
432 ERR_FAIL_COND(!particles);
433 if (particles->trail_bind_pose_buffer.is_valid() && particles->trail_bind_poses.size() != p_bind_poses.size()) {
434 _particles_free_data(particles);
435
436 particles->prev_ticks = 0;
437 particles->phase = 0;
438 particles->prev_phase = 0;
439 particles->clear = true;
440 }
441 particles->trail_bind_poses = p_bind_poses;
442 particles->trail_bind_poses_dirty = true;
443
444 particles->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_PARTICLES);
445}
446
447void ParticlesStorage::particles_set_collision_base_size(RID p_particles, real_t p_size) {
448 Particles *particles = particles_owner.get_or_null(p_particles);
449 ERR_FAIL_COND(!particles);
450
451 particles->collision_base_size = p_size;
452}
453
454void ParticlesStorage::particles_set_transform_align(RID p_particles, RS::ParticlesTransformAlign p_transform_align) {
455 Particles *particles = particles_owner.get_or_null(p_particles);
456 ERR_FAIL_COND(!particles);
457
458 particles->transform_align = p_transform_align;
459}
460
461void ParticlesStorage::particles_set_process_material(RID p_particles, RID p_material) {
462 Particles *particles = particles_owner.get_or_null(p_particles);
463 ERR_FAIL_COND(!particles);
464
465 particles->process_material = p_material;
466 particles->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_PARTICLES); //the instance buffer may have changed
467}
468
469RID ParticlesStorage::particles_get_process_material(RID p_particles) const {
470 Particles *particles = particles_owner.get_or_null(p_particles);
471 ERR_FAIL_COND_V(!particles, RID());
472
473 return particles->process_material;
474}
475
476void ParticlesStorage::particles_set_draw_order(RID p_particles, RS::ParticlesDrawOrder p_order) {
477 Particles *particles = particles_owner.get_or_null(p_particles);
478 ERR_FAIL_COND(!particles);
479
480 particles->draw_order = p_order;
481}
482
483void ParticlesStorage::particles_set_draw_passes(RID p_particles, int p_passes) {
484 Particles *particles = particles_owner.get_or_null(p_particles);
485 ERR_FAIL_COND(!particles);
486
487 particles->draw_passes.resize(p_passes);
488}
489
490void ParticlesStorage::particles_set_draw_pass_mesh(RID p_particles, int p_pass, RID p_mesh) {
491 Particles *particles = particles_owner.get_or_null(p_particles);
492 ERR_FAIL_COND(!particles);
493 ERR_FAIL_INDEX(p_pass, particles->draw_passes.size());
494 particles->draw_passes.write[p_pass] = p_mesh;
495}
496
497void ParticlesStorage::particles_restart(RID p_particles) {
498 Particles *particles = particles_owner.get_or_null(p_particles);
499 ERR_FAIL_COND(!particles);
500
501 particles->restart_request = true;
502}
503
504void ParticlesStorage::_particles_allocate_emission_buffer(Particles *particles) {
505 ERR_FAIL_COND(particles->emission_buffer != nullptr);
506
507 particles->emission_buffer_data.resize(sizeof(ParticleEmissionBuffer::Data) * particles->amount + sizeof(uint32_t) * 4);
508 memset(particles->emission_buffer_data.ptrw(), 0, particles->emission_buffer_data.size());
509 particles->emission_buffer = reinterpret_cast<ParticleEmissionBuffer *>(particles->emission_buffer_data.ptrw());
510 particles->emission_buffer->particle_max = particles->amount;
511
512 particles->emission_storage_buffer = RD::get_singleton()->storage_buffer_create(particles->emission_buffer_data.size(), particles->emission_buffer_data);
513
514 if (RD::get_singleton()->uniform_set_is_valid(particles->particles_material_uniform_set)) {
515 //will need to be re-created
516 RD::get_singleton()->free(particles->particles_material_uniform_set);
517 particles->particles_material_uniform_set = RID();
518 }
519}
520
521void ParticlesStorage::particles_set_subemitter(RID p_particles, RID p_subemitter_particles) {
522 Particles *particles = particles_owner.get_or_null(p_particles);
523 ERR_FAIL_COND(!particles);
524 ERR_FAIL_COND(p_particles == p_subemitter_particles);
525
526 particles->sub_emitter = p_subemitter_particles;
527
528 if (RD::get_singleton()->uniform_set_is_valid(particles->particles_material_uniform_set)) {
529 RD::get_singleton()->free(particles->particles_material_uniform_set);
530 particles->particles_material_uniform_set = RID(); //clear and force to re create sub emitting
531 }
532}
533
534void ParticlesStorage::particles_emit(RID p_particles, const Transform3D &p_transform, const Vector3 &p_velocity, const Color &p_color, const Color &p_custom, uint32_t p_emit_flags) {
535 Particles *particles = particles_owner.get_or_null(p_particles);
536 ERR_FAIL_COND(!particles);
537 ERR_FAIL_COND(particles->amount == 0);
538
539 if (particles->emitting) {
540 particles->clear = true;
541 particles->emitting = false;
542 }
543
544 if (particles->emission_buffer == nullptr) {
545 _particles_allocate_emission_buffer(particles);
546 }
547
548 particles->inactive = false;
549 particles->inactive_time = 0;
550
551 int32_t idx = particles->emission_buffer->particle_count;
552 if (idx < particles->emission_buffer->particle_max) {
553 RendererRD::MaterialStorage::store_transform(p_transform, particles->emission_buffer->data[idx].xform);
554
555 particles->emission_buffer->data[idx].velocity[0] = p_velocity.x;
556 particles->emission_buffer->data[idx].velocity[1] = p_velocity.y;
557 particles->emission_buffer->data[idx].velocity[2] = p_velocity.z;
558
559 particles->emission_buffer->data[idx].custom[0] = p_custom.r;
560 particles->emission_buffer->data[idx].custom[1] = p_custom.g;
561 particles->emission_buffer->data[idx].custom[2] = p_custom.b;
562 particles->emission_buffer->data[idx].custom[3] = p_custom.a;
563
564 particles->emission_buffer->data[idx].color[0] = p_color.r;
565 particles->emission_buffer->data[idx].color[1] = p_color.g;
566 particles->emission_buffer->data[idx].color[2] = p_color.b;
567 particles->emission_buffer->data[idx].color[3] = p_color.a;
568
569 particles->emission_buffer->data[idx].flags = p_emit_flags;
570 particles->emission_buffer->particle_count++;
571 }
572}
573
574void ParticlesStorage::particles_request_process(RID p_particles) {
575 Particles *particles = particles_owner.get_or_null(p_particles);
576 ERR_FAIL_COND(!particles);
577
578 if (!particles->dirty) {
579 particles->dirty = true;
580 particles->update_list = particle_update_list;
581 particle_update_list = particles;
582 }
583}
584
585AABB ParticlesStorage::particles_get_current_aabb(RID p_particles) {
586 if (RSG::threaded) {
587 WARN_PRINT_ONCE("Calling this function with threaded rendering enabled stalls the renderer, use with care.");
588 }
589
590 const Particles *particles = particles_owner.get_or_null(p_particles);
591 ERR_FAIL_COND_V(!particles, AABB());
592
593 int total_amount = particles->amount;
594 if (particles->trails_enabled && particles->trail_bind_poses.size() > 1) {
595 total_amount *= particles->trail_bind_poses.size();
596 }
597
598 Vector<uint8_t> buffer = RD::get_singleton()->buffer_get_data(particles->particle_buffer);
599 ERR_FAIL_COND_V(buffer.size() != (int)(total_amount * sizeof(ParticleData)), AABB());
600
601 Transform3D inv = particles->emission_transform.affine_inverse();
602
603 AABB aabb;
604 if (buffer.size()) {
605 bool first = true;
606
607 const uint8_t *data_ptr = (const uint8_t *)buffer.ptr();
608 uint32_t particle_data_size = sizeof(ParticleData) + sizeof(float) * particles->userdata_count;
609
610 for (int i = 0; i < total_amount; i++) {
611 const ParticleData &particle_data = *(const ParticleData *)&data_ptr[particle_data_size * i];
612 if (particle_data.active) {
613 Vector3 pos = Vector3(particle_data.xform[12], particle_data.xform[13], particle_data.xform[14]);
614 if (!particles->use_local_coords) {
615 pos = inv.xform(pos);
616 }
617 if (first) {
618 aabb.position = pos;
619 first = false;
620 } else {
621 aabb.expand_to(pos);
622 }
623 }
624 }
625 }
626
627 float longest_axis_size = 0;
628 for (int i = 0; i < particles->draw_passes.size(); i++) {
629 if (particles->draw_passes[i].is_valid()) {
630 AABB maabb = MeshStorage::get_singleton()->mesh_get_aabb(particles->draw_passes[i], RID());
631 longest_axis_size = MAX(maabb.get_longest_axis_size(), longest_axis_size);
632 }
633 }
634
635 aabb.grow_by(longest_axis_size);
636
637 return aabb;
638}
639
640AABB ParticlesStorage::particles_get_aabb(RID p_particles) const {
641 const Particles *particles = particles_owner.get_or_null(p_particles);
642 ERR_FAIL_COND_V(!particles, AABB());
643
644 return particles->custom_aabb;
645}
646
647void ParticlesStorage::particles_set_emission_transform(RID p_particles, const Transform3D &p_transform) {
648 Particles *particles = particles_owner.get_or_null(p_particles);
649 ERR_FAIL_COND(!particles);
650
651 particles->emission_transform = p_transform;
652}
653
654int ParticlesStorage::particles_get_draw_passes(RID p_particles) const {
655 const Particles *particles = particles_owner.get_or_null(p_particles);
656 ERR_FAIL_COND_V(!particles, 0);
657
658 return particles->draw_passes.size();
659}
660
661RID ParticlesStorage::particles_get_draw_pass_mesh(RID p_particles, int p_pass) const {
662 const Particles *particles = particles_owner.get_or_null(p_particles);
663 ERR_FAIL_COND_V(!particles, RID());
664 ERR_FAIL_INDEX_V(p_pass, particles->draw_passes.size(), RID());
665
666 return particles->draw_passes[p_pass];
667}
668
669void ParticlesStorage::particles_update_dependency(RID p_particles, DependencyTracker *p_instance) {
670 Particles *particles = particles_owner.get_or_null(p_particles);
671 ERR_FAIL_COND(!particles);
672 p_instance->update_dependency(&particles->dependency);
673}
674
675void ParticlesStorage::particles_get_instance_buffer_motion_vectors_offsets(RID p_particles, uint32_t &r_current_offset, uint32_t &r_prev_offset) {
676 Particles *particles = particles_owner.get_or_null(p_particles);
677 ERR_FAIL_COND(!particles);
678 r_current_offset = particles->instance_motion_vectors_current_offset;
679 r_prev_offset = particles->instance_motion_vectors_previous_offset;
680}
681
682void ParticlesStorage::particles_add_collision(RID p_particles, RID p_particles_collision_instance) {
683 Particles *particles = particles_owner.get_or_null(p_particles);
684 ERR_FAIL_COND(!particles);
685 particles->collisions.insert(p_particles_collision_instance);
686}
687
688void ParticlesStorage::particles_remove_collision(RID p_particles, RID p_particles_collision_instance) {
689 Particles *particles = particles_owner.get_or_null(p_particles);
690 ERR_FAIL_COND(!particles);
691 particles->collisions.erase(p_particles_collision_instance);
692}
693
694void ParticlesStorage::particles_set_canvas_sdf_collision(RID p_particles, bool p_enable, const Transform2D &p_xform, const Rect2 &p_to_screen, RID p_texture) {
695 Particles *particles = particles_owner.get_or_null(p_particles);
696 ERR_FAIL_COND(!particles);
697 particles->has_sdf_collision = p_enable;
698 particles->sdf_collision_transform = p_xform;
699 particles->sdf_collision_to_screen = p_to_screen;
700 particles->sdf_collision_texture = p_texture;
701}
702
703void ParticlesStorage::_particles_process(Particles *p_particles, double p_delta) {
704 TextureStorage *texture_storage = TextureStorage::get_singleton();
705 MaterialStorage *material_storage = MaterialStorage::get_singleton();
706
707 if (p_particles->particles_material_uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(p_particles->particles_material_uniform_set)) {
708 Vector<RD::Uniform> uniforms;
709
710 {
711 RD::Uniform u;
712 u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
713 u.binding = 0;
714 u.append_id(p_particles->frame_params_buffer);
715 uniforms.push_back(u);
716 }
717 {
718 RD::Uniform u;
719 u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
720 u.binding = 1;
721 u.append_id(p_particles->particle_buffer);
722 uniforms.push_back(u);
723 }
724
725 {
726 RD::Uniform u;
727 u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
728 u.binding = 2;
729 if (p_particles->emission_storage_buffer.is_valid()) {
730 u.append_id(p_particles->emission_storage_buffer);
731 } else {
732 u.append_id(MeshStorage::get_singleton()->get_default_rd_storage_buffer());
733 }
734 uniforms.push_back(u);
735 }
736 {
737 RD::Uniform u;
738 u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
739 u.binding = 3;
740 Particles *sub_emitter = particles_owner.get_or_null(p_particles->sub_emitter);
741 if (sub_emitter) {
742 if (sub_emitter->emission_buffer == nullptr) { //no emission buffer, allocate emission buffer
743 _particles_allocate_emission_buffer(sub_emitter);
744 }
745 u.append_id(sub_emitter->emission_storage_buffer);
746 } else {
747 u.append_id(MeshStorage::get_singleton()->get_default_rd_storage_buffer());
748 }
749 uniforms.push_back(u);
750 }
751
752 p_particles->particles_material_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, particles_shader.default_shader_rd, 1);
753 }
754
755 double new_phase = Math::fmod((double)p_particles->phase + (p_delta / p_particles->lifetime) * p_particles->speed_scale, 1.0);
756
757 //move back history (if there is any)
758 for (uint32_t i = p_particles->frame_history.size() - 1; i > 0; i--) {
759 p_particles->frame_history[i] = p_particles->frame_history[i - 1];
760 }
761 //update current frame
762 ParticlesFrameParams &frame_params = p_particles->frame_history[0];
763
764 if (p_particles->clear) {
765 p_particles->cycle_number = 0;
766 p_particles->random_seed = Math::rand();
767 } else if (new_phase < p_particles->phase) {
768 if (p_particles->one_shot) {
769 p_particles->emitting = false;
770 }
771 p_particles->cycle_number++;
772 }
773
774 frame_params.emitting = p_particles->emitting;
775 frame_params.system_phase = new_phase;
776 frame_params.prev_system_phase = p_particles->phase;
777
778 p_particles->phase = new_phase;
779
780 frame_params.time = RendererCompositorRD::get_singleton()->get_total_time();
781 frame_params.delta = p_delta * p_particles->speed_scale;
782 frame_params.random_seed = p_particles->random_seed;
783 frame_params.explosiveness = p_particles->explosiveness;
784 frame_params.randomness = p_particles->randomness;
785
786 if (p_particles->use_local_coords) {
787 RendererRD::MaterialStorage::store_transform(Transform3D(), frame_params.emission_transform);
788 } else {
789 RendererRD::MaterialStorage::store_transform(p_particles->emission_transform, frame_params.emission_transform);
790 }
791
792 frame_params.cycle = p_particles->cycle_number;
793 frame_params.frame = p_particles->frame_counter++;
794 frame_params.pad0 = 0;
795 frame_params.pad1 = 0;
796 frame_params.pad2 = 0;
797
798 { //collision and attractors
799
800 frame_params.collider_count = 0;
801 frame_params.attractor_count = 0;
802 frame_params.particle_size = p_particles->collision_base_size;
803
804 RID collision_3d_textures[ParticlesFrameParams::MAX_3D_TEXTURES];
805 RID collision_heightmap_texture;
806
807 Transform3D to_particles;
808 if (p_particles->use_local_coords) {
809 to_particles = p_particles->emission_transform.affine_inverse();
810 }
811
812 if (p_particles->has_sdf_collision && RD::get_singleton()->texture_is_valid(p_particles->sdf_collision_texture)) {
813 //2D collision
814
815 Transform2D xform = p_particles->sdf_collision_transform; //will use dotproduct manually so invert beforehand
816
817 if (!p_particles->use_local_coords) {
818 Transform2D emission;
819 emission.columns[0] = Vector2(p_particles->emission_transform.basis.get_column(0).x, p_particles->emission_transform.basis.get_column(0).y);
820 emission.columns[1] = Vector2(p_particles->emission_transform.basis.get_column(1).x, p_particles->emission_transform.basis.get_column(1).y);
821 emission.set_origin(Vector2(p_particles->emission_transform.origin.x, p_particles->emission_transform.origin.y));
822 xform = xform * emission.affine_inverse();
823 }
824
825 Transform2D revert = xform.affine_inverse();
826 frame_params.collider_count = 1;
827 frame_params.colliders[0].transform[0] = xform.columns[0][0];
828 frame_params.colliders[0].transform[1] = xform.columns[0][1];
829 frame_params.colliders[0].transform[2] = 0;
830 frame_params.colliders[0].transform[3] = xform.columns[2][0];
831
832 frame_params.colliders[0].transform[4] = xform.columns[1][0];
833 frame_params.colliders[0].transform[5] = xform.columns[1][1];
834 frame_params.colliders[0].transform[6] = 0;
835 frame_params.colliders[0].transform[7] = xform.columns[2][1];
836
837 frame_params.colliders[0].transform[8] = revert.columns[0][0];
838 frame_params.colliders[0].transform[9] = revert.columns[0][1];
839 frame_params.colliders[0].transform[10] = 0;
840 frame_params.colliders[0].transform[11] = revert.columns[2][0];
841
842 frame_params.colliders[0].transform[12] = revert.columns[1][0];
843 frame_params.colliders[0].transform[13] = revert.columns[1][1];
844 frame_params.colliders[0].transform[14] = 0;
845 frame_params.colliders[0].transform[15] = revert.columns[2][1];
846
847 frame_params.colliders[0].extents[0] = p_particles->sdf_collision_to_screen.size.x;
848 frame_params.colliders[0].extents[1] = p_particles->sdf_collision_to_screen.size.y;
849 frame_params.colliders[0].extents[2] = p_particles->sdf_collision_to_screen.position.x;
850 frame_params.colliders[0].scale = p_particles->sdf_collision_to_screen.position.y;
851 frame_params.colliders[0].texture_index = 0;
852 frame_params.colliders[0].type = ParticlesFrameParams::COLLISION_TYPE_2D_SDF;
853
854 collision_heightmap_texture = p_particles->sdf_collision_texture;
855
856 //replace in all other history frames where used because parameters are no longer valid if screen moves
857 for (ParticlesFrameParams &params : p_particles->frame_history) {
858 if (params.collider_count > 0 && params.colliders[0].type == ParticlesFrameParams::COLLISION_TYPE_2D_SDF) {
859 params.colliders[0] = frame_params.colliders[0];
860 }
861 }
862 }
863
864 uint32_t collision_3d_textures_used = 0;
865 for (const RID &E : p_particles->collisions) {
866 ParticlesCollisionInstance *pci = particles_collision_instance_owner.get_or_null(E);
867 if (!pci || !pci->active) {
868 continue;
869 }
870 ParticlesCollision *pc = particles_collision_owner.get_or_null(pci->collision);
871 ERR_CONTINUE(!pc);
872
873 Transform3D to_collider = pci->transform;
874 if (p_particles->use_local_coords) {
875 to_collider = to_particles * to_collider;
876 }
877 Vector3 scale = to_collider.basis.get_scale();
878 to_collider.basis.orthonormalize();
879
880 if (pc->type <= RS::PARTICLES_COLLISION_TYPE_VECTOR_FIELD_ATTRACT) {
881 //attractor
882 if (frame_params.attractor_count >= ParticlesFrameParams::MAX_ATTRACTORS) {
883 continue;
884 }
885
886 ParticlesFrameParams::Attractor &attr = frame_params.attractors[frame_params.attractor_count];
887
888 RendererRD::MaterialStorage::store_transform(to_collider, attr.transform);
889 attr.strength = pc->attractor_strength;
890 attr.attenuation = pc->attractor_attenuation;
891 attr.directionality = pc->attractor_directionality;
892
893 switch (pc->type) {
894 case RS::PARTICLES_COLLISION_TYPE_SPHERE_ATTRACT: {
895 attr.type = ParticlesFrameParams::ATTRACTOR_TYPE_SPHERE;
896 float radius = pc->radius;
897 radius *= (scale.x + scale.y + scale.z) / 3.0;
898 attr.extents[0] = radius;
899 attr.extents[1] = radius;
900 attr.extents[2] = radius;
901 } break;
902 case RS::PARTICLES_COLLISION_TYPE_BOX_ATTRACT: {
903 attr.type = ParticlesFrameParams::ATTRACTOR_TYPE_BOX;
904 Vector3 extents = pc->extents * scale;
905 attr.extents[0] = extents.x;
906 attr.extents[1] = extents.y;
907 attr.extents[2] = extents.z;
908 } break;
909 case RS::PARTICLES_COLLISION_TYPE_VECTOR_FIELD_ATTRACT: {
910 if (collision_3d_textures_used >= ParticlesFrameParams::MAX_3D_TEXTURES) {
911 continue;
912 }
913 attr.type = ParticlesFrameParams::ATTRACTOR_TYPE_VECTOR_FIELD;
914 Vector3 extents = pc->extents * scale;
915 attr.extents[0] = extents.x;
916 attr.extents[1] = extents.y;
917 attr.extents[2] = extents.z;
918 attr.texture_index = collision_3d_textures_used;
919
920 collision_3d_textures[collision_3d_textures_used] = pc->field_texture;
921 collision_3d_textures_used++;
922 } break;
923 default: {
924 }
925 }
926
927 frame_params.attractor_count++;
928 } else {
929 //collider
930 if (frame_params.collider_count >= ParticlesFrameParams::MAX_COLLIDERS) {
931 continue;
932 }
933
934 ParticlesFrameParams::Collider &col = frame_params.colliders[frame_params.collider_count];
935
936 RendererRD::MaterialStorage::store_transform(to_collider, col.transform);
937 switch (pc->type) {
938 case RS::PARTICLES_COLLISION_TYPE_SPHERE_COLLIDE: {
939 col.type = ParticlesFrameParams::COLLISION_TYPE_SPHERE;
940 float radius = pc->radius;
941 radius *= (scale.x + scale.y + scale.z) / 3.0;
942 col.extents[0] = radius;
943 col.extents[1] = radius;
944 col.extents[2] = radius;
945 } break;
946 case RS::PARTICLES_COLLISION_TYPE_BOX_COLLIDE: {
947 col.type = ParticlesFrameParams::COLLISION_TYPE_BOX;
948 Vector3 extents = pc->extents * scale;
949 col.extents[0] = extents.x;
950 col.extents[1] = extents.y;
951 col.extents[2] = extents.z;
952 } break;
953 case RS::PARTICLES_COLLISION_TYPE_SDF_COLLIDE: {
954 if (collision_3d_textures_used >= ParticlesFrameParams::MAX_3D_TEXTURES) {
955 continue;
956 }
957 col.type = ParticlesFrameParams::COLLISION_TYPE_SDF;
958 Vector3 extents = pc->extents * scale;
959 col.extents[0] = extents.x;
960 col.extents[1] = extents.y;
961 col.extents[2] = extents.z;
962 col.texture_index = collision_3d_textures_used;
963 col.scale = (scale.x + scale.y + scale.z) * 0.333333333333; //non uniform scale non supported
964
965 collision_3d_textures[collision_3d_textures_used] = pc->field_texture;
966 collision_3d_textures_used++;
967 } break;
968 case RS::PARTICLES_COLLISION_TYPE_HEIGHTFIELD_COLLIDE: {
969 if (collision_heightmap_texture != RID()) { //already taken
970 continue;
971 }
972
973 col.type = ParticlesFrameParams::COLLISION_TYPE_HEIGHT_FIELD;
974 Vector3 extents = pc->extents * scale;
975 col.extents[0] = extents.x;
976 col.extents[1] = extents.y;
977 col.extents[2] = extents.z;
978 collision_heightmap_texture = pc->heightfield_texture;
979 } break;
980 default: {
981 }
982 }
983
984 frame_params.collider_count++;
985 }
986 }
987
988 bool different = false;
989 if (collision_3d_textures_used == p_particles->collision_3d_textures_used) {
990 for (int i = 0; i < ParticlesFrameParams::MAX_3D_TEXTURES; i++) {
991 if (p_particles->collision_3d_textures[i] != collision_3d_textures[i]) {
992 different = true;
993 break;
994 }
995 }
996 }
997
998 if (collision_heightmap_texture != p_particles->collision_heightmap_texture) {
999 different = true;
1000 }
1001
1002 bool uniform_set_valid = RD::get_singleton()->uniform_set_is_valid(p_particles->collision_textures_uniform_set);
1003
1004 if (different || !uniform_set_valid) {
1005 if (uniform_set_valid) {
1006 RD::get_singleton()->free(p_particles->collision_textures_uniform_set);
1007 }
1008
1009 Vector<RD::Uniform> uniforms;
1010
1011 {
1012 RD::Uniform u;
1013 u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
1014 u.binding = 0;
1015 for (uint32_t i = 0; i < ParticlesFrameParams::MAX_3D_TEXTURES; i++) {
1016 RID rd_tex;
1017 if (i < collision_3d_textures_used) {
1018 if (TextureStorage::get_singleton()->texture_get_type(collision_3d_textures[i]) == TextureStorage::TYPE_3D) {
1019 rd_tex = TextureStorage::get_singleton()->texture_get_rd_texture(collision_3d_textures[i]);
1020 }
1021 }
1022
1023 if (rd_tex == RID()) {
1024 rd_tex = texture_storage->texture_rd_get_default(TextureStorage::DEFAULT_RD_TEXTURE_3D_WHITE);
1025 }
1026 u.append_id(rd_tex);
1027 }
1028 uniforms.push_back(u);
1029 }
1030 {
1031 RD::Uniform u;
1032 u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
1033 u.binding = 1;
1034 if (collision_heightmap_texture.is_valid()) {
1035 u.append_id(collision_heightmap_texture);
1036 } else {
1037 u.append_id(texture_storage->texture_rd_get_default(TextureStorage::DEFAULT_RD_TEXTURE_BLACK));
1038 }
1039 uniforms.push_back(u);
1040 }
1041 p_particles->collision_textures_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, particles_shader.default_shader_rd, 2);
1042 p_particles->collision_heightmap_texture = collision_heightmap_texture;
1043 }
1044 }
1045
1046 ParticlesShader::PushConstant push_constant;
1047
1048 int process_amount = p_particles->amount;
1049
1050 if (p_particles->trails_enabled && p_particles->trail_bind_poses.size() > 1) {
1051 process_amount *= p_particles->trail_bind_poses.size();
1052 }
1053 push_constant.clear = p_particles->clear;
1054 push_constant.total_particles = p_particles->amount;
1055 push_constant.lifetime = p_particles->lifetime;
1056 push_constant.trail_size = p_particles->trail_params.size();
1057 push_constant.use_fractional_delta = p_particles->fractional_delta;
1058 push_constant.sub_emitter_mode = !p_particles->emitting && p_particles->emission_buffer && (p_particles->emission_buffer->particle_count > 0 || p_particles->force_sub_emit);
1059 push_constant.trail_pass = false;
1060
1061 p_particles->force_sub_emit = false; //reset
1062
1063 Particles *sub_emitter = particles_owner.get_or_null(p_particles->sub_emitter);
1064
1065 if (sub_emitter && sub_emitter->emission_storage_buffer.is_valid()) {
1066 // print_line("updating subemitter buffer");
1067 int32_t zero[4] = { 0, sub_emitter->amount, 0, 0 };
1068 RD::get_singleton()->buffer_update(sub_emitter->emission_storage_buffer, 0, sizeof(uint32_t) * 4, zero);
1069 push_constant.can_emit = true;
1070
1071 if (sub_emitter->emitting) {
1072 sub_emitter->emitting = false;
1073 sub_emitter->clear = true; //will need to clear if it was emitting, sorry
1074 }
1075 //make sure the sub emitter processes particles too
1076 sub_emitter->inactive = false;
1077 sub_emitter->inactive_time = 0;
1078
1079 sub_emitter->force_sub_emit = true;
1080
1081 } else {
1082 push_constant.can_emit = false;
1083 }
1084
1085 if (p_particles->emission_buffer && p_particles->emission_buffer->particle_count) {
1086 RD::get_singleton()->buffer_update(p_particles->emission_storage_buffer, 0, sizeof(uint32_t) * 4 + sizeof(ParticleEmissionBuffer::Data) * p_particles->emission_buffer->particle_count, p_particles->emission_buffer);
1087 p_particles->emission_buffer->particle_count = 0;
1088 }
1089
1090 p_particles->clear = false;
1091
1092 if (p_particles->trail_params.size() > 1) {
1093 //fill the trail params
1094 for (uint32_t i = 0; i < p_particles->trail_params.size(); i++) {
1095 uint32_t src_idx = i * p_particles->frame_history.size() / p_particles->trail_params.size();
1096 p_particles->trail_params[i] = p_particles->frame_history[src_idx];
1097 }
1098 } else {
1099 p_particles->trail_params[0] = p_particles->frame_history[0];
1100 }
1101
1102 RD::get_singleton()->buffer_update(p_particles->frame_params_buffer, 0, sizeof(ParticlesFrameParams) * p_particles->trail_params.size(), p_particles->trail_params.ptr());
1103
1104 ParticleProcessMaterialData *m = static_cast<ParticleProcessMaterialData *>(material_storage->material_get_data(p_particles->process_material, MaterialStorage::SHADER_TYPE_PARTICLES));
1105 if (!m) {
1106 m = static_cast<ParticleProcessMaterialData *>(material_storage->material_get_data(particles_shader.default_material, MaterialStorage::SHADER_TYPE_PARTICLES));
1107 }
1108
1109 ERR_FAIL_COND(!m);
1110
1111 p_particles->has_collision_cache = m->shader_data->uses_collision;
1112
1113 //todo should maybe compute all particle systems together?
1114 RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
1115 RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, m->shader_data->pipeline);
1116 RD::get_singleton()->compute_list_bind_uniform_set(compute_list, particles_shader.base_uniform_set, BASE_UNIFORM_SET);
1117 RD::get_singleton()->compute_list_bind_uniform_set(compute_list, p_particles->particles_material_uniform_set, MATERIAL_UNIFORM_SET);
1118 RD::get_singleton()->compute_list_bind_uniform_set(compute_list, p_particles->collision_textures_uniform_set, COLLISION_TEXTURTES_UNIFORM_SET);
1119
1120 if (m->uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(m->uniform_set)) {
1121 RD::get_singleton()->compute_list_bind_uniform_set(compute_list, m->uniform_set, 3);
1122 m->set_as_used();
1123 }
1124
1125 RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(ParticlesShader::PushConstant));
1126
1127 if (p_particles->trails_enabled && p_particles->trail_bind_poses.size() > 1) {
1128 //trails requires two passes in order to catch particle starts
1129 RD::get_singleton()->compute_list_dispatch_threads(compute_list, process_amount / p_particles->trail_bind_poses.size(), 1, 1);
1130
1131 RD::get_singleton()->compute_list_add_barrier(compute_list);
1132
1133 push_constant.trail_pass = true;
1134 RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(ParticlesShader::PushConstant));
1135 RD::get_singleton()->compute_list_dispatch_threads(compute_list, process_amount - p_particles->amount, 1, 1);
1136 } else {
1137 RD::get_singleton()->compute_list_dispatch_threads(compute_list, process_amount, 1, 1);
1138 }
1139
1140 RD::get_singleton()->compute_list_end();
1141}
1142
1143void ParticlesStorage::particles_set_view_axis(RID p_particles, const Vector3 &p_axis, const Vector3 &p_up_axis) {
1144 Particles *particles = particles_owner.get_or_null(p_particles);
1145 ERR_FAIL_COND(!particles);
1146
1147 if (particles->draw_order != RS::PARTICLES_DRAW_ORDER_VIEW_DEPTH && particles->transform_align != RS::PARTICLES_TRANSFORM_ALIGN_Z_BILLBOARD && particles->transform_align != RS::PARTICLES_TRANSFORM_ALIGN_Z_BILLBOARD_Y_TO_VELOCITY) {
1148 return;
1149 }
1150
1151 if (particles->particle_buffer.is_null() || particles->trail_bind_pose_uniform_set.is_null()) {
1152 return; //particles have not processed yet
1153 }
1154
1155 bool do_sort = particles->draw_order == RS::PARTICLES_DRAW_ORDER_VIEW_DEPTH;
1156
1157 //copy to sort buffer
1158 if (do_sort && particles->particles_sort_buffer == RID()) {
1159 uint32_t size = particles->amount;
1160 if (size & 1) {
1161 size++; //make multiple of 16
1162 }
1163 size *= sizeof(float) * 2;
1164 particles->particles_sort_buffer = RD::get_singleton()->storage_buffer_create(size);
1165
1166 {
1167 Vector<RD::Uniform> uniforms;
1168
1169 {
1170 RD::Uniform u;
1171 u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
1172 u.binding = 0;
1173 u.append_id(particles->particles_sort_buffer);
1174 uniforms.push_back(u);
1175 }
1176
1177 particles->particles_sort_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, particles_shader.copy_shader.version_get_shader(particles_shader.copy_shader_version, ParticlesShader::COPY_MODE_FILL_SORT_BUFFER), 1);
1178 }
1179 }
1180
1181 ParticlesShader::CopyPushConstant copy_push_constant;
1182
1183 if (particles->trails_enabled && particles->trail_bind_poses.size() > 1) {
1184 int fixed_fps = 60.0;
1185 if (particles->fixed_fps > 0) {
1186 fixed_fps = particles->fixed_fps;
1187 }
1188
1189 copy_push_constant.trail_size = particles->trail_bind_poses.size();
1190 copy_push_constant.trail_total = particles->frame_history.size();
1191 copy_push_constant.frame_delta = 1.0 / fixed_fps;
1192 } else {
1193 copy_push_constant.trail_size = 1;
1194 copy_push_constant.trail_total = 1;
1195 copy_push_constant.frame_delta = 0.0;
1196 }
1197
1198 copy_push_constant.order_by_lifetime = (particles->draw_order == RS::PARTICLES_DRAW_ORDER_LIFETIME || particles->draw_order == RS::PARTICLES_DRAW_ORDER_REVERSE_LIFETIME);
1199 copy_push_constant.lifetime_split = (MIN(int(particles->amount * particles->phase), particles->amount - 1) + 1) % particles->amount;
1200 copy_push_constant.lifetime_reverse = particles->draw_order == RS::PARTICLES_DRAW_ORDER_REVERSE_LIFETIME;
1201 copy_push_constant.motion_vectors_current_offset = particles->instance_motion_vectors_current_offset;
1202
1203 copy_push_constant.frame_remainder = particles->interpolate ? particles->frame_remainder : 0.0;
1204 copy_push_constant.total_particles = particles->amount;
1205 copy_push_constant.copy_mode_2d = false;
1206
1207 Vector3 axis = -p_axis; // cameras look to z negative
1208
1209 if (particles->use_local_coords) {
1210 axis = particles->emission_transform.basis.xform_inv(axis).normalized();
1211 }
1212
1213 copy_push_constant.sort_direction[0] = axis.x;
1214 copy_push_constant.sort_direction[1] = axis.y;
1215 copy_push_constant.sort_direction[2] = axis.z;
1216
1217 copy_push_constant.align_up[0] = p_up_axis.x;
1218 copy_push_constant.align_up[1] = p_up_axis.y;
1219 copy_push_constant.align_up[2] = p_up_axis.z;
1220
1221 copy_push_constant.align_mode = particles->transform_align;
1222
1223 if (do_sort) {
1224 RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
1225
1226 RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, particles_shader.copy_pipelines[ParticlesShader::COPY_MODE_FILL_SORT_BUFFER + particles->userdata_count * ParticlesShader::COPY_MODE_MAX]);
1227 RD::get_singleton()->compute_list_bind_uniform_set(compute_list, particles->particles_copy_uniform_set, 0);
1228 RD::get_singleton()->compute_list_bind_uniform_set(compute_list, particles->particles_sort_uniform_set, 1);
1229 RD::get_singleton()->compute_list_bind_uniform_set(compute_list, particles->trail_bind_pose_uniform_set, 2);
1230 RD::get_singleton()->compute_list_set_push_constant(compute_list, &copy_push_constant, sizeof(ParticlesShader::CopyPushConstant));
1231
1232 RD::get_singleton()->compute_list_dispatch_threads(compute_list, particles->amount, 1, 1);
1233
1234 RD::get_singleton()->compute_list_end();
1235 sort_effects->sort_buffer(particles->particles_sort_uniform_set, particles->amount);
1236 }
1237
1238 if (particles->trails_enabled && particles->trail_bind_poses.size() > 1) {
1239 copy_push_constant.total_particles *= particles->trail_bind_poses.size();
1240 }
1241
1242 RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
1243 uint32_t copy_pipeline = do_sort ? ParticlesShader::COPY_MODE_FILL_INSTANCES_WITH_SORT_BUFFER : ParticlesShader::COPY_MODE_FILL_INSTANCES;
1244 copy_pipeline += particles->userdata_count * ParticlesShader::COPY_MODE_MAX;
1245 copy_push_constant.copy_mode_2d = particles->mode == RS::PARTICLES_MODE_2D ? 1 : 0;
1246 RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, particles_shader.copy_pipelines[copy_pipeline]);
1247 RD::get_singleton()->compute_list_bind_uniform_set(compute_list, particles->particles_copy_uniform_set, 0);
1248 if (do_sort) {
1249 RD::get_singleton()->compute_list_bind_uniform_set(compute_list, particles->particles_sort_uniform_set, 1);
1250 }
1251 RD::get_singleton()->compute_list_bind_uniform_set(compute_list, particles->trail_bind_pose_uniform_set, 2);
1252
1253 RD::get_singleton()->compute_list_set_push_constant(compute_list, &copy_push_constant, sizeof(ParticlesShader::CopyPushConstant));
1254
1255 RD::get_singleton()->compute_list_dispatch_threads(compute_list, copy_push_constant.total_particles, 1, 1);
1256
1257 RD::get_singleton()->compute_list_end();
1258}
1259
1260void ParticlesStorage::_particles_update_buffers(Particles *particles) {
1261 uint32_t userdata_count = 0;
1262
1263 MaterialStorage::ShaderData *shader_data = MaterialStorage::get_singleton()->material_get_shader_data(particles->process_material);
1264 if (shader_data) {
1265 const ParticlesShaderData *particle_shader_data = static_cast<const ParticlesShaderData *>(shader_data);
1266 userdata_count = particle_shader_data->userdata_count;
1267 }
1268
1269 bool uses_motion_vectors = RSG::viewport->get_num_viewports_with_motion_vectors() > 0;
1270 bool index_draw_order = particles->draw_order == RS::ParticlesDrawOrder::PARTICLES_DRAW_ORDER_INDEX;
1271 bool enable_motion_vectors = uses_motion_vectors && index_draw_order && !particles->instance_motion_vectors_enabled;
1272 bool only_instances_changed = false;
1273
1274 if (userdata_count != particles->userdata_count) {
1275 // Mismatch userdata, re-create all buffers.
1276 _particles_free_data(particles);
1277 } else if (enable_motion_vectors) {
1278 // Only motion vectors are required, release the transforms buffer and uniform set.
1279 if (particles->particle_instance_buffer.is_valid()) {
1280 RD::get_singleton()->free(particles->particle_instance_buffer);
1281 particles->particle_instance_buffer = RID();
1282 }
1283
1284 particles->particles_transforms_buffer_uniform_set = RID();
1285 only_instances_changed = true;
1286 } else if (!particles->particle_buffer.is_null()) {
1287 // No operation is required because a buffer already exists, return early.
1288 return;
1289 }
1290
1291 if (particles->amount > 0) {
1292 int total_amount = particles->amount;
1293 if (particles->trails_enabled && particles->trail_bind_poses.size() > 1) {
1294 total_amount *= particles->trail_bind_poses.size();
1295 }
1296
1297 uint32_t xform_size = particles->mode == RS::PARTICLES_MODE_2D ? 2 : 3;
1298 if (particles->particle_buffer.is_null()) {
1299 particles->particle_buffer = RD::get_singleton()->storage_buffer_create((sizeof(ParticleData) + userdata_count * sizeof(float) * 4) * total_amount);
1300 particles->userdata_count = userdata_count;
1301 }
1302
1303 PackedByteArray data;
1304 uint32_t particle_instance_buffer_size = total_amount * (xform_size + 1 + 1) * sizeof(float) * 4;
1305 if (uses_motion_vectors) {
1306 particle_instance_buffer_size *= 2;
1307 particles->instance_motion_vectors_enabled = true;
1308 }
1309
1310 data.resize_zeroed(particle_instance_buffer_size);
1311
1312 particles->particle_instance_buffer = RD::get_singleton()->storage_buffer_create(particle_instance_buffer_size, data);
1313
1314 {
1315 Vector<RD::Uniform> uniforms;
1316
1317 {
1318 RD::Uniform u;
1319 u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
1320 u.binding = 1;
1321 u.append_id(particles->particle_buffer);
1322 uniforms.push_back(u);
1323 }
1324 {
1325 RD::Uniform u;
1326 u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
1327 u.binding = 2;
1328 u.append_id(particles->particle_instance_buffer);
1329 uniforms.push_back(u);
1330 }
1331
1332 particles->particles_copy_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, particles_shader.copy_shader.version_get_shader(particles_shader.copy_shader_version, 0), 0);
1333 }
1334
1335 particles->instance_motion_vectors_current_offset = 0;
1336 particles->instance_motion_vectors_previous_offset = 0;
1337 particles->instance_motion_vectors_last_change = -1;
1338
1339 if (only_instances_changed) {
1340 // Notify the renderer the instances uniform must be retrieved again, as it's the only element that has been changed because motion vectors were enabled.
1341 particles->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_PARTICLES_INSTANCES);
1342 }
1343 }
1344}
1345void ParticlesStorage::update_particles() {
1346 uint32_t frame = RSG::rasterizer->get_frame_number();
1347 bool uses_motion_vectors = RSG::viewport->get_num_viewports_with_motion_vectors() > 0;
1348 while (particle_update_list) {
1349 //use transform feedback to process particles
1350
1351 Particles *particles = particle_update_list;
1352
1353 //take and remove
1354 particle_update_list = particles->update_list;
1355 particles->update_list = nullptr;
1356 particles->dirty = false;
1357
1358 _particles_update_buffers(particles);
1359
1360 if (particles->restart_request) {
1361 particles->prev_ticks = 0;
1362 particles->phase = 0;
1363 particles->prev_phase = 0;
1364 particles->clear = true;
1365 particles->restart_request = false;
1366 }
1367
1368 if (particles->inactive && !particles->emitting) {
1369 //go next
1370 continue;
1371 }
1372
1373 if (particles->emitting) {
1374 if (particles->inactive) {
1375 //restart system from scratch
1376 particles->prev_ticks = 0;
1377 particles->phase = 0;
1378 particles->prev_phase = 0;
1379 particles->clear = true;
1380 }
1381 particles->inactive = false;
1382 particles->inactive_time = 0;
1383 } else {
1384 particles->inactive_time += particles->speed_scale * RendererCompositorRD::get_singleton()->get_frame_delta_time();
1385 if (particles->inactive_time > particles->lifetime * 1.2) {
1386 particles->inactive = true;
1387 continue;
1388 }
1389 }
1390
1391 // TODO: Should use display refresh rate for all this.
1392 float screen_hz = 60;
1393
1394 int fixed_fps = 0;
1395 if (particles->fixed_fps > 0) {
1396 fixed_fps = particles->fixed_fps;
1397 } else if (particles->trails_enabled && particles->trail_bind_poses.size() > 1) {
1398 fixed_fps = screen_hz;
1399 }
1400 {
1401 //update trails
1402 int history_size = 1;
1403 int trail_steps = 1;
1404 if (particles->trails_enabled && particles->trail_bind_poses.size() > 1) {
1405 history_size = MAX(1, int(particles->trail_lifetime * fixed_fps));
1406 trail_steps = particles->trail_bind_poses.size();
1407 }
1408
1409 if (uint32_t(history_size) != particles->frame_history.size()) {
1410 particles->frame_history.resize(history_size);
1411 memset(particles->frame_history.ptr(), 0, sizeof(ParticlesFrameParams) * history_size);
1412 }
1413
1414 if (uint32_t(trail_steps) != particles->trail_params.size() || particles->frame_params_buffer.is_null()) {
1415 particles->trail_params.resize(trail_steps);
1416 if (particles->frame_params_buffer.is_valid()) {
1417 RD::get_singleton()->free(particles->frame_params_buffer);
1418 }
1419 particles->frame_params_buffer = RD::get_singleton()->storage_buffer_create(sizeof(ParticlesFrameParams) * trail_steps);
1420 }
1421
1422 if (particles->trail_bind_poses.size() > 1 && particles->trail_bind_pose_buffer.is_null()) {
1423 particles->trail_bind_pose_buffer = RD::get_singleton()->storage_buffer_create(sizeof(float) * 16 * particles->trail_bind_poses.size());
1424 particles->trail_bind_poses_dirty = true;
1425 }
1426
1427 if (particles->trail_bind_pose_uniform_set.is_null()) {
1428 Vector<RD::Uniform> uniforms;
1429 {
1430 RD::Uniform u;
1431 u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
1432 u.binding = 0;
1433 if (particles->trail_bind_pose_buffer.is_valid()) {
1434 u.append_id(particles->trail_bind_pose_buffer);
1435 } else {
1436 u.append_id(MeshStorage::get_singleton()->get_default_rd_storage_buffer());
1437 }
1438 uniforms.push_back(u);
1439 }
1440
1441 particles->trail_bind_pose_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, particles_shader.copy_shader.version_get_shader(particles_shader.copy_shader_version, 0), 2);
1442 }
1443
1444 if (particles->trail_bind_pose_buffer.is_valid() && particles->trail_bind_poses_dirty) {
1445 if (particles_shader.pose_update_buffer.size() < uint32_t(particles->trail_bind_poses.size()) * 16) {
1446 particles_shader.pose_update_buffer.resize(particles->trail_bind_poses.size() * 16);
1447 }
1448
1449 for (int i = 0; i < particles->trail_bind_poses.size(); i++) {
1450 RendererRD::MaterialStorage::store_transform(particles->trail_bind_poses[i], &particles_shader.pose_update_buffer[i * 16]);
1451 }
1452
1453 RD::get_singleton()->buffer_update(particles->trail_bind_pose_buffer, 0, particles->trail_bind_poses.size() * 16 * sizeof(float), particles_shader.pose_update_buffer.ptr());
1454 }
1455 }
1456
1457 bool zero_time_scale = Engine::get_singleton()->get_time_scale() <= 0.0;
1458
1459 if (particles->clear && particles->pre_process_time > 0.0) {
1460 double frame_time;
1461 if (fixed_fps > 0) {
1462 frame_time = 1.0 / fixed_fps;
1463 } else {
1464 frame_time = 1.0 / 30.0;
1465 }
1466
1467 double todo = particles->pre_process_time;
1468
1469 while (todo >= 0) {
1470 _particles_process(particles, frame_time);
1471 todo -= frame_time;
1472 }
1473 }
1474
1475 if (fixed_fps > 0) {
1476 double frame_time;
1477 double decr;
1478 if (zero_time_scale) {
1479 frame_time = 0.0;
1480 decr = 1.0 / fixed_fps;
1481 } else {
1482 frame_time = 1.0 / fixed_fps;
1483 decr = frame_time;
1484 }
1485 double delta = RendererCompositorRD::get_singleton()->get_frame_delta_time();
1486 if (delta > 0.1) { //avoid recursive stalls if fps goes below 10
1487 delta = 0.1;
1488 } else if (delta <= 0.0) { //unlikely but..
1489 delta = 0.001;
1490 }
1491 double todo = particles->frame_remainder + delta;
1492
1493 while (todo >= frame_time || particles->clear) {
1494 _particles_process(particles, frame_time);
1495 todo -= decr;
1496 }
1497
1498 particles->frame_remainder = todo;
1499
1500 } else {
1501 if (zero_time_scale) {
1502 _particles_process(particles, 0.0);
1503 } else {
1504 _particles_process(particles, RendererCompositorRD::get_singleton()->get_frame_delta_time());
1505 }
1506 }
1507
1508 // Ensure that memory is initialized (the code above should ensure that _particles_process is always called at least once upon clearing).
1509 DEV_ASSERT(!particles->clear);
1510
1511 int total_amount = particles->amount;
1512 if (particles->trails_enabled && particles->trail_bind_poses.size() > 1) {
1513 total_amount *= particles->trail_bind_poses.size();
1514 }
1515
1516 // Swap offsets for motion vectors. Motion vectors can only be used when the draw order keeps the indices consistent across frames.
1517 bool index_draw_order = particles->draw_order == RS::ParticlesDrawOrder::PARTICLES_DRAW_ORDER_INDEX;
1518 particles->instance_motion_vectors_previous_offset = particles->instance_motion_vectors_current_offset;
1519 if (uses_motion_vectors && index_draw_order && particles->instance_motion_vectors_enabled && (frame - particles->instance_motion_vectors_last_change) == 1) {
1520 particles->instance_motion_vectors_current_offset = total_amount - particles->instance_motion_vectors_current_offset;
1521 }
1522
1523 particles->instance_motion_vectors_last_change = frame;
1524
1525 // Copy particles to instance buffer.
1526 if (particles->draw_order != RS::PARTICLES_DRAW_ORDER_VIEW_DEPTH && particles->transform_align != RS::PARTICLES_TRANSFORM_ALIGN_Z_BILLBOARD && particles->transform_align != RS::PARTICLES_TRANSFORM_ALIGN_Z_BILLBOARD_Y_TO_VELOCITY) {
1527 //does not need view dependent operation, do copy here
1528 ParticlesShader::CopyPushConstant copy_push_constant;
1529
1530 // Affect 2D only.
1531 if (particles->use_local_coords) {
1532 // In local mode, particle positions are calculated locally (relative to the node position)
1533 // and they're also drawn locally.
1534 // It works as expected, so we just pass an identity transform.
1535 RendererRD::MaterialStorage::store_transform(Transform3D(), copy_push_constant.inv_emission_transform);
1536 } else {
1537 // In global mode, particle positions are calculated globally (relative to the canvas origin)
1538 // but they're drawn locally.
1539 // So, we need to pass the inverse of the emission transform to bring the
1540 // particles to local coordinates before drawing.
1541 Transform3D inv = particles->emission_transform.affine_inverse();
1542 RendererRD::MaterialStorage::store_transform(inv, copy_push_constant.inv_emission_transform);
1543 }
1544
1545 copy_push_constant.total_particles = total_amount;
1546 copy_push_constant.frame_remainder = particles->interpolate ? particles->frame_remainder : 0.0;
1547 copy_push_constant.align_mode = particles->transform_align;
1548 copy_push_constant.align_up[0] = 0;
1549 copy_push_constant.align_up[1] = 0;
1550 copy_push_constant.align_up[2] = 0;
1551
1552 if (particles->trails_enabled && particles->trail_bind_poses.size() > 1) {
1553 copy_push_constant.trail_size = particles->trail_bind_poses.size();
1554 copy_push_constant.trail_total = particles->frame_history.size();
1555 copy_push_constant.frame_delta = 1.0 / fixed_fps;
1556 } else {
1557 copy_push_constant.trail_size = 1;
1558 copy_push_constant.trail_total = 1;
1559 copy_push_constant.frame_delta = 0.0;
1560 }
1561
1562 copy_push_constant.order_by_lifetime = (particles->draw_order == RS::PARTICLES_DRAW_ORDER_LIFETIME || particles->draw_order == RS::PARTICLES_DRAW_ORDER_REVERSE_LIFETIME);
1563 copy_push_constant.lifetime_split = (MIN(int(particles->amount * particles->phase), particles->amount - 1) + 1) % particles->amount;
1564 copy_push_constant.lifetime_reverse = particles->draw_order == RS::PARTICLES_DRAW_ORDER_REVERSE_LIFETIME;
1565 copy_push_constant.motion_vectors_current_offset = particles->instance_motion_vectors_current_offset;
1566
1567 RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
1568 copy_push_constant.copy_mode_2d = particles->mode == RS::PARTICLES_MODE_2D ? 1 : 0;
1569 RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, particles_shader.copy_pipelines[ParticlesShader::COPY_MODE_FILL_INSTANCES + particles->userdata_count * ParticlesShader::COPY_MODE_MAX]);
1570 RD::get_singleton()->compute_list_bind_uniform_set(compute_list, particles->particles_copy_uniform_set, 0);
1571 RD::get_singleton()->compute_list_bind_uniform_set(compute_list, particles->trail_bind_pose_uniform_set, 2);
1572 RD::get_singleton()->compute_list_set_push_constant(compute_list, &copy_push_constant, sizeof(ParticlesShader::CopyPushConstant));
1573
1574 RD::get_singleton()->compute_list_dispatch_threads(compute_list, total_amount, 1, 1);
1575
1576 RD::get_singleton()->compute_list_end();
1577 }
1578
1579 particles->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_AABB);
1580 }
1581}
1582
1583Dependency *ParticlesStorage::particles_get_dependency(RID p_particles) const {
1584 Particles *particles = particles_owner.get_or_null(p_particles);
1585 ERR_FAIL_NULL_V(particles, nullptr);
1586
1587 return &particles->dependency;
1588}
1589
1590bool ParticlesStorage::particles_is_inactive(RID p_particles) const {
1591 ERR_FAIL_COND_V_MSG(RSG::threaded, false, "This function should never be used with threaded rendering, as it stalls the renderer.");
1592 const Particles *particles = particles_owner.get_or_null(p_particles);
1593 ERR_FAIL_COND_V(!particles, false);
1594 return !particles->emitting && particles->inactive;
1595}
1596
1597/* Particles SHADER */
1598
1599void ParticlesStorage::ParticlesShaderData::set_code(const String &p_code) {
1600 ParticlesStorage *particles_storage = ParticlesStorage::get_singleton();
1601 //compile
1602
1603 code = p_code;
1604 valid = false;
1605 ubo_size = 0;
1606 uniforms.clear();
1607 uses_collision = false;
1608
1609 if (code.is_empty()) {
1610 return; //just invalid, but no error
1611 }
1612
1613 ShaderCompiler::GeneratedCode gen_code;
1614 ShaderCompiler::IdentifierActions actions;
1615 actions.entry_point_stages["start"] = ShaderCompiler::STAGE_COMPUTE;
1616 actions.entry_point_stages["process"] = ShaderCompiler::STAGE_COMPUTE;
1617
1618 /*
1619 uses_time = false;
1620
1621 actions.render_mode_flags["use_half_res_pass"] = &uses_half_res;
1622 actions.render_mode_flags["use_quarter_res_pass"] = &uses_quarter_res;
1623
1624 actions.usage_flag_pointers["TIME"] = &uses_time;
1625*/
1626
1627 actions.usage_flag_pointers["COLLIDED"] = &uses_collision;
1628
1629 userdata_count = 0;
1630 for (uint32_t i = 0; i < ParticlesShader::MAX_USERDATAS; i++) {
1631 userdatas_used[i] = false;
1632 actions.usage_flag_pointers["USERDATA" + itos(i + 1)] = &userdatas_used[i];
1633 }
1634
1635 actions.uniforms = &uniforms;
1636
1637 Error err = particles_storage->particles_shader.compiler.compile(RS::SHADER_PARTICLES, code, &actions, path, gen_code);
1638 ERR_FAIL_COND_MSG(err != OK, "Shader compilation failed.");
1639
1640 if (version.is_null()) {
1641 version = particles_storage->particles_shader.shader.version_create();
1642 }
1643
1644 for (uint32_t i = 0; i < ParticlesShader::MAX_USERDATAS; i++) {
1645 if (userdatas_used[i]) {
1646 userdata_count++;
1647 }
1648 }
1649
1650 particles_storage->particles_shader.shader.version_set_compute_code(version, gen_code.code, gen_code.uniforms, gen_code.stage_globals[ShaderCompiler::STAGE_COMPUTE], gen_code.defines);
1651 ERR_FAIL_COND(!particles_storage->particles_shader.shader.version_is_valid(version));
1652
1653 ubo_size = gen_code.uniform_total_size;
1654 ubo_offsets = gen_code.uniform_offsets;
1655 texture_uniforms = gen_code.texture_uniforms;
1656
1657 //update pipelines
1658
1659 pipeline = RD::get_singleton()->compute_pipeline_create(particles_storage->particles_shader.shader.version_get_shader(version, 0));
1660
1661 valid = true;
1662}
1663
1664bool ParticlesStorage::ParticlesShaderData::is_animated() const {
1665 return false;
1666}
1667
1668bool ParticlesStorage::ParticlesShaderData::casts_shadows() const {
1669 return false;
1670}
1671
1672RS::ShaderNativeSourceCode ParticlesStorage::ParticlesShaderData::get_native_source_code() const {
1673 return ParticlesStorage::get_singleton()->particles_shader.shader.version_get_native_source_code(version);
1674}
1675
1676ParticlesStorage::ParticlesShaderData::~ParticlesShaderData() {
1677 //pipeline variants will clear themselves if shader is gone
1678 if (version.is_valid()) {
1679 ParticlesStorage::get_singleton()->particles_shader.shader.version_free(version);
1680 }
1681}
1682
1683MaterialStorage::ShaderData *ParticlesStorage::_create_particles_shader_func() {
1684 ParticlesShaderData *shader_data = memnew(ParticlesShaderData);
1685 return shader_data;
1686}
1687
1688bool ParticlesStorage::ParticleProcessMaterialData::update_parameters(const HashMap<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) {
1689 return update_parameters_uniform_set(p_parameters, p_uniform_dirty, p_textures_dirty, shader_data->uniforms, shader_data->ubo_offsets.ptr(), shader_data->texture_uniforms, shader_data->default_texture_params, shader_data->ubo_size, uniform_set, ParticlesStorage::get_singleton()->particles_shader.shader.version_get_shader(shader_data->version, 0), 3, true, false);
1690}
1691
1692ParticlesStorage::ParticleProcessMaterialData::~ParticleProcessMaterialData() {
1693 free_parameters_uniform_set(uniform_set);
1694}
1695
1696MaterialStorage::MaterialData *ParticlesStorage::_create_particles_material_func(ParticlesShaderData *p_shader) {
1697 ParticleProcessMaterialData *material_data = memnew(ParticleProcessMaterialData);
1698 material_data->shader_data = p_shader;
1699 //update will happen later anyway so do nothing.
1700 return material_data;
1701}
1702////////
1703
1704/* PARTICLES COLLISION API */
1705
1706RID ParticlesStorage::particles_collision_allocate() {
1707 return particles_collision_owner.allocate_rid();
1708}
1709void ParticlesStorage::particles_collision_initialize(RID p_rid) {
1710 particles_collision_owner.initialize_rid(p_rid, ParticlesCollision());
1711}
1712
1713void ParticlesStorage::particles_collision_free(RID p_rid) {
1714 ParticlesCollision *particles_collision = particles_collision_owner.get_or_null(p_rid);
1715
1716 if (particles_collision->heightfield_texture.is_valid()) {
1717 RD::get_singleton()->free(particles_collision->heightfield_texture);
1718 }
1719 particles_collision->dependency.deleted_notify(p_rid);
1720 particles_collision_owner.free(p_rid);
1721}
1722
1723RID ParticlesStorage::particles_collision_get_heightfield_framebuffer(RID p_particles_collision) const {
1724 ParticlesCollision *particles_collision = particles_collision_owner.get_or_null(p_particles_collision);
1725 ERR_FAIL_COND_V(!particles_collision, RID());
1726 ERR_FAIL_COND_V(particles_collision->type != RS::PARTICLES_COLLISION_TYPE_HEIGHTFIELD_COLLIDE, RID());
1727
1728 if (particles_collision->heightfield_texture == RID()) {
1729 //create
1730 const int resolutions[RS::PARTICLES_COLLISION_HEIGHTFIELD_RESOLUTION_MAX] = { 256, 512, 1024, 2048, 4096, 8192 };
1731 Size2i size;
1732 if (particles_collision->extents.x > particles_collision->extents.z) {
1733 size.x = resolutions[particles_collision->heightfield_resolution];
1734 size.y = int32_t(particles_collision->extents.z / particles_collision->extents.x * size.x);
1735 } else {
1736 size.y = resolutions[particles_collision->heightfield_resolution];
1737 size.x = int32_t(particles_collision->extents.x / particles_collision->extents.z * size.y);
1738 }
1739
1740 RD::TextureFormat tf;
1741 tf.format = RD::DATA_FORMAT_D32_SFLOAT;
1742 tf.width = size.x;
1743 tf.height = size.y;
1744 tf.texture_type = RD::TEXTURE_TYPE_2D;
1745 tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
1746
1747 particles_collision->heightfield_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
1748
1749 Vector<RID> fb_tex;
1750 fb_tex.push_back(particles_collision->heightfield_texture);
1751 particles_collision->heightfield_fb = RD::get_singleton()->framebuffer_create(fb_tex);
1752 particles_collision->heightfield_fb_size = size;
1753 }
1754
1755 return particles_collision->heightfield_fb;
1756}
1757
1758void ParticlesStorage::particles_collision_set_collision_type(RID p_particles_collision, RS::ParticlesCollisionType p_type) {
1759 ParticlesCollision *particles_collision = particles_collision_owner.get_or_null(p_particles_collision);
1760 ERR_FAIL_COND(!particles_collision);
1761
1762 if (p_type == particles_collision->type) {
1763 return;
1764 }
1765
1766 if (particles_collision->heightfield_texture.is_valid()) {
1767 RD::get_singleton()->free(particles_collision->heightfield_texture);
1768 particles_collision->heightfield_texture = RID();
1769 }
1770 particles_collision->type = p_type;
1771 particles_collision->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_AABB);
1772}
1773
1774void ParticlesStorage::particles_collision_set_cull_mask(RID p_particles_collision, uint32_t p_cull_mask) {
1775 ParticlesCollision *particles_collision = particles_collision_owner.get_or_null(p_particles_collision);
1776 ERR_FAIL_COND(!particles_collision);
1777 particles_collision->cull_mask = p_cull_mask;
1778}
1779
1780void ParticlesStorage::particles_collision_set_sphere_radius(RID p_particles_collision, real_t p_radius) {
1781 ParticlesCollision *particles_collision = particles_collision_owner.get_or_null(p_particles_collision);
1782 ERR_FAIL_COND(!particles_collision);
1783
1784 particles_collision->radius = p_radius;
1785 particles_collision->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_AABB);
1786}
1787
1788void ParticlesStorage::particles_collision_set_box_extents(RID p_particles_collision, const Vector3 &p_extents) {
1789 ParticlesCollision *particles_collision = particles_collision_owner.get_or_null(p_particles_collision);
1790 ERR_FAIL_COND(!particles_collision);
1791
1792 particles_collision->extents = p_extents;
1793 particles_collision->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_AABB);
1794}
1795
1796void ParticlesStorage::particles_collision_set_attractor_strength(RID p_particles_collision, real_t p_strength) {
1797 ParticlesCollision *particles_collision = particles_collision_owner.get_or_null(p_particles_collision);
1798 ERR_FAIL_COND(!particles_collision);
1799
1800 particles_collision->attractor_strength = p_strength;
1801}
1802
1803void ParticlesStorage::particles_collision_set_attractor_directionality(RID p_particles_collision, real_t p_directionality) {
1804 ParticlesCollision *particles_collision = particles_collision_owner.get_or_null(p_particles_collision);
1805 ERR_FAIL_COND(!particles_collision);
1806
1807 particles_collision->attractor_directionality = p_directionality;
1808}
1809
1810void ParticlesStorage::particles_collision_set_attractor_attenuation(RID p_particles_collision, real_t p_curve) {
1811 ParticlesCollision *particles_collision = particles_collision_owner.get_or_null(p_particles_collision);
1812 ERR_FAIL_COND(!particles_collision);
1813
1814 particles_collision->attractor_attenuation = p_curve;
1815}
1816
1817void ParticlesStorage::particles_collision_set_field_texture(RID p_particles_collision, RID p_texture) {
1818 ParticlesCollision *particles_collision = particles_collision_owner.get_or_null(p_particles_collision);
1819 ERR_FAIL_COND(!particles_collision);
1820
1821 particles_collision->field_texture = p_texture;
1822}
1823
1824void ParticlesStorage::particles_collision_height_field_update(RID p_particles_collision) {
1825 ParticlesCollision *particles_collision = particles_collision_owner.get_or_null(p_particles_collision);
1826 ERR_FAIL_COND(!particles_collision);
1827 particles_collision->dependency.changed_notify(Dependency::DEPENDENCY_CHANGED_AABB);
1828}
1829
1830void ParticlesStorage::particles_collision_set_height_field_resolution(RID p_particles_collision, RS::ParticlesCollisionHeightfieldResolution p_resolution) {
1831 ParticlesCollision *particles_collision = particles_collision_owner.get_or_null(p_particles_collision);
1832 ERR_FAIL_COND(!particles_collision);
1833 ERR_FAIL_INDEX(p_resolution, RS::PARTICLES_COLLISION_HEIGHTFIELD_RESOLUTION_MAX);
1834
1835 if (particles_collision->heightfield_resolution == p_resolution) {
1836 return;
1837 }
1838
1839 particles_collision->heightfield_resolution = p_resolution;
1840
1841 if (particles_collision->heightfield_texture.is_valid()) {
1842 RD::get_singleton()->free(particles_collision->heightfield_texture);
1843 particles_collision->heightfield_texture = RID();
1844 }
1845}
1846
1847AABB ParticlesStorage::particles_collision_get_aabb(RID p_particles_collision) const {
1848 ParticlesCollision *particles_collision = particles_collision_owner.get_or_null(p_particles_collision);
1849 ERR_FAIL_COND_V(!particles_collision, AABB());
1850
1851 switch (particles_collision->type) {
1852 case RS::PARTICLES_COLLISION_TYPE_SPHERE_ATTRACT:
1853 case RS::PARTICLES_COLLISION_TYPE_SPHERE_COLLIDE: {
1854 AABB aabb;
1855 aabb.position = -Vector3(1, 1, 1) * particles_collision->radius;
1856 aabb.size = Vector3(2, 2, 2) * particles_collision->radius;
1857 return aabb;
1858 }
1859 default: {
1860 AABB aabb;
1861 aabb.position = -particles_collision->extents;
1862 aabb.size = particles_collision->extents * 2;
1863 return aabb;
1864 }
1865 }
1866}
1867
1868Vector3 ParticlesStorage::particles_collision_get_extents(RID p_particles_collision) const {
1869 const ParticlesCollision *particles_collision = particles_collision_owner.get_or_null(p_particles_collision);
1870 ERR_FAIL_COND_V(!particles_collision, Vector3());
1871 return particles_collision->extents;
1872}
1873
1874bool ParticlesStorage::particles_collision_is_heightfield(RID p_particles_collision) const {
1875 const ParticlesCollision *particles_collision = particles_collision_owner.get_or_null(p_particles_collision);
1876 ERR_FAIL_COND_V(!particles_collision, false);
1877 return particles_collision->type == RS::PARTICLES_COLLISION_TYPE_HEIGHTFIELD_COLLIDE;
1878}
1879
1880Dependency *ParticlesStorage::particles_collision_get_dependency(RID p_particles_collision) const {
1881 ParticlesCollision *pc = particles_collision_owner.get_or_null(p_particles_collision);
1882 ERR_FAIL_NULL_V(pc, nullptr);
1883
1884 return &pc->dependency;
1885}
1886
1887/* Particles collision instance */
1888
1889RID ParticlesStorage::particles_collision_instance_create(RID p_collision) {
1890 ParticlesCollisionInstance pci;
1891 pci.collision = p_collision;
1892 return particles_collision_instance_owner.make_rid(pci);
1893}
1894
1895void ParticlesStorage::particles_collision_instance_free(RID p_rid) {
1896 particles_collision_instance_owner.free(p_rid);
1897}
1898
1899void ParticlesStorage::particles_collision_instance_set_transform(RID p_collision_instance, const Transform3D &p_transform) {
1900 ParticlesCollisionInstance *pci = particles_collision_instance_owner.get_or_null(p_collision_instance);
1901 ERR_FAIL_COND(!pci);
1902 pci->transform = p_transform;
1903}
1904
1905void ParticlesStorage::particles_collision_instance_set_active(RID p_collision_instance, bool p_active) {
1906 ParticlesCollisionInstance *pci = particles_collision_instance_owner.get_or_null(p_collision_instance);
1907 ERR_FAIL_COND(!pci);
1908 pci->active = p_active;
1909}
1910