Blender V5.3
particle_system.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2007 Janne Karhu. All rights reserved.
2 * SPDX-FileCopyrightText: 2011-2012 AutoCRC (adaptive time step, Classical SPH).
3 *
4 * SPDX-License-Identifier: GPL-2.0-or-later */
5
9
10#include <algorithm>
11#include <cmath>
12#include <cstddef>
13#include <cstdlib>
14#include <cstring>
15
16#include "MEM_guardedalloc.h"
17
18#include "DNA_boid_types.h"
19#include "DNA_cloth_types.h"
20#include "DNA_listBase.h"
21#include "DNA_mesh_types.h"
22#include "DNA_meshdata_types.h"
23#include "DNA_modifier_types.h"
25#include "DNA_object_types.h"
26#include "DNA_particle_types.h"
27#include "DNA_scene_types.h"
28#include "DNA_texture_types.h"
29
30#include "BLI_kdopbvh.hh"
31#include "BLI_kdtree.hh"
32#include "BLI_linklist.hh"
33#include "BLI_listbase.hh"
34#include "BLI_math_base_safe.hh"
35#include "BLI_math_matrix_c.hh"
37#include "BLI_math_vector_c.hh"
38#include "BLI_rand_c.hh"
39#include "BLI_string.hh"
40#include "BLI_string_utils.hh"
41#include "BLI_task_c.hh"
42#include "BLI_threads.hh"
43#include "BLI_utildefines.hh"
44#include "BLI_vector.hh"
45
46#include "BKE_animsys.hh"
47#include "BKE_boids.h"
48#include "BKE_collision.h"
49#include "BKE_colortools.hh"
50#include "BKE_customdata.hh"
51#include "BKE_effect.h"
52#include "BKE_lib_id.hh"
53#include "BKE_lib_query.hh"
55#include "BKE_particle.h"
56
57#include "BKE_cloth.hh"
58#include "BKE_material.hh"
59#include "BKE_mesh.hh"
60#include "BKE_modifier.hh"
61#include "BKE_object.hh"
62#include "BKE_pointcache.h"
63#include "BKE_scene.hh"
64
65#include "DEG_depsgraph.hh"
67
68/* FLUID sim particle import */
69#ifdef WITH_FLUID
70# include "DNA_fluid_types.h"
71# include "manta_fluid_API.h"
72#endif // WITH_FLUID
73
74namespace blender {
75
77
78/* -------------------------------------------------------------------- */
81
83{
84 if (psys->pointcache->flag & PTCACHE_BAKED) {
85 return 0;
86 }
87
88 if (psys->part->type == PART_HAIR) {
89 return psys->flag & PSYS_HAIR_DYNAMICS;
90 }
91
93}
94
95float psys_get_current_display_percentage(ParticleSystem *psys, const bool use_render_params)
96{
97 ParticleSettings *part = psys->part;
98
99 if ((use_render_params &&
100 !particles_are_dynamic(psys)) || /* non-dynamic particles can be rendered fully */
101 (part->child_percent && part->childtype) || /* display percentage applies to children */
102 (psys->pointcache->flag & PTCACHE_BAKING)) /* baking is always done with full amount */
103 {
104 return 1.0f;
105 }
106
107 return psys->part->disp / 100.0f;
108}
109
111{
112 if (pid && psys->pointcache->flag & PTCACHE_EXTERNAL) {
113 return pid->cache->totpoint;
114 }
115 if (psys->part->distr == PART_DISTR_GRID && psys->part->from != PART_FROM_VERT) {
116 return psys->part->grid_res * psys->part->grid_res * psys->part->grid_res - psys->totunexist;
117 }
118
119 return psys->part->totpart - psys->totunexist;
120}
121
122void psys_reset(ParticleSystem *psys, int mode)
123{
125
127 if (mode == PSYS_RESET_ALL || !(psys->flag & PSYS_EDITED)) {
128 /* don't free if not absolutely necessary */
129 if (psys->totpart != tot_particles(psys, nullptr)) {
131 psys->totpart = 0;
132 }
133
134 psys->totkeyed = 0;
135 psys->flag &= ~(PSYS_HAIR_DONE | PSYS_KEYED);
136
137 if (psys->edit && psys->free_edit) {
138 psys->free_edit(psys->edit);
139 psys->edit = nullptr;
140 psys->free_edit = nullptr;
141 }
142 }
143 }
144 else if (mode == PSYS_RESET_CACHE_MISS) {
145 /* set all particles to be skipped */
147 {
148 pa->flag |= PARS_NO_DISP;
149 }
150 }
151
152 /* reset children */
153 MEM_SAFE_DELETE(psys->child);
154
155 psys->totchild = 0;
156
157 /* reset path cache */
158 psys_free_path_cache(psys, psys->edit);
159
160 /* reset point cache */
162
163 MEM_SAFE_DELETE(psys->fluid_springs);
164
165 psys->tot_fluidsprings = psys->alloc_fluidsprings = 0;
166}
167
168void psys_unique_name(Object *object, ParticleSystem *psys, const char *defname)
169{
170 BLI_uniquename(&object->particlesystem,
171 psys,
172 defname,
173 '.',
175 sizeof(psys->name));
176}
177
178static void realloc_particles(ParticleSimulationData *sim, int new_totpart)
179{
180 ParticleSystem *psys = sim->psys;
181 ParticleSettings *part = psys->part;
182 ParticleData *newpars = nullptr;
183 BoidParticle *newboids = nullptr;
185 int totpart, totsaved = 0;
186
187 if (new_totpart < 0) {
188 if ((part->distr == PART_DISTR_GRID) && (part->from != PART_FROM_VERT)) {
189 totpart = part->grid_res;
190 totpart *= totpart * totpart;
191 }
192 else {
193 totpart = part->totpart;
194 }
195 }
196 else {
197 totpart = new_totpart;
198 }
199
200 if (totpart != psys->totpart) {
201 if (psys->edit && psys->free_edit) {
202 psys->free_edit(psys->edit);
203 psys->edit = nullptr;
204 psys->free_edit = nullptr;
205 }
206
207 if (totpart) {
208 newpars = MEM_new_array<ParticleData>(totpart, "particles");
209 if (newpars == nullptr) {
210 return;
211 }
212
213 if (psys->part->phystype == PART_PHYS_BOIDS) {
214 newboids = MEM_new_array<BoidParticle>(totpart, "boid particles");
215
216 if (newboids == nullptr) {
217 /* allocation error! */
218 if (newpars) {
219 MEM_delete(newpars);
220 }
221 return;
222 }
223 }
224 }
225
226 if (psys->particles) {
227 totsaved = std::min(psys->totpart, totpart);
228 /* Save old pars. */
229 if (totsaved) {
230 memcpy(newpars, psys->particles, totsaved * sizeof(ParticleData));
231
232 if (psys->particles->boid) {
233 memcpy(newboids, psys->particles->boid, totsaved * sizeof(BoidParticle));
234 }
235 }
236
237 if (psys->particles->keys) {
238 MEM_delete(psys->particles->keys);
239 }
240
241 if (psys->particles->boid) {
242 MEM_delete(psys->particles->boid);
243 }
244
245 for (p = 0, pa = newpars; p < totsaved; p++, pa++) {
246 if (pa->keys) {
247 pa->keys = nullptr;
248 pa->totkey = 0;
249 }
250 }
251
252 for (p = totsaved, pa = psys->particles + totsaved; p < psys->totpart; p++, pa++) {
253 if (pa->hair) {
254 MEM_delete(pa->hair);
255 }
256 }
257
258 MEM_delete(psys->particles);
259 psys_free_pdd(psys);
260 }
261
262 psys->particles = newpars;
263 psys->totpart = totpart;
264
265 if (newboids) {
267 {
268 pa->boid = newboids++;
269 }
270 }
271 }
272
273 if (psys->child) {
274 MEM_delete(psys->child);
275 psys->child = nullptr;
276 psys->totchild = 0;
277 }
278}
279
280int psys_get_child_number(Scene *scene, ParticleSystem *psys, const bool use_render_params)
281{
282 int child_num;
283
284 if (!psys->part->childtype) {
285 return 0;
286 }
287
288 if (use_render_params) {
289 child_num = psys->part->child_render_percent;
290 }
291 else {
292 child_num = psys->part->child_percent;
293 }
294
295 return get_render_child_particle_number(&scene->r, child_num, use_render_params);
296}
297
298int psys_get_tot_child(Scene *scene, ParticleSystem *psys, const bool use_render_params)
299{
300 return psys->totpart * psys_get_child_number(scene, psys, use_render_params);
301}
302
304
305/* -------------------------------------------------------------------- */
308
309void psys_calc_dmcache(Object *ob, Mesh *mesh_final, Mesh *mesh_original, ParticleSystem *psys)
310{
311 /* use for building derived mesh mapping info:
312 *
313 * node: the allocated links - total derived mesh element count
314 * nodearray: the array of nodes aligned with the base mesh's elements, so
315 * each original elements can reference its derived elements
316 */
317 Mesh *mesh = id_cast<Mesh *>(ob->data);
318 bool use_modifier_stack = psys->part->use_modifier_stack;
320
321 /* CACHE LOCATIONS */
322 if (!mesh_final->runtime->deformed_only) {
323 /* Will use later to speed up subsurf/evaluated mesh. */
324 LinkNode *node, *nodedmelem, **nodearray;
325 int totdmelem, totelem, i;
326 const int *origindex;
327 const int *origindex_poly = nullptr;
328 if (psys->part->from == PART_FROM_VERT) {
329 totdmelem = mesh_final->verts_num;
330
331 if (use_modifier_stack) {
332 totelem = totdmelem;
333 origindex = nullptr;
334 }
335 else {
336 totelem = mesh->verts_num;
337 origindex = static_cast<const int *>(
339 }
340 }
341 else { /* FROM_FACE/FROM_VOLUME */
342 totdmelem = mesh_final->totface_legacy;
343
344 if (use_modifier_stack) {
345 totelem = totdmelem;
346 origindex = nullptr;
347 origindex_poly = nullptr;
348 }
349 else {
350 totelem = mesh_original->totface_legacy;
351 origindex = static_cast<const int *>(
353
354 /* for face lookups we need the poly origindex too */
355 origindex_poly = static_cast<const int *>(
357 if (origindex_poly == nullptr) {
358 origindex = nullptr;
359 }
360 }
361 }
362
363 nodedmelem = MEM_new_array_zeroed<LinkNode>(totdmelem, "psys node elems");
364 nodearray = MEM_new_array_zeroed<LinkNode *>(totelem, "psys node array");
365
366 for (i = 0, node = nodedmelem; i < totdmelem; i++, node++) {
367 int origindex_final;
368 node->link = POINTER_FROM_INT(i);
369
370 /* may be vertex or face origindex */
371 if (use_modifier_stack) {
372 origindex_final = i;
373 }
374 else {
375 origindex_final = origindex ? origindex[i] : ORIGINDEX_NONE;
376
377 /* if we have a poly source, do an index lookup */
378 if (origindex_poly && origindex_final != ORIGINDEX_NONE) {
379 origindex_final = origindex_poly[origindex_final];
380 }
381 }
382
383 if (origindex_final != ORIGINDEX_NONE && origindex_final < totelem) {
384 if (nodearray[origindex_final]) {
385 /* prepend */
386 node->next = nodearray[origindex_final];
387 nodearray[origindex_final] = node;
388 }
389 else {
390 nodearray[origindex_final] = node;
391 }
392 }
393 }
394
395 /* cache the verts/faces! */
397 {
398 if (pa->num < 0) {
399 pa->num_dmcache = DMCACHE_NOTFOUND;
400 continue;
401 }
402
403 if (use_modifier_stack) {
404 if (pa->num < totelem) {
405 pa->num_dmcache = DMCACHE_ISCHILD;
406 }
407 else {
408 pa->num_dmcache = DMCACHE_NOTFOUND;
409 }
410 }
411 else {
412 if (psys->part->from == PART_FROM_VERT) {
413 if (pa->num < totelem && nodearray[pa->num]) {
414 pa->num_dmcache = POINTER_AS_INT(nodearray[pa->num]->link);
415 }
416 else {
417 pa->num_dmcache = DMCACHE_NOTFOUND;
418 }
419 }
420 else { /* FROM_FACE/FROM_VOLUME */
421 pa->num_dmcache = psys_particle_dm_face_lookup(
422 mesh_final, mesh_original, pa->num, pa->fuv, nodearray);
423 }
424 }
425 }
426
427 MEM_delete(nodearray);
428 MEM_delete(nodedmelem);
429 }
430 else {
431 /* TODO_PARTICLE: make the following line unnecessary, each function
432 * should know to use the num or num_dmcache, set the num_dmcache to
433 * an invalid value, just in case. */
434
436 {
437 pa->num_dmcache = DMCACHE_NOTFOUND;
438 }
439 }
440}
441
443{
444 memset(ctx, 0, sizeof(ParticleThreadContext));
445 ctx->sim = *sim;
446 ctx->mesh = ctx->sim.psmd->mesh_final;
447 ctx->ma = BKE_object_material_get(sim->ob, sim->psys->part->omat);
448}
449
451{
452 int numtasks = min_ii(BLI_system_thread_count() * 4, endpart - startpart);
453 int particles_per_task = numtasks > 0 ? (endpart - startpart) / numtasks : 0;
454 int remainder = numtasks > 0 ? (endpart - startpart) - particles_per_task * numtasks : 0;
455
456 Vector<ParticleTask> tasks(numtasks);
457
458 int p = startpart;
459 for (int i = 0; i < numtasks; i++) {
460 tasks[i].ctx = ctx;
461 tasks[i].begin = p;
462 p = p + particles_per_task + (i < remainder ? 1 : 0);
463 tasks[i].end = p;
464 }
465
466 /* Verify that all particles are accounted for. */
467 if (numtasks > 0) {
468 BLI_assert(tasks[numtasks - 1].end == endpart);
469 }
470
471 return tasks;
472}
473
475{
476 /* threads */
477 for (ParticleTask &task : tasks) {
478 if (task.rng) {
479 BLI_rng_free(task.rng);
480 }
481 if (task.rng_path) {
482 BLI_rng_free(task.rng_path);
483 }
484 }
485
486 tasks.clear();
487}
488
490{
491 /* path caching */
492 if (ctx->vg_length) {
493 MEM_delete(ctx->vg_length);
494 }
495 if (ctx->vg_clump) {
496 MEM_delete(ctx->vg_clump);
497 }
498 if (ctx->vg_kink) {
499 MEM_delete(ctx->vg_kink);
500 }
501 if (ctx->vg_rough1) {
502 MEM_delete(ctx->vg_rough1);
503 }
504 if (ctx->vg_rough2) {
505 MEM_delete(ctx->vg_rough2);
506 }
507 if (ctx->vg_roughe) {
508 MEM_delete(ctx->vg_roughe);
509 }
510 if (ctx->vg_twist) {
511 MEM_delete(ctx->vg_twist);
512 }
513
514 psys_sim_data_free(&ctx->sim);
515
516 /* distribution */
517 if (ctx->jit) {
518 MEM_delete(ctx->jit);
519 }
520 if (ctx->jitoff) {
521 MEM_delete(ctx->jitoff);
522 }
523 if (ctx->weight) {
524 MEM_delete(ctx->weight);
525 }
526 if (ctx->index) {
527 MEM_delete(ctx->index);
528 }
529 if (ctx->seams) {
530 MEM_delete(ctx->seams);
531 }
532 // if (ctx->vertpart) MEM_delete(ctx->vertpart);
534
535 if (ctx->clumpcurve != nullptr) {
537 }
538 if (ctx->roughcurve != nullptr) {
540 }
541 if (ctx->twistcurve != nullptr) {
543 }
544}
545
547{
548 ParticleSystem *psys = sim->psys;
549 ParticleSettings *part = psys->part;
550 ParticleTexture ptex;
551
552 psys_get_texture(sim, pa, &ptex, PAMAP_INIT, 0.0f);
553
554 switch (part->type) {
555 case PART_EMITTER:
556 if (ptex.exist < psys_frand(psys, p + 125)) {
557 pa->flag |= PARS_UNEXIST;
558 }
559 pa->time = part->sta + (part->end - part->sta) * ptex.time;
560 break;
561 case PART_HAIR:
562 if (ptex.exist < psys_frand(psys, p + 125)) {
563 pa->flag |= PARS_UNEXIST;
564 }
565 pa->time = 0.0f;
566 break;
567 default:
568 break;
569 }
570}
571
573{
574 ParticleSettings *part = sim->psys->part;
575 float birth_time = float(pa - sim->psys->particles) / float(sim->psys->totpart);
576
577 pa->flag &= ~PARS_UNEXIST;
578 pa->time = part->sta + (part->end - part->sta) * birth_time;
579
580 pa->hair_index = 0;
581 /* We can't reset to -1 anymore since we've figured out correct index in #distribute_particles
582 * usage other than straight after distribute has to handle this index by itself - jahka. */
583 // pa->num_dmcache = DMCACHE_NOTFOUND; /* assume we don't have a derived mesh face */
584}
585
587{
588 ParticleSystem *psys = sim->psys;
589 ParticleSettings *part = psys->part;
590 /* Grid distribution-sets UNEXIST flag, need to take care of
591 * it here because later this flag is being reset.
592 *
593 * We can't do it for any distribution, because it'll then
594 * conflict with texture influence, which does not free
595 * unexisting particles and only sets flag.
596 *
597 * It's not so bad, because only grid distribution sets
598 * UNEXIST flag.
599 */
600 const bool emit_from_volume_grid = (part->distr == PART_DISTR_GRID) &&
604 {
605 if (!(emit_from_volume_grid && (pa->flag & PARS_UNEXIST) != 0)) {
606 init_particle(sim, pa);
607 }
608 }
609}
610
612{
613 ParticleSystem *psys = sim->psys;
615
616 psys->totunexist = 0;
617
619 {
620 if (pa->flag & PARS_UNEXIST) {
621 psys->totunexist++;
622 }
623 }
624
625 if (psys->totpart && psys->totunexist == psys->totpart) {
626 if (psys->particles->boid) {
627 MEM_delete(psys->particles->boid);
628 }
629
630 MEM_delete(psys->particles);
631 psys->particles = nullptr;
632 psys->totpart = psys->totunexist = 0;
633 }
634
635 if (psys->totunexist) {
636 int newtotpart = psys->totpart - psys->totunexist;
637 ParticleData *npa, *newpars;
638
639 npa = newpars = MEM_new_array<ParticleData>(newtotpart, "particles");
640
641 for (p = 0, pa = psys->particles; p < newtotpart; p++, pa++, npa++) {
642 while (pa->flag & PARS_UNEXIST) {
643 pa++;
644 }
645
646 memcpy(npa, pa, sizeof(ParticleData));
647 }
648
649 if (psys->particles->boid) {
650 MEM_delete(psys->particles->boid);
651 }
652 MEM_delete(psys->particles);
653 psys->particles = newpars;
654 psys->totpart -= psys->totunexist;
655
656 if (psys->particles->boid) {
657 BoidParticle *newboids = MEM_new_array<BoidParticle>(psys->totpart, "boid particles");
658
660 {
661 pa->boid = newboids++;
662 }
663 }
664 }
665}
666
667static void get_angular_velocity_vector(short avemode, ParticleKey *state, float vec[3])
668{
669 switch (avemode) {
671 copy_v3_v3(vec, state->vel);
672 break;
673 case PART_AVE_HORIZONTAL: {
674 float zvec[3];
675 zvec[0] = zvec[1] = 0;
676 zvec[2] = 1.0f;
677 cross_v3_v3v3(vec, state->vel, zvec);
678 break;
679 }
680 case PART_AVE_VERTICAL: {
681 float zvec[3], temp[3];
682 zvec[0] = zvec[1] = 0;
683 zvec[2] = 1.0f;
684 cross_v3_v3v3(temp, state->vel, zvec);
685 cross_v3_v3v3(vec, temp, state->vel);
686 break;
687 }
689 vec[0] = 1.0f;
690 vec[1] = vec[2] = 0;
691 break;
693 vec[1] = 1.0f;
694 vec[0] = vec[2] = 0;
695 break;
697 vec[2] = 1.0f;
698 vec[0] = vec[1] = 0;
699 break;
700 }
701}
702
704 ParticleSimulationData *sim, ParticleData *pa, ParticleKey *state, float dtime, float cfra)
705{
706 Object *ob = sim->ob;
707 ParticleSystem *psys = sim->psys;
708 ParticleSettings *part = psys->part;
709 ParticleTexture ptex;
710 float fac, phasefac, nor[3] = {0, 0, 0}, loc[3], vel[3] = {0.0, 0.0, 0.0}, rot[4], q2[4];
711 float r_vel[3], r_ave[3], r_rot[4], vec[3], p_vel[3] = {0.0, 0.0, 0.0};
712 float x_vec[3] = {1.0, 0.0, 0.0}, utan[3] = {0.0, 1.0, 0.0}, vtan[3] = {0.0, 0.0, 1.0},
713 rot_vec[3] = {0.0, 0.0, 0.0};
714 float q_phase[4];
715
716 const bool use_boids = ((part->phystype == PART_PHYS_BOIDS) && (pa->boid != nullptr));
717 const bool use_tangents = ((use_boids == false) &&
718 ((part->tanfac != 0.0f) || (part->rotmode == PART_ROT_NOR_TAN)));
719
720 int p = pa - psys->particles;
721
722 /* get birth location from object */
723 if (use_tangents) {
725 part->from,
726 pa->num,
727 pa->num_dmcache,
728 pa->fuv,
729 pa->foffset,
730 loc,
731 nor,
732 utan,
733 vtan,
734 nullptr);
735 }
736 else {
738 part->from,
739 pa->num,
740 pa->num_dmcache,
741 pa->fuv,
742 pa->foffset,
743 loc,
744 nor,
745 nullptr,
746 nullptr,
747 nullptr);
748 }
749
750 /* get possible textural influence */
751 psys_get_texture(sim, pa, &ptex, PAMAP_IVEL, cfra);
752
753 /* particles live in global space so */
754 /* let's convert: */
755 /* -location */
756 mul_m4_v3(ob->object_to_world().ptr(), loc);
757
758 /* -normal */
759 mul_mat3_m4_v3(ob->object_to_world().ptr(), nor);
760 normalize_v3(nor);
761
762 /* -tangent */
763 if (use_tangents) {
764#if 0
765 float phase = vg_rot ?
766 2.0f *
767 (psys_particle_value_from_verts(sim->psmd->dm, part->from, pa, vg_rot) -
768 0.5f) :
769 0.0f;
770#else
771 float phase = 0.0f;
772#endif
773 mul_v3_fl(vtan, -cosf(float(M_PI) * (part->tanphase + phase)));
774 fac = -sinf(float(M_PI) * (part->tanphase + phase));
775 madd_v3_v3fl(vtan, utan, fac);
776
777 mul_mat3_m4_v3(ob->object_to_world().ptr(), vtan);
778
779 copy_v3_v3(utan, nor);
780 mul_v3_fl(utan, dot_v3v3(vtan, nor));
781 sub_v3_v3(vtan, utan);
782
783 normalize_v3(vtan);
784 }
785
786 /* -velocity (boids need this even if there's no random velocity) */
787 if (part->randfac != 0.0f || (part->phystype == PART_PHYS_BOIDS && pa->boid)) {
788 r_vel[0] = 2.0f * (psys_frand(psys, p + 10) - 0.5f);
789 r_vel[1] = 2.0f * (psys_frand(psys, p + 11) - 0.5f);
790 r_vel[2] = 2.0f * (psys_frand(psys, p + 12) - 0.5f);
791
792 mul_mat3_m4_v3(ob->object_to_world().ptr(), r_vel);
793 normalize_v3(r_vel);
794 }
795
796 /* -angular velocity */
797 if (part->avemode == PART_AVE_RAND) {
798 r_ave[0] = 2.0f * (psys_frand(psys, p + 13) - 0.5f);
799 r_ave[1] = 2.0f * (psys_frand(psys, p + 14) - 0.5f);
800 r_ave[2] = 2.0f * (psys_frand(psys, p + 15) - 0.5f);
801
802 mul_mat3_m4_v3(ob->object_to_world().ptr(), r_ave);
803 normalize_v3(r_ave);
804 }
805
806 /* -rotation */
807 if (part->randrotfac != 0.0f) {
808 r_rot[0] = 2.0f * (psys_frand(psys, p + 16) - 0.5f);
809 r_rot[1] = 2.0f * (psys_frand(psys, p + 17) - 0.5f);
810 r_rot[2] = 2.0f * (psys_frand(psys, p + 18) - 0.5f);
811 r_rot[3] = 2.0f * (psys_frand(psys, p + 19) - 0.5f);
812 normalize_qt(r_rot);
813
814 mat4_to_quat(rot, ob->object_to_world().ptr());
815 mul_qt_qtqt(r_rot, r_rot, rot);
816 }
817
818 if (use_boids) {
819 float dvec[3], q[4], mat[3][3];
820
821 copy_v3_v3(state->co, loc);
822
823 /* boids don't get any initial velocity. */
824 zero_v3(state->vel);
825
826 /* boids store direction in ave */
827 if (fabsf(nor[2]) == 1.0f) {
828 sub_v3_v3v3(state->ave, loc, ob->object_to_world().location());
829 normalize_v3(state->ave);
830 }
831 else {
832 copy_v3_v3(state->ave, nor);
833 }
834
835 /* calculate rotation matrix */
836 project_v3_v3v3(dvec, r_vel, state->ave);
837 sub_v3_v3v3(mat[0], state->ave, dvec);
838 normalize_v3(mat[0]);
839 negate_v3_v3(mat[2], r_vel);
840 normalize_v3(mat[2]);
841 cross_v3_v3v3(mat[1], mat[2], mat[0]);
842
843 /* apply rotation */
844 mat3_to_quat_legacy(q, mat);
845 copy_qt_qt(state->rot, q);
846 }
847 else {
848 /* conversion done so now we apply new: */
849 /* -velocity from: */
850
851 /* *reactions */
852 if (dtime > 0.0f) {
853 sub_v3_v3v3(vel, pa->state.vel, pa->prev_state.vel);
854 }
855
856 /* *emitter velocity */
857 if (dtime != 0.0f && part->obfac != 0.0f) {
858 sub_v3_v3v3(vel, loc, state->co);
859 mul_v3_fl(vel, part->obfac / dtime);
860 }
861
862 /* *emitter normal */
863 if (part->normfac != 0.0f) {
864 madd_v3_v3fl(vel, nor, part->normfac);
865 }
866
867 /* *emitter tangent */
868 if (sim->psmd && part->tanfac != 0.0f) {
869 madd_v3_v3fl(vel, vtan, part->tanfac);
870 }
871
872 /* *emitter object orientation */
873 if (part->ob_vel[0] != 0.0f) {
874 normalize_v3_v3(vec, ob->object_to_world().ptr()[0]);
875 madd_v3_v3fl(vel, vec, part->ob_vel[0]);
876 }
877 if (part->ob_vel[1] != 0.0f) {
878 normalize_v3_v3(vec, ob->object_to_world().ptr()[1]);
879 madd_v3_v3fl(vel, vec, part->ob_vel[1]);
880 }
881 if (part->ob_vel[2] != 0.0f) {
882 normalize_v3_v3(vec, ob->object_to_world().ptr()[2]);
883 madd_v3_v3fl(vel, vec, part->ob_vel[2]);
884 }
885
886 /* *texture */
887 /* TODO */
888
889 /* *random */
890 if (part->randfac != 0.0f) {
891 madd_v3_v3fl(vel, r_vel, part->randfac);
892 }
893
894 /* *particle */
895 if (part->partfac != 0.0f) {
896 madd_v3_v3fl(vel, p_vel, part->partfac);
897 }
898
899 mul_v3_v3fl(state->vel, vel, ptex.ivel);
900
901 /* -location from emitter */
902 copy_v3_v3(state->co, loc);
903
904 /* -rotation */
905 unit_qt(state->rot);
906
907 if (part->rotmode) {
908 bool use_global_space;
909
910 /* create vector into which rotation is aligned */
911 switch (part->rotmode) {
912 case PART_ROT_NOR:
913 case PART_ROT_NOR_TAN:
914 copy_v3_v3(rot_vec, nor);
915 use_global_space = false;
916 break;
917 case PART_ROT_VEL:
918 copy_v3_v3(rot_vec, vel);
919 use_global_space = true;
920 break;
921 case PART_ROT_GLOB_X:
922 case PART_ROT_GLOB_Y:
923 case PART_ROT_GLOB_Z:
924 rot_vec[part->rotmode - PART_ROT_GLOB_X] = 1.0f;
925 use_global_space = true;
926 break;
927 case PART_ROT_OB_X:
928 case PART_ROT_OB_Y:
929 case PART_ROT_OB_Z:
930 copy_v3_v3(rot_vec, ob->object_to_world().ptr()[part->rotmode - PART_ROT_OB_X]);
931 use_global_space = false;
932 break;
933 default:
934 use_global_space = true;
935 break;
936 }
937
938 /* create rotation quat */
939
940 if (use_global_space) {
941 negate_v3(rot_vec);
942 vec_to_quat(q2, rot_vec, OB_POSX, OB_POSZ);
943
944 /* randomize rotation quat */
945 if (part->randrotfac != 0.0f) {
946 interp_qt_qtqt(rot, q2, r_rot, part->randrotfac);
947 }
948 else {
949 copy_qt_qt(rot, q2);
950 }
951 }
952 else {
953 /* calculate rotation in local-space */
954 float q_obmat[4];
955 float q_imat[4];
956
957 mat4_to_quat(q_obmat, ob->object_to_world().ptr());
958 invert_qt_qt_normalized(q_imat, q_obmat);
959
960 if (part->rotmode != PART_ROT_NOR_TAN) {
961 float rot_vec_local[3];
962
963 /* rot_vec */
964 negate_v3(rot_vec);
965 copy_v3_v3(rot_vec_local, rot_vec);
966 mul_qt_v3(q_imat, rot_vec_local);
967 normalize_v3(rot_vec_local);
968
969 vec_to_quat(q2, rot_vec_local, OB_POSX, OB_POSZ);
970 }
971 else {
972 /* (part->rotmode == PART_ROT_NOR_TAN) */
973 float tmat[3][3];
974
975 /* NOTE: utan_local is not taken from 'utan', we calculate from rot_vec/vtan. */
976 /* NOTE(@ideasman42): it looks like rotation phase may be applied twice
977 * (once with vtan, again below) however this isn't the case. */
978 float *rot_vec_local = tmat[0];
979 float *vtan_local = tmat[1];
980 float *utan_local = tmat[2];
981
982 /* use tangents */
983 BLI_assert(use_tangents == true);
984
985 /* rot_vec */
986 copy_v3_v3(rot_vec_local, rot_vec);
987 mul_qt_v3(q_imat, rot_vec_local);
988
989 /* vtan_local */
990 copy_v3_v3(vtan_local, vtan); /* flips, can't use */
991 mul_qt_v3(q_imat, vtan_local);
992
993 /* ensure orthogonal matrix (rot_vec aligned) */
994 cross_v3_v3v3(utan_local, vtan_local, rot_vec_local);
995 cross_v3_v3v3(vtan_local, utan_local, rot_vec_local);
996
997 /* NOTE: no need to normalize. */
998 mat3_to_quat(q2, tmat);
999 }
1000
1001 /* randomize rotation quat */
1002 if (part->randrotfac != 0.0f) {
1003 mul_qt_qtqt(r_rot, r_rot, q_imat);
1004 interp_qt_qtqt(rot, q2, r_rot, part->randrotfac);
1005 }
1006 else {
1007 copy_qt_qt(rot, q2);
1008 }
1009
1010 mul_qt_qtqt(rot, q_obmat, rot);
1011 }
1012
1013 /* rotation phase */
1014 phasefac = part->phasefac;
1015 if (part->randphasefac != 0.0f) {
1016 phasefac += part->randphasefac * psys_frand(psys, p + 20);
1017 }
1018 axis_angle_to_quat(q_phase, x_vec, phasefac * float(M_PI));
1019
1020 /* combine base rotation & phase */
1021 mul_qt_qtqt(state->rot, rot, q_phase);
1022 }
1023
1024 /* -angular velocity */
1025
1026 zero_v3(state->ave);
1027
1028 if (part->avemode) {
1029 if (part->avemode == PART_AVE_RAND) {
1030 copy_v3_v3(state->ave, r_ave);
1031 }
1032 else {
1034 }
1035
1036 normalize_v3(state->ave);
1037 mul_v3_fl(state->ave, part->avefac);
1038 }
1039 }
1040}
1041
1042/* recursively evaluate emitter parent anim at cfra */
1043static void evaluate_emitter_anim(Depsgraph *depsgraph, Scene *scene, Object *ob, float cfra)
1044{
1045 if (ob->parent) {
1046 evaluate_emitter_anim(depsgraph, scene, ob->parent, cfra);
1047 }
1048
1049 BKE_object_where_is_calc_time(depsgraph, scene, ob, cfra);
1050}
1051
1052void reset_particle(ParticleSimulationData *sim, ParticleData *pa, float dtime, float cfra)
1053{
1054 ParticleSystem *psys = sim->psys;
1055 ParticleSettings *part;
1056 ParticleTexture ptex;
1057 int p = pa - psys->particles;
1058 part = psys->part;
1059
1060 /* get precise emitter matrix if particle is born */
1061 if (part->type != PART_HAIR && dtime > 0.0f && pa->time < cfra && pa->time >= sim->psys->cfra) {
1062 evaluate_emitter_anim(sim->depsgraph, sim->scene, sim->ob, pa->time);
1063
1064 psys->flag |= PSYS_OB_ANIM_RESTORE;
1065 }
1066
1067 psys_get_birth_coords(sim, pa, &pa->state, dtime, cfra);
1068
1069 /* Initialize particle settings which depends on texture.
1070 *
1071 * We could only do it now because we'll need to know coordinate
1072 * before sampling the texture.
1073 */
1074 init_particle_texture(sim, pa, p);
1075
1076 if (part->phystype == PART_PHYS_BOIDS && pa->boid) {
1077 BoidParticle *bpa = pa->boid;
1078
1079 /* and gravity in r_ve */
1080 bpa->gravity[0] = bpa->gravity[1] = 0.0f;
1081 bpa->gravity[2] = -1.0f;
1083 (sim->scene->physics_settings.gravity[2] != 0.0f))
1084 {
1085 bpa->gravity[2] = sim->scene->physics_settings.gravity[2];
1086 }
1087
1088 bpa->data.health = part->boids->health;
1089 bpa->data.mode = eBoidMode_InAir;
1090 bpa->data.state_id = (part->boids->states.first())->id;
1091 bpa->data.acc[0] = bpa->data.acc[1] = bpa->data.acc[2] = 0.0f;
1092 }
1093
1094 if (part->type == PART_HAIR) {
1095 pa->lifetime = 100.0f;
1096 }
1097 else {
1098 /* initialize the lifetime, in case the texture coordinates
1099 * are from Particles/Strands, which would cause undefined values
1100 */
1101 pa->lifetime = part->lifetime * (1.0f - part->randlife * psys_frand(psys, p + 21));
1102 pa->dietime = pa->time + pa->lifetime;
1103
1104 /* get possible textural influence */
1105 psys_get_texture(sim, pa, &ptex, PAMAP_LIFE, cfra);
1106
1107 pa->lifetime = part->lifetime * ptex.life;
1108
1109 if (part->randlife != 0.0f) {
1110 pa->lifetime *= 1.0f - part->randlife * psys_frand(psys, p + 21);
1111 }
1112 }
1113
1114 pa->dietime = pa->time + pa->lifetime;
1115
1116 if ((sim->psys->pointcache) && (sim->psys->pointcache->flag & PTCACHE_BAKED) &&
1117 (sim->psys->pointcache->mem_cache.first()))
1118 {
1119 float dietime = psys_get_dietime_from_cache(sim->psys->pointcache, p);
1120 pa->dietime = std::min(pa->dietime, dietime);
1121 }
1122
1123 if (pa->time > cfra) {
1124 pa->alive = PARS_UNBORN;
1125 }
1126 else if (pa->dietime <= cfra) {
1127 pa->alive = PARS_DEAD;
1128 }
1129 else {
1130 pa->alive = PARS_ALIVE;
1131 }
1132
1133 pa->state.time = cfra;
1134}
1135static void reset_all_particles(ParticleSimulationData *sim, float dtime, float cfra, int from)
1136{
1137 ParticleData *pa;
1138 int p, totpart = sim->psys->totpart;
1139
1140 for (p = from, pa = sim->psys->particles + from; p < totpart; p++, pa++) {
1141 reset_particle(sim, pa, dtime, cfra);
1142 }
1143}
1144
1146
1147/* -------------------------------------------------------------------- */
1150
1152{
1153 ParticleSystem *psys = nullptr;
1154
1155 if (ELEM(pt->ob, nullptr, ob)) {
1156 psys = static_cast<ParticleSystem *>(BLI_findlink(&ob->particlesystem, pt->psys - 1));
1157 }
1158 else {
1159 psys = static_cast<ParticleSystem *>(BLI_findlink(&pt->ob->particlesystem, pt->psys - 1));
1160 }
1161
1162 if (psys) {
1163 pt->flag |= PTARGET_VALID;
1164 }
1165 else {
1166 pt->flag &= ~PTARGET_VALID;
1167 }
1168
1169 return psys;
1170}
1171
1173
1174/* -------------------------------------------------------------------- */
1177
1179{
1180 ParticleSystem *psys = sim->psys, *kpsys;
1181 ParticleTarget *pt = psys->targets.first();
1182 int keys_valid = 1;
1183 psys->totkeyed = 0;
1184
1185 for (; pt; pt = pt->next) {
1186 kpsys = psys_get_target_system(sim->ob, pt);
1187
1188 if (kpsys && kpsys->totpart) {
1189 psys->totkeyed += keys_valid;
1190 if (psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f) {
1191 psys->totkeyed += 1;
1192 }
1193 }
1194 else {
1195 keys_valid = 0;
1196 }
1197 }
1198
1199 psys->totkeyed *= psys->flag & PSYS_KEYED_TIMING ? 1 : psys->part->keyed_loops;
1200}
1201
1203{
1204 ParticleSystem *psys = sim->psys;
1205 ParticleSimulationData ksim = {nullptr};
1206 ParticleTarget *pt;
1207 PARTICLE_P;
1208 ParticleKey *key;
1209 int totpart = psys->totpart, k, totkeys = psys->totkeyed;
1211
1212 ksim.depsgraph = sim->depsgraph;
1213 ksim.scene = sim->scene;
1214
1215 /* no proper targets so let's clear and bail out */
1216 if (psys->totkeyed == 0) {
1217 free_keyed_keys(psys);
1218 psys->flag &= ~PSYS_KEYED;
1219 return;
1220 }
1221
1222 if (totpart && psys->particles->totkey != totkeys) {
1223 free_keyed_keys(psys);
1224
1225 key = MEM_new_array_zeroed<ParticleKey>(size_t(totpart) * size_t(totkeys), "Keyed keys");
1226
1228 {
1229 pa->keys = key;
1230 pa->totkey = totkeys;
1231 key += totkeys;
1232 }
1233 }
1234
1235 psys->flag &= ~PSYS_KEYED;
1236
1237 pt = psys->targets.first();
1238 for (k = 0; k < totkeys; k++) {
1239 ksim.ob = pt->ob ? pt->ob : sim->ob;
1240 ksim.psys = static_cast<ParticleSystem *>(
1241 BLI_findlink(&ksim.ob->particlesystem, pt->psys - 1));
1242 keyed_flag = (ksim.psys->flag & PSYS_KEYED);
1243 ksim.psys->flag &= ~PSYS_KEYED;
1244
1246 {
1247 key = pa->keys + k;
1248 key->time = -1.0; /* use current time */
1249
1250 const int p_ksim = (ksim.psys->totpart) ? p % ksim.psys->totpart : 0;
1251 psys_get_particle_state(&ksim, p_ksim, key, true);
1252
1253 if (psys->flag & PSYS_KEYED_TIMING) {
1254 key->time = pa->time + pt->time;
1255 if (pt->duration != 0.0f && k + 1 < totkeys) {
1256 copy_particle_key(key + 1, key, 1);
1257 (key + 1)->time = pa->time + pt->time + pt->duration;
1258 }
1259 }
1260 else if (totkeys > 1) {
1261 key->time = pa->time + float(k) / float(totkeys - 1) * pa->lifetime;
1262 }
1263 else {
1264 key->time = pa->time;
1265 }
1266 }
1267
1268 if (psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f) {
1269 k++;
1270 }
1271
1272 ksim.psys->flag |= keyed_flag;
1273
1274 pt = (pt->next && pt->next->flag & PTARGET_VALID) ? pt->next : psys->targets.first();
1275 }
1276
1277 psys->flag |= PSYS_KEYED;
1278}
1279
1281
1282/* -------------------------------------------------------------------- */
1285
1287{
1288 PointCache *cache = psys->pointcache;
1289
1290 if (cache->flag & PTCACHE_DISK_CACHE && cache->mem_cache.is_empty()) {
1291 PTCacheID pid;
1292 BKE_ptcache_id_from_particles(&pid, ob, psys);
1293 cache->flag &= ~PTCACHE_DISK_CACHE;
1295 cache->flag |= PTCACHE_DISK_CACHE;
1296 }
1297}
1299{
1300 if (psys->pointcache->flag & PTCACHE_DISK_CACHE) {
1302 }
1303}
1304void psys_get_pointcache_start_end(Scene *scene, ParticleSystem *psys, int *sfra, int *efra)
1305{
1306 ParticleSettings *part = psys->part;
1307
1308 *sfra = max_ii(1, int(part->sta));
1309 *efra = min_ii(int(part->end + part->lifetime + 1.0f), max_ii(scene->r.pefra, scene->r.efra));
1310}
1311
1312/* BVH tree balancing inside a mutex lock must be run in isolation. Balancing
1313 * is multithreaded, and we do not want the current thread to start another task
1314 * that may involve acquiring the same mutex lock that it is waiting for. */
1315static void bvhtree_balance_isolated(void *userdata)
1316{
1317 BLI_bvhtree_balance(static_cast<BVHTree *>(userdata));
1318}
1319
1321
1322/* -------------------------------------------------------------------- */
1325
1326static void psys_update_particle_bvhtree(ParticleSystem *psys, float cfra)
1327{
1328 if (psys) {
1329 PARTICLE_P;
1330 int totpart = 0;
1331 bool need_rebuild;
1332
1334 need_rebuild = !psys->bvhtree || psys->bvhtree_frame != cfra;
1336
1337 if (need_rebuild) {
1339 {
1340 totpart++;
1341 }
1342
1344
1346 psys->bvhtree = BLI_bvhtree_new(totpart, 0.0, 4, 6);
1347
1349 {
1350 if (pa->alive == PARS_ALIVE) {
1351 if (pa->state.time == cfra) {
1352 BLI_bvhtree_insert(psys->bvhtree, p, pa->prev_state.co, 1);
1353 }
1354 else {
1355 BLI_bvhtree_insert(psys->bvhtree, p, pa->state.co, 1);
1356 }
1357 }
1358 }
1359
1361
1362 psys->bvhtree_frame = cfra;
1363
1365 }
1366 }
1367}
1369{
1370 if (psys) {
1371 PARTICLE_P;
1372
1373 if (!psys->tree || psys->tree_frame != cfra) {
1374 int totpart = 0;
1376 {
1377 if (pa->alive == PARS_ALIVE) {
1378 totpart++;
1379 }
1380 }
1381
1383 psys->tree = kdtree_new<float3>(totpart);
1384
1386 {
1387 if (pa->alive == PARS_ALIVE) {
1388 const float *co = (pa->state.time == cfra) ? pa->prev_state.co : pa->state.co;
1389 kdtree_insert<float3>(psys->tree, p, co);
1390 }
1391 }
1393
1394 psys->tree_frame = cfra;
1395 }
1396 }
1397}
1398
1400{
1402 bool use_rotation = (sim->psys->part->flag & PART_ROT_DYN) != 0;
1403 sim->psys->effectors = static_cast<ListBaseT<EffectorCache> *>(BKE_effectors_create(
1404 sim->depsgraph, sim->ob, sim->psys, sim->psys->part->effector_weights, use_rotation));
1405 precalc_guides(sim, sim->psys->effectors);
1406}
1407
1409 ParticleSettings *part,
1410 ParticleData *pa,
1411 float dtime,
1412 float *external_acceleration,
1413 void (*force_func)(void *forcedata, ParticleKey *state, float *force, float *impulse),
1414 void *forcedata)
1415{
1416#define ZERO_F43 \
1417 { \
1418 {0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f} \
1419 }
1420
1421 ParticleKey states[5];
1422 float force[3], acceleration[3], impulse[3], dx[4][3] = ZERO_F43, dv[4][3] = ZERO_F43, oldpos[3];
1423 float pa_mass = (part->flag & PART_SIZEMASS) ? (part->mass * pa->size) : part->mass;
1424 int i, steps = 1;
1425 int integrator = part->integrator;
1426
1427#undef ZERO_F43
1428
1429 copy_v3_v3(oldpos, pa->state.co);
1430
1431 /* Verlet integration behaves strangely with moving emitters, so do first step with euler. */
1432 if (pa->prev_state.time < 0.0f && integrator == PART_INT_VERLET) {
1433 integrator = PART_INT_EULER;
1434 }
1435
1436 switch (integrator) {
1437 case PART_INT_EULER:
1438 steps = 1;
1439 break;
1440 case PART_INT_MIDPOINT:
1441 steps = 2;
1442 break;
1443 case PART_INT_RK4:
1444 steps = 4;
1445 break;
1446 case PART_INT_VERLET:
1447 steps = 1;
1448 break;
1449 }
1450
1451 for (i = 0; i < steps; i++) {
1452 copy_particle_key(states + i, &pa->state, 1);
1453 }
1454
1455 states->time = 0.0f;
1456
1457 for (i = 0; i < steps; i++) {
1458 zero_v3(force);
1459 zero_v3(impulse);
1460
1461 force_func(forcedata, states + i, force, impulse);
1462
1463 /* Force to acceleration. */
1464 mul_v3_v3fl(acceleration, force, 1.0f / pa_mass);
1465
1466 if (external_acceleration) {
1467 add_v3_v3(acceleration, external_acceleration);
1468 }
1469
1470 /* calculate next state */
1471 add_v3_v3(states[i].vel, impulse);
1472
1473 switch (integrator) {
1474 case PART_INT_EULER:
1475 madd_v3_v3v3fl(pa->state.co, states->co, states->vel, dtime);
1476 madd_v3_v3v3fl(pa->state.vel, states->vel, acceleration, dtime);
1477 break;
1478 case PART_INT_MIDPOINT:
1479 if (i == 0) {
1480 madd_v3_v3v3fl(states[1].co, states->co, states->vel, dtime * 0.5f);
1481 madd_v3_v3v3fl(states[1].vel, states->vel, acceleration, dtime * 0.5f);
1482 states[1].time = dtime * 0.5f;
1483 // fra = sim->psys->cfra + 0.5f * dfra;
1484 }
1485 else {
1486 madd_v3_v3v3fl(pa->state.co, states->co, states[1].vel, dtime);
1487 madd_v3_v3v3fl(pa->state.vel, states->vel, acceleration, dtime);
1488 }
1489 break;
1490 case PART_INT_RK4:
1491 switch (i) {
1492 case 0:
1493 copy_v3_v3(dx[0], states->vel);
1494 mul_v3_fl(dx[0], dtime);
1495 copy_v3_v3(dv[0], acceleration);
1496 mul_v3_fl(dv[0], dtime);
1497
1498 madd_v3_v3v3fl(states[1].co, states->co, dx[0], 0.5f);
1499 madd_v3_v3v3fl(states[1].vel, states->vel, dv[0], 0.5f);
1500 states[1].time = dtime * 0.5f;
1501 // fra = sim->psys->cfra + 0.5f * dfra;
1502 break;
1503 case 1:
1504 madd_v3_v3v3fl(dx[1], states->vel, dv[0], 0.5f);
1505 mul_v3_fl(dx[1], dtime);
1506 copy_v3_v3(dv[1], acceleration);
1507 mul_v3_fl(dv[1], dtime);
1508
1509 madd_v3_v3v3fl(states[2].co, states->co, dx[1], 0.5f);
1510 madd_v3_v3v3fl(states[2].vel, states->vel, dv[1], 0.5f);
1511 states[2].time = dtime * 0.5f;
1512 break;
1513 case 2:
1514 madd_v3_v3v3fl(dx[2], states->vel, dv[1], 0.5f);
1515 mul_v3_fl(dx[2], dtime);
1516 copy_v3_v3(dv[2], acceleration);
1517 mul_v3_fl(dv[2], dtime);
1518
1519 add_v3_v3v3(states[3].co, states->co, dx[2]);
1520 add_v3_v3v3(states[3].vel, states->vel, dv[2]);
1521 states[3].time = dtime;
1522 // fra = cfra;
1523 break;
1524 case 3:
1525 add_v3_v3v3(dx[3], states->vel, dv[2]);
1526 mul_v3_fl(dx[3], dtime);
1527 copy_v3_v3(dv[3], acceleration);
1528 mul_v3_fl(dv[3], dtime);
1529
1530 madd_v3_v3v3fl(pa->state.co, states->co, dx[0], 1.0f / 6.0f);
1531 madd_v3_v3fl(pa->state.co, dx[1], 1.0f / 3.0f);
1532 madd_v3_v3fl(pa->state.co, dx[2], 1.0f / 3.0f);
1533 madd_v3_v3fl(pa->state.co, dx[3], 1.0f / 6.0f);
1534
1535 madd_v3_v3v3fl(pa->state.vel, states->vel, dv[0], 1.0f / 6.0f);
1536 madd_v3_v3fl(pa->state.vel, dv[1], 1.0f / 3.0f);
1537 madd_v3_v3fl(pa->state.vel, dv[2], 1.0f / 3.0f);
1538 madd_v3_v3fl(pa->state.vel, dv[3], 1.0f / 6.0f);
1539 }
1540 break;
1541 case PART_INT_VERLET: /* Verlet integration */
1542 madd_v3_v3v3fl(pa->state.vel, pa->prev_state.vel, acceleration, dtime);
1543 madd_v3_v3v3fl(pa->state.co, pa->prev_state.co, pa->state.vel, dtime);
1544
1545 sub_v3_v3v3(pa->state.vel, pa->state.co, oldpos);
1546 mul_v3_fl(pa->state.vel, 1.0f / dtime);
1547 break;
1548 }
1549 }
1550}
1551
1553
1554/* -------------------------------------------------------------------- */
1568
1569#define PSYS_FLUID_SPRINGS_INITIAL_SIZE 256
1571{
1572 /* Are more refs required? */
1573 if (psys->alloc_fluidsprings == 0 || psys->fluid_springs == nullptr) {
1576 "Particle Fluid Springs");
1577 }
1578 else if (psys->tot_fluidsprings == psys->alloc_fluidsprings) {
1579 /* Double the number of refs allocated */
1580 psys->alloc_fluidsprings *= 2;
1582 psys->fluid_springs, psys->alloc_fluidsprings * sizeof(ParticleSpring)));
1583 }
1584
1585 memcpy(psys->fluid_springs + psys->tot_fluidsprings, spring, sizeof(ParticleSpring));
1586 psys->tot_fluidsprings++;
1587
1588 return psys->fluid_springs + psys->tot_fluidsprings - 1;
1589}
1590static void sph_spring_delete(ParticleSystem *psys, int j)
1591{
1592 if (j != psys->tot_fluidsprings - 1) {
1593 psys->fluid_springs[j] = psys->fluid_springs[psys->tot_fluidsprings - 1];
1594 }
1595
1596 psys->tot_fluidsprings--;
1597
1598 if (psys->tot_fluidsprings < psys->alloc_fluidsprings / 2 &&
1600 {
1601 psys->alloc_fluidsprings /= 2;
1603 psys->fluid_springs, psys->alloc_fluidsprings * sizeof(ParticleSpring)));
1604 }
1605}
1606static void sph_springs_modify(ParticleSystem *psys, float dtime)
1607{
1608 SPHFluidSettings *fluid = psys->part->fluid;
1609 ParticleData *pa1, *pa2;
1610 ParticleSpring *spring = psys->fluid_springs;
1611
1612 float h, d, Rij[3], rij, Lij;
1613 int i;
1614
1615 float yield_ratio = fluid->yield_ratio;
1616 float plasticity = fluid->plasticity_constant;
1617 /* scale things according to dtime */
1618 float timefix = 25.0f * dtime;
1619
1620 if ((fluid->flag & SPH_VISCOELASTIC_SPRINGS) == 0 || fluid->spring_k == 0.0f) {
1621 return;
1622 }
1623
1624 /* Loop through the springs */
1625 for (i = 0; i < psys->tot_fluidsprings; i++, spring++) {
1626 pa1 = psys->particles + spring->particle_index[0];
1627 pa2 = psys->particles + spring->particle_index[1];
1628
1629 sub_v3_v3v3(Rij, pa2->prev_state.co, pa1->prev_state.co);
1630 rij = normalize_v3(Rij);
1631
1632 /* adjust rest length */
1633 Lij = spring->rest_length;
1634 d = yield_ratio * timefix * Lij;
1635
1636 if (rij > Lij + d) { /* Stretch */
1637 spring->rest_length += plasticity * (rij - Lij - d) * timefix;
1638 }
1639 else if (rij < Lij - d) { /* Compress */
1640 spring->rest_length -= plasticity * (Lij - d - rij) * timefix;
1641 }
1642
1643 h = 4.0f * pa1->size;
1644
1645 if (spring->rest_length > h) {
1646 spring->delete_flag = 1;
1647 }
1648 }
1649
1650 /* Loop through springs backwards - for efficient delete function. */
1651 for (i = psys->tot_fluidsprings - 1; i >= 0; i--) {
1652 if (psys->fluid_springs[i].delete_flag) {
1653 sph_spring_delete(psys, i);
1654 }
1655 }
1656}
1658{
1659 Map<OrderedEdge, int> springhash;
1660 springhash.reserve(psys->tot_fluidsprings);
1661
1662 ParticleSpring *spring;
1663 int i = 0;
1664
1665 for (i = 0, spring = psys->fluid_springs; i < psys->tot_fluidsprings; i++, spring++) {
1666 springhash.add({spring->particle_index[0], spring->particle_index[1]}, i + 1);
1667 }
1668
1669 return springhash;
1670}
1671
1672#define SPH_NEIGHBORS 512
1677
1692
1693static void sph_evaluate_func(BVHTree *tree,
1694 ParticleSystem **psys,
1695 const float co[3],
1696 SPHRangeData *pfr,
1697 float interaction_radius,
1698 BVHTree_RangeQuery callback)
1699{
1700 int i;
1701
1702 pfr->tot_neighbors = 0;
1703
1704 for (i = 0; i < 10 && psys[i]; i++) {
1705 pfr->npsys = psys[i];
1706 pfr->massfac = psys[i]->part->mass / pfr->mass;
1707 pfr->use_size = psys[i]->part->flag & PART_SIZEMASS;
1708
1709 if (tree) {
1710 BLI_bvhtree_range_query(tree, co, interaction_radius, callback, pfr);
1711 break;
1712 }
1713
1715
1716 BLI_bvhtree_range_query(psys[i]->bvhtree, co, interaction_radius, callback, pfr);
1717
1719 }
1720}
1721static void sph_density_accum_cb(void *userdata, int index, const float co[3], float squared_dist)
1722{
1723 SPHRangeData *pfr = static_cast<SPHRangeData *>(userdata);
1724 ParticleData *npa = pfr->npsys->particles + index;
1725 float q;
1726 float dist;
1727
1728 UNUSED_VARS(co);
1729
1730 if (npa == pfr->pa || squared_dist < FLT_EPSILON) {
1731 return;
1732 }
1733
1734 /* Ugh! One particle has too many neighbors! If some aren't taken into
1735 * account, the forces will be biased by the tree search order. This
1736 * effectively adds energy to the system, and results in a churning motion.
1737 * But, we have to stop somewhere, and it's not the end of the world.
1738 * - jahka and z0r
1739 */
1740 if (pfr->tot_neighbors >= SPH_NEIGHBORS) {
1741 return;
1742 }
1743
1744 pfr->neighbors[pfr->tot_neighbors].index = index;
1745 pfr->neighbors[pfr->tot_neighbors].psys = pfr->npsys;
1746 pfr->tot_neighbors++;
1747
1748 dist = sqrtf(squared_dist);
1749 q = (1.0f - dist / pfr->h) * pfr->massfac;
1750
1751 if (pfr->use_size) {
1752 q *= npa->size;
1753 }
1754
1755 pfr->data[0] += q * q;
1756 pfr->data[1] += q * q * q;
1757}
1758
1759/*
1760 * Find the Courant number for an SPH particle (used for adaptive time step).
1761 */
1762static void sph_particle_courant(SPHData *sphdata, SPHRangeData *pfr)
1763{
1764 ParticleData *pa, *npa;
1765 int i;
1766 float flow[3], offset[3], dist;
1767
1768 zero_v3(flow);
1769
1770 dist = 0.0f;
1771 if (pfr->tot_neighbors > 0) {
1772 pa = pfr->pa;
1773 for (i = 0; i < pfr->tot_neighbors; i++) {
1774 npa = pfr->neighbors[i].psys->particles + pfr->neighbors[i].index;
1775 sub_v3_v3v3(offset, pa->prev_state.co, npa->prev_state.co);
1776 dist += len_v3(offset);
1777 add_v3_v3(flow, npa->prev_state.vel);
1778 }
1779 dist += sphdata->psys[0]->part->fluid->radius; /* TODO(@z0r): remove this? */
1780 sphdata->element_size = dist / pfr->tot_neighbors;
1781 mul_v3_v3fl(sphdata->flow, flow, 1.0f / pfr->tot_neighbors);
1782 }
1783 else {
1784 sphdata->element_size = FLT_MAX;
1785 copy_v3_v3(sphdata->flow, flow);
1786 }
1787}
1788static void sph_force_cb(void *sphdata_v, ParticleKey *state, float *force, float * /*impulse*/)
1789{
1790 SPHData *sphdata = static_cast<SPHData *>(sphdata_v);
1791 ParticleSystem **psys = sphdata->psys;
1792 ParticleData *pa = sphdata->pa;
1793 SPHFluidSettings *fluid = psys[0]->part->fluid;
1794 ParticleSpring *spring = nullptr;
1795 SPHRangeData pfr;
1796 SPHNeighbor *pfn;
1797 const float *gravity = sphdata->gravity;
1798 const Map<OrderedEdge, int> *springhash = sphdata->eh;
1799
1800 float q, u, rij, dv[3];
1801 float pressure, near_pressure;
1802
1803 float visc = fluid->viscosity_omega;
1804 float stiff_visc = fluid->viscosity_beta *
1805 (fluid->flag & SPH_FAC_VISCOSITY ? fluid->viscosity_omega : 1.0f);
1806
1807 float inv_mass = 1.0f / sphdata->mass;
1808 float spring_constant = fluid->spring_k;
1809
1810 /* 4.0 seems to be a pretty good value */
1811 float interaction_radius = fluid->radius *
1812 (fluid->flag & SPH_FAC_RADIUS ? 4.0f * pa->size : 1.0f);
1813 float h = interaction_radius * sphdata->hfac;
1814 /* 4.77 is an experimentally determined density factor */
1815 float rest_density = fluid->rest_density * (fluid->flag & SPH_FAC_DENSITY ? 4.77f : 1.0f);
1816 float rest_length = fluid->rest_length *
1817 (fluid->flag & SPH_FAC_REST_LENGTH ? 2.588f * pa->size : 1.0f);
1818
1819 float stiffness = fluid->stiffness_k;
1820 float stiffness_near_fac = fluid->stiffness_knear *
1821 (fluid->flag & SPH_FAC_REPULSION ? fluid->stiffness_k : 1.0f);
1822
1823 ParticleData *npa;
1824 float vec[3];
1825 float vel[3];
1826 float co[3];
1827 float data[2];
1828 float density, near_density;
1829
1830 int i, spring_index, index = pa - psys[0]->particles;
1831
1832 data[0] = data[1] = 0;
1833 pfr.data = data;
1834 pfr.h = h;
1835 pfr.pa = pa;
1836 pfr.mass = sphdata->mass;
1837
1838 sph_evaluate_func(nullptr, psys, state->co, &pfr, interaction_radius, sph_density_accum_cb);
1839
1840 density = data[0];
1841 near_density = data[1];
1842
1843 pressure = stiffness * (density - rest_density);
1844 near_pressure = stiffness_near_fac * near_density;
1845
1846 pfn = pfr.neighbors;
1847 for (i = 0; i < pfr.tot_neighbors; i++, pfn++) {
1848 npa = pfn->psys->particles + pfn->index;
1849
1850 madd_v3_v3v3fl(co, npa->prev_state.co, npa->prev_state.vel, state->time);
1851
1852 sub_v3_v3v3(vec, co, state->co);
1853 rij = normalize_v3(vec);
1854
1855 q = (1.0f - rij / h) * pfn->psys->part->mass * inv_mass;
1856
1857 if (pfn->psys->part->flag & PART_SIZEMASS) {
1858 q *= npa->size;
1859 }
1860
1861 copy_v3_v3(vel, npa->prev_state.vel);
1862
1863 /* Double Density Relaxation */
1864 madd_v3_v3fl(force, vec, -(pressure + near_pressure * q) * q);
1865
1866 /* Viscosity */
1867 if (visc > 0.0f || stiff_visc > 0.0f) {
1868 sub_v3_v3v3(dv, vel, state->vel);
1869 u = dot_v3v3(vec, dv);
1870
1871 if (u < 0.0f && visc > 0.0f) {
1872 madd_v3_v3fl(force, vec, 0.5f * q * visc * u);
1873 }
1874
1875 if (u > 0.0f && stiff_visc > 0.0f) {
1876 madd_v3_v3fl(force, vec, 0.5f * q * stiff_visc * u);
1877 }
1878 }
1879
1880 if (spring_constant > 0.0f) {
1881 /* Viscoelastic spring force */
1882 if (pfn->psys == psys[0] && fluid->flag & SPH_VISCOELASTIC_SPRINGS && springhash) {
1883 spring_index = springhash->lookup_default({index, pfn->index}, 0);
1884
1885 if (spring_index) {
1886 spring = psys[0]->fluid_springs + spring_index - 1;
1887
1888 madd_v3_v3fl(force,
1889 vec,
1890 -10.0f * spring_constant * (1.0f - rij / h) * (spring->rest_length - rij));
1891 }
1892 else if (fluid->spring_frames == 0 ||
1893 (pa->prev_state.time - pa->time) <= fluid->spring_frames)
1894 {
1895 ParticleSpring temp_spring;
1896 temp_spring.particle_index[0] = index;
1897 temp_spring.particle_index[1] = pfn->index;
1898 temp_spring.rest_length = (fluid->flag & SPH_CURRENT_REST_LENGTH) ? rij : rest_length;
1899 temp_spring.delete_flag = 0;
1900
1901 sphdata->new_springs.append(temp_spring);
1902 }
1903 }
1904 else { /* PART_SPRING_HOOKES - Hooke's spring force */
1906 force, vec, -10.0f * spring_constant * (1.0f - rij / h) * (rest_length - rij));
1907 }
1908 }
1909 }
1910
1911 /* Artificial buoyancy force in negative gravity direction. */
1912 if (fluid->buoyancy > 0.0f && gravity) {
1913 madd_v3_v3fl(force, gravity, fluid->buoyancy * (density - rest_density));
1914 }
1915
1916 if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF) {
1917 sph_particle_courant(sphdata, &pfr);
1918 }
1919 sphdata->pass++;
1920}
1921
1922static void sphclassical_density_accum_cb(void *userdata,
1923 int index,
1924 const float co[3],
1925 float /*squared_dist*/)
1926{
1927 SPHRangeData *pfr = static_cast<SPHRangeData *>(userdata);
1928 ParticleData *npa = pfr->npsys->particles + index;
1929 float q;
1930 float qfac = 21.0f / (256.0f * float(M_PI));
1931 float rij, rij_h;
1932 float vec[3];
1933
1934 /* Exclude particles that are more than 2h away. Can't use squared_dist here
1935 * because it is not accurate enough. Use current state, i.e. the output of
1936 * basic_integrate() - z0r */
1937 sub_v3_v3v3(vec, npa->state.co, co);
1938 rij = len_v3(vec);
1939 rij_h = rij / pfr->h;
1940 if (rij_h > 2.0f) {
1941 return;
1942 }
1943
1944 /* Smoothing factor. Utilize the Wendland kernel. `gnuplot`:
1945 * q1(x) = (2.0 - x)**4 * ( 1.0 + 2.0 * x)
1946 * plot [0:2] q1(x) */
1947 q = qfac / pow3f(pfr->h) * pow4f(2.0f - rij_h) * (1.0f + 2.0f * rij_h);
1948 q *= pfr->npsys->part->mass;
1949
1950 if (pfr->use_size) {
1951 q *= pfr->pa->size;
1952 }
1953
1954 pfr->data[0] += q;
1955 pfr->data[1] += q / npa->sphdensity;
1956}
1957
1958static void sphclassical_neighbor_accum_cb(void *userdata,
1959 int index,
1960 const float co[3],
1961 float /*squared_dist*/)
1962{
1963 SPHRangeData *pfr = static_cast<SPHRangeData *>(userdata);
1964 ParticleData *npa = pfr->npsys->particles + index;
1965 float rij, rij_h;
1966 float vec[3];
1967
1968 if (pfr->tot_neighbors >= SPH_NEIGHBORS) {
1969 return;
1970 }
1971
1972 /* Exclude particles that are more than 2h away. Can't use squared_dist here
1973 * because it is not accurate enough. Use current state, i.e. the output of
1974 * basic_integrate() - z0r */
1975 sub_v3_v3v3(vec, npa->state.co, co);
1976 rij = len_v3(vec);
1977 rij_h = rij / pfr->h;
1978 if (rij_h > 2.0f) {
1979 return;
1980 }
1981
1982 pfr->neighbors[pfr->tot_neighbors].index = index;
1983 pfr->neighbors[pfr->tot_neighbors].psys = pfr->npsys;
1984 pfr->tot_neighbors++;
1985}
1986static void sphclassical_force_cb(void *sphdata_v,
1988 float *force,
1989 float * /*impulse*/)
1990{
1991 SPHData *sphdata = static_cast<SPHData *>(sphdata_v);
1992 ParticleSystem **psys = sphdata->psys;
1993 ParticleData *pa = sphdata->pa;
1994 SPHFluidSettings *fluid = psys[0]->part->fluid;
1995 SPHRangeData pfr;
1996 SPHNeighbor *pfn;
1997 const float *gravity = sphdata->gravity;
1998
1999 float dq, u, rij, dv[3];
2000 float pressure, npressure;
2001
2002 float visc = fluid->viscosity_omega;
2003
2004 float interaction_radius;
2005 float h, hinv;
2006 /* 4.77 is an experimentally determined density factor */
2007 float rest_density = fluid->rest_density * (fluid->flag & SPH_FAC_DENSITY ? 4.77f : 1.0f);
2008
2009 /* Use speed of sound squared */
2010 float stiffness = pow2f(fluid->stiffness_k);
2011
2012 ParticleData *npa;
2013 float vec[3];
2014 float co[3];
2015 float pressureTerm;
2016
2017 int i;
2018
2019 float qfac2 = 42.0f / (256.0f * float(M_PI));
2020 float rij_h;
2021
2022 /* 4.0 here is to be consistent with previous formulation/interface */
2023 interaction_radius = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * pa->size : 1.0f);
2024 h = interaction_radius * sphdata->hfac;
2025 hinv = 1.0f / h;
2026
2027 pfr.h = h;
2028 pfr.pa = pa;
2029
2031 nullptr, psys, state->co, &pfr, interaction_radius, sphclassical_neighbor_accum_cb);
2032 pressure = stiffness * (pow7f(pa->sphdensity / rest_density) - 1.0f);
2033
2034 /* Multiply by mass so that we return a force, not acceleration. */
2035 qfac2 *= sphdata->mass / pow3f(pfr.h);
2036
2037 pfn = pfr.neighbors;
2038 for (i = 0; i < pfr.tot_neighbors; i++, pfn++) {
2039 npa = pfn->psys->particles + pfn->index;
2040 if (npa == pa) {
2041 /* we do not contribute to ourselves */
2042 continue;
2043 }
2044
2045 /* Find vector to neighbor. Exclude particles that are more than 2h
2046 * away. Can't use current state here because it may have changed on
2047 * another thread - so do own mini integration. Unlike basic_integrate,
2048 * SPH integration depends on neighboring particles. - z0r */
2049 madd_v3_v3v3fl(co, npa->prev_state.co, npa->prev_state.vel, state->time);
2050 sub_v3_v3v3(vec, co, state->co);
2051 rij = normalize_v3(vec);
2052 rij_h = rij / pfr.h;
2053 if (rij_h > 2.0f) {
2054 continue;
2055 }
2056
2057 npressure = stiffness * (pow7f(npa->sphdensity / rest_density) - 1.0f);
2058
2059 /* First derivative of smoothing factor. Utilize the Wendland kernel.
2060 * `gnuplot`:
2061 * q2(x) = 2.0 * (2.0 - x)**4 - 4.0 * (2.0 - x)**3 * (1.0 + 2.0 * x)
2062 * plot [0:2] q2(x)
2063 * Particles > 2h away are excluded above. */
2064 dq = qfac2 * (2.0f * pow4f(2.0f - rij_h) - 4.0f * pow3f(2.0f - rij_h) * (1.0f + 2.0f * rij_h));
2065
2066 if (pfn->psys->part->flag & PART_SIZEMASS) {
2067 dq *= npa->size;
2068 }
2069
2070 pressureTerm = pressure / pow2f(pa->sphdensity) + npressure / pow2f(npa->sphdensity);
2071
2072 /* Note that 'minus' is removed, because vec = vecBA, not vecAB.
2073 * This applies to the viscosity calculation below, too. */
2074 madd_v3_v3fl(force, vec, pressureTerm * dq);
2075
2076 /* Viscosity */
2077 if (visc > 0.0f) {
2078 sub_v3_v3v3(dv, npa->prev_state.vel, pa->prev_state.vel);
2079 u = dot_v3v3(vec, dv);
2080 /* Apply parameters */
2081 u *= -dq * hinv * visc / (0.5f * npa->sphdensity + 0.5f * pa->sphdensity);
2082 madd_v3_v3fl(force, vec, u);
2083 }
2084 }
2085
2086 /* Artificial buoyancy force in negative gravity direction. */
2087 if (fluid->buoyancy > 0.0f && gravity) {
2088 madd_v3_v3fl(force, gravity, fluid->buoyancy * (pa->sphdensity - rest_density));
2089 }
2090
2091 if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF) {
2092 sph_particle_courant(sphdata, &pfr);
2093 }
2094 sphdata->pass++;
2095}
2096
2097static void sphclassical_calc_dens(ParticleData *pa, float /*dfra*/, SPHData *sphdata)
2098{
2099 ParticleSystem **psys = sphdata->psys;
2100 SPHFluidSettings *fluid = psys[0]->part->fluid;
2101 /* 4.0 seems to be a pretty good value */
2102 float interaction_radius = fluid->radius *
2103 (fluid->flag & SPH_FAC_RADIUS ? 4.0f * psys[0]->part->size : 1.0f);
2104 SPHRangeData pfr;
2105 float data[2];
2106
2107 data[0] = 0;
2108 data[1] = 0;
2109 pfr.data = data;
2110 pfr.h = interaction_radius * sphdata->hfac;
2111 pfr.pa = pa;
2112 pfr.mass = sphdata->mass;
2113
2115 nullptr, psys, pa->state.co, &pfr, interaction_radius, sphclassical_density_accum_cb);
2116 pa->sphdensity = min_ff(max_ff(data[0], fluid->rest_density * 0.9f), fluid->rest_density * 1.1f);
2117}
2118
2120 SPHData *sphdata,
2122{
2123 ParticleTarget *pt;
2124 int i;
2125
2126 /* Add other coupled particle systems. */
2127 sphdata->psys[0] = sim->psys;
2128 for (i = 1, pt = sim->psys->targets.first(); i < 10; i++, pt = (pt ? pt->next : nullptr)) {
2129 sphdata->psys[i] = pt ? psys_get_target_system(sim->ob, pt) : nullptr;
2130 }
2131
2132 if (psys_uses_gravity(sim)) {
2133 sphdata->gravity = sim->scene->physics_settings.gravity;
2134 }
2135 else {
2136 sphdata->gravity = nullptr;
2137 }
2138 r_eh = sph_springhash_build(sim->psys);
2139 sphdata->eh = &r_eh;
2140
2141 /* These per-particle values should be overridden later, but just for
2142 * completeness we give them default values now. */
2143 sphdata->pa = nullptr;
2144 sphdata->mass = 1.0f;
2145
2146 if (sim->psys->part->fluid->solver == SPH_SOLVER_DDR) {
2147 sphdata->force_cb = sph_force_cb;
2149 sphdata->hfac = 1.0f;
2150 }
2151 else {
2152 /* SPH_SOLVER_CLASSICAL */
2155 sphdata->hfac = 0.5f;
2156 }
2157}
2158
2159static void psys_sph_flush_springs(SPHData *sphdata)
2160{
2161 for (int i = 0; i < sphdata->new_springs.size(); i++) {
2162 /* sph_spring_add is not thread-safe. - z0r */
2163 sph_spring_add(sphdata->psys[0], &sphdata->new_springs[i]);
2164 }
2165
2166 sphdata->new_springs.clear_and_shrink();
2167}
2168
2170{
2171 psys_sph_flush_springs(sphdata);
2172}
2173
2174void psys_sph_density(BVHTree *tree, SPHData *sphdata, float co[3], float vars[2])
2175{
2176 ParticleSystem **psys = sphdata->psys;
2177 SPHFluidSettings *fluid = psys[0]->part->fluid;
2178 /* 4.0 seems to be a pretty good value */
2179 float interaction_radius = fluid->radius *
2180 (fluid->flag & SPH_FAC_RADIUS ? 4.0f * psys[0]->part->size : 1.0f);
2181 SPHRangeData pfr;
2182 float density[2];
2183
2184 density[0] = density[1] = 0.0f;
2185 pfr.data = density;
2186 pfr.h = interaction_radius * sphdata->hfac;
2187 pfr.mass = sphdata->mass;
2188
2189 sph_evaluate_func(tree, psys, co, &pfr, interaction_radius, sphdata->density_cb);
2190
2191 vars[0] = pfr.data[0];
2192 vars[1] = pfr.data[1];
2193}
2194
2196 ParticleData *pa,
2197 float dfra,
2198 SPHData *sphdata)
2199{
2200 ParticleSettings *part = sim->psys->part;
2201 // float timestep = psys_get_timestep(sim); /* UNUSED */
2202 float pa_mass = part->mass * ((part->flag & PART_SIZEMASS) ? pa->size : 1.0f);
2203 float dtime = dfra * psys_get_timestep(sim);
2204 // int steps = 1; // UNUSED
2205 float effector_acceleration[3];
2206
2207 sphdata->pa = pa;
2208 sphdata->mass = pa_mass;
2209 sphdata->pass = 0;
2210 /* #sphdata.element_size and #sphdata.flow are set in the callback. */
2211
2212 /* Restore previous state and treat gravity & effectors as external acceleration. */
2213 sub_v3_v3v3(effector_acceleration, pa->state.vel, pa->prev_state.vel);
2214 mul_v3_fl(effector_acceleration, 1.0f / dtime);
2215
2216 copy_particle_key(&pa->state, &pa->prev_state, 0);
2217
2218 integrate_particle(part, pa, dtime, effector_acceleration, sphdata->force_cb, sphdata);
2219}
2220
2222
2223/* -------------------------------------------------------------------- */
2226
2232static void basic_force_cb(void *efdata_v, ParticleKey *state, float *force, float *impulse)
2233{
2234 EfData *efdata = static_cast<EfData *>(efdata_v);
2235 ParticleSimulationData *sim = efdata->sim;
2236 ParticleSettings *part = sim->psys->part;
2237 ParticleData *pa = efdata->pa;
2238 EffectedPoint epoint;
2239 RNG *rng = sim->rng;
2240
2241 /* add effectors */
2242 pd_point_from_particle(efdata->sim, efdata->pa, state, &epoint);
2243 if (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR) {
2245 sim->colliders,
2246 part->effector_weights,
2247 &epoint,
2248 force,
2249 nullptr,
2250 impulse);
2251 }
2252
2253 mul_v3_fl(force, efdata->ptex.field);
2254 mul_v3_fl(impulse, efdata->ptex.field);
2255
2256 /* calculate air-particle interaction */
2257 if (part->dragfac != 0.0f) {
2258 madd_v3_v3fl(force, state->vel, -part->dragfac * pa->size * pa->size * len_v3(state->vel));
2259 }
2260
2261 /* brownian force */
2262 if (part->brownfac != 0.0f) {
2263 force[0] += (BLI_rng_get_float(rng) - 0.5f) * part->brownfac;
2264 force[1] += (BLI_rng_get_float(rng) - 0.5f) * part->brownfac;
2265 force[2] += (BLI_rng_get_float(rng) - 0.5f) * part->brownfac;
2266 }
2267
2268 if (part->flag & PART_ROT_DYN && epoint.ave) {
2269 copy_v3_v3(pa->state.ave, epoint.ave);
2270 }
2271}
2272/* gathers all forces that effect particles and calculates a new state for the particle */
2273static void basic_integrate(ParticleSimulationData *sim, int p, float dfra, float cfra)
2274{
2275 ParticleSettings *part = sim->psys->part;
2276 ParticleData *pa = sim->psys->particles + p;
2277 ParticleKey tkey;
2278 float dtime = dfra * psys_get_timestep(sim), time;
2279 float *gravity = nullptr, gr[3];
2280 EfData efdata;
2281
2282 psys_get_texture(sim, pa, &efdata.ptex, PAMAP_PHYSICS, cfra);
2283
2284 efdata.pa = pa;
2285 efdata.sim = sim;
2286
2287 /* add global acceleration (gravitation) */
2288 if (psys_uses_gravity(sim) &&
2289 /* normal gravity is too strong for hair so it's disabled by default */
2290 (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR))
2291 {
2292 zero_v3(gr);
2293 madd_v3_v3fl(gr,
2296 gravity = gr;
2297 }
2298
2299 /* maintain angular velocity */
2300 copy_v3_v3(pa->state.ave, pa->prev_state.ave);
2301
2302 integrate_particle(part, pa, dtime, gravity, basic_force_cb, &efdata);
2303
2304 /* damp affects final velocity */
2305 if (part->dampfac != 0.0f) {
2306 mul_v3_fl(pa->state.vel, 1.0f - part->dampfac * efdata.ptex.damp * 25.0f * dtime);
2307 }
2308
2309 // copy_v3_v3(pa->state.ave, states->ave);
2310
2311 /* finally we do guides */
2312 time = (cfra - pa->time) / pa->lifetime;
2313 CLAMP(time, 0.0f, 1.0f);
2314
2315 copy_v3_v3(tkey.co, pa->state.co);
2316 copy_v3_v3(tkey.vel, pa->state.vel);
2317 tkey.time = pa->state.time;
2318
2319 if (part->type != PART_HAIR) {
2320 if (do_guides(sim->depsgraph, sim->psys->part, sim->psys->effectors, &tkey, p, time)) {
2321 copy_v3_v3(pa->state.co, tkey.co);
2322 /* guides don't produce valid velocity */
2323 sub_v3_v3v3(pa->state.vel, tkey.co, pa->prev_state.co);
2324 mul_v3_fl(pa->state.vel, 1.0f / dtime);
2325 pa->state.time = tkey.time;
2326 }
2327 }
2328}
2329static void basic_rotate(ParticleSettings *part, ParticleData *pa, float dfra, float timestep)
2330{
2331 float rotfac, rot1[4], rot2[4] = {1.0, 0.0, 0.0, 0.0}, dtime = dfra * timestep, extrotfac;
2332
2333 if ((part->flag & PART_ROTATIONS) == 0) {
2334 unit_qt(pa->state.rot);
2335 return;
2336 }
2337
2338 if (part->flag & PART_ROT_DYN) {
2339 extrotfac = len_v3(pa->state.ave);
2340 }
2341 else {
2342 extrotfac = 0.0f;
2343 }
2344
2345 if ((part->flag & PART_ROT_DYN) &&
2347 {
2348 float angle;
2349 float len1 = len_v3(pa->prev_state.vel);
2350 float len2 = len_v3(pa->state.vel);
2351 float vec[3];
2352
2353 if (len1 == 0.0f || len2 == 0.0f) {
2354 zero_v3(pa->state.ave);
2355 }
2356 else {
2357 cross_v3_v3v3(pa->state.ave, pa->prev_state.vel, pa->state.vel);
2358 normalize_v3(pa->state.ave);
2359 angle = dot_v3v3(pa->prev_state.vel, pa->state.vel) / (len1 * len2);
2360 mul_v3_fl(pa->state.ave, safe_acosf(angle) / dtime);
2361 }
2362
2363 get_angular_velocity_vector(part->avemode, &pa->state, vec);
2364 axis_angle_to_quat(rot2, vec, dtime * part->avefac);
2365 }
2366
2367 rotfac = len_v3(pa->state.ave);
2368 if (rotfac == 0.0f || (part->flag & PART_ROT_DYN) == 0 || extrotfac == 0.0f) {
2369 unit_qt(rot1);
2370 }
2371 else {
2372 axis_angle_to_quat(rot1, pa->state.ave, rotfac * dtime);
2373 }
2374 mul_qt_qtqt(pa->state.rot, rot1, pa->prev_state.rot);
2375 mul_qt_qtqt(pa->state.rot, rot2, pa->state.rot);
2376
2377 /* keep rotation quat in good health */
2378 normalize_qt(pa->state.rot);
2379}
2380
2382
2383/* -------------------------------------------------------------------- */
2391
2392#define COLLISION_MIN_RADIUS 0.001f
2393#define COLLISION_MIN_DISTANCE 0.0001f
2394#define COLLISION_ZERO 0.00001f
2395#define COLLISION_INIT_STEP 0.00008f
2396using NRDistanceFunc = float (*)(float *p,
2397 float radius,
2399 float *nor);
2400static float nr_signed_distance_to_plane(float *p,
2401 float radius,
2403 float *nor)
2404{
2405 float p0[3], e1[3], e2[3], d;
2406
2407 sub_v3_v3v3(e1, pce->x1, pce->x0);
2408 sub_v3_v3v3(e2, pce->x2, pce->x0);
2409 sub_v3_v3v3(p0, p, pce->x0);
2410
2411 cross_v3_v3v3(nor, e1, e2);
2412 normalize_v3(nor);
2413
2414 d = dot_v3v3(p0, nor);
2415
2416 if (pce->inv_nor == -1) {
2417 if (d < 0.0f) {
2418 pce->inv_nor = 1;
2419 }
2420 else {
2421 pce->inv_nor = 0;
2422 }
2423 }
2424
2425 if (pce->inv_nor == 1) {
2426 negate_v3(nor);
2427 d = -d;
2428 }
2429
2430 return d - radius;
2431}
2432static float nr_distance_to_edge(float *p,
2433 float radius,
2435 float * /*nor*/)
2436{
2437 float v0[3], v1[3], v2[3], c[3];
2438
2439 sub_v3_v3v3(v0, pce->x1, pce->x0);
2440 sub_v3_v3v3(v1, p, pce->x0);
2441 sub_v3_v3v3(v2, p, pce->x1);
2442
2443 cross_v3_v3v3(c, v1, v2);
2444
2445 return fabsf(len_v3(c) / len_v3(v0)) - radius;
2446}
2447static float nr_distance_to_vert(float *p,
2448 float radius,
2450 float * /*nor*/)
2451{
2452 return len_v3v3(p, pce->x0) - radius;
2453}
2454
2461 float t,
2462 float fac,
2463 ParticleCollision *col)
2464{
2465 float f = fac + t * (1.0f - fac);
2466 float mul = col->fac1 + f * (col->fac2 - col->fac1);
2467 if (pce->tot > 0) {
2468 madd_v3_v3v3fl(pce->x0, pce->x[0], pce->v[0], mul);
2469
2470 if (pce->tot > 1) {
2471 madd_v3_v3v3fl(pce->x1, pce->x[1], pce->v[1], mul);
2472
2473 if (pce->tot > 2) {
2474 madd_v3_v3v3fl(pce->x2, pce->x[2], pce->v[2], mul);
2475 }
2476 }
2477 }
2478}
2480{
2481 float v[3];
2482
2483 copy_v3_v3(pce->vel, pce->v[0]);
2484
2485 if (pce->tot > 1) {
2486 sub_v3_v3v3(v, pce->v[1], pce->v[0]);
2487 madd_v3_v3fl(pce->vel, v, pce->uv[0]);
2488
2489 if (pce->tot > 2) {
2490 sub_v3_v3v3(v, pce->v[2], pce->v[0]);
2491 madd_v3_v3fl(pce->vel, v, pce->uv[1]);
2492 }
2493 }
2494}
2496 float p[3], ParticleCollisionElement *pce, float fac, ParticleCollision *col, float *nor)
2497{
2498 if (fac >= 0.0f) {
2499 collision_interpolate_element(pce, 0.0f, fac, col);
2500 }
2501
2502 switch (pce->tot) {
2503 case 1: {
2504 sub_v3_v3v3(nor, p, pce->x0);
2505 return normalize_v3(nor);
2506 }
2507 case 2: {
2508 float u, e[3], vec[3];
2509 sub_v3_v3v3(e, pce->x1, pce->x0);
2510 sub_v3_v3v3(vec, p, pce->x0);
2511 u = dot_v3v3(vec, e) / dot_v3v3(e, e);
2512
2513 madd_v3_v3v3fl(nor, vec, e, -u);
2514 return normalize_v3(nor);
2515 }
2516 case 3:
2517 return nr_signed_distance_to_plane(p, 0.0f, pce, nor);
2518 }
2519 return 0;
2520}
2522 const float p[3], ParticleCollisionElement *pce, float fac, ParticleCollision *col, float *co)
2523{
2524 collision_interpolate_element(pce, 0.0f, fac, col);
2525
2526 switch (pce->tot) {
2527 case 1: {
2528 sub_v3_v3v3(co, p, pce->x0);
2529 normalize_v3(co);
2530 madd_v3_v3v3fl(co, pce->x0, co, col->radius);
2531 break;
2532 }
2533 case 2: {
2534 float u, e[3], vec[3], nor[3];
2535 sub_v3_v3v3(e, pce->x1, pce->x0);
2536 sub_v3_v3v3(vec, p, pce->x0);
2537 u = dot_v3v3(vec, e) / dot_v3v3(e, e);
2538
2539 madd_v3_v3v3fl(nor, vec, e, -u);
2540 normalize_v3(nor);
2541
2542 madd_v3_v3v3fl(co, pce->x0, e, pce->uv[0]);
2543 madd_v3_v3fl(co, nor, col->radius);
2544 break;
2545 }
2546 case 3: {
2547 float p0[3], e1[3], e2[3], nor[3];
2548
2549 sub_v3_v3v3(e1, pce->x1, pce->x0);
2550 sub_v3_v3v3(e2, pce->x2, pce->x0);
2551 sub_v3_v3v3(p0, p, pce->x0);
2552
2553 cross_v3_v3v3(nor, e1, e2);
2554 normalize_v3(nor);
2555
2556 if (pce->inv_nor == 1) {
2557 negate_v3(nor);
2558 }
2559
2560 madd_v3_v3v3fl(co, pce->x0, nor, col->radius);
2561 madd_v3_v3fl(co, e1, pce->uv[0]);
2562 madd_v3_v3fl(co, e2, pce->uv[1]);
2563 break;
2564 }
2565 }
2566}
2567/* find first root in range [0-1] starting from 0 */
2569 float radius,
2571 NRDistanceFunc distance_func)
2572{
2573 float t0, t1, dt_init, d0, d1, dd, n[3];
2574 int iter;
2575
2576 pce->inv_nor = -1;
2577
2578 if (col->inv_total_time > 0.0f) {
2579 /* Initial step size should be small, but not too small or floating point
2580 * precision errors will appear. - z0r */
2581 dt_init = COLLISION_INIT_STEP * col->inv_total_time;
2582 }
2583 else {
2584 dt_init = 0.001f;
2585 }
2586
2587 /* start from the beginning */
2588 t0 = 0.0f;
2589 collision_interpolate_element(pce, t0, col->f, col);
2590 d0 = distance_func(col->co1, radius, pce, n);
2591 t1 = dt_init;
2592 d1 = 0.0f;
2593
2594 for (iter = 0; iter < 10; iter++) { //, itersum++) {
2595 /* get current location */
2596 collision_interpolate_element(pce, t1, col->f, col);
2597 interp_v3_v3v3(pce->p, col->co1, col->co2, t1);
2598
2599 d1 = distance_func(pce->p, radius, pce, n);
2600
2601 /* particle already inside face, so report collision */
2602 if (iter == 0 && d0 < 0.0f && d0 > -radius) {
2603 copy_v3_v3(pce->p, col->co1);
2604 copy_v3_v3(pce->nor, n);
2605 pce->inside = 1;
2606 return 0.0f;
2607 }
2608
2609 /* Zero gradient (no movement relative to element). Can't step from
2610 * here. */
2611 if (d1 == d0) {
2612 /* If first iteration, try from other end where the gradient may be
2613 * greater. NOTE: code duplicated below. */
2614 if (iter == 0) {
2615 t0 = 1.0f;
2616 collision_interpolate_element(pce, t0, col->f, col);
2617 d0 = distance_func(col->co2, radius, pce, n);
2618 t1 = 1.0f - dt_init;
2619 d1 = 0.0f;
2620 continue;
2621 }
2622
2623 return -1.0f;
2624 }
2625
2626 dd = (t1 - t0) / (d1 - d0);
2627
2628 t0 = t1;
2629 d0 = d1;
2630
2631 t1 -= d1 * dd;
2632
2633 /* Particle moving away from plane could also mean a strangely rotating
2634 * face, so check from end. NOTE: code duplicated above. */
2635 if (iter == 0 && t1 < 0.0f) {
2636 t0 = 1.0f;
2637 collision_interpolate_element(pce, t0, col->f, col);
2638 d0 = distance_func(col->co2, radius, pce, n);
2639 t1 = 1.0f - dt_init;
2640 d1 = 0.0f;
2641 continue;
2642 }
2643 if (iter == 1 && (t1 < -COLLISION_ZERO || t1 > 1.0f)) {
2644 return -1.0f;
2645 }
2646
2647 if (d1 <= COLLISION_ZERO && d1 >= -COLLISION_ZERO) {
2648 if (t1 >= -COLLISION_ZERO && t1 <= 1.0f) {
2649 if (distance_func == nr_signed_distance_to_plane) {
2650 copy_v3_v3(pce->nor, n);
2651 }
2652
2653 CLAMP(t1, 0.0f, 1.0f);
2654
2655 return t1;
2656 }
2657
2658 return -1.0f;
2659 }
2660 }
2661 return -1.0;
2662}
2664 float radius,
2666 float *t)
2667{
2669 float ct, u, v;
2670
2671 pce->inv_nor = -1;
2672 pce->inside = 0;
2673
2675
2676 if (ct >= 0.0f && ct < *t && (result->inside == 0 || pce->inside == 1)) {
2677 float e1[3], e2[3], p0[3];
2678 float e1e1, e1e2, e1p0, e2e2, e2p0, inv;
2679
2680 sub_v3_v3v3(e1, pce->x1, pce->x0);
2681 sub_v3_v3v3(e2, pce->x2, pce->x0);
2682 /* XXX: add radius correction here? */
2683 sub_v3_v3v3(p0, pce->p, pce->x0);
2684
2685 e1e1 = dot_v3v3(e1, e1);
2686 e1e2 = dot_v3v3(e1, e2);
2687 e1p0 = dot_v3v3(e1, p0);
2688 e2e2 = dot_v3v3(e2, e2);
2689 e2p0 = dot_v3v3(e2, p0);
2690
2691 inv = 1.0f / (e1e1 * e2e2 - e1e2 * e1e2);
2692 u = (e2e2 * e1p0 - e1e2 * e2p0) * inv;
2693 v = (e1e1 * e2p0 - e1e2 * e1p0) * inv;
2694
2695 if (u >= 0.0f && u <= 1.0f && v >= 0.0f && u + v <= 1.0f) {
2696 *result = *pce;
2697
2698 /* normal already calculated in pce */
2699
2700 result->uv[0] = u;
2701 result->uv[1] = v;
2702
2703 *t = ct;
2704 return 1;
2705 }
2706 }
2707 return 0;
2708}
2710 float radius,
2712 float *t)
2713{
2714 ParticleCollisionElement edge[3], *cur = nullptr, *hit = nullptr;
2716
2717 float ct;
2718 int i;
2719
2720 for (i = 0; i < 3; i++) {
2721 cur = edge + i;
2722 cur->x[0] = pce->x[i];
2723 cur->x[1] = pce->x[(i + 1) % 3];
2724 cur->v[0] = pce->v[i];
2725 cur->v[1] = pce->v[(i + 1) % 3];
2726 cur->tot = 2;
2727 cur->inside = 0;
2728
2729 ct = collision_newton_rhapson(col, radius, cur, nr_distance_to_edge);
2730
2731 if (ct >= 0.0f && ct < *t) {
2732 float u, e[3], vec[3];
2733
2734 sub_v3_v3v3(e, cur->x1, cur->x0);
2735 sub_v3_v3v3(vec, cur->p, cur->x0);
2736 u = dot_v3v3(vec, e) / dot_v3v3(e, e);
2737
2738 if (u < 0.0f || u > 1.0f) {
2739 break;
2740 }
2741
2742 *result = *cur;
2743
2744 madd_v3_v3v3fl(result->nor, vec, e, -u);
2745 normalize_v3(result->nor);
2746
2747 result->uv[0] = u;
2748
2749 hit = cur;
2750 *t = ct;
2751 }
2752 }
2753
2754 return hit != nullptr;
2755}
2757 float radius,
2759 float *t)
2760{
2761 ParticleCollisionElement vert[3], *cur = nullptr, *hit = nullptr;
2763
2764 float ct;
2765 int i;
2766
2767 for (i = 0; i < 3; i++) {
2768 cur = vert + i;
2769 cur->x[0] = pce->x[i];
2770 cur->v[0] = pce->v[i];
2771 cur->tot = 1;
2772 cur->inside = 0;
2773
2774 ct = collision_newton_rhapson(col, radius, cur, nr_distance_to_vert);
2775
2776 if (ct >= 0.0f && ct < *t) {
2777 *result = *cur;
2778
2779 sub_v3_v3v3(result->nor, cur->p, cur->x0);
2780 normalize_v3(result->nor);
2781
2782 hit = cur;
2783 *t = ct;
2784 }
2785 }
2786
2787 return hit != nullptr;
2788}
2790 int index,
2791 const BVHTreeRay *ray,
2792 BVHTreeRayHit *hit)
2793{
2794 ParticleCollision *col = static_cast<ParticleCollision *>(userdata);
2796 const int3 vert_tri = &col->md->vert_tris[index];
2797 float (*x)[3] = col->md->x;
2798 float (*v)[3] = col->md->current_v;
2799 float t = hit->dist / col->original_ray_length;
2800 int collision = 0;
2801
2802 pce.x[0] = x[vert_tri[0]];
2803 pce.x[1] = x[vert_tri[1]];
2804 pce.x[2] = x[vert_tri[2]];
2805
2806 pce.v[0] = v[vert_tri[0]];
2807 pce.v[1] = v[vert_tri[1]];
2808 pce.v[2] = v[vert_tri[2]];
2809
2810 pce.tot = 3;
2811 pce.inside = 0;
2812 pce.index = index;
2813
2814 collision = collision_sphere_to_tri(col, ray->radius, &pce, &t);
2815 if (col->pce.inside == 0) {
2816 collision += collision_sphere_to_edges(col, ray->radius, &pce, &t);
2817 collision += collision_sphere_to_verts(col, ray->radius, &pce, &t);
2818 }
2819
2820 if (collision) {
2821 hit->dist = col->original_ray_length * t;
2822 hit->index = index;
2823
2825
2826 col->hit = col->current;
2827 }
2828}
2830 ParticleCollision *col,
2831 BVHTreeRayHit *hit,
2832 ListBaseT<ColliderCache> *colliders)
2833{
2834 const int raycast_flag = BVH_RAYCAST_DEFAULT & ~BVH_RAYCAST_WATERTIGHT;
2835 float ray_dir[3];
2836
2837 if (colliders->is_empty()) {
2838 return 0;
2839 }
2840
2841 sub_v3_v3v3(ray_dir, col->co2, col->co1);
2842 hit->index = -1;
2843 hit->dist = col->original_ray_length = normalize_v3(ray_dir);
2844 col->pce.inside = 0;
2845
2846 /* even if particle is stationary we want to check for moving colliders */
2847 /* if hit.dist is zero the bvhtree_ray_cast will just ignore everything */
2848 if (hit->dist == 0.0f) {
2849 hit->dist = col->original_ray_length = 0.000001f;
2850 }
2851
2852 for (ColliderCache &coll : *colliders) {
2853 /* for boids: don't check with current ground object; also skip if permeated */
2854 bool skip = false;
2855
2856 for (int i = 0; i < col->skip_count; i++) {
2857 if (coll.ob == col->skip[i]) {
2858 skip = true;
2859 break;
2860 }
2861 }
2862
2863 if (skip) {
2864 continue;
2865 }
2866
2867 /* particles should not collide with emitter at birth */
2868 if (coll.ob == col->emitter && pa->time < col->cfra && pa->time >= col->old_cfra) {
2869 continue;
2870 }
2871
2872 col->current = coll.ob;
2873 col->md = coll.collmd;
2874 col->fac1 = (col->old_cfra - coll.collmd->time_x) /
2875 (coll.collmd->time_xnew - coll.collmd->time_x);
2876 col->fac2 = (col->cfra - coll.collmd->time_x) / (coll.collmd->time_xnew - coll.collmd->time_x);
2877
2878 if (col->md && col->md->bvhtree) {
2880 col->co1,
2881 ray_dir,
2882 col->radius,
2883 hit,
2885 col,
2886 raycast_flag);
2887 }
2888 }
2889
2890 return hit->index >= 0;
2891}
2893 ParticleData *pa,
2894 ParticleCollision *col,
2895 BVHTreeRayHit *hit,
2896 int kill,
2897 int dynamic_rotation)
2898{
2899 ParticleCollisionElement *pce = &col->pce;
2900 PartDeflect *pd = col->hit->pd;
2901 RNG *rng = sim->rng;
2902 /* point of collision */
2903 float co[3];
2904 /* location factor of collision between this iteration */
2905 float x = hit->dist / col->original_ray_length;
2906 /* time factor of collision between timestep */
2907 float f = col->f + x * (1.0f - col->f);
2908 /* time since previous collision (in seconds) */
2909 float dt1 = (f - col->f) * col->total_time;
2910 /* time left after collision (in seconds) */
2911 float dt2 = (1.0f - f) * col->total_time;
2912 /* did particle pass through the collision surface? */
2913 int through = (BLI_rng_get_float(rng) < pd->pdef_perm) ? 1 : 0;
2914
2915 /* calculate exact collision location */
2916 interp_v3_v3v3(co, col->co1, col->co2, x);
2917
2918 /* particle dies in collision */
2919 if (through == 0 && (kill || pd->flag & PDEFLE_KILL_PART)) {
2920 pa->alive = PARS_DYING;
2921 pa->dietime = col->old_cfra + (col->cfra - col->old_cfra) * f;
2922
2923 copy_v3_v3(pa->state.co, co);
2924 interp_v3_v3v3(pa->state.vel, pa->prev_state.vel, pa->state.vel, f);
2925 interp_qt_qtqt(pa->state.rot, pa->prev_state.rot, pa->state.rot, f);
2926 interp_v3_v3v3(pa->state.ave, pa->prev_state.ave, pa->state.ave, f);
2927
2928 /* particle is dead so we don't need to calculate further */
2929 return 0;
2930 }
2931 /* figure out velocity and other data after collision */
2932
2933 /* velocity directly before collision to be modified into velocity directly after collision */
2934 float v0[3];
2935 /* normal component of v0 */
2936 float v0_nor[3];
2937 /* tangential component of v0 */
2938 float v0_tan[3];
2939 /* tangential component of collision surface velocity */
2940 float vc_tan[3];
2941 float v0_dot, vc_dot;
2942 float damp = pd->pdef_damp + pd->pdef_rdamp * 2 * (BLI_rng_get_float(rng) - 0.5f);
2943 float frict = pd->pdef_frict + pd->pdef_rfrict * 2 * (BLI_rng_get_float(rng) - 0.5f);
2944 float distance, nor[3], dot;
2945
2946 CLAMP(damp, 0.0f, 1.0f);
2947 CLAMP(frict, 0.0f, 1.0f);
2948
2949 /* get exact velocity right before collision */
2950 madd_v3_v3v3fl(v0, col->ve1, col->acc, dt1);
2951
2952 /* Convert collider velocity from `1/frame_step` to `1/s` TODO:
2953 * here we assume 1 frame step for collision modifier. */
2954 mul_v3_fl(pce->vel, col->inv_timestep);
2955
2956 /* calculate tangential particle velocity */
2957 v0_dot = dot_v3v3(pce->nor, v0);
2958 madd_v3_v3v3fl(v0_tan, v0, pce->nor, -v0_dot);
2959
2960 /* calculate tangential collider velocity */
2961 vc_dot = dot_v3v3(pce->nor, pce->vel);
2962 madd_v3_v3v3fl(vc_tan, pce->vel, pce->nor, -vc_dot);
2963
2964 /* handle friction effects (tangential and angular velocity) */
2965 if (frict > 0.0f) {
2966 /* angular <-> linear velocity */
2967 if (dynamic_rotation) {
2968 float vr_tan[3], v1_tan[3], ave[3];
2969
2970 /* linear velocity of particle surface */
2971 cross_v3_v3v3(vr_tan, pce->nor, pa->state.ave);
2972 mul_v3_fl(vr_tan, pa->size);
2973
2974 /* change to coordinates that move with the collision plane */
2975 sub_v3_v3v3(v1_tan, v0_tan, vc_tan);
2976
2977 /* The resulting velocity is a weighted average of particle cm & surface
2978 * velocity. This weight (related to particle's moment of inertia) could
2979 * be made a parameter for angular <-> linear conversion.
2980 */
2981 madd_v3_v3fl(v1_tan, vr_tan, -0.4);
2982 mul_v3_fl(v1_tan, 1.0f / 1.4f); /* 1/(1+0.4) */
2983
2984 /* rolling friction is around 0.01 of sliding friction
2985 * (could be made a parameter) */
2986 mul_v3_fl(v1_tan, 1.0f - 0.01f * frict);
2987
2988 /* surface_velocity is opposite to cm velocity */
2989 negate_v3_v3(vr_tan, v1_tan);
2990
2991 /* get back to global coordinates */
2992 add_v3_v3(v1_tan, vc_tan);
2993
2994 /* Convert to angular velocity. */
2995 cross_v3_v3v3(ave, vr_tan, pce->nor);
2996 mul_v3_fl(ave, 1.0f / std::max(pa->size, 0.001f));
2997
2998 /* only friction will cause change in linear & angular velocity */
2999 interp_v3_v3v3(pa->state.ave, pa->state.ave, ave, frict);
3000 interp_v3_v3v3(v0_tan, v0_tan, v1_tan, frict);
3001 }
3002 else {
3003 /* Just basic friction (nonphysical due to the friction model used in Blender). */
3004 interp_v3_v3v3(v0_tan, v0_tan, vc_tan, frict);
3005 }
3006 }
3007
3008 /* Stickiness was possibly added before,
3009 * so cancel that before calculating new normal velocity.
3010 * Otherwise particles go flying out of the surface
3011 * because of high reversed sticky velocity. */
3012 if (v0_dot < 0.0f) {
3013 v0_dot += pd->pdef_stickness;
3014 v0_dot = std::min(v0_dot, 0.0f);
3015 }
3016
3017 /* damping and flipping of velocity around normal */
3018 v0_dot *= 1.0f - damp;
3019 vc_dot *= through ? damp : 1.0f;
3020
3021 /* calculate normal particle velocity */
3022 /* special case for object hitting the particle from behind */
3023 if (through == 0 && ((vc_dot > 0.0f && v0_dot > 0.0f && vc_dot > v0_dot) ||
3024 (vc_dot < 0.0f && v0_dot < 0.0f && vc_dot < v0_dot)))
3025 {
3026 mul_v3_v3fl(v0_nor, pce->nor, vc_dot);
3027 }
3028 else if (v0_dot > 0.0f) {
3029 mul_v3_v3fl(v0_nor, pce->nor, vc_dot + v0_dot);
3030 }
3031 else {
3032 mul_v3_v3fl(v0_nor, pce->nor, vc_dot + (through ? 1.0f : -1.0f) * v0_dot);
3033 }
3034
3035 /* combine components together again */
3036 add_v3_v3v3(v0, v0_nor, v0_tan);
3037
3038 if (col->boid) {
3039 /* keep boids above ground */
3040 BoidParticle *bpa = pa->boid;
3041 if (bpa->data.mode == eBoidMode_OnLand || co[2] <= col->boid_z) {
3042 co[2] = col->boid_z;
3043 v0[2] = 0.0f;
3044 }
3045 }
3046
3047 /* re-apply acceleration to final location and velocity */
3048 madd_v3_v3v3fl(pa->state.co, co, v0, dt2);
3049 madd_v3_v3fl(pa->state.co, col->acc, 0.5f * dt2 * dt2);
3050 madd_v3_v3v3fl(pa->state.vel, v0, col->acc, dt2);
3051
3052 /* make sure particle stays on the right side of the surface */
3053 if (!through) {
3054 distance = collision_point_distance_with_normal(co, pce, -1.0f, col, nor);
3055
3058 }
3059
3060 dot = dot_v3v3(nor, v0);
3061 if (dot < 0.0f) {
3062 madd_v3_v3fl(v0, nor, -dot);
3063 }
3064
3065 distance = collision_point_distance_with_normal(pa->state.co, pce, 1.0f, col, nor);
3066
3069 }
3070
3071 dot = dot_v3v3(nor, pa->state.vel);
3072 if (dot < 0.0f) {
3073 madd_v3_v3fl(pa->state.vel, nor, -dot);
3074 }
3075 }
3076
3077 /* add stickiness to surface */
3078 madd_v3_v3fl(pa->state.vel, pce->nor, -pd->pdef_stickness);
3079
3080 /* set coordinates for next iteration */
3081 copy_v3_v3(col->co1, co);
3082 copy_v3_v3(col->co2, pa->state.co);
3083
3084 copy_v3_v3(col->ve1, v0);
3085 copy_v3_v3(col->ve2, pa->state.vel);
3086
3087 col->f = f;
3088
3089 /* if permeability random roll succeeded, disable collider for this sim step */
3090 if (through) {
3091 col->skip[col->skip_count++] = col->hit;
3092 }
3093
3094 return 1;
3095}
3097{
3098 /* final chance to prevent total failure, so stick to the surface and hope for the best */
3099 collision_point_on_surface(col->co1, &col->pce, 1.0f, col, pa->state.co);
3100
3101 copy_v3_v3(pa->state.vel, col->pce.vel);
3102 mul_v3_fl(pa->state.vel, col->inv_timestep);
3103
3104 // printf("max iterations\n");
3105}
3106
3117static void collision_check(ParticleSimulationData *sim, int p, float dfra, float cfra)
3118{
3119 ParticleSettings *part = sim->psys->part;
3120 ParticleData *pa = sim->psys->particles + p;
3122 BVHTreeRayHit hit;
3123 int collision_count = 0;
3124
3125 float timestep = psys_get_timestep(sim);
3126
3127 memset(&col, 0, sizeof(ParticleCollision));
3128
3129 col.total_time = timestep * dfra;
3130 col.inv_total_time = 1.0f / col.total_time;
3131 col.inv_timestep = 1.0f / timestep;
3132
3133 col.cfra = cfra;
3134 col.old_cfra = sim->psys->cfra;
3135
3136 /* Get acceleration (from gravity, force-fields etc. to be re-applied in collision response). */
3137 sub_v3_v3v3(col.acc, pa->state.vel, pa->prev_state.vel);
3138 mul_v3_fl(col.acc, 1.0f / col.total_time);
3139
3140 /* set values for first iteration */
3141 copy_v3_v3(col.co1, pa->prev_state.co);
3142 copy_v3_v3(col.co2, pa->state.co);
3143 copy_v3_v3(col.ve1, pa->prev_state.vel);
3144 copy_v3_v3(col.ve2, pa->state.vel);
3145 col.f = 0.0f;
3146
3147 col.radius = ((part->flag & PART_SIZE_DEFL) || (part->phystype == PART_PHYS_BOIDS)) ?
3148 pa->size :
3150
3151 /* override for boids */
3152 if (part->phystype == PART_PHYS_BOIDS && part->boids->options & BOID_ALLOW_LAND) {
3153 col.boid = 1;
3154 col.boid_z = pa->state.co[2];
3155 col.skip[col.skip_count++] = pa->boid->ground;
3156 }
3157
3158 /* 10 iterations to catch multiple collisions */
3159 while (collision_count < PARTICLE_COLLISION_MAX_COLLISIONS) {
3160 if (collision_detect(pa, &col, &hit, sim->colliders)) {
3161
3162 collision_count++;
3163
3164 if (collision_count == PARTICLE_COLLISION_MAX_COLLISIONS) {
3165 collision_fail(pa, &col);
3166 }
3167 else if (collision_response(
3168 sim, pa, &col, &hit, part->flag & PART_DIE_ON_COL, part->flag & PART_ROT_DYN) ==
3169 0)
3170 {
3171 return;
3172 }
3173 }
3174 else {
3175 return;
3176 }
3177 }
3178}
3179
3181
3182/* -------------------------------------------------------------------- */
3185
3190 float cfra,
3191 const bool use_render_params)
3192{
3193 ParticleSystem *psys = sim->psys;
3194 ParticleSettings *part = psys->part;
3196 int distr = 0, alloc = 0, skip = 0;
3197
3198 if ((psys->part->childtype &&
3199 psys->totchild != psys_get_tot_child(sim->scene, psys, use_render_params)) ||
3201 {
3202 alloc = 1;
3203 }
3204
3205 if (alloc || psys->recalc & ID_RECALC_PSYS_CHILD ||
3206 (psys->vgroup[PSYS_VG_DENSITY] && (sim->ob && sim->ob->mode & OB_MODE_WEIGHT_PAINT)))
3207 {
3208 distr = 1;
3209 }
3210
3211 if (distr) {
3212 if (alloc) {
3213 realloc_particles(sim, sim->psys->totpart);
3214 }
3215
3216 if (psys_get_tot_child(sim->scene, psys, use_render_params)) {
3217 /* don't generate children while computing the hair keys */
3218 if (!(psys->part->type == PART_HAIR) || (psys->flag & PSYS_HAIR_DONE)) {
3220
3221 if (part->childtype == PART_CHILD_FACES && part->parents != 0.0f) {
3222 psys_find_parents(sim, use_render_params);
3223 }
3224 }
3225 }
3226 else {
3227 psys_free_children(psys);
3228 }
3229 }
3230
3231 if ((part->type == PART_HAIR || psys->flag & PSYS_KEYED ||
3232 psys->pointcache->flag & PTCACHE_BAKED) == 0)
3233 {
3234 skip = 1; /* only hair, keyed and baked stuff can have paths */
3235 }
3236 else if (part->ren_as != PART_DRAW_PATH &&
3237 !(part->type == PART_HAIR && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR)))
3238 {
3239 skip = 1; /* particle visualization must be set as path */
3240 }
3241 else if (DEG_get_mode(sim->depsgraph) != DAG_EVAL_RENDER) {
3242 if (part->draw_as != PART_DRAW_REND) {
3243 skip = 1; /* draw visualization */
3244 }
3245 else if (psys->pointcache->flag & PTCACHE_BAKING) {
3246 skip = 1; /* no need to cache paths while baking dynamics */
3247 }
3248 else if (psys_in_edit_mode(sim->depsgraph, psys)) {
3249 if ((pset->flag & PE_DRAW_PART) == 0) {
3250 skip = 1;
3251 }
3252 else if (part->childtype == 0 &&
3253 (psys->flag & PSYS_HAIR_DYNAMICS && psys->pointcache->flag & PTCACHE_BAKED) == 0)
3254 {
3255 skip = 1; /* in edit mode paths are needed for child particles and dynamic hair */
3256 }
3257 }
3258 }
3259
3260 if (!skip) {
3261 psys_cache_paths(sim, cfra, use_render_params);
3262
3263 /* for render, child particle paths are computed on the fly */
3264 if (part->childtype) {
3265 if (!psys->totchild) {
3266 skip = 1;
3267 }
3268 else if (psys->part->type == PART_HAIR && (psys->flag & PSYS_HAIR_DONE) == 0) {
3269 skip = 1;
3270 }
3271
3272 if (!skip) {
3273 psys_cache_child_paths(sim, cfra, false, use_render_params);
3274 }
3275 }
3276 }
3277 else if (psys->pathcache) {
3278 psys_free_path_cache(psys, nullptr);
3279 }
3280}
3281
3282static bool psys_hair_use_simulation(ParticleData *pa, float max_length)
3283{
3284 /* Minimum segment length relative to average length.
3285 * Hairs with segments below this length will be excluded from the simulation,
3286 * because otherwise the solver will become unstable.
3287 * The hair system should always make sure the hair segments have reasonable length ratios,
3288 * but this can happen in old files when e.g. cutting hair.
3289 */
3290 const float min_length = 0.1f * max_length;
3291
3292 HairKey *key;
3293 int k;
3294
3295 if (pa->totkey < 2) {
3296 return false;
3297 }
3298
3299 for (k = 1, key = pa->hair + 1; k < pa->totkey; k++, key++) {
3300 float length = len_v3v3(key->co, (key - 1)->co);
3301 if (length < min_length) {
3302 return false;
3303 }
3304 }
3305
3306 return true;
3307}
3308
3309static MDeformVert *hair_set_pinning(MDeformVert *dvert, float weight)
3310{
3311 if (dvert) {
3312 if (!dvert->totweight) {
3313 dvert->dw = MEM_new_zeroed<MDeformWeight>("deformWeight");
3314 dvert->totweight = 1;
3315 }
3316
3317 dvert->dw->weight = weight;
3318 dvert++;
3319 }
3320 return dvert;
3321}
3322
3324 int totpoint,
3325 int totedge,
3326 Mesh **r_mesh)
3327{
3328 ParticleSystem *psys = sim->psys;
3329 ParticleSettings *part = psys->part;
3330 Mesh *mesh;
3331 MDeformVert *dvert;
3332 HairKey *key;
3333 PARTICLE_P;
3334 int k, hair_index;
3335 float hairmat[4][4];
3336 float max_length;
3337 float hair_radius;
3338
3339 mesh = *r_mesh;
3340 if (!mesh) {
3341 *r_mesh = mesh = BKE_mesh_new_nomain(totpoint, totedge, 0, 0);
3342 }
3343 MutableSpan<float3> positions = mesh->vert_positions_for_write();
3344 int2 *edge = mesh->edges_for_write().data();
3345 dvert = mesh->deform_verts_for_write().data();
3346
3347 if (psys->clmd->hairdata == nullptr) {
3349 "hair data");
3350 }
3351
3352 /* calculate maximum segment length */
3353 max_length = 0.0f;
3355 {
3356 if (!(pa->flag & PARS_UNEXIST)) {
3357 for (k = 1, key = pa->hair + 1; k < pa->totkey; k++, key++) {
3358 float length = len_v3v3(key->co, (key - 1)->co);
3359 max_length = std::max(max_length, length);
3360 }
3361 }
3362 }
3363
3364 psys->clmd->sim_parms->vgroup_mass = 1;
3365
3366 int vert_index = 0;
3367
3368 /* XXX placeholder for more flexible future hair settings */
3369 hair_radius = part->size;
3370
3371 /* Make vgroup for pin roots etc. */
3372 hair_index = 1;
3374 {
3375 if (!(pa->flag & PARS_UNEXIST)) {
3376 float root_mat[4][4];
3377 float bending_stiffness;
3378 bool use_hair;
3379
3380 pa->hair_index = hair_index;
3381 use_hair = psys_hair_use_simulation(pa, max_length);
3382
3383 psys_mat_hair_to_object(sim->ob, sim->psmd->mesh_final, psys->part->from, pa, hairmat);
3384 mul_m4_m4m4(root_mat, sim->ob->object_to_world().ptr(), hairmat);
3385 normalize_m4(root_mat);
3386
3387 bending_stiffness = std::clamp(
3388 1.0f - part->bending_random * psys_frand(psys, p + 666), 0.0f, 1.0f);
3389
3390 for (k = 0, key = pa->hair; k < pa->totkey; k++, key++) {
3391 ClothHairData *hair;
3392 float *co, *co_next;
3393
3394 co = key->co;
3395 co_next = (key + 1)->co;
3396
3397 /* create fake root before actual root to resist bending */
3398 if (k == 0) {
3399 hair = &psys->clmd->hairdata[pa->hair_index - 1];
3400 copy_v3_v3(hair->loc, root_mat[3]);
3401 copy_m3_m4(hair->rot, root_mat);
3402
3403 hair->radius = hair_radius;
3404 hair->bending_stiffness = bending_stiffness;
3405
3406 add_v3_v3v3(positions[vert_index], co, co);
3407 sub_v3_v3(positions[vert_index], co_next);
3408 mul_m4_v3(hairmat, positions[vert_index]);
3409
3410 edge->x = pa->hair_index - 1;
3411 edge->y = pa->hair_index;
3412
3413 dvert = hair_set_pinning(dvert, 1.0f);
3414
3415 vert_index++;
3416 edge++;
3417 }
3418
3419 /* store root transform in cloth data */
3420 hair = &psys->clmd->hairdata[pa->hair_index + k];
3421 copy_v3_v3(hair->loc, root_mat[3]);
3422 copy_m3_m4(hair->rot, root_mat);
3423
3424 hair->radius = hair_radius;
3425 hair->bending_stiffness = bending_stiffness;
3426
3427 copy_v3_v3(positions[vert_index], co);
3428 mul_m4_v3(hairmat, positions[vert_index]);
3429
3430 if (k) {
3431 edge->x = pa->hair_index + k - 1;
3432 edge->y = pa->hair_index + k;
3433 }
3434
3435 /* roots and disabled hairs should be 1.0, the rest can be anything from 0.0 to 1.0 */
3436 if (use_hair) {
3437 dvert = hair_set_pinning(dvert, key->weight);
3438 }
3439 else {
3440 dvert = hair_set_pinning(dvert, 1.0f);
3441 }
3442
3443 vert_index++;
3444 if (k) {
3445 edge++;
3446 }
3447 }
3448
3449 hair_index += pa->totkey + 1;
3450 }
3451 }
3452}
3453
3455{
3456 ParticleSystem *psys = sim->psys;
3457 PARTICLE_P;
3458 EffectorWeights *clmd_effweights;
3459 int totpoint;
3460 int totedge;
3461 bool realloc_roots;
3462
3463 if (!psys->clmd) {
3464 psys->clmd = reinterpret_cast<ClothModifierData *>(BKE_modifier_new(eModifierType_Cloth));
3465 psys->clmd->sim_parms->goalspring = 0.0f;
3468 }
3469
3470 /* count simulated points */
3471 totpoint = 0;
3472 totedge = 0;
3474 {
3475 if (!(pa->flag & PARS_UNEXIST)) {
3476 /* "out" dm contains all hairs */
3477 totedge += pa->totkey;
3478 totpoint += pa->totkey + 1; /* +1 for virtual root point */
3479 }
3480 }
3481
3482 /* whether hair root info array has to be reallocated */
3483 realloc_roots = false;
3484 if (psys->hair_in_mesh) {
3485 Mesh *mesh = psys->hair_in_mesh;
3486 if (totpoint != mesh->verts_num || totedge != mesh->edges_num) {
3487 BKE_id_free(nullptr, mesh);
3488 psys->hair_in_mesh = nullptr;
3489 realloc_roots = true;
3490 }
3491 }
3492
3493 if (!psys->hair_in_mesh || !psys->clmd->hairdata || realloc_roots) {
3494 if (psys->clmd->hairdata) {
3495 MEM_delete(psys->clmd->hairdata);
3496 psys->clmd->hairdata = nullptr;
3497 }
3498 }
3499
3500 /* Free hair_out_mesh before modifying hair_in_mesh in hair_create_input_mesh() to avoid copying
3501 * on write since they share some data */
3502 if (psys->hair_out_mesh) {
3503 BKE_id_free(nullptr, psys->hair_out_mesh);
3504 }
3505
3506 hair_create_input_mesh(sim, totpoint, totedge, &psys->hair_in_mesh);
3507
3508 psys->clmd->point_cache = psys->pointcache;
3509 /* for hair sim we replace the internal cloth effector weights temporarily
3510 * to use the particle settings
3511 */
3512 clmd_effweights = psys->clmd->sim_parms->effector_weights;
3514
3515 BKE_id_copy_ex(nullptr,
3516 &psys->hair_in_mesh->id,
3517 reinterpret_cast<ID **>(&psys->hair_out_mesh),
3519
3521 psys->clmd,
3522 sim->depsgraph,
3523 sim->scene,
3524 sim->ob,
3525 psys->hair_in_mesh,
3526 reinterpret_cast<float (*)[3]>(psys->hair_out_mesh->vert_positions_for_write().data()));
3527 psys->hair_out_mesh->tag_positions_changed();
3528
3529 /* restore cloth effector weights */
3530 psys->clmd->sim_parms->effector_weights = clmd_effweights;
3531}
3532static void hair_step(ParticleSimulationData *sim, float cfra, const bool use_render_params)
3533{
3534 ParticleSystem *psys = sim->psys;
3535 ParticleSettings *part = psys->part;
3536 PARTICLE_P;
3537 float disp = psys_get_current_display_percentage(psys, use_render_params);
3538
3540 {
3541 pa->size = part->size;
3542 if (part->randsize > 0.0f) {
3543 pa->size *= 1.0f - part->randsize * psys_frand(psys, p + 1);
3544 }
3545
3546 if (psys_frand(psys, p) > disp) {
3547 pa->flag |= PARS_NO_DISP;
3548 }
3549 else {
3550 pa->flag &= ~PARS_NO_DISP;
3551 }
3552 }
3553
3554 if (psys->recalc & ID_RECALC_PSYS_RESET) {
3555 /* need this for changing subsurf levels */
3556 psys_calc_dmcache(sim->ob, sim->psmd->mesh_final, sim->psmd->mesh_original, psys);
3557
3558 if (psys->clmd) {
3560 }
3561 }
3562
3563 /* dynamics with cloth simulation, psys->particles can be nullptr with 0 particles #25519. */
3564 if (psys->part->type == PART_HAIR && psys->flag & PSYS_HAIR_DYNAMICS && psys->particles) {
3565 do_hair_dynamics(sim);
3566 }
3567
3568 /* following lines were removed r29079 but cause bug #22811, see report for details */
3570 psys_update_path_cache(sim, cfra, use_render_params);
3571
3572 psys->flag |= PSYS_HAIR_UPDATED;
3573}
3574
3575static void save_hair(ParticleSimulationData *sim, float /*cfra*/)
3576{
3577 Object *ob = sim->ob;
3578 ParticleSystem *psys = sim->psys;
3579 HairKey *key, *root;
3580 PARTICLE_P;
3581
3582 invert_m4_m4(ob->runtime->world_to_object.ptr(), ob->object_to_world().ptr());
3583
3584 if (psys->totpart == 0) {
3585 return;
3586 }
3587
3588 psys_sim_data_init(sim);
3589
3590 /* save new keys for elements if needed */
3592 {
3593 /* first time alloc */
3594 if (pa->totkey == 0 || pa->hair == nullptr) {
3595 pa->hair = MEM_new_array_zeroed<HairKey>(size_t(psys->part->hair_step) + 1, "HairKeys");
3596 pa->totkey = 0;
3597 }
3598
3599 key = root = pa->hair;
3600 key += pa->totkey;
3601
3602 /* convert from global to geometry space */
3603 copy_v3_v3(key->co, pa->state.co);
3604 mul_m4_v3(ob->world_to_object().ptr(), key->co);
3605
3606 if (pa->totkey) {
3607 sub_v3_v3(key->co, root->co);
3608 psys_vec_rot_to_face(sim->psmd->mesh_final, pa, key->co);
3609 }
3610
3611 key->time = pa->state.time;
3612
3613 key->weight = 1.0f - key->time / 100.0f;
3614
3615 pa->totkey++;
3616
3617 /* Root is always in the origin of hair space
3618 * so we set it to be so after the last key is saved. */
3619 if (pa->totkey == psys->part->hair_step + 1) {
3620 zero_v3(root->co);
3621 }
3622 }
3623
3624 psys_sim_data_free(sim);
3625}
3626
3628static const float MIN_TIMESTEP = 1.0f / 101.0f;
3633static const float TIMESTEP_EXPANSION_FACTOR = 0.1f;
3634static const float TIMESTEP_EXPANSION_TOLERANCE = 1.5f;
3635
3643 ParticleSimulationData *sim, ParticleData *pa, float dtime, SPHData *sphdata, SpinLock *spin)
3644{
3645 float relative_vel[3];
3646
3647 sub_v3_v3v3(relative_vel, pa->prev_state.vel, sphdata->flow);
3648
3649 const float courant_num = len_v3(relative_vel) * dtime / sphdata->element_size;
3650 if (sim->courant_num < courant_num) {
3651 BLI_spin_lock(spin);
3652 sim->courant_num = std::max(sim->courant_num, courant_num);
3653 BLI_spin_unlock(spin);
3654 }
3655}
3657{
3658 return 1.0f / float(part->subframes + 1);
3659}
3660/* Update time step size to suit current conditions. */
3662{
3663 float dt_target;
3664 if (sim->courant_num == 0.0f) {
3665 dt_target = 1.0f;
3666 }
3667 else {
3668 dt_target = psys->dt_frac * (psys->part->courant_target / sim->courant_num);
3669 }
3670
3671 /* Make sure the time step is reasonable. For some reason, the CLAMP macro
3672 * doesn't work here. The time step becomes too large. - z0r */
3673 if (dt_target < MIN_TIMESTEP) {
3674 dt_target = MIN_TIMESTEP;
3675 }
3676 else if (dt_target > get_base_time_step(psys->part)) {
3677 dt_target = get_base_time_step(psys->part);
3678 }
3679
3680 /* Decrease time step instantly, but increase slowly. */
3681 if (dt_target > psys->dt_frac) {
3682 psys->dt_frac = interpf(dt_target, psys->dt_frac, TIMESTEP_EXPANSION_FACTOR);
3683 }
3684 else {
3685 psys->dt_frac = dt_target;
3686 }
3687}
3688
3689static float sync_timestep(ParticleSystem *psys, float t_frac)
3690{
3691 /* Sync with frame end if it's close. */
3692 if (t_frac == 1.0f) {
3693 return psys->dt_frac;
3694 }
3695 if (t_frac + (psys->dt_frac * TIMESTEP_EXPANSION_TOLERANCE) >= 1.0f) {
3696 return 1.0f - t_frac;
3697 }
3698
3699 return psys->dt_frac;
3700}
3701
3703
3704/* -------------------------------------------------------------------- */
3707
3717
3718static SPHData dynamics_step_sphdata_reduce(const SPHData &sphdata_to, const SPHData &sphdata_from)
3719{
3720 SPHData result = sphdata_to;
3721 result.new_springs.extend(sphdata_from.new_springs);
3722 return result;
3723}
3724
3726 const int p,
3727 SPHData *sphdata)
3728{
3729 ParticleSimulationData *sim = data->sim;
3730 ParticleSystem *psys = sim->psys;
3731 ParticleSettings *part = psys->part;
3732
3733 ParticleData *pa;
3734
3735 if ((pa = psys->particles + p)->state.time <= 0.0f) {
3736 return;
3737 }
3738
3739 /* do global forces & effectors */
3740 basic_integrate(sim, p, pa->state.time, data->cfra);
3741
3742 /* actual fluids calculations */
3743 sph_integrate(sim, pa, pa->state.time, sphdata);
3744
3745 if (sim->colliders) {
3746 collision_check(sim, p, pa->state.time, data->cfra);
3747 }
3748
3749 /* SPH particles are not physical particles, just interpolation
3750 * particles, thus rotation has not a direct sense for them. */
3751 basic_rotate(part, pa, pa->state.time, data->timestep);
3752
3753 if (part->time_flag & PART_TIME_AUTOSF) {
3754 update_courant_num(sim, pa, data->dtime, sphdata, &data->spin);
3755 }
3756}
3757
3759 void *__restrict userdata, const int p, const TaskParallelTLS *__restrict /*tls*/)
3760{
3761 DynamicStepSolverTaskData *data = static_cast<DynamicStepSolverTaskData *>(userdata);
3762 ParticleSimulationData *sim = data->sim;
3763 ParticleSystem *psys = sim->psys;
3764
3765 ParticleData *pa;
3766
3767 if ((pa = psys->particles + p)->state.time <= 0.0f) {
3768 return;
3769 }
3770
3771 basic_integrate(sim, p, pa->state.time, data->cfra);
3772}
3773
3775 void *__restrict userdata, const int p, const TaskParallelTLS *__restrict tls)
3776{
3777 DynamicStepSolverTaskData *data = static_cast<DynamicStepSolverTaskData *>(userdata);
3778 ParticleSimulationData *sim = data->sim;
3779 ParticleSystem *psys = sim->psys;
3780
3781 SPHData *sphdata = static_cast<SPHData *>(tls->userdata_chunk);
3782
3783 ParticleData *pa;
3784
3785 if ((pa = psys->particles + p)->state.time <= 0.0f) {
3786 return;
3787 }
3788
3789 sphclassical_calc_dens(pa, pa->state.time, sphdata);
3790}
3791
3792static void dynamics_step_sph_classical_integrate_task_cb_ex(void *__restrict userdata,
3793 const int p,
3794 const TaskParallelTLS *__restrict tls)
3795{
3796 DynamicStepSolverTaskData *data = static_cast<DynamicStepSolverTaskData *>(userdata);
3797 ParticleSimulationData *sim = data->sim;
3798 ParticleSystem *psys = sim->psys;
3799 ParticleSettings *part = psys->part;
3800
3801 SPHData *sphdata = static_cast<SPHData *>(tls->userdata_chunk);
3802
3803 ParticleData *pa;
3804
3805 if ((pa = psys->particles + p)->state.time <= 0.0f) {
3806 return;
3807 }
3808
3809 /* actual fluids calculations */
3810 sph_integrate(sim, pa, pa->state.time, sphdata);
3811
3812 if (sim->colliders) {
3813 collision_check(sim, p, pa->state.time, data->cfra);
3814 }
3815
3816 /* SPH particles are not physical particles, just interpolation
3817 * particles, thus rotation has not a direct sense for them. */
3818 basic_rotate(part, pa, pa->state.time, data->timestep);
3819
3820 if (part->time_flag & PART_TIME_AUTOSF) {
3821 update_courant_num(sim, pa, data->dtime, sphdata, &data->spin);
3822 }
3823}
3824
3825/* unbaked particles are calculated dynamically */
3826static void dynamics_step(ParticleSimulationData *sim, float cfra)
3827{
3828 ParticleSystem *psys = sim->psys;
3829 ParticleSettings *part = psys->part;
3830 BoidBrainData bbd;
3831 ParticleTexture ptex;
3832 PARTICLE_P;
3833 float timestep;
3834 /* frame & time changes */
3835 float dfra, dtime;
3836 float birthtime, dietime;
3837
3838 /* where have we gone in time since last time */
3839 dfra = cfra - psys->cfra;
3840
3841 timestep = psys_get_timestep(sim);
3842 dtime = dfra * timestep;
3843
3844 if (dfra < 0.0f) {
3846 {
3847 psys_get_texture(sim, pa, &ptex, PAMAP_SIZE, cfra);
3848 pa->size = part->size * ptex.size;
3849 if (part->randsize > 0.0f) {
3850 pa->size *= 1.0f - part->randsize * psys_frand(psys, p + 1);
3851 }
3852
3853 reset_particle(sim, pa, dtime, cfra);
3854 }
3855 return;
3856 }
3857
3858 /* for now do both, boids us 'rng' */
3859 sim->rng = BLI_rng_new_srandom(31415926 + int(cfra) + psys->seed);
3860
3862
3863 if (part->type != PART_HAIR) {
3865 }
3866
3867 /* initialize physics type specific stuff */
3868 switch (part->phystype) {
3869 case PART_PHYS_BOIDS: {
3870 ParticleTarget *pt = psys->targets.first();
3871 bbd.sim = sim;
3872 bbd.part = part;
3873 bbd.cfra = cfra;
3874 bbd.dfra = dfra;
3875 bbd.timestep = timestep;
3876 bbd.rng = sim->rng;
3877
3878 psys_update_particle_tree(psys, cfra);
3879
3880 boids_precalc_rules(part, cfra);
3881
3882 for (; pt; pt = pt->next) {
3883 ParticleSystem *psys_target = psys_get_target_system(sim->ob, pt);
3884 if (psys_target && psys_target != psys) {
3885 psys_update_particle_tree(psys_target, cfra);
3886 }
3887 }
3888 break;
3889 }
3890 case PART_PHYS_FLUID: {
3891 ParticleTarget *pt = psys->targets.first();
3892 psys_update_particle_bvhtree(psys, cfra);
3893
3894 /* Updating others systems particle tree for fluid-fluid interaction. */
3895 for (; pt; pt = pt->next) {
3896 if (pt->ob) {
3898 static_cast<ParticleSystem *>(BLI_findlink(&pt->ob->particlesystem, pt->psys - 1)),
3899 cfra);
3900 }
3901 }
3902 break;
3903 }
3904 case PART_PHYS_NEWTON:
3905 case PART_PHYS_KEYED:
3906 case PART_PHYS_NO:
3907 break;
3908 }
3909 /* initialize all particles for dynamics */
3911 {
3912 copy_particle_key(&pa->prev_state, &pa->state, 1);
3913
3914 psys_get_texture(sim, pa, &ptex, PAMAP_SIZE, cfra);
3915
3916 pa->size = part->size * ptex.size;
3917 if (part->randsize > 0.0f) {
3918 pa->size *= 1.0f - part->randsize * psys_frand(psys, p + 1);
3919 }
3920
3921 birthtime = pa->time;
3922 dietime = pa->dietime;
3923
3924 /* store this, so we can do multiple loops over particles */
3925 pa->state.time = dfra;
3926
3927 if (dietime <= cfra && psys->cfra < dietime) {
3928 /* particle dies some time between this and last step */
3929 pa->state.time = dietime - ((birthtime > psys->cfra) ? birthtime : psys->cfra);
3930 pa->alive = PARS_DYING;
3931 }
3932 else if (birthtime <= cfra && birthtime >= psys->cfra) {
3933 /* Particle is born some time between this and last step. */
3934 reset_particle(sim, pa, dfra * timestep, cfra);
3935 pa->alive = PARS_ALIVE;
3936 pa->state.time = cfra - birthtime;
3937 }
3938 else if (dietime < cfra) {
3939 /* nothing to be done when particle is dead */
3940 }
3941
3942 /* Only reset unborn particles if they're shown or if the particle is born soon. */
3943 if (pa->alive == PARS_UNBORN &&
3944 (part->flag & PART_UNBORN || (cfra + psys->pointcache->step > pa->time)))
3945 {
3946 reset_particle(sim, pa, dtime, cfra);
3947 }
3948 else if (part->phystype == PART_PHYS_NO) {
3949 reset_particle(sim, pa, dtime, cfra);
3950 }
3951
3952 if (ELEM(pa->alive, PARS_ALIVE, PARS_DYING) == 0 || (pa->flag & (PARS_UNEXIST | PARS_NO_DISP)))
3953 {
3954 pa->state.time = -1.0f;
3955 }
3956 }
3957
3958 switch (part->phystype) {
3959 case PART_PHYS_NEWTON: {
3961 {
3962 /* do global forces & effectors */
3963 basic_integrate(sim, p, pa->state.time, cfra);
3964
3965 /* deflection */
3966 if (sim->colliders) {
3967 collision_check(sim, p, pa->state.time, cfra);
3968 }
3969
3970 /* rotations */
3971 basic_rotate(part, pa, pa->state.time, timestep);
3972 }
3973 break;
3974 }
3975 case PART_PHYS_BOIDS: {
3977 {
3978 bbd.goal_ob = nullptr;
3979
3980 boid_brain(&bbd, p, pa);
3981
3982 if (pa->alive != PARS_DYING) {
3983 boid_body(&bbd, pa);
3984
3985 /* deflection */
3986 if (sim->colliders) {
3987 collision_check(sim, p, pa->state.time, cfra);
3988 }
3989 }
3990 }
3991 break;
3992 }
3993 case PART_PHYS_FLUID: {
3995 SPHData sphdata;
3996 psys_sph_init(sim, &sphdata, eh);
3997
3998 DynamicStepSolverTaskData task_data{};
3999 task_data.sim = sim;
4000 task_data.cfra = cfra;
4001 task_data.timestep = timestep;
4002 task_data.dtime = dtime;
4003
4004 BLI_spin_init(&task_data.spin);
4005
4006 if (part->fluid->solver == SPH_SOLVER_DDR) {
4007 /* Apply SPH forces using double-density relaxation algorithm
4008 * (Clavat et al.) */
4010 IndexRange(psys->totpart),
4011 100,
4012 sphdata,
4013 [&](const IndexRange range, SPHData data) {
4014 for (const int i : range) {
4015 dynamics_step_sph_ddr_task_cb_ex(&task_data, i, &data);
4016 }
4017 return data;
4018 },
4020
4021 sph_springs_modify(psys, timestep);
4022 }
4023 else {
4024 /* SPH_SOLVER_CLASSICAL */
4025 /* Apply SPH forces using classical algorithm (due to Gingold
4026 * and Monaghan). Note that, unlike double-density relaxation,
4027 * this algorithm is separated into distinct loops. */
4028
4029 {
4030 TaskParallelSettings settings;
4032 settings.use_threading = (psys->totpart > 100);
4034 psys->totpart,
4035 &task_data,
4037 &settings);
4038 }
4039
4040 /* calculate summation density */
4041 /* Note that we could avoid copying sphdata for each thread here (it's only read here),
4042 * but doubt this would gain us anything except confusion... */
4043 {
4044 TaskParallelSettings settings;
4046 settings.use_threading = (psys->totpart > 100);
4047 settings.userdata_chunk = &sphdata;
4048 settings.userdata_chunk_size = sizeof(sphdata);
4050 psys->totpart,
4051 &task_data,
4053 &settings);
4054 }
4055
4056 /* do global forces & effectors */
4057 {
4058 TaskParallelSettings settings;
4060 settings.use_threading = (psys->totpart > 100);
4061 settings.userdata_chunk = &sphdata;
4062 settings.userdata_chunk_size = sizeof(sphdata);
4064 psys->totpart,
4065 &task_data,
4067 &settings);
4068 }
4069 }
4070
4071 BLI_spin_end(&task_data.spin);
4072
4073 psys_sph_finalize(&sphdata);
4074 break;
4075 }
4076 case PART_PHYS_NO:
4077 case PART_PHYS_KEYED:
4078 break;
4079 }
4080
4081 /* finalize particle state and time after dynamics */
4083 {
4084 if (pa->alive == PARS_DYING) {
4085 pa->alive = PARS_DEAD;
4086 pa->state.time = pa->dietime;
4087 }
4088 else {
4089 pa->state.time = cfra;
4090 }
4091 }
4092
4093 BKE_collider_cache_free(&sim->colliders);
4094 BLI_rng_free(sim->rng);
4095 sim->rng = nullptr;
4096}
4097
4098static void update_children(ParticleSimulationData *sim, const bool use_render_params)
4099{
4100 if ((sim->psys->part->type == PART_HAIR) && (sim->psys->flag & PSYS_HAIR_DONE) == 0) {
4101 /* don't generate children while growing hair - waste of time */
4103 }
4104 else if (sim->psys->part->childtype) {
4105 if (sim->psys->totchild != psys_get_tot_child(sim->scene, sim->psys, use_render_params)) {
4107 }
4108 else {
4109 /* Children are up to date, nothing to do. */
4110 }
4111 }
4112 else {
4114 }
4115}
4116/* Updates cached particles' alive & other flags etc. */
4117static void cached_step(ParticleSimulationData *sim, float cfra, const bool use_render_params)
4118{
4119 ParticleSystem *psys = sim->psys;
4120 ParticleSettings *part = psys->part;
4121 ParticleTexture ptex;
4122 PARTICLE_P;
4123 float disp, dietime;
4124
4126
4127 disp = psys_get_current_display_percentage(psys, use_render_params);
4128
4129 psys_sim_data_init(sim);
4130
4132 {
4133 psys_get_texture(sim, pa, &ptex, PAMAP_SIZE, cfra);
4134 pa->size = part->size * ptex.size;
4135 if (part->randsize > 0.0f) {
4136 pa->size *= 1.0f - part->randsize * psys_frand(psys, p + 1);
4137 }
4138
4139 dietime = pa->dietime;
4140
4141 /* update alive status and push events */
4142 if (pa->time > cfra) {
4143 pa->alive = PARS_UNBORN;
4144 if (part->flag & PART_UNBORN && (psys->pointcache->flag & PTCACHE_EXTERNAL) == 0) {
4145 reset_particle(sim, pa, 0.0f, cfra);
4146 }
4147 }
4148 else if (dietime <= cfra) {
4149 pa->alive = PARS_DEAD;
4150 }
4151 else {
4152 pa->alive = PARS_ALIVE;
4153 }
4154
4155 if (psys_frand(psys, p) > disp) {
4156 pa->flag |= PARS_NO_DISP;
4157 }
4158 else {
4159 pa->flag &= ~PARS_NO_DISP;
4160 }
4161 }
4162
4163 psys_sim_data_free(sim);
4164}
4165
4166static bool particles_has_flip(short parttype)
4167{
4168 return (parttype == PART_FLUID_FLIP);
4169}
4170
4171static bool particles_has_tracer(short parttype)
4172{
4173 return (parttype == PART_FLUID_TRACER);
4174}
4175
4176static bool particles_has_spray(short parttype)
4177{
4179}
4180
4181static bool particles_has_bubble(short parttype)
4182{
4184}
4185
4186static bool particles_has_foam(short parttype)
4187{
4189}
4190
4192 int cfra,
4193 const bool use_render_params)
4194{
4195 ParticleSystem *psys = sim->psys;
4196 if (psys->particles) {
4197 MEM_delete(psys->particles);
4198 psys->particles = nullptr;
4199 psys->totpart = 0;
4200 }
4201
4202#ifndef WITH_FLUID
4203 UNUSED_VARS(use_render_params, cfra);
4204#else
4205 {
4206 Object *ob = sim->ob;
4209
4210 if (fmd && fmd->domain && fmd->domain->fluid) {
4211 FluidDomainSettings *fds = fmd->domain;
4212
4213 ParticleSettings *part = psys->part;
4214 ParticleData *pa = nullptr;
4215
4216 int p, totpart = 0, tottypepart = 0;
4217 int flagActivePart, activeParts = 0;
4218 float posX, posY, posZ, velX, velY, velZ;
4219 float resX, resY, resZ;
4220 int upres = 1;
4221 char debugStrBuffer[256];
4222 float tmp[3] = {0}, tmp2[3] = {0};
4223
4224 /* Helper variables for scaling. */
4225 float min[3], max[3], size[3], cell_size_scaled[3], max_size;
4226
4227 /* Sanity check: parts also enabled in fluid domain? */
4228 if ((particles_has_flip(part->type) &&
4230 (particles_has_spray(part->type) &&
4232 (particles_has_bubble(part->type) &&
4234 (particles_has_foam(part->type) &&
4236 (particles_has_tracer(part->type) &&
4238 {
4239 BLI_snprintf(debugStrBuffer,
4240 sizeof(debugStrBuffer),
4241 "particles_fluid_step::error - found particle system that is not enabled in "
4242 "fluid domain\n");
4243 return;
4244 }
4245
4246 /* Count particle amount. tottypepart is only important for snd particles. */
4247 if (part->type == PART_FLUID_FLIP) {
4248 tottypepart = totpart = manta_liquid_get_num_flip_particles(fds->fluid);
4249 }
4250 if (particles_has_spray(part->type) || particles_has_bubble(part->type) ||
4252 {
4254
4255 /* tottypepart is the amount of particles of a snd particle type. */
4256 for (p = 0; p < totpart; p++) {
4257 flagActivePart = manta_liquid_get_snd_particle_flag_at(fds->fluid, p);
4258 if (particles_has_spray(part->type) && (flagActivePart & PARTICLE_TYPE_SPRAY)) {
4259 tottypepart++;
4260 }
4261 if (particles_has_bubble(part->type) && (flagActivePart & PARTICLE_TYPE_BUBBLE)) {
4262 tottypepart++;
4263 }
4264 if (particles_has_foam(part->type) && (flagActivePart & PARTICLE_TYPE_FOAM)) {
4265 tottypepart++;
4266 }
4267 if (particles_has_tracer(part->type) && (flagActivePart & PARTICLE_TYPE_TRACER)) {
4268 tottypepart++;
4269 }
4270 }
4271 }
4272 /* Sanity check: no particles present. */
4273 if (!totpart || !tottypepart) {
4274 return;
4275 }
4276
4277 /* How many particles to display? */
4278 tottypepart = (use_render_params) ? tottypepart : (part->disp * tottypepart) / 100;
4279
4280 part->totpart = tottypepart;
4281 part->sta = part->end = 1.0f;
4282 part->lifetime = sim->scene->r.efra + 1;
4283
4284 /* Allocate particles. */
4285 realloc_particles(sim, part->totpart);
4286
4287 /* Set some randomness when choosing which particles to display. */
4288 sim->rng = BLI_rng_new_srandom(31415926 + cfra + psys->seed);
4289 double r, dispProb = double(part->disp) / 100.0;
4290
4291 /* Loop over *all* particles. Will break out of loop before tottypepart amount exceeded. */
4292 for (p = 0, pa = psys->particles; p < totpart; p++) {
4293
4294 /* Apply some randomness and determine which particles to skip. */
4295 r = BLI_rng_get_double(sim->rng);
4296 if (r > dispProb) {
4297 continue;
4298 }
4299
4300 /* flag, res, upres, pos, vel for FLIP and snd particles have different getters. */
4301 if (part->type == PART_FLUID_FLIP) {
4302 flagActivePart = manta_liquid_get_flip_particle_flag_at(fds->fluid, p);
4303
4304 resX = float(manta_get_res_x(fds->fluid));
4305 resY = float(manta_get_res_y(fds->fluid));
4306 resZ = float(manta_get_res_z(fds->fluid));
4307
4308 upres = 1;
4309
4313
4317 }
4318 else if (particles_has_spray(part->type) || particles_has_bubble(part->type) ||
4320 {
4321 flagActivePart = manta_liquid_get_snd_particle_flag_at(fds->fluid, p);
4322
4326
4328
4332
4336 }
4337 else {
4338 BLI_snprintf(debugStrBuffer,
4339 sizeof(debugStrBuffer),
4340 "particles_fluid_step::error - unknown particle system type\n");
4341 BLI_rng_free(sim->rng);
4342 return;
4343 }
4344# if 0
4345 /* Debugging: Print type of particle system and current particles. */
4346 printf("system type is %d and particle type is %d\n", part->type, flagActivePart);
4347# endif
4348
4349 /* Type of particle must match current particle system type
4350 * (only important for snd particles). */
4351 if ((flagActivePart & PARTICLE_TYPE_SPRAY) && !particles_has_spray(part->type)) {
4352 continue;
4353 }
4354 if ((flagActivePart & PARTICLE_TYPE_BUBBLE) && !particles_has_bubble(part->type)) {
4355 continue;
4356 }
4357 if ((flagActivePart & PARTICLE_TYPE_FOAM) && !particles_has_foam(part->type)) {
4358 continue;
4359 }
4360 if ((flagActivePart & PARTICLE_TYPE_TRACER) && !particles_has_tracer(part->type)) {
4361 continue;
4362 }
4363# if 0
4364 /* Debugging: Print type of particle system and current particles. */
4365 printf("system type is %d and particle type is %d\n", part->type, flagActivePart);
4366# endif
4367 /* Particle system has allocated 'tottypepart' particles - so break early before exceeded.
4368 */
4369 if (activeParts >= tottypepart) {
4370 break;
4371 }
4372
4373 /* Only show active particles, i.e. filter out dead particles that just Mantaflow needs.
4374 * Mantaflow convention: PARTICLE_TYPE_DELETE == inactive particle. */
4375 if ((flagActivePart & PARTICLE_TYPE_DELETE) == 0) {
4376 activeParts++;
4377
4378 /* Use particle system settings for particle size. */
4379 pa->size = part->size;
4380 if (part->randsize > 0.0f) {
4381 pa->size *= 1.0f - part->randsize * psys_frand(psys, p + 1);
4382 }
4383
4384 /* Get size (dimension) but considering scaling */
4385 copy_v3_v3(cell_size_scaled, fds->cell_size);
4386 mul_v3_v3(cell_size_scaled, ob->scale);
4387 madd_v3fl_v3fl_v3fl_v3i(min, fds->p0, cell_size_scaled, fds->res_min);
4388 madd_v3fl_v3fl_v3fl_v3i(max, fds->p0, cell_size_scaled, fds->res_max);
4389 sub_v3_v3v3(size, max, min);
4390
4391 /* Biggest dimension will be used for up-scaling. */
4392 max_size = std::max(
4393 {size[0] / float(upres), size[1] / float(upres), size[2] / float(upres)});
4394
4395 /* Set particle position. */
4396 const float posParticle[3] = {posX, posY, posZ};
4397 copy_v3_v3(pa->state.co, posParticle);
4398
4399 /* Normalize to unit cube around 0. */
4400 float resDomain[3] = {resX, resY, resZ};
4401 mul_v3_fl(resDomain, 0.5f);
4402 sub_v3_v3(pa->state.co, resDomain);
4403 mul_v3_fl(pa->state.co, fds->dx);
4404
4405 /* Match domain dimension / size. */
4406 float scaleAbs[3] = {
4407 1.0f / fabsf(ob->scale[0]), 1.0f / fabsf(ob->scale[1]), 1.0f / fabsf(ob->scale[2])};
4408 mul_v3_fl(scaleAbs, max_size);
4409 mul_v3_v3(pa->state.co, scaleAbs);
4410
4411 /* Match domain scale. */
4412 mul_m4_v3(ob->object_to_world().ptr(), pa->state.co);
4413
4414 /* Add origin offset to particle position. */
4415 zero_v3(tmp);
4416 zero_v3(tmp2);
4417 sub_v3_v3v3(tmp2, fds->p1, fds->p0);
4418 mul_v3_fl(tmp2, 0.5f);
4419 add_v3_v3v3(tmp, tmp, fds->p1);
4420 sub_v3_v3(tmp, tmp2);
4421 mul_v3_v3(tmp, ob->scale);
4422 add_v3_v3(pa->state.co, tmp);
4423# if 0
4424 /* Debugging: Print particle coordinates. */
4425 printf("pa->state.co[0]: %f, pa->state.co[1]: %f, pa->state.co[2]: %f\n",
4426 pa->state.co[0],
4427 pa->state.co[1],
4428 pa->state.co[2]);
4429# endif
4430 /* Set particle velocity. */
4431 const float velParticle[3] = {velX, velY, velZ};
4432 copy_v3_v3(pa->state.vel, velParticle);
4433 mul_v3_fl(pa->state.vel, fds->dx);
4434# if 0
4435 /* Debugging: Print particle velocity. */
4436 printf("pa->state.vel[0]: %f, pa->state.vel[1]: %f, pa->state.vel[2]: %f\n",
4437 pa->state.vel[0],
4438 pa->state.vel[1],
4439 pa->state.vel[2]);
4440# endif
4441 /* Set default angular velocity and particle rotation. */
4442 zero_v3(pa->state.ave);
4443 unit_qt(pa->state.rot);
4444
4445 pa->time = 1.0f;
4446 pa->dietime = sim->scene->r.efra + 1;
4447 pa->lifetime = sim->scene->r.efra;
4448 pa->alive = PARS_ALIVE;
4449
4450 /* Increasing particle settings pointer only for active particles. */
4451 pa++;
4452 }
4453 }
4454# if 0
4455 /* Debugging: Print number of active particles. */
4456 printf("active parts: %d\n", activeParts);
4457# endif
4458 totpart = psys->totpart = part->totpart = activeParts;
4459
4460 BLI_rng_free(sim->rng);
4461 sim->rng = nullptr;
4462
4463 } /* Fluid sim particles done. */
4464 }
4465#endif /* WITH_FLUID */
4466}
4467
4468static int emit_particles(ParticleSimulationData *sim, PTCacheID *pid, float /*cfra*/)
4469{
4470 ParticleSystem *psys = sim->psys;
4471 int oldtotpart = psys->totpart;
4472 int totpart = tot_particles(psys, pid);
4473
4474 if (totpart != oldtotpart) {
4475 realloc_particles(sim, totpart);
4476 }
4477
4478 return totpart - oldtotpart;
4479}
4480
4491static void system_step(ParticleSimulationData *sim, float cfra, const bool use_render_params)
4492{
4493 ParticleSystem *psys = sim->psys;
4494 ParticleSettings *part = psys->part;
4495 PointCache *cache = psys->pointcache;
4496 PTCacheID ptcacheid, *pid = nullptr;
4497 PARTICLE_P;
4498 float disp, cache_cfra = cfra; /* , *vg_vel= 0, *vg_tan= 0, *vg_rot= 0, *vg_size= 0; */
4499 int startframe = 0, endframe = 100, oldtotpart = 0;
4500
4501 /* cache shouldn't be used for hair or "continue physics" */
4502 if (part->type != PART_HAIR) {
4504
4505 /* set suitable cache range automatically */
4506 if ((cache->flag & (PTCACHE_BAKING | PTCACHE_BAKED)) == 0) {
4507 psys_get_pointcache_start_end(sim->scene, psys, &cache->startframe, &cache->endframe);
4508 }
4509
4510 pid = &ptcacheid;
4511 BKE_ptcache_id_from_particles(pid, sim->ob, psys);
4512
4513 BKE_ptcache_id_time(pid, sim->scene, 0.0f, &startframe, &endframe, nullptr);
4514
4515 /* clear everything on start frame, or when psys needs full reset! */
4516 if ((cfra == startframe) || (psys->recalc & ID_RECALC_PSYS_RESET)) {
4518 BKE_ptcache_validate(cache, startframe);
4519 cache->flag &= ~PTCACHE_REDO_NEEDED;
4520 }
4521
4522 CLAMP(cache_cfra, startframe, endframe);
4523 }
4524
4525 /* 1. emit particles and redo particles if needed */
4526 oldtotpart = psys->totpart;
4527 if (emit_particles(sim, pid, cfra) || psys->recalc & ID_RECALC_PSYS_RESET) {
4528 distribute_particles(sim, part->from);
4530 /* reset only just created particles (on startframe all particles are recreated) */
4531 reset_all_particles(sim, 0.0, cfra, oldtotpart);
4533
4534 MEM_SAFE_DELETE(psys->fluid_springs);
4535
4536 psys->tot_fluidsprings = psys->alloc_fluidsprings = 0;
4537
4538 /* flag for possible explode modifiers after this system */
4540
4542 }
4543
4544 /* 2. try to read from the cache */
4545 if (pid) {
4546 int cache_result = BKE_ptcache_read(pid, cache_cfra, true);
4547
4549 cached_step(sim, cfra, use_render_params);
4550 update_children(sim, use_render_params);
4551 psys_update_path_cache(sim, cfra, use_render_params);
4552
4553 BKE_ptcache_validate(cache, int(cache_cfra));
4554
4555 if (cache_result == PTCACHE_READ_INTERPOLATED && cache->flag & PTCACHE_REDO_NEEDED) {
4556 BKE_ptcache_write(pid, int(cache_cfra));
4557 }
4558
4559 return;
4560 }
4561 /* Cache is supposed to be baked, but no data was found so bail out */
4562 if (cache->flag & PTCACHE_BAKED) {
4564 return;
4565 }
4566 if (cache_result == PTCACHE_READ_OLD) {
4567 psys->cfra = float(cache->simframe);
4568 cached_step(sim, psys->cfra, use_render_params);
4569 }
4570
4571 /* if on second frame, write cache for first frame */
4572 if (psys->cfra == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) {
4573 BKE_ptcache_write(pid, startframe);
4574 }
4575 }
4576 else {
4578 }
4579
4580 /* 3. do dynamics */
4581 /* set particles to be not calculated TODO: can't work with pointcache */
4582 disp = psys_get_current_display_percentage(psys, use_render_params);
4583
4585 {
4586 if (psys_frand(psys, p) > disp) {
4587 pa->flag |= PARS_NO_DISP;
4588 }
4589 else {
4590 pa->flag &= ~PARS_NO_DISP;
4591 }
4592 }
4593
4594 if (psys->totpart) {
4595 int dframe, totframesback = 0;
4596 float t_frac, dt_frac;
4597
4598 /* handle negative frame start at the first frame by doing
4599 * all the steps before the first frame */
4600 if (int(cfra) == startframe && part->sta < startframe) {
4601 totframesback = startframe - int(part->sta);
4602 }
4603
4604 if (!(part->time_flag & PART_TIME_AUTOSF)) {
4605 /* Constant time step */
4606 psys->dt_frac = get_base_time_step(part);
4607 }
4608 else if (int(cfra) == startframe) {
4609 /* Variable time step; initialize to sub-frames. */
4610 psys->dt_frac = get_base_time_step(part);
4611 }
4612 else if (psys->dt_frac < MIN_TIMESTEP) {
4613 /* Variable time step; subsequent frames */
4614 psys->dt_frac = MIN_TIMESTEP;
4615 }
4616
4617 for (dframe = -totframesback; dframe <= 0; dframe++) {
4618 /* Simulate each sub-frame. */
4619 dt_frac = psys->dt_frac;
4620 for (t_frac = dt_frac; t_frac <= 1.0f; t_frac += dt_frac) {
4621 sim->courant_num = 0.0f;
4622 dynamics_step(sim, cfra + dframe + t_frac - 1.0f);
4623 psys->cfra = cfra + dframe + t_frac - 1.0f;
4624
4625 if (part->time_flag & PART_TIME_AUTOSF) {
4626 update_timestep(psys, sim);
4627 }
4628 /* Even without AUTOSF dt_frac may not add up to 1.0 due to float precision. */
4629 dt_frac = sync_timestep(psys, t_frac);
4630 }
4631 }
4632 }
4633
4634 /* 4. only write cache starting from second frame */
4635 if (pid) {
4636 BKE_ptcache_validate(cache, int(cache_cfra));
4637 if (int(cache_cfra) != startframe) {
4638 BKE_ptcache_write(pid, int(cache_cfra));
4639 }
4640 }
4641
4642 update_children(sim, use_render_params);
4643
4644 /* cleanup */
4645 psys_sim_data_free(sim);
4646}
4647
4649{
4650 ParticleSettings *part = psys->part;
4651 PTCacheID pid;
4652
4653 BKE_ptcache_id_from_particles(&pid, ob, psys);
4654
4655 if (part->phystype != PART_PHYS_KEYED) {
4656 psys->flag &= ~PSYS_KEYED;
4657 }
4658
4659 if (part->type == PART_HAIR) {
4661 part->ren_as = PART_DRAW_PATH;
4662 }
4663
4664 if (part->distr == PART_DISTR_GRID) {
4665 part->distr = PART_DISTR_JIT;
4666 }
4667
4669 part->draw_as = PART_DRAW_REND;
4670 }
4671
4672 CLAMP(part->path_start, 0.0f, 100.0f);
4673 CLAMP(part->path_end, 0.0f, 100.0f);
4674
4676 }
4677 else {
4678 free_hair(ob, psys, 1);
4679
4680 CLAMP(part->path_start, 0.0f, std::max(100.0f, part->end + part->lifetime));
4681 CLAMP(part->path_end, 0.0f, std::max(100.0f, part->end + part->lifetime));
4682 }
4683
4685}
4687{
4688 BoidParticle *bpa;
4689 PARTICLE_P;
4690
4691 pa = psys->particles;
4692
4693 if (!pa) {
4694 return;
4695 }
4696
4697 if (psys->part && psys->part->phystype == PART_PHYS_BOIDS) {
4698 if (!pa->boid) {
4699 bpa = MEM_new_array<BoidParticle>(psys->totpart, "Boid Data");
4700
4702 {
4703 pa->boid = bpa++;
4704 }
4705 }
4706 }
4707 else if (pa->boid) {
4708 MEM_delete(pa->boid);
4710 {
4711 pa->boid = nullptr;
4712 }
4713 }
4714}
4715
4717{
4718 SPHFluidSettings *fluid = part->fluid;
4719
4720 fluid->spring_k = 0.0f;
4721 fluid->plasticity_constant = 0.1f;
4722 fluid->yield_ratio = 0.1f;
4723 fluid->rest_length = 1.0f;
4724 fluid->viscosity_omega = 2.0f;
4725 fluid->viscosity_beta = 0.1f;
4726 fluid->stiffness_k = 1.0f;
4727 fluid->stiffness_knear = 1.0f;
4728 fluid->rest_density = 1.0f;
4729 fluid->buoyancy = 0.0f;
4730 fluid->radius = 1.0f;
4733}
4734
4736{
4737 ParticleSettings *part = sim->psys->part;
4738
4740 PTCacheID pid;
4741 BKE_ptcache_id_from_particles(&pid, sim->ob, sim->psys);
4743 }
4744 else {
4745 free_keyed_keys(sim->psys);
4746 sim->psys->flag &= ~PSYS_KEYED;
4747 }
4748
4749 /* RNA Update must ensure this is true. */
4750 if (part->phystype == PART_PHYS_BOIDS) {
4751 BLI_assert(part->boids != nullptr);
4752 }
4753 else if (part->phystype == PART_PHYS_FLUID) {
4754 BLI_assert(part->fluid != nullptr);
4755 }
4756
4758}
4760{
4761 if (!(psys->flag & PSYS_EDITED) && (!psys->edit || !psys->edit->edited) &&
4762 ((psys->flag & PSYS_HAIR_DONE) == 0 || psys->recalc & ID_RECALC_PSYS_RESET ||
4763 (psys->part->flag & PART_HAIR_REGROW && !psys->edit)))
4764 {
4765 return 1;
4766 }
4767
4768 return 0;
4769}
4770
4772{
4773 ParticleSettings *particle_settings_local = id_cast<ParticleSettings *>(
4774 BKE_id_copy_ex(nullptr, (&particle_settings->id), nullptr, LIB_ID_COPY_LOCALIZE));
4775 return particle_settings_local;
4776}
4777
4778static void particle_settings_free_local(ParticleSettings *particle_settings)
4779{
4780 BKE_libblock_free_datablock(&particle_settings->id, 0);
4781 BKE_libblock_free_data(&particle_settings->id, false);
4782 BLI_assert(!particle_settings->id.py_instance); /* Or call #BKE_libblock_free_data_py. */
4783 MEM_delete(particle_settings);
4784}
4785
4786void particle_system_update(Depsgraph *depsgraph,
4787 Scene *scene,
4788 Object *ob,
4789 ParticleSystem *psys,
4790 const bool use_render_params)
4791{
4792 ParticleSimulationData sim = {nullptr};
4793 ParticleSettings *part = psys->part;
4794 ParticleSystem *psys_orig = psys_orig_get(psys);
4795 float cfra;
4797
4798 /* Draw data is outdated after ANY change. */
4799 if (psys->pdd) {
4801 }
4802
4803 if (!psys_check_enabled(ob, psys, use_render_params)) {
4804 return;
4805 }
4806
4807 cfra = DEG_get_ctime(depsgraph);
4808
4809 sim.depsgraph = depsgraph;
4810 sim.scene = scene;
4811 sim.ob = ob;
4812 sim.psys = psys;
4813 sim.psmd = psmd;
4814
4815 /* system was already updated from modifier stack */
4818 /* make sure it really was updated to cfra */
4819 if (psys->cfra == cfra) {
4820 return;
4821 }
4822 }
4823
4824 if (!sim.psmd->mesh_final) {
4825 return;
4826 }
4827
4828 if (part->from != PART_FROM_VERT) {
4830 }
4831
4832 /* to verify if we need to restore object afterwards */
4833 psys->flag &= ~PSYS_OB_ANIM_RESTORE;
4834
4835 if (psys->recalc & ID_RECALC_PSYS_RESET) {
4836 psys->totunexist = 0;
4837 }
4838
4839 /* setup necessary physics type dependent additional data if it doesn't yet exist */
4841
4842 if (part->type == PART_HAIR) {
4843 /* nothing to do so bail out early */
4844 if (psys->totpart == 0 && part->totpart == 0) {
4845 psys_free_path_cache(psys, nullptr);
4846 free_hair(ob, psys, 0);
4847 psys->flag |= PSYS_HAIR_DONE;
4848 }
4849 /* (re-)create hair */
4850 else if (hair_needs_recalc(psys)) {
4851 float hcfra = 0.0f;
4852 int i, recalc = psys->recalc;
4853
4854 free_hair(ob, psys, 0);
4855
4856 if (psys_orig->edit && psys_orig->free_edit) {
4857 psys_orig->free_edit(psys_orig->edit);
4858 psys_orig->edit = nullptr;
4859 psys_orig->free_edit = nullptr;
4860 }
4861
4862 /* first step is negative so particles get killed and reset */
4863 psys->cfra = 1.0f;
4864
4865 ParticleSettings *part_local = part;
4866 if ((part->flag & PART_HAIR_REGROW) == 0) {
4867 part_local = particle_settings_localize(part);
4868 psys->part = part_local;
4869 }
4870
4871 for (i = 0; i <= part->hair_step; i++) {
4872 hcfra = 100.0f * float(i) / float(psys->part->hair_step);
4873 if ((part->flag & PART_HAIR_REGROW) == 0) {
4875 depsgraph, hcfra);
4877 &part_local->id, part_local->adt, &anim_eval_context, ADT_RECALC_ANIM, false);
4878 }
4879 system_step(&sim, hcfra, use_render_params);
4880 psys->cfra = hcfra;
4881 psys->recalc = 0;
4882 save_hair(&sim, hcfra);
4883 }
4884
4885 if (part_local != part) {
4886 particle_settings_free_local(part_local);
4887 psys->part = part;
4888 }
4889
4890 psys->flag |= PSYS_HAIR_DONE;
4891 psys->recalc = recalc;
4892 }
4893 else if (psys->flag & PSYS_EDITED) {
4894 psys->flag |= PSYS_HAIR_DONE;
4895 }
4896
4897 if (psys->flag & PSYS_HAIR_DONE) {
4898 hair_step(&sim, cfra, use_render_params);
4899 }
4900 }
4901 else if (particles_has_flip(part->type) || particles_has_spray(part->type) ||
4904 {
4905 particles_fluid_step(&sim, int(cfra), use_render_params);
4906 }
4907 else {
4908 switch (part->phystype) {
4909 case PART_PHYS_NO:
4910 case PART_PHYS_KEYED: {
4911 PARTICLE_P;
4912 float disp = psys_get_current_display_percentage(psys, use_render_params);
4913 bool free_unexisting = false;
4914
4915 /* Particles without dynamics haven't been reset yet because they don't use pointcache */
4916 if (psys->recalc & ID_RECALC_PSYS_RESET) {
4918 }
4919
4920 if (emit_particles(&sim, nullptr, cfra) || (psys->recalc & ID_RECALC_PSYS_RESET)) {
4921 free_keyed_keys(psys);
4922 distribute_particles(&sim, part->from);
4924 free_unexisting = true;
4925
4926 /* flag for possible explode modifiers after this system */
4928 }
4929
4930 ParticleTexture ptex;
4931
4933 {
4934 psys_get_texture(&sim, pa, &ptex, PAMAP_SIZE, cfra);
4935 pa->size = part->size * ptex.size;
4936 if (part->randsize > 0.0f) {
4937 pa->size *= 1.0f - part->randsize * psys_frand(psys, p + 1);
4938 }
4939
4940 reset_particle(&sim, pa, 0.0, cfra);
4941
4942 if (psys_frand(psys, p) > disp) {
4943 pa->flag |= PARS_NO_DISP;
4944 }
4945 else {
4946 pa->flag &= ~PARS_NO_DISP;
4947 }
4948 }
4949
4950 /* free unexisting after resetting particles */
4951 if (free_unexisting) {
4953 }
4954
4955 if (part->phystype == PART_PHYS_KEYED) {
4957 set_keyed_keys(&sim);
4958 psys_update_path_cache(&sim, int(cfra), use_render_params);
4959 }
4960 break;
4961 }
4962 default: {
4963 /* the main dynamic particle system step */
4964 system_step(&sim, cfra, use_render_params);
4965 break;
4966 }
4967 }
4968 }
4969
4970 /* make sure emitter is left at correct time (particle emission can change this) */
4971 if (psys->flag & PSYS_OB_ANIM_RESTORE) {
4972 evaluate_emitter_anim(depsgraph, scene, ob, cfra);
4973 psys->flag &= ~PSYS_OB_ANIM_RESTORE;
4974 }
4975
4976 if (psys_orig->edit) {
4978 }
4979
4980 psys->cfra = cfra;
4981 psys->recalc = 0;
4982
4983 if (DEG_is_active(depsgraph)) {
4984 if (psys_orig != psys) {
4985 if (psys_orig->edit != nullptr && psys_orig->edit->psys == psys_orig) {
4986 psys_orig->edit->psys_eval = psys;
4987 psys_orig->edit->psmd_eval = psmd;
4988 }
4989 psys_orig->flag = (psys->flag & ~PSYS_SHARED_CACHES);
4990 psys_orig->cfra = psys->cfra;
4991 psys_orig->recalc = psys->recalc;
4992 psys_orig->part->totpart = part->totpart;
4993 }
4994 }
4995
4996 /* Save matrix for duplicators,
4997 * at render-time the actual dupli-object's matrix is used so don't update! */
4998 invert_m4_m4(psys->imat, ob->object_to_world().ptr());
4999
5001}
5002
5003/* ID looper */
5004
5005/* unfortunately PSys and modifier ID loopers are not directly compatible, so we need this struct
5006 * and the callback below to map the former to the latter (thanks to psys embedding a Cloth
5007 * modifier data struct now, for Hair physics simulations). */
5013
5014static void particlesystem_modifiersForeachIDLink(void *user_data,
5015 Object * /*object*/,
5016 ID **id_pointer,
5017 const LibraryForeachIDCallbackFlag cb_flag)
5018{
5020 user_data);
5021 data->func(data->psys, id_pointer, data->userdata, cb_flag);
5022}
5023
5025{
5026 LibraryForeachIDData *foreachid_data = static_cast<LibraryForeachIDData *>(userdata);
5027 const int foreachid_data_flags = BKE_lib_query_foreachid_process_flags_get(foreachid_data);
5028
5029 func(
5030 psys, reinterpret_cast<ID **>(&psys->part), userdata, IDWALK_CB_USER | IDWALK_CB_NEVER_NULL);
5031 func(psys, reinterpret_cast<ID **>(&psys->target_ob), userdata, IDWALK_CB_NOP);
5032 func(psys, reinterpret_cast<ID **>(&psys->parent), userdata, IDWALK_CB_NOP);
5033
5034 if (psys->clmd != nullptr) {
5036
5037 if (mti->foreach_ID_link != nullptr) {
5039 data.psys = psys;
5040 data.func = func;
5041 data.userdata = userdata;
5042 mti->foreach_ID_link(
5044 }
5045 }
5046
5047 for (ParticleTarget &pt : psys->targets) {
5048 func(psys, reinterpret_cast<ID **>(&pt.ob), userdata, IDWALK_CB_NOP);
5049 }
5050
5051 /* In case `psys->part` is nullptr (See ID_REMAP_SKIP/FORCE/FLAG_NEVER_NULL_USAGE in
5052 * #BKE_library_remap), or accessing it is forbidden, always handle particles for potential boids
5053 * data. Unfortunate, but for now there is no other proper way to do this. */
5054 if (!(psys->part && (foreachid_data_flags & IDWALK_NO_ORIG_POINTERS_ACCESS) == 0) ||
5055 psys->part->phystype == PART_PHYS_BOIDS)
5056 {
5057 ParticleData *pa;
5058 int p;
5059
5060 for (p = 0, pa = psys->particles; p < psys->totpart; p++, pa++) {
5061 if (pa->boid != nullptr) {
5062 func(psys, reinterpret_cast<ID **>(&pa->boid->ground), userdata, IDWALK_CB_NOP);
5063 }
5064 }
5065 }
5066}
5067
5069{
5070 for (ModifierData *md = object->modifiers.first(); md != nullptr; md = md->next) {
5071 if (md->type != eModifierType_ParticleSystem) {
5072 continue;
5073 }
5074 ParticleSystemModifierData *psmd = reinterpret_cast<ParticleSystemModifierData *>(md);
5075 ParticleSystem *psys = psmd->psys;
5077 }
5078}
5079
5081
5082/* -------------------------------------------------------------------- */
5085
5086void BKE_particle_settings_eval_reset(Depsgraph *depsgraph, ParticleSettings *particle_settings)
5087{
5088 DEG_debug_print_eval(depsgraph, __func__, particle_settings->id.name, particle_settings);
5089 particle_settings->id.recalc |= ID_RECALC_PSYS_RESET;
5090}
5091
5092void BKE_particle_system_eval_init(Depsgraph *depsgraph, Object *object)
5093{
5094 DEG_debug_print_eval(depsgraph, __func__, object->id.name, object);
5095 for (ParticleSystem *psys = object->particlesystem.first(); psys != nullptr; psys = psys->next) {
5096 psys->recalc |= (psys->part->id.recalc & ID_RECALC_PSYS_ALL);
5097 }
5098}
5099
5101
5102} // namespace blender
CustomData interface, see also DNA_customdata_types.h.
#define ORIGINDEX_NONE
General operations, lookup, etc. for materials.
General operations, lookup, etc. for blender objects.
#define PARTICLE_DRAW_DATA_UPDATED
#define DMCACHE_NOTFOUND
#define LOOP_SHOWN_PARTICLES
#define PSYS_RESET_CACHE_MISS
#define LOOP_PARTICLES
#define PSYS_RESET_ALL
#define LOOP_DYNAMIC_PARTICLES
#define DMCACHE_ISCHILD
#define PARTICLE_COLLISION_MAX_COLLISIONS
#define LOOP_EXISTING_PARTICLES
#define PSYS_RESET_DEPSGRAPH
#define PARTICLE_P
#define PTCACHE_CLEAR_AFTER
#define PTCACHE_CLEAR_ALL
#define PTCACHE_READ_INTERPOLATED
#define PTCACHE_READ_OLD
#define PTCACHE_RESET_OUTDATED
#define PTCACHE_READ_EXACT
#define BVH_RAYCAST_DEFAULT
A KD-tree for nearest neighbor search.
#define M_PI
Random number functions.
#define THREAD_LOCK_READ
#define THREAD_LOCK_WRITE
#define BLI_RWLOCK_INITIALIZER
These structs are the foundation for all linked lists in the library system.
Object is a sort of wrapper for general info.
Read Blender memory allocation and freeing.
#define CLAMP(a, b, c)
#define UNUSED_VARS(...)
#define POINTER_FROM_INT(i)
#define POINTER_AS_INT(i)
#define ELEM(...)
#define MEM_realloc_uninitialized(vmemh, len)
btScalar max
SIMD_FORCE_INLINE btScalar angle(const btVector3 &v) const
Return the angle between this and another vector.
Definition btVector3.h:356
constexpr IndexRange()=default
bool add(const Key &key, const Value &value)
Definition BLI_map.hh:295
Value lookup_default(const Key &key, const Value &default_value) const
Definition BLI_map.hh:570
void reserve(int64_t n)
Definition BLI_map.hh:1028
#define offsetof(t, d)
#define rot(x, k)
#define FLT_MAX
#define FLT_EPSILON
float dot(VecOp< float, D >, VecOp< float, D >) RET
float distance(float, float) RET
float length(VecOp< float, D >) RET
const int state
Value parallel_reduce(IndexRange range, int64_t grain_size, const Value &identity, const Function &function, const Reduction &reduction)
Definition BLI_task.hh:127
BMesh Iterators.
void psys_free_path_cache(struct ParticleSystem *psys, struct PTCacheEdit *edit)
Definition particle.cc:938
MINLINE float min_ff(float a, float b)
MINLINE void madd_v3_v3v3fl(float r[3], const float a[3], const float b[3], float f)
int manta_liquid_get_snd_particle_flag_at(struct MANTA *liquid, int i)
void BKE_object_where_is_calc_time(Depsgraph *depsgraph, Scene *scene, Object *ob, float ctime)
Definition object.cc:3549
void BKE_particle_system_eval_init(struct Depsgraph *depsgraph, struct Object *object)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
int BKE_ptcache_read(PTCacheID *pid, float cfra, bool no_extrapolate_old)
MINLINE void negate_v3_v3(float r[3], const float a[3])
int manta_liquid_get_particle_res_z(struct MANTA *liquid)
void kdtree_balance(KDTree< CoordT > *tree)
static void dynamics_step_sph_ddr_task_cb_ex(DynamicStepSolverTaskData *data, const int p, SPHData *sphdata)
void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra)
void(*) ParticleSystemIDFunc(struct ParticleSystem *psys, struct ID **idpoin, void *userdata, LibraryForeachIDCallbackFlag cb_flag)
static void psys_update_particle_bvhtree(ParticleSystem *psys, float cfra)
static Map< OrderedEdge, int > sph_springhash_build(ParticleSystem *psys)
size_t BLI_snprintf(char *__restrict dst, size_t dst_maxncpy, const char *__restrict format,...) ATTR_NONNULL(1
static void sphclassical_force_cb(void *sphdata_v, ParticleKey *state, float *force, float *)
static void dynamics_step_sph_classical_calc_density_task_cb_ex(void *__restrict userdata, const int p, const TaskParallelTLS *__restrict tls)
static int collision_sphere_to_edges(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
@ ADT_RECALC_ANIM
int manta_liquid_get_flip_particle_flag_at(struct MANTA *liquid, int i)
static void collision_point_on_surface(const float p[3], ParticleCollisionElement *pce, float fac, ParticleCollision *col, float *co)
float psys_get_current_display_percentage(struct ParticleSystem *psys, bool use_render_params)
void BKE_particle_batch_cache_dirty_tag(struct ParticleSystem *psys, int mode)
Definition particle.cc:5580
static bool particles_has_bubble(short parttype)
struct ParticleSystem * psys_get_target_system(struct Object *ob, struct ParticleTarget *pt)
static void set_keyed_keys(ParticleSimulationData *sim)
BLI_INLINE void BLI_parallel_range_settings_defaults(TaskParallelSettings *settings)
void(*)(void *userdata, int index, const float co[3], float dist_sq) BVHTree_RangeQuery
void psys_sph_finalize(struct SPHData *sphdata)
int manta_liquid_get_particle_res_y(struct MANTA *liquid)
MINLINE void copy_v3_v3(float r[3], const float a[3])
void mat4_to_quat(float q[4], const float mat[4][4])
pthread_spinlock_t SpinLock
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
Vector< ParticleTask > psys_tasks_create(struct ParticleThreadContext *ctx, int startpart, int endpart)
static void collision_fail(ParticleData *pa, ParticleCollision *col)
void copy_m3_m4(float m1[3][3], const float m2[4][4])
float manta_liquid_get_flip_particle_position_y_at(struct MANTA *liquid, int i)
@ eParticleSystemFlag_psys_updated
bool DEG_is_active(const Depsgraph *depsgraph)
Definition depsgraph.cc:324
void BKE_collider_cache_free(ListBaseT< ColliderCache > **colliders)
void psys_sim_data_init(struct ParticleSimulationData *sim)
Definition particle.cc:621
double BLI_rng_get_double(struct RNG *rng) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition rand.cc:85
static ParticleSettings * particle_settings_localize(ParticleSettings *particle_settings)
MINLINE void add_v3_v3v3(float r[3], const float a[3], const float b[3])
void psys_get_birth_coords(struct ParticleSimulationData *sim, struct ParticleData *pa, struct ParticleKey *state, float dtime, float cfra)
void BKE_ptcache_disk_to_mem(struct PTCacheID *pid)
void vec_to_quat(float q[4], const float vec[3], short axis, short upflag)
float manta_liquid_get_flip_particle_velocity_y_at(struct MANTA *liquid, int i)
int manta_get_res_y(struct MANTA *fluid)
Material * BKE_object_material_get(Object *ob, short act)
static void psys_sph_flush_springs(SPHData *sphdata)
@ IDWALK_NO_ORIG_POINTERS_ACCESS
struct RNG * BLI_rng_new_srandom(unsigned int seed)
Definition rand.cc:48
void BLI_bvhtree_free(BVHTree *tree)
float manta_liquid_get_snd_particle_position_z_at(struct MANTA *liquid, int i)
static bool particles_has_spray(short parttype)
int manta_liquid_get_particle_res_x(struct MANTA *liquid)
int BKE_ptcache_id_reset(struct Scene *scene, PTCacheID *pid, int mode)
static void do_hair_dynamics(ParticleSimulationData *sim)
static float nr_distance_to_vert(float *p, float radius, ParticleCollisionElement *pce, float *)
void cloth_free_modifier(ClothModifierData *clmd)
Definition cloth.cc:445
int BLI_bvhtree_ray_cast_ex(const BVHTree *tree, const float co[3], const float dir[3], float radius, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata, int flag)
static ParticleSpring * sph_spring_add(ParticleSystem *psys, ParticleSpring *spring)
float normalize_qt(float q[4])
void void psys_cache_paths(struct ParticleSimulationData *sim, float cfra, bool use_render_params)
Definition particle.cc:3291
void boid_brain(BoidBrainData *bbd, int p, struct ParticleData *pa)
Definition boids.cc:1053
bool invert_m4_m4(float inverse[4][4], const float mat[4][4])
@ eModifierType_ParticleSystem
MINLINE float safe_acosf(float a)
static void update_timestep(ParticleSystem *psys, ParticleSimulationData *sim)
void pd_point_from_particle(struct ParticleSimulationData *sim, struct ParticleData *pa, struct ParticleKey *state, struct EffectedPoint *point)
Definition effect.cc:388
void BLI_bvhtree_balance(BVHTree *tree)
void DEG_debug_print_eval(Depsgraph *depsgraph, const char *function_name, const char *object_name, const void *object_address)
float manta_liquid_get_snd_particle_position_y_at(struct MANTA *liquid, int i)
void psys_find_parents(struct ParticleSimulationData *sim, bool use_render_params)
Definition particle.cc:2647
void reset_particle(struct ParticleSimulationData *sim, struct ParticleData *pa, float dtime, float cfra)
void psys_thread_context_init(struct ParticleThreadContext *ctx, struct ParticleSimulationData *sim)
static int emit_particles(ParticleSimulationData *sim, PTCacheID *pid, float)
void axis_angle_to_quat(float r[4], const float axis[3], float angle)
static void sph_density_accum_cb(void *userdata, int index, const float co[3], float squared_dist)
void BKE_effectors_apply(ListBaseT< EffectorCache > *effectors, ListBaseT< ColliderCache > *colliders, struct EffectorWeights *weights, struct EffectedPoint *point, float *force, float *wind_force, float *impulse)
Definition effect.cc:1134
void mul_m4_m4m4(float R[4][4], const float A[4][4], const float B[4][4])
static int hair_needs_recalc(ParticleSystem *psys)
static void dynamics_step(ParticleSimulationData *sim, float cfra)
static void basic_integrate(ParticleSimulationData *sim, int p, float dfra, float cfra)
void BKE_particlesystem_id_loop(struct ParticleSystem *psys, ParticleSystemIDFunc func, void *userdata)
MINLINE int max_ii(int a, int b)
float manta_liquid_get_flip_particle_position_z_at(struct MANTA *liquid, int i)
void BLI_task_parallel_range(int start, int stop, void *userdata, TaskParallelRangeFunc func, const TaskParallelSettings *settings)
MINLINE void madd_v3fl_v3fl_v3fl_v3i(float r[3], const float a[3], const float b[3], const int c[3])
void mul_qt_qtqt(float q[4], const float a[4], const float b[4])
ATTR_WARN_UNUSED_RESULT const BMVert * v
struct ParticleSystem * psys_orig_get(struct ParticleSystem *psys)
Definition particle.cc:689
@ PART_FLUID_SPRAYFOAMBUBBLE
struct ParticleSystemModifierData * psys_get_modifier(struct Object *ob, struct ParticleSystem *psys)
Definition particle.cc:2190
static ThreadRWMutex psys_bvhtree_rwlock
void BKE_curvemapping_free(CurveMapping *cumap)
static void update_courant_num(ParticleSimulationData *sim, ParticleData *pa, float dtime, SPHData *sphdata, SpinLock *spin)
static bool particles_has_flip(short parttype)
LibraryForeachIDFlag BKE_lib_query_foreachid_process_flags_get(const LibraryForeachIDData *data)
Definition lib_query.cc:133
void psys_free_particles(struct ParticleSystem *psys)
Definition particle.cc:963
float psys_get_timestep(struct ParticleSimulationData *sim)
Definition particle.cc:4518
void BLI_rw_mutex_lock(ThreadRWMutex *mutex, int mode)
Definition threads.cc:470
static void particlesystem_modifiersForeachIDLink(void *user_data, Object *, ID **id_pointer, const LibraryForeachIDCallbackFlag cb_flag)
static void collision_point_velocity(ParticleCollisionElement *pce)
void boids_precalc_rules(struct ParticleSettings *part, float cfra)
Definition boids.cc:956
static void free_unexisting_particles(ParticleSimulationData *sim)
static void hair_step(ParticleSimulationData *sim, float cfra, const bool use_render_params)
int manta_liquid_get_num_snd_particles(struct MANTA *liquid)
static int collision_detect(ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, ListBaseT< ColliderCache > *colliders)
void init_particle(struct ParticleSimulationData *sim, struct ParticleData *pa)
MINLINE float pow3f(float x)
static void realloc_particles(ParticleSimulationData *sim, int new_totpart)
@ LIB_ID_COPY_LOCALIZE
MINLINE float pow4f(float x)
static void dynamics_step_sph_classical_integrate_task_cb_ex(void *__restrict userdata, const int p, const TaskParallelTLS *__restrict tls)
static bool psys_hair_use_simulation(ParticleData *pa, float max_length)
MINLINE void mul_v3_fl(float r[3], float f)
MINLINE float pow2f(float x)
AnimationEvalContext BKE_animsys_eval_context_construct(Depsgraph *depsgraph, float eval_time) ATTR_WARN_UNUSED_RESULT
Definition anim_sys.cc:602
void normalize_m4(float R[4][4]) ATTR_NONNULL()
static float collision_point_distance_with_normal(float p[3], ParticleCollisionElement *pce, float fac, ParticleCollision *col, float *nor)
void BKE_libblock_free_data(ID *id, bool do_id_user) ATTR_NONNULL()
static void evaluate_emitter_anim(Depsgraph *depsgraph, Scene *scene, Object *ob, float cfra)
void project_v3_v3v3(float out[3], const float p[3], const float v_proj[3])
static void psys_sph_init(ParticleSimulationData *sim, SPHData *sphdata, Map< OrderedEdge, int > &r_eh)
MINLINE void sub_v3_v3(float r[3], const float a[3])
void mul_qt_v3(const float q[4], float r[3])
void clothModifier_do(ClothModifierData *clmd, Depsgraph *depsgraph, Scene *scene, Object *ob, const Mesh *mesh, float(*vertexCos)[3])
Definition cloth.cc:327
void psys_count_keyed_targets(struct ParticleSimulationData *sim)
KDTree< CoordT > * kdtree_new(uint nodes_len_capacity)
Definition BLI_kdtree.hh:65
bool psys_in_edit_mode(struct Depsgraph *depsgraph, const struct ParticleSystem *psys)
void mul_m4_v3(const float M[4][4], float r[3])
void unit_qt(float q[4])
int BLI_system_thread_count()
Definition threads.cc:258
MINLINE void madd_v3_v3fl(float r[3], const float a[3], float f)
float manta_liquid_get_flip_particle_velocity_z_at(struct MANTA *liquid, int i)
void * BLI_findlink(const ListBase *listbase, int number) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:541
void BLI_uniquename(const ListBase *list, void *vlink, const char *defname, char delim, int name_offset, size_t name_maxncpy) ATTR_NONNULL(1
void BLI_spin_end(SpinLock *spin)
Definition threads.cc:448
static void basic_force_cb(void *efdata_v, ParticleKey *state, float *force, float *impulse)
static void hair_create_input_mesh(ParticleSimulationData *sim, int totpoint, int totedge, Mesh **r_mesh)
VecBase< int32_t, 2 > int2
bool psys_get_particle_state(struct ParticleSimulationData *sim, int p, struct ParticleKey *state, bool always)
Definition particle.cc:4930
VecBase< int32_t, 3 > int3
static void sph_particle_courant(SPHData *sphdata, SPHRangeData *pfr)
MINLINE void mul_v3_v3(float r[3], const float a[3])
void * MEM_new_zeroed(size_t len, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2)
static void bvhtree_balance_isolated(void *userdata)
static float sync_timestep(ParticleSystem *psys, float t_frac)
void BKE_particle_settings_eval_reset(struct Depsgraph *depsgraph, struct ParticleSettings *particle_settings)
MINLINE void cross_v3_v3v3(float r[3], const float a[3], const float b[3])
int BKE_ptcache_write(PTCacheID *pid, unsigned int cfra)
void BLI_rw_mutex_unlock(ThreadRWMutex *mutex)
Definition threads.cc:480
ListBaseT< ColliderCache > * BKE_collider_cache_create(struct Depsgraph *depsgraph, struct Object *self, struct Collection *collection)
void copy_qt_qt(float q[4], const float a[4])
void precalc_guides(struct ParticleSimulationData *sim, ListBaseT< EffectorCache > *effectors)
Definition particle.cc:2323
static float nr_signed_distance_to_plane(float *p, float radius, ParticleCollisionElement *pce, float *nor)
float manta_liquid_get_flip_particle_position_x_at(struct MANTA *liquid, int i)
BMesh const char void * data
void free_hair(struct Object *ob, struct ParticleSystem *psys, int dynamics)
Definition particle.cc:877
void interp_qt_qtqt(float q[4], const float a[4], const float b[4], float t)
static void sphclassical_density_accum_cb(void *userdata, int index, const float co[3], float)
void psys_make_temp_pointcache(struct Object *ob, struct ParticleSystem *psys)
ModifierData * BKE_modifier_new(int type)
int BLI_bvhtree_range_query(const BVHTree *tree, const float co[3], float radius, BVHTree_RangeQuery callback, void *userdata)
void BKE_psys_collision_neartest_cb(void *userdata, int index, const struct BVHTreeRay *ray, struct BVHTreeRayHit *hit)
static void save_hair(ParticleSimulationData *sim, float)
void kdtree_insert(KDTree< CoordT > *tree, int index, const CoordT &co)
Definition BLI_kdtree.hh:96
void mat3_to_quat_legacy(float q[4], const float wmat[3][3])
void free_keyed_keys(struct ParticleSystem *psys)
Definition particle.cc:912
@ PT_CACHE_EDIT_UPDATE_PARTICLE_FROM_EVAL
Mesh * BKE_mesh_new_nomain(int verts_num, int edges_num, int faces_num, int corners_num)
BVHTree * BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis)
float psys_get_dietime_from_cache(struct PointCache *cache, int index)
Definition particle.cc:1307
static void psys_update_effectors(ParticleSimulationData *sim)
static void psys_update_path_cache(ParticleSimulationData *sim, float cfra, const bool use_render_params)
static MDeformVert * hair_set_pinning(MDeformVert *dvert, float weight)
MINLINE void negate_v3(float r[3])
static void system_step(ParticleSimulationData *sim, float cfra, const bool use_render_params)
void BKE_ptcache_id_time(PTCacheID *pid, struct Scene *scene, float cfra, int *startframe, int *endframe, float *timescale)
float manta_liquid_get_snd_particle_position_x_at(struct MANTA *liquid, int i)
static void dynamics_step_sph_classical_basic_integrate_task_cb_ex(void *__restrict userdata, const int p, const TaskParallelTLS *__restrict)
void psys_sph_density(struct BVHTree *tree, struct SPHData *data, float co[3], float vars[2])
void interp_v3_v3v3(float r[3], const float a[3], const float b[3], float t)
static bool particles_has_tracer(short parttype)
void psys_mat_hair_to_object(struct Object *ob, struct Mesh *mesh, short from, struct ParticleData *pa, float hairmat[4][4])
Definition particle.cc:3888
static void initialize_all_particles(ParticleSimulationData *sim)
void BLI_rng_free(struct RNG *rng) ATTR_NONNULL(1)
Definition rand.cc:55
void psys_get_texture(struct ParticleSimulationData *sim, struct ParticleData *pa, struct ParticleTexture *ptex, int event, float cfra)
Definition particle.cc:4380
const void * CustomData_get_layer(const CustomData *data, eCustomDataType type)
MINLINE float len_v3(const float a[3]) ATTR_WARN_UNUSED_RESULT
static void init_particle_texture(ParticleSimulationData *sim, ParticleData *pa, int p)
static void psys_prepare_physics(ParticleSimulationData *sim)
void BKE_particlesystem_reset_all(struct Object *object)
static void integrate_particle(ParticleSettings *part, ParticleData *pa, float dtime, float *external_acceleration, void(*force_func)(void *forcedata, ParticleKey *state, float *force, float *impulse), void *forcedata)
void psys_free_children(struct ParticleSystem *psys)
Definition particle.cc:953
MINLINE void zero_v3(float r[3])
void BKE_id_free(Main *bmain, void *idv)
MINLINE float pow7f(float x)
eEvaluationMode DEG_get_mode(const Depsgraph *graph)
bool psys_check_enabled(struct Object *ob, struct ParticleSystem *psys, bool use_render_params)
Definition particle.cc:739
static void particles_fluid_step(ParticleSimulationData *sim, int cfra, const bool use_render_params)
@ BVH_RAYCAST_WATERTIGHT
float manta_liquid_get_snd_particle_velocity_x_at(struct MANTA *liquid, int i)
static void update_children(ParticleSimulationData *sim, const bool use_render_params)
void distribute_particles(struct ParticleSimulationData *sim, int from)
float BLI_rng_get_float(struct RNG *rng) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition rand.cc:90
void mul_mat3_m4_v3(const float mat[4][4], float r[3])
MINLINE float normalize_v3_v3(float r[3], const float a[3])
void BKE_ptcache_validate(struct PointCache *cache, int framenr)
static void sph_force_cb(void *sphdata_v, ParticleKey *state, float *force, float *)
void psys_calc_dmcache(struct Object *ob, struct Mesh *mesh_final, struct Mesh *mesh_original, struct ParticleSystem *psys)
static const float MIN_TIMESTEP
void particle_system_update(struct Depsgraph *depsgraph, struct Scene *scene, struct Object *ob, struct ParticleSystem *psys, bool use_render_params)
MINLINE void mul_v3_v3fl(float r[3], const float a[3], float f)
void BKE_animsys_evaluate_animdata(ID *id, AnimData *adt, const AnimationEvalContext *anim_eval_context, eAnimData_Recalc recalc, bool flush_to_original)
Definition anim_sys.cc:3716
void BKE_ptcache_free_mem(ListBaseT< PTCacheMem > *mem_cache)
void BLI_spin_unlock(SpinLock *spin)
Definition threads.cc:433
MINLINE float normalize_v3(float n[3])
static void sphclassical_neighbor_accum_cb(void *userdata, int index, const float co[3], float)
void BKE_ptcache_id_from_particles(PTCacheID *pid, struct Object *ob, struct ParticleSystem *psys)
ModifierData * BKE_modifiers_findby_type(const Object *ob, ModifierType type)
int manta_get_res_z(struct MANTA *fluid)
MINLINE void add_v3_v3(float r[3], const float a[3])
void kdtree_free(KDTree< CoordT > *tree)
Definition BLI_kdtree.hh:84
static void sph_springs_modify(ParticleSystem *psys, float dtime)
static void reset_all_particles(ParticleSimulationData *sim, float dtime, float cfra, int from)
@ CLOTH_SIMSETTINGS_FLAG_RESIST_SPRING_COMPRESS
MINLINE void sub_v3_v3v3(float r[3], const float a[3], const float b[3])
void BLI_spin_init(SpinLock *spin)
Definition threads.cc:394
void psys_free_pdd(struct ParticleSystem *psys)
Definition particle.cc:993
int psys_get_tot_child(struct Scene *scene, struct ParticleSystem *psys, bool use_render_params)
void psys_vec_rot_to_face(struct Mesh *mesh, struct ParticleData *pa, float vec[3])
Definition particle.cc:3935
void BLI_task_isolate(void(*func)(void *userdata), void *userdata)
static void sph_spring_delete(ParticleSystem *psys, int j)
int psys_particle_dm_face_lookup(struct Mesh *mesh_final, struct Mesh *mesh_original, int findex_orig, const float fw[4], struct LinkNode **poly_nodes)
Definition particle.cc:1869
static void get_angular_velocity_vector(short avemode, ParticleKey *state, float vec[3])
ATTR_WARN_UNUSED_RESULT const BMVert * v2
void psys_update_particle_tree(struct ParticleSystem *psys, float cfra)
static void collision_interpolate_element(ParticleCollisionElement *pce, float t, float fac, ParticleCollision *col)
MINLINE float max_ff(float a, float b)
float psys_particle_value_from_verts(struct Mesh *mesh, short from, struct ParticleData *pa, float *values)
Definition particle.cc:2176
static const float TIMESTEP_EXPANSION_FACTOR
static const float TIMESTEP_EXPANSION_TOLERANCE
ListBaseT< EffectorCache > * BKE_effectors_create(struct Depsgraph *depsgraph, struct Object *ob_src, struct ParticleSystem *psys_src, struct EffectorWeights *weights, bool use_rotation)
Definition effect.cc:316
void psys_thread_context_free(struct ParticleThreadContext *ctx)
@ ID_RECALC_PSYS_RESET
Definition DNA_ID.h:1083
@ ID_RECALC_PSYS_CHILD
Definition DNA_ID.h:1085
@ ID_RECALC_PSYS_ALL
Definition DNA_ID.h:1193
void BKE_mesh_tessface_ensure(Mesh *mesh)
int manta_liquid_get_num_flip_particles(struct MANTA *liquid)
void BLI_bvhtree_insert(BVHTree *tree, int index, const float co[3], int numpoints)
static float collision_newton_rhapson(ParticleCollision *col, float radius, ParticleCollisionElement *pce, NRDistanceFunc distance_func)
static float get_base_time_step(ParticleSettings *part)
void psys_particle_on_emitter(struct ParticleSystemModifierData *psmd, int from, int index, int index_dmcache, float fuv[4], float foffset, float vec[3], float nor[3], float utan[3], float vtan[3], float orco[3])
Definition particle.cc:2285
MINLINE float interpf(float target, float origin, float t)
void psys_tasks_free(Vector< ParticleTask > &tasks)
float(*)(float *p, float radius, ParticleCollisionElement *pce, float *nor) NRDistanceFunc
float manta_liquid_get_snd_particle_velocity_y_at(struct MANTA *liquid, int i)
static void particle_settings_free_local(ParticleSettings *particle_settings)
void psys_reset(struct ParticleSystem *psys, int mode)
void invert_qt_qt_normalized(float q1[4], const float q2[4])
void boid_body(BoidBrainData *bbd, struct ParticleData *pa)
Definition boids.cc:1210
static void cached_step(ParticleSimulationData *sim, float cfra, const bool use_render_params)
void BKE_libblock_free_datablock(ID *id, int flag) ATTR_NONNULL()
void psys_cache_child_paths(struct ParticleSimulationData *sim, float cfra, bool editupdate, bool use_render_params)
Definition particle.cc:3192
int manta_liquid_get_particle_upres(struct MANTA *liquid)
static int collision_sphere_to_verts(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
ID * BKE_id_copy_ex(Main *bmain, const ID *id, ID **new_id_p, int flag)
Definition lib_id.cc:851
void psys_get_pointcache_start_end(struct Scene *scene, ParticleSystem *psys, int *sfra, int *efra)
bool do_guides(struct Depsgraph *depsgraph, struct ParticleSettings *part, ListBaseT< EffectorCache > *effectors, ParticleKey *state, int index, float time)
Definition particle.cc:2378
LibraryForeachIDCallbackFlag
@ IDWALK_CB_NEVER_NULL
BLI_INLINE float psys_frand(ParticleSystem *psys, unsigned int seed)
static int collision_sphere_to_tri(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
MINLINE float len_v3v3(const float a[3], const float b[3]) ATTR_WARN_UNUSED_RESULT
static void collision_check(ParticleSimulationData *sim, int p, float dfra, float cfra)
int psys_uses_gravity(struct ParticleSimulationData *sim)
Definition particle.cc:858
static void sph_evaluate_func(BVHTree *tree, ParticleSystem **psys, const float co[3], SPHRangeData *pfr, float interaction_radius, BVHTree_RangeQuery callback)
static int particles_are_dynamic(ParticleSystem *psys)
void psys_changed_type(struct Object *ob, struct ParticleSystem *psys)
@ CLOTH_COLLSETTINGS_FLAG_SELF
static void sph_integrate(ParticleSimulationData *sim, ParticleData *pa, float dfra, SPHData *sphdata)
static SPHData dynamics_step_sphdata_reduce(const SPHData &sphdata_to, const SPHData &sphdata_from)
MINLINE int min_ii(int a, int b)
pthread_rwlock_t ThreadRWMutex
void BLI_spin_lock(SpinLock *spin)
Definition threads.cc:408
MINLINE float dot_v3v3(const float a[3], const float b[3]) ATTR_WARN_UNUSED_RESULT
float DEG_get_ctime(const Depsgraph *graph)
const ModifierTypeInfo * BKE_modifier_get_info(ModifierType type)
void BKE_ptcache_invalidate(struct PointCache *cache)
void BKE_particlesettings_fluid_default_settings(struct ParticleSettings *part)
static float nr_distance_to_edge(float *p, float radius, ParticleCollisionElement *pce, float *)
static bool particles_has_foam(short parttype)
void psys_check_boid_data(struct ParticleSystem *psys)
void mat3_to_quat(float q[4], const float mat[3][3])
int manta_get_res_x(struct MANTA *fluid)
static void sphclassical_calc_dens(ParticleData *pa, float, SPHData *sphdata)
static int tot_particles(ParticleSystem *psys, PTCacheID *pid)
ATTR_WARN_UNUSED_RESULT const BMVert const BMEdge * e
void psys_sim_data_free(struct ParticleSimulationData *sim)
Definition particle.cc:662
static void basic_rotate(ParticleSettings *part, ParticleData *pa, float dfra, float timestep)
static int collision_response(ParticleSimulationData *sim, ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, int kill, int dynamic_rotation)
float manta_liquid_get_flip_particle_velocity_x_at(struct MANTA *liquid, int i)
void copy_particle_key(struct ParticleKey *to, struct ParticleKey *from, int time)
Definition particle.cc:3778
void BKE_effectors_free(ListBaseT< EffectorCache > *lb)
Definition effect.cc:371
int psys_get_child_number(struct Scene *scene, struct ParticleSystem *psys, bool use_render_params)
static void psys_clear_temp_pointcache(ParticleSystem *psys)
@ BKE_PARTICLE_BATCH_DIRTY_ALL
void * MEM_new_array_zeroed(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
int get_render_child_particle_number(const RenderData *r, int child_num, bool for_render)
Definition scene.cc:3019
@ FLUID_DOMAIN_PARTICLE_FLIP
@ FLUID_DOMAIN_PARTICLE_TRACER
@ FLUID_DOMAIN_PARTICLE_FOAM
@ FLUID_DOMAIN_PARTICLE_SPRAY
@ FLUID_DOMAIN_PARTICLE_BUBBLE
float manta_liquid_get_snd_particle_velocity_z_at(struct MANTA *liquid, int i)
void psys_unique_name(struct Object *object, struct ParticleSystem *psys, const char *defname) ATTR_NONNULL(1
#define COLLISION_ZERO
#define SPH_NEIGHBORS
#define ZERO_F43
#define PSYS_FLUID_SPRINGS_INITIAL_SIZE
#define COLLISION_MIN_RADIUS
#define COLLISION_INIT_STEP
#define COLLISION_MIN_DISTANCE
#define fabsf
#define sqrtf
#define sinf
#define cosf
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
#define min(a, b)
Definition sort.cc:38
struct Object * goal_ob
Definition BKE_boids.h:30
struct ParticleSimulationData * sim
Definition BKE_boids.h:24
struct ParticleSettings * part
Definition BKE_boids.h:25
ListBaseT< BoidState > states
CLOTH_COLLISIONSETTINGS_FLAGS flags
struct ClothHairData * hairdata
struct ClothSimSettings * sim_parms
struct PointCache * point_cache
struct ClothCollSettings * coll_parms
struct EffectorWeights * effector_weights
CLOTH_SIMSETTINGS_FLAGS flags
ParticleTexture ptex
ParticleData * pa
ParticleSimulationData * sim
eFluidDomain_ParticleTypes particle_type
struct FluidDomainSettings * domain
char name[258]
Definition DNA_ID.h:433
unsigned int recalc
Definition DNA_ID.h:446
void * py_instance
Definition DNA_ID.h:519
struct MDeformWeight * dw
const c_style_mat & ptr() const
bke::MeshRuntime * runtime
CustomData face_data
CustomData fdata_legacy
CustomData vert_data
void(*) foreach_ID_link(ModifierData *md, Object *ob, IDWalkFunc walk, void *user_data)
struct PartDeflect * pd
struct Object * parent
bke::ObjectRuntime * runtime
ListBaseT< struct ParticleSystem > particlesystem
struct ParticleSystem * psys
struct ParticleSystem * psys_eval
struct ParticleSystemModifierData * psmd_eval
struct PointCache * cache
ParticleCollisionElement pce
struct Object * skip[PARTICLE_COLLISION_MAX_COLLISIONS+1]
struct CollisionModifierData * md
eParticle_AliveState alive
struct Collection * collision_group
struct BoidSettings * boids
struct SPHFluidSettings * fluid
eParticleDistribution distr
eParticleRotationMode rotmode
eParticlePhysicsType phystype
eParticleAngularVelocityMode avemode
struct EffectorWeights * effector_weights
eParticleIntegrator integrator
ListBaseT< ColliderCache > * colliders
struct ParticleSystem * psys
struct ParticleSystemModifierData * psmd
struct ParticleDrawData * pdd
struct ClothModifierData * clmd
struct PTCacheEdit * edit
ListBaseT< ParticleTarget > targets
void(*) free_edit(struct PTCacheEdit *edit)
struct ListBaseT< struct EffectorCache > * effectors
struct ParticleCacheKey ** pathcache
eParticleSystem_Flag flag
struct PointCache * pointcache
eParticleTarget_Flag flag
struct ParticleTarget * next
struct CurveMapping * clumpcurve
struct CurveMapping * roughcurve
struct ParticleSeam * seams
struct CurveMapping * twistcurve
struct ParticleSimulationData sim
ListBaseT< PTCacheMem > mem_cache
ParticleData * pa
void(*) density_cb(void *rangedata_v, int index, const float co[3], float squared_dist)
Vector< ParticleSpring > new_springs
const Map< OrderedEdge, int > * eh
ParticleSystem * psys[10]
const float * gravity
void(*) force_cb(void *sphdata_v, ParticleKey *state, float *force, float *impulse)
SPHNeighbor neighbors[SPH_NEIGHBORS]
struct PhysicsSettings physics_settings
struct RenderData r
struct ToolSettings * toolsettings
struct ParticleEditSettings particle