Cleanup: remove redundant BKE/BLI/BIF headers
[blender.git] / source / blender / blenkernel / intern / particle_system.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2007 by Janne Karhu.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Raul Fernandez Hernandez (Farsthary), Stephen Swhitehorn.
24  *
25  * Adaptive time step
26  * Classical SPH
27  * Copyright 2011-2012 AutoCRC
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 /** \file blender/blenkernel/intern/particle_system.c
33  *  \ingroup bke
34  */
35
36
37 #include <stddef.h>
38
39 #include <stdlib.h>
40 #include <math.h>
41 #include <string.h>
42
43 #include "MEM_guardedalloc.h"
44
45 #include "DNA_anim_types.h"
46 #include "DNA_boid_types.h"
47 #include "DNA_particle_types.h"
48 #include "DNA_mesh_types.h"
49 #include "DNA_meshdata_types.h"
50 #include "DNA_modifier_types.h"
51 #include "DNA_object_force_types.h"
52 #include "DNA_object_types.h"
53 #include "DNA_curve_types.h"
54 #include "DNA_scene_types.h"
55 #include "DNA_texture_types.h"
56 #include "DNA_listBase.h"
57
58 #include "BLI_utildefines.h"
59 #include "BLI_edgehash.h"
60 #include "BLI_rand.h"
61 #include "BLI_math.h"
62 #include "BLI_blenlib.h"
63 #include "BLI_kdtree.h"
64 #include "BLI_kdopbvh.h"
65 #include "BLI_task.h"
66 #include "BLI_threads.h"
67 #include "BLI_linklist.h"
68
69 #include "BKE_animsys.h"
70 #include "BKE_boids.h"
71 #include "BKE_collision.h"
72 #include "BKE_colortools.h"
73 #include "BKE_effect.h"
74 #include "BKE_library.h"
75 #include "BKE_library_query.h"
76 #include "BKE_particle.h"
77
78 #include "BKE_collection.h"
79 #include "BKE_object.h"
80 #include "BKE_material.h"
81 #include "BKE_cloth.h"
82 #include "BKE_lattice.h"
83 #include "BKE_pointcache.h"
84 #include "BKE_mesh.h"
85 #include "BKE_modifier.h"
86 #include "BKE_scene.h"
87 #include "BKE_bvhutils.h"
88
89 #include "DEG_depsgraph.h"
90 #include "DEG_depsgraph_physics.h"
91 #include "DEG_depsgraph_query.h"
92
93 #include "PIL_time.h"
94
95 #include "RE_shader_ext.h"
96
97 /* fluid sim particle import */
98 #ifdef WITH_MOD_FLUID
99 #include "DNA_object_fluidsim_types.h"
100 #include "LBM_fluidsim.h"
101 #include <zlib.h>
102 #include <string.h>
103
104 #endif // WITH_MOD_FLUID
105
106 static ThreadRWMutex psys_bvhtree_rwlock = BLI_RWLOCK_INITIALIZER;
107
108 /************************************************/
109 /*                      Reacting to system events                       */
110 /************************************************/
111
112 static int particles_are_dynamic(ParticleSystem *psys)
113 {
114         if (psys->pointcache->flag & PTCACHE_BAKED)
115                 return 0;
116
117         if (psys->part->type == PART_HAIR)
118                 return psys->flag & PSYS_HAIR_DYNAMICS;
119         else
120                 return ELEM(psys->part->phystype, PART_PHYS_NEWTON, PART_PHYS_BOIDS, PART_PHYS_FLUID);
121 }
122
123 float psys_get_current_display_percentage(ParticleSystem *psys, const bool use_render_params)
124 {
125         ParticleSettings *part=psys->part;
126
127         if ((use_render_params && !particles_are_dynamic(psys)) ||  /* non-dynamic particles can be rendered fully */
128             (part->child_nbr && part->childtype)  ||    /* display percentage applies to children */
129             (psys->pointcache->flag & PTCACHE_BAKING))  /* baking is always done with full amount */
130         {
131                 return 1.0f;
132         }
133
134         return psys->part->disp/100.0f;
135 }
136
137 static int tot_particles(ParticleSystem *psys, PTCacheID *pid)
138 {
139         if (pid && psys->pointcache->flag & PTCACHE_EXTERNAL)
140                 return pid->cache->totpoint;
141         else if (psys->part->distr == PART_DISTR_GRID && psys->part->from != PART_FROM_VERT)
142                 return psys->part->grid_res * psys->part->grid_res * psys->part->grid_res - psys->totunexist;
143         else
144                 return psys->part->totpart - psys->totunexist;
145 }
146
147 void psys_reset(ParticleSystem *psys, int mode)
148 {
149         PARTICLE_P;
150
151         if (ELEM(mode, PSYS_RESET_ALL, PSYS_RESET_DEPSGRAPH)) {
152                 if (mode == PSYS_RESET_ALL || !(psys->flag & PSYS_EDITED)) {
153                         /* don't free if not absolutely necessary */
154                         if (psys->totpart != tot_particles(psys, NULL)) {
155                                 psys_free_particles(psys);
156                                 psys->totpart= 0;
157                         }
158
159                         psys->totkeyed= 0;
160                         psys->flag &= ~(PSYS_HAIR_DONE|PSYS_KEYED);
161
162                         if (psys->edit && psys->free_edit) {
163                                 psys->free_edit(psys->edit);
164                                 psys->edit = NULL;
165                                 psys->free_edit = NULL;
166                         }
167                 }
168         }
169         else if (mode == PSYS_RESET_CACHE_MISS) {
170                 /* set all particles to be skipped */
171                 LOOP_PARTICLES {
172                         pa->flag |= PARS_NO_DISP;
173                 }
174         }
175
176         /* reset children */
177         if (psys->child) {
178                 MEM_freeN(psys->child);
179                 psys->child= NULL;
180         }
181
182         psys->totchild= 0;
183
184         /* reset path cache */
185         psys_free_path_cache(psys, psys->edit);
186
187         /* reset point cache */
188         BKE_ptcache_invalidate(psys->pointcache);
189
190         if (psys->fluid_springs) {
191                 MEM_freeN(psys->fluid_springs);
192                 psys->fluid_springs = NULL;
193         }
194
195         psys->tot_fluidsprings = psys->alloc_fluidsprings = 0;
196 }
197
198 static void realloc_particles(ParticleSimulationData *sim, int new_totpart)
199 {
200         ParticleSystem *psys = sim->psys;
201         ParticleSettings *part = psys->part;
202         ParticleData *newpars = NULL;
203         BoidParticle *newboids = NULL;
204         PARTICLE_P;
205         int totpart, totsaved = 0;
206
207         if (new_totpart<0) {
208                 if ((part->distr == PART_DISTR_GRID) && (part->from != PART_FROM_VERT)) {
209                         totpart= part->grid_res;
210                         totpart*=totpart*totpart;
211                 }
212                 else
213                         totpart=part->totpart;
214         }
215         else
216                 totpart=new_totpart;
217
218         if (totpart != psys->totpart) {
219                 if (psys->edit && psys->free_edit) {
220                         psys->free_edit(psys->edit);
221                         psys->edit = NULL;
222                         psys->free_edit = NULL;
223                 }
224
225                 if (totpart) {
226                         newpars= MEM_callocN(totpart*sizeof(ParticleData), "particles");
227                         if (newpars == NULL)
228                                 return;
229
230                         if (psys->part->phystype == PART_PHYS_BOIDS) {
231                                 newboids= MEM_callocN(totpart*sizeof(BoidParticle), "boid particles");
232
233                                 if (newboids == NULL) {
234                                         /* allocation error! */
235                                         if (newpars)
236                                                 MEM_freeN(newpars);
237                                         return;
238                                 }
239                         }
240                 }
241
242                 if (psys->particles) {
243                         totsaved=MIN2(psys->totpart,totpart);
244                         /*save old pars*/
245                         if (totsaved) {
246                                 memcpy(newpars,psys->particles,totsaved*sizeof(ParticleData));
247
248                                 if (psys->particles->boid)
249                                         memcpy(newboids, psys->particles->boid, totsaved*sizeof(BoidParticle));
250                         }
251
252                         if (psys->particles->keys)
253                                 MEM_freeN(psys->particles->keys);
254
255                         if (psys->particles->boid)
256                                 MEM_freeN(psys->particles->boid);
257
258                         for (p=0, pa=newpars; p<totsaved; p++, pa++) {
259                                 if (pa->keys) {
260                                         pa->keys= NULL;
261                                         pa->totkey= 0;
262                                 }
263                         }
264
265                         for (p=totsaved, pa=psys->particles+totsaved; p<psys->totpart; p++, pa++)
266                                 if (pa->hair) MEM_freeN(pa->hair);
267
268                         MEM_freeN(psys->particles);
269                         psys_free_pdd(psys);
270                 }
271
272                 psys->particles=newpars;
273                 psys->totpart=totpart;
274
275                 if (newboids) {
276                         LOOP_PARTICLES {
277                                 pa->boid = newboids++;
278                         }
279                 }
280         }
281
282         if (psys->child) {
283                 MEM_freeN(psys->child);
284                 psys->child=NULL;
285                 psys->totchild=0;
286         }
287 }
288
289 int psys_get_child_number(Scene *scene, ParticleSystem *psys, const bool use_render_params)
290 {
291         int nbr;
292
293         if (!psys->part->childtype)
294                 return 0;
295
296         if (use_render_params)
297                 nbr= psys->part->ren_child_nbr;
298         else
299                 nbr= psys->part->child_nbr;
300
301         return get_render_child_particle_number(&scene->r, nbr, use_render_params);
302 }
303
304 int psys_get_tot_child(Scene *scene, ParticleSystem *psys, const bool use_render_params)
305 {
306         return psys->totpart*psys_get_child_number(scene, psys, use_render_params);
307 }
308
309 /************************************************/
310 /*                      Distribution                                            */
311 /************************************************/
312
313 void psys_calc_dmcache(Object *ob, Mesh *mesh_final, Mesh *mesh_original, ParticleSystem *psys)
314 {
315         /* use for building derived mesh mapping info:
316          *
317          * node: the allocated links - total derived mesh element count
318          * nodearray: the array of nodes aligned with the base mesh's elements, so
319          *            each original elements can reference its derived elements
320          */
321         Mesh *me= (Mesh*)ob->data;
322         bool use_modifier_stack= psys->part->use_modifier_stack;
323         PARTICLE_P;
324
325         /* CACHE LOCATIONS */
326         if (!mesh_final->runtime.deformed_only) {
327                 /* Will use later to speed up subsurf/evaluated mesh. */
328                 LinkNode *node, *nodedmelem, **nodearray;
329                 int totdmelem, totelem, i, *origindex, *origindex_poly = NULL;
330
331                 if (psys->part->from == PART_FROM_VERT) {
332                         totdmelem = mesh_final->totvert;
333
334                         if (use_modifier_stack) {
335                                 totelem= totdmelem;
336                                 origindex= NULL;
337                         }
338                         else {
339                                 totelem= me->totvert;
340                                 origindex = CustomData_get_layer(&mesh_final->vdata, CD_ORIGINDEX);
341                         }
342                 }
343                 else { /* FROM_FACE/FROM_VOLUME */
344                         totdmelem= mesh_final->totface;
345
346                         if (use_modifier_stack) {
347                                 totelem= totdmelem;
348                                 origindex= NULL;
349                                 origindex_poly= NULL;
350                         }
351                         else {
352                                 totelem = mesh_original->totface;
353                                 origindex = CustomData_get_layer(&mesh_final->fdata, CD_ORIGINDEX);
354
355                                 /* for face lookups we need the poly origindex too */
356                                 origindex_poly = CustomData_get_layer(&mesh_final->pdata, CD_ORIGINDEX);
357                                 if (origindex_poly == NULL) {
358                                         origindex= NULL;
359                                 }
360                         }
361                 }
362
363                 nodedmelem= MEM_callocN(sizeof(LinkNode)*totdmelem, "psys node elems");
364                 nodearray= MEM_callocN(sizeof(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! */
396                 LOOP_PARTICLES {
397                         if (pa->num < 0) {
398                                 pa->num_dmcache = DMCACHE_NOTFOUND;
399                                 continue;
400                         }
401
402                         if (use_modifier_stack) {
403                                 if (pa->num < totelem)
404                                         pa->num_dmcache = DMCACHE_ISCHILD;
405                                 else
406                                         pa->num_dmcache = DMCACHE_NOTFOUND;
407                         }
408                         else {
409                                 if (psys->part->from == PART_FROM_VERT) {
410                                         if (pa->num < totelem && nodearray[pa->num])
411                                                 pa->num_dmcache= POINTER_AS_INT(nodearray[pa->num]->link);
412                                         else
413                                                 pa->num_dmcache = DMCACHE_NOTFOUND;
414                                 }
415                                 else { /* FROM_FACE/FROM_VOLUME */
416                                         pa->num_dmcache = psys_particle_dm_face_lookup(mesh_final, mesh_original, pa->num, pa->fuv, nodearray);
417                                 }
418                         }
419                 }
420
421                 MEM_freeN(nodearray);
422                 MEM_freeN(nodedmelem);
423         }
424         else {
425                 /* TODO PARTICLE, make the following line unnecessary, each function
426                  * should know to use the num or num_dmcache, set the num_dmcache to
427                  * an invalid value, just in case */
428
429                 LOOP_PARTICLES {
430                         pa->num_dmcache = DMCACHE_NOTFOUND;
431                 }
432         }
433 }
434
435 /* threaded child particle distribution and path caching */
436 void psys_thread_context_init(ParticleThreadContext *ctx, ParticleSimulationData *sim)
437 {
438         memset(ctx, 0, sizeof(ParticleThreadContext));
439         ctx->sim = *sim;
440         ctx->mesh = ctx->sim.psmd->mesh_final;
441         ctx->ma = give_current_material(sim->ob, sim->psys->part->omat);
442 }
443
444 #define MAX_PARTICLES_PER_TASK 256 /* XXX arbitrary - maybe use at least number of points instead for better balancing? */
445
446 BLI_INLINE int ceil_ii(int a, int b)
447 {
448         return (a + b - 1) / b;
449 }
450
451 void psys_tasks_create(ParticleThreadContext *ctx, int startpart, int endpart, ParticleTask **r_tasks, int *r_numtasks)
452 {
453         ParticleTask *tasks;
454         int numtasks = ceil_ii((endpart - startpart), MAX_PARTICLES_PER_TASK);
455         float particles_per_task = (float)(endpart - startpart) / (float)numtasks, p, pnext;
456         int i;
457
458         tasks = MEM_callocN(sizeof(ParticleTask) * numtasks, "ParticleThread");
459         *r_numtasks = numtasks;
460         *r_tasks = tasks;
461
462         p = (float)startpart;
463         for (i = 0; i < numtasks; i++, p = pnext) {
464                 pnext = p + particles_per_task;
465
466                 tasks[i].ctx = ctx;
467                 tasks[i].begin = (int)p;
468                 tasks[i].end = min_ii((int)pnext, endpart);
469         }
470 }
471
472 void psys_tasks_free(ParticleTask *tasks, int numtasks)
473 {
474         int i;
475
476         /* threads */
477         for (i = 0; i < numtasks; ++i) {
478                 if (tasks[i].rng)
479                         BLI_rng_free(tasks[i].rng);
480                 if (tasks[i].rng_path)
481                         BLI_rng_free(tasks[i].rng_path);
482         }
483
484         MEM_freeN(tasks);
485 }
486
487 void psys_thread_context_free(ParticleThreadContext *ctx)
488 {
489         /* path caching */
490         if (ctx->vg_length)
491                 MEM_freeN(ctx->vg_length);
492         if (ctx->vg_clump)
493                 MEM_freeN(ctx->vg_clump);
494         if (ctx->vg_kink)
495                 MEM_freeN(ctx->vg_kink);
496         if (ctx->vg_rough1)
497                 MEM_freeN(ctx->vg_rough1);
498         if (ctx->vg_rough2)
499                 MEM_freeN(ctx->vg_rough2);
500         if (ctx->vg_roughe)
501                 MEM_freeN(ctx->vg_roughe);
502         if (ctx->vg_twist)
503                 MEM_freeN(ctx->vg_twist);
504
505         if (ctx->sim.psys->lattice_deform_data) {
506                 end_latt_deform(ctx->sim.psys->lattice_deform_data);
507                 ctx->sim.psys->lattice_deform_data = NULL;
508         }
509
510         /* distribution */
511         if (ctx->jit) MEM_freeN(ctx->jit);
512         if (ctx->jitoff) MEM_freeN(ctx->jitoff);
513         if (ctx->weight) MEM_freeN(ctx->weight);
514         if (ctx->index) MEM_freeN(ctx->index);
515         if (ctx->seams) MEM_freeN(ctx->seams);
516         //if (ctx->vertpart) MEM_freeN(ctx->vertpart);
517         BLI_kdtree_free(ctx->tree);
518
519         if (ctx->clumpcurve != NULL) {
520                 curvemapping_free(ctx->clumpcurve);
521         }
522         if (ctx->roughcurve != NULL) {
523                 curvemapping_free(ctx->roughcurve);
524         }
525         if (ctx->twistcurve != NULL) {
526                 curvemapping_free(ctx->twistcurve);
527         }
528 }
529
530 static void initialize_particle_texture(ParticleSimulationData *sim, ParticleData *pa, int p)
531 {
532         ParticleSystem *psys = sim->psys;
533         ParticleSettings *part = psys->part;
534         ParticleTexture ptex;
535
536         psys_get_texture(sim, pa, &ptex, PAMAP_INIT, 0.f);
537
538         switch (part->type) {
539                 case PART_EMITTER:
540                         if (ptex.exist < psys_frand(psys, p + 125)) {
541                                 pa->flag |= PARS_UNEXIST;
542                         }
543                         pa->time = part->sta + (part->end - part->sta)*ptex.time;
544                         break;
545                 case PART_HAIR:
546                         if (ptex.exist < psys_frand(psys, p + 125)) {
547                                 pa->flag |= PARS_UNEXIST;
548                         }
549                         pa->time = 0.f;
550                         break;
551                 case PART_FLUID:
552                         break;
553         }
554 }
555
556 /* set particle parameters that don't change during particle's life */
557 void initialize_particle(ParticleSimulationData *sim, ParticleData *pa)
558 {
559         ParticleSettings *part = sim->psys->part;
560         float birth_time = (float)(pa - sim->psys->particles) / (float)sim->psys->totpart;
561
562         pa->flag &= ~PARS_UNEXIST;
563         pa->time = part->sta + (part->end - part->sta) * birth_time;
564
565         pa->hair_index = 0;
566         /* we can't reset to -1 anymore since we've figured out correct index in distribute_particles */
567         /* usage other than straight after distribute has to handle this index by itself - jahka*/
568         //pa->num_dmcache = DMCACHE_NOTFOUND; /* assume we don't have a derived mesh face */
569 }
570
571 static void initialize_all_particles(ParticleSimulationData *sim)
572 {
573         ParticleSystem *psys = sim->psys;
574         ParticleSettings *part = psys->part;
575         /* Grid distributionsets UNEXIST flag, need to take care of
576          * it here because later this flag is being reset.
577          *
578          * We can't do it for any distribution, because it'll then
579          * conflict with texture influence, which does not free
580          * unexisting particles and only sets flag.
581          *
582          * It's not so bad, because only grid distribution sets
583          * UNEXIST flag.
584          */
585         const bool emit_from_volume_grid = (part->distr == PART_DISTR_GRID) &&
586                                            (!ELEM(part->from, PART_FROM_VERT, PART_FROM_CHILD));
587         PARTICLE_P;
588         LOOP_PARTICLES {
589                 if (!(emit_from_volume_grid && (pa->flag & PARS_UNEXIST) != 0)) {
590                         initialize_particle(sim, pa);
591                 }
592         }
593 }
594
595 static void free_unexisting_particles(ParticleSimulationData *sim)
596 {
597         ParticleSystem *psys = sim->psys;
598         PARTICLE_P;
599
600         psys->totunexist = 0;
601
602         LOOP_PARTICLES {
603                 if (pa->flag & PARS_UNEXIST) {
604                         psys->totunexist++;
605                 }
606         }
607
608         if (psys->totpart && psys->totunexist == psys->totpart) {
609                 if (psys->particles->boid)
610                         MEM_freeN(psys->particles->boid);
611
612                 MEM_freeN(psys->particles);
613                 psys->particles = NULL;
614                 psys->totpart = psys->totunexist = 0;
615         }
616
617         if (psys->totunexist) {
618                 int newtotpart = psys->totpart - psys->totunexist;
619                 ParticleData *npa, *newpars;
620
621                 npa = newpars = MEM_callocN(newtotpart * sizeof(ParticleData), "particles");
622
623                 for (p=0, pa=psys->particles; p<newtotpart; p++, pa++, npa++) {
624                         while (pa->flag & PARS_UNEXIST)
625                                 pa++;
626
627                         memcpy(npa, pa, sizeof(ParticleData));
628                 }
629
630                 if (psys->particles->boid)
631                         MEM_freeN(psys->particles->boid);
632                 MEM_freeN(psys->particles);
633                 psys->particles = newpars;
634                 psys->totpart -= psys->totunexist;
635
636                 if (psys->particles->boid) {
637                         BoidParticle *newboids = MEM_callocN(psys->totpart * sizeof(BoidParticle), "boid particles");
638
639                         LOOP_PARTICLES {
640                                 pa->boid = newboids++;
641                         }
642
643                 }
644         }
645 }
646
647 static void get_angular_velocity_vector(short avemode, ParticleKey *state, float vec[3])
648 {
649         switch (avemode) {
650                 case PART_AVE_VELOCITY:
651                         copy_v3_v3(vec, state->vel);
652                         break;
653                 case PART_AVE_HORIZONTAL:
654                 {
655                         float zvec[3];
656                         zvec[0] = zvec[1] = 0;
657                         zvec[2] = 1.f;
658                         cross_v3_v3v3(vec, state->vel, zvec);
659                         break;
660                 }
661                 case PART_AVE_VERTICAL:
662                 {
663                         float zvec[3], temp[3];
664                         zvec[0] = zvec[1] = 0;
665                         zvec[2] = 1.f;
666                         cross_v3_v3v3(temp, state->vel, zvec);
667                         cross_v3_v3v3(vec, temp, state->vel);
668                         break;
669                 }
670                 case PART_AVE_GLOBAL_X:
671                         vec[0] = 1.f;
672                         vec[1] = vec[2] = 0;
673                         break;
674                 case PART_AVE_GLOBAL_Y:
675                         vec[1] = 1.f;
676                         vec[0] = vec[2] = 0;
677                         break;
678                 case PART_AVE_GLOBAL_Z:
679                         vec[2] = 1.f;
680                         vec[0] = vec[1] = 0;
681                         break;
682         }
683 }
684
685 void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, ParticleKey *state, float dtime, float cfra)
686 {
687         Object *ob = sim->ob;
688         ParticleSystem *psys = sim->psys;
689         ParticleSettings *part = psys->part;
690         ParticleTexture ptex;
691         float fac, phasefac, nor[3] = {0,0,0},loc[3],vel[3] = {0.0,0.0,0.0},rot[4],q2[4];
692         float r_vel[3],r_ave[3],r_rot[4],vec[3],p_vel[3] = {0.0,0.0,0.0};
693         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}, rot_vec[3] = {0.0,0.0,0.0};
694         float q_phase[4];
695
696         const bool use_boids = ((part->phystype == PART_PHYS_BOIDS) &&
697                                 (pa->boid != NULL));
698         const bool use_tangents = ((use_boids == false) &&
699                                    ((part->tanfac != 0.0f) || (part->rotmode == PART_ROT_NOR_TAN)));
700
701         int p = pa - psys->particles;
702
703         /* get birth location from object               */
704         if (use_tangents)
705                 psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,utan,vtan,0);
706         else
707                 psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,0,0,0);
708
709         /* get possible textural influence */
710         psys_get_texture(sim, pa, &ptex, PAMAP_IVEL, cfra);
711
712         /* particles live in global space so    */
713         /* let's convert:                                               */
714         /* -location                                                    */
715         mul_m4_v3(ob->obmat, loc);
716
717         /* -normal                                                              */
718         mul_mat3_m4_v3(ob->obmat, nor);
719         normalize_v3(nor);
720
721         /* -tangent                                                             */
722         if (use_tangents) {
723                 //float phase=vg_rot?2.0f*(psys_particle_value_from_verts(sim->psmd->dm,part->from,pa,vg_rot)-0.5f):0.0f;
724                 float phase=0.0f;
725                 mul_v3_fl(vtan,-cosf((float)M_PI*(part->tanphase+phase)));
726                 fac= -sinf((float)M_PI*(part->tanphase+phase));
727                 madd_v3_v3fl(vtan, utan, fac);
728
729                 mul_mat3_m4_v3(ob->obmat,vtan);
730
731                 copy_v3_v3(utan, nor);
732                 mul_v3_fl(utan,dot_v3v3(vtan,nor));
733                 sub_v3_v3(vtan, utan);
734
735                 normalize_v3(vtan);
736         }
737
738
739         /* -velocity (boids need this even if there's no random velocity) */
740         if (part->randfac != 0.0f || (part->phystype==PART_PHYS_BOIDS && pa->boid)) {
741                 r_vel[0] = 2.0f * (psys_frand(psys, p + 10) - 0.5f);
742                 r_vel[1] = 2.0f * (psys_frand(psys, p + 11) - 0.5f);
743                 r_vel[2] = 2.0f * (psys_frand(psys, p + 12) - 0.5f);
744
745                 mul_mat3_m4_v3(ob->obmat, r_vel);
746                 normalize_v3(r_vel);
747         }
748
749         /* -angular velocity                                    */
750         if (part->avemode==PART_AVE_RAND) {
751                 r_ave[0] = 2.0f * (psys_frand(psys, p + 13) - 0.5f);
752                 r_ave[1] = 2.0f * (psys_frand(psys, p + 14) - 0.5f);
753                 r_ave[2] = 2.0f * (psys_frand(psys, p + 15) - 0.5f);
754
755                 mul_mat3_m4_v3(ob->obmat,r_ave);
756                 normalize_v3(r_ave);
757         }
758
759         /* -rotation                                                    */
760         if (part->randrotfac != 0.0f) {
761                 r_rot[0] = 2.0f * (psys_frand(psys, p + 16) - 0.5f);
762                 r_rot[1] = 2.0f * (psys_frand(psys, p + 17) - 0.5f);
763                 r_rot[2] = 2.0f * (psys_frand(psys, p + 18) - 0.5f);
764                 r_rot[3] = 2.0f * (psys_frand(psys, p + 19) - 0.5f);
765                 normalize_qt(r_rot);
766
767                 mat4_to_quat(rot,ob->obmat);
768                 mul_qt_qtqt(r_rot,r_rot,rot);
769         }
770
771         if (use_boids) {
772                 float dvec[3], q[4], mat[3][3];
773
774                 copy_v3_v3(state->co,loc);
775
776                 /* boids don't get any initial velocity  */
777                 zero_v3(state->vel);
778
779                 /* boids store direction in ave */
780                 if (fabsf(nor[2])==1.0f) {
781                         sub_v3_v3v3(state->ave, loc, ob->obmat[3]);
782                         normalize_v3(state->ave);
783                 }
784                 else {
785                         copy_v3_v3(state->ave, nor);
786                 }
787
788                 /* calculate rotation matrix */
789                 project_v3_v3v3(dvec, r_vel, state->ave);
790                 sub_v3_v3v3(mat[0], state->ave, dvec);
791                 normalize_v3(mat[0]);
792                 negate_v3_v3(mat[2], r_vel);
793                 normalize_v3(mat[2]);
794                 cross_v3_v3v3(mat[1], mat[2], mat[0]);
795
796                 /* apply rotation */
797                 mat3_to_quat_is_ok( q,mat);
798                 copy_qt_qt(state->rot, q);
799         }
800         else {
801                 /* conversion done so now we apply new: */
802                 /* -velocity from:                                              */
803
804                 /*              *reactions                                              */
805                 if (dtime > 0.f) {
806                         sub_v3_v3v3(vel, pa->state.vel, pa->prev_state.vel);
807                 }
808
809                 /*              *emitter velocity                               */
810                 if (dtime != 0.f && part->obfac != 0.f) {
811                         sub_v3_v3v3(vel, loc, state->co);
812                         mul_v3_fl(vel, part->obfac/dtime);
813                 }
814
815                 /*              *emitter normal                                 */
816                 if (part->normfac != 0.f)
817                         madd_v3_v3fl(vel, nor, part->normfac);
818
819                 /*              *emitter tangent                                */
820                 if (sim->psmd && part->tanfac != 0.f)
821                         madd_v3_v3fl(vel, vtan, part->tanfac);
822
823                 /*              *emitter object orientation             */
824                 if (part->ob_vel[0] != 0.f) {
825                         normalize_v3_v3(vec, ob->obmat[0]);
826                         madd_v3_v3fl(vel, vec, part->ob_vel[0]);
827                 }
828                 if (part->ob_vel[1] != 0.f) {
829                         normalize_v3_v3(vec, ob->obmat[1]);
830                         madd_v3_v3fl(vel, vec, part->ob_vel[1]);
831                 }
832                 if (part->ob_vel[2] != 0.f) {
833                         normalize_v3_v3(vec, ob->obmat[2]);
834                         madd_v3_v3fl(vel, vec, part->ob_vel[2]);
835                 }
836
837                 /*              *texture                                                */
838                 /* TODO */
839
840                 /*              *random                                                 */
841                 if (part->randfac != 0.f)
842                         madd_v3_v3fl(vel, r_vel, part->randfac);
843
844                 /*              *particle                                               */
845                 if (part->partfac != 0.f)
846                         madd_v3_v3fl(vel, p_vel, part->partfac);
847
848                 mul_v3_v3fl(state->vel, vel, ptex.ivel);
849
850                 /* -location from emitter                               */
851                 copy_v3_v3(state->co,loc);
852
853                 /* -rotation                                                    */
854                 unit_qt(state->rot);
855
856                 if (part->rotmode) {
857                         bool use_global_space;
858
859                         /* create vector into which rotation is aligned */
860                         switch (part->rotmode) {
861                                 case PART_ROT_NOR:
862                                 case PART_ROT_NOR_TAN:
863                                         copy_v3_v3(rot_vec, nor);
864                                         use_global_space = false;
865                                         break;
866                                 case PART_ROT_VEL:
867                                         copy_v3_v3(rot_vec, vel);
868                                         use_global_space = true;
869                                         break;
870                                 case PART_ROT_GLOB_X:
871                                 case PART_ROT_GLOB_Y:
872                                 case PART_ROT_GLOB_Z:
873                                         rot_vec[part->rotmode - PART_ROT_GLOB_X] = 1.0f;
874                                         use_global_space = true;
875                                         break;
876                                 case PART_ROT_OB_X:
877                                 case PART_ROT_OB_Y:
878                                 case PART_ROT_OB_Z:
879                                         copy_v3_v3(rot_vec, ob->obmat[part->rotmode - PART_ROT_OB_X]);
880                                         use_global_space = false;
881                                         break;
882                                 default:
883                                         use_global_space = true;
884                                         break;
885                         }
886
887                         /* create rotation quat */
888
889
890                         if (use_global_space) {
891                                 negate_v3(rot_vec);
892                                 vec_to_quat(q2, rot_vec, OB_POSX, OB_POSZ);
893
894                                 /* randomize rotation quat */
895                                 if (part->randrotfac != 0.0f) {
896                                         interp_qt_qtqt(rot, q2, r_rot, part->randrotfac);
897                                 }
898                                 else {
899                                         copy_qt_qt(rot, q2);
900                                 }
901                         }
902                         else {
903                                 /* calculate rotation in local-space */
904                                 float q_obmat[4];
905                                 float q_imat[4];
906
907                                 mat4_to_quat(q_obmat, ob->obmat);
908                                 invert_qt_qt_normalized(q_imat, q_obmat);
909
910
911                                 if (part->rotmode != PART_ROT_NOR_TAN) {
912                                         float rot_vec_local[3];
913
914                                         /* rot_vec */
915                                         negate_v3(rot_vec);
916                                         copy_v3_v3(rot_vec_local, rot_vec);
917                                         mul_qt_v3(q_imat, rot_vec_local);
918                                         normalize_v3(rot_vec_local);
919
920                                         vec_to_quat(q2, rot_vec_local, OB_POSX, OB_POSZ);
921                                 }
922                                 else {
923                                         /* (part->rotmode == PART_ROT_NOR_TAN) */
924                                         float tmat[3][3];
925
926                                         /* note: utan_local is not taken from 'utan', we calculate from rot_vec/vtan */
927                                         /* note: it looks like rotation phase may be applied twice (once with vtan, again below)
928                                          * however this isn't the case - campbell */
929                                         float *rot_vec_local = tmat[0];
930                                         float *vtan_local    = tmat[1];
931                                         float *utan_local    = tmat[2];
932
933                                         /* use tangents */
934                                         BLI_assert(use_tangents == true);
935
936                                         /* rot_vec */
937                                         copy_v3_v3(rot_vec_local, rot_vec);
938                                         mul_qt_v3(q_imat, rot_vec_local);
939
940                                         /* vtan_local */
941                                         copy_v3_v3(vtan_local, vtan);  /* flips, cant use */
942                                         mul_qt_v3(q_imat, vtan_local);
943
944                                         /* ensure orthogonal matrix (rot_vec aligned) */
945                                         cross_v3_v3v3(utan_local, vtan_local, rot_vec_local);
946                                         cross_v3_v3v3(vtan_local, utan_local, rot_vec_local);
947
948                                         /* note: no need to normalize */
949                                         mat3_to_quat(q2, tmat);
950                                 }
951
952                                 /* randomize rotation quat */
953                                 if (part->randrotfac != 0.0f) {
954                                         mul_qt_qtqt(r_rot, r_rot, q_imat);
955                                         interp_qt_qtqt(rot, q2, r_rot, part->randrotfac);
956                                 }
957                                 else {
958                                         copy_qt_qt(rot, q2);
959                                 }
960
961                                 mul_qt_qtqt(rot, q_obmat, rot);
962                         }
963
964                         /* rotation phase */
965                         phasefac = part->phasefac;
966                         if (part->randphasefac != 0.0f)
967                                 phasefac += part->randphasefac * psys_frand(psys, p + 20);
968                         axis_angle_to_quat( q_phase,x_vec, phasefac*(float)M_PI);
969
970                         /* combine base rotation & phase */
971                         mul_qt_qtqt(state->rot, rot, q_phase);
972                 }
973
974                 /* -angular velocity                                    */
975
976                 zero_v3(state->ave);
977
978                 if (part->avemode) {
979                         if (part->avemode == PART_AVE_RAND)
980                                 copy_v3_v3(state->ave, r_ave);
981                         else
982                                 get_angular_velocity_vector(part->avemode, state, state->ave);
983
984                         normalize_v3(state->ave);
985                         mul_v3_fl(state->ave, part->avefac);
986                 }
987         }
988 }
989
990 /* recursively evaluate emitter parent anim at cfra */
991 static void evaluate_emitter_anim(struct Depsgraph *depsgraph, Scene *scene, Object *ob, float cfra)
992 {
993         if (ob->parent)
994                 evaluate_emitter_anim(depsgraph, scene, ob->parent, cfra);
995
996         /* we have to force RECALC_ANIM here since where_is_objec_time only does drivers */
997         BKE_animsys_evaluate_animdata(depsgraph, scene, &ob->id, ob->adt, cfra, ADT_RECALC_ANIM);
998         BKE_object_where_is_calc_time(depsgraph, scene, ob, cfra);
999 }
1000
1001 /* sets particle to the emitter surface with initial velocity & rotation */
1002 void reset_particle(ParticleSimulationData *sim, ParticleData *pa, float dtime, float cfra)
1003 {
1004         ParticleSystem *psys = sim->psys;
1005         ParticleSettings *part;
1006         ParticleTexture ptex;
1007         int p = pa - psys->particles;
1008         part=psys->part;
1009
1010         /* get precise emitter matrix if particle is born */
1011         if (part->type != PART_HAIR && dtime > 0.f && pa->time < cfra && pa->time >= sim->psys->cfra) {
1012                 evaluate_emitter_anim(sim->depsgraph, sim->scene, sim->ob, pa->time);
1013
1014                 psys->flag |= PSYS_OB_ANIM_RESTORE;
1015         }
1016
1017         psys_get_birth_coords(sim, pa, &pa->state, dtime, cfra);
1018
1019         /* Initialize particle settings which depends on texture.
1020          *
1021          * We could only do it now because we'll need to know coordinate
1022          * before sampling the texture.
1023          */
1024         initialize_particle_texture(sim, pa, p);
1025
1026         if (part->phystype==PART_PHYS_BOIDS && pa->boid) {
1027                 BoidParticle *bpa = pa->boid;
1028
1029                 /* and gravity in r_ve */
1030                 bpa->gravity[0] = bpa->gravity[1] = 0.0f;
1031                 bpa->gravity[2] = -1.0f;
1032                 if ((sim->scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) &&
1033                     (sim->scene->physics_settings.gravity[2] != 0.0f))
1034                 {
1035                         bpa->gravity[2] = sim->scene->physics_settings.gravity[2];
1036                 }
1037
1038                 bpa->data.health = part->boids->health;
1039                 bpa->data.mode = eBoidMode_InAir;
1040                 bpa->data.state_id = ((BoidState*)part->boids->states.first)->id;
1041                 bpa->data.acc[0]=bpa->data.acc[1]=bpa->data.acc[2]=0.0f;
1042         }
1043
1044         if (part->type == PART_HAIR) {
1045                 pa->lifetime = 100.0f;
1046         }
1047         else {
1048                 /* initialize the lifetime, in case the texture coordinates
1049                  * are from Particles/Strands, which would cause undefined values
1050                  */
1051                 pa->lifetime = part->lifetime * (1.0f - part->randlife * psys_frand(psys, p + 21));
1052                 pa->dietime = pa->time + pa->lifetime;
1053
1054                 /* get possible textural influence */
1055                 psys_get_texture(sim, pa, &ptex, PAMAP_LIFE, cfra);
1056
1057                 pa->lifetime = part->lifetime * ptex.life;
1058
1059                 if (part->randlife != 0.0f)
1060                         pa->lifetime *= 1.0f - part->randlife * psys_frand(psys, p + 21);
1061         }
1062
1063         pa->dietime = pa->time + pa->lifetime;
1064
1065         if ((sim->psys->pointcache) &&
1066             (sim->psys->pointcache->flag & PTCACHE_BAKED) &&
1067             (sim->psys->pointcache->mem_cache.first))
1068         {
1069                 float dietime = psys_get_dietime_from_cache(sim->psys->pointcache, p);
1070                 pa->dietime = MIN2(pa->dietime, dietime);
1071         }
1072
1073         if (pa->time > cfra)
1074                 pa->alive = PARS_UNBORN;
1075         else if (pa->dietime <= cfra)
1076                 pa->alive = PARS_DEAD;
1077         else
1078                 pa->alive = PARS_ALIVE;
1079
1080         pa->state.time = cfra;
1081 }
1082 static void reset_all_particles(ParticleSimulationData *sim, float dtime, float cfra, int from)
1083 {
1084         ParticleData *pa;
1085         int p, totpart=sim->psys->totpart;
1086
1087         for (p=from, pa=sim->psys->particles+from; p<totpart; p++, pa++)
1088                 reset_particle(sim, pa, dtime, cfra);
1089 }
1090 /************************************************/
1091 /*                      Particle targets                                        */
1092 /************************************************/
1093 ParticleSystem *psys_get_target_system(Object *ob, ParticleTarget *pt)
1094 {
1095         ParticleSystem *psys = NULL;
1096
1097         if (pt->ob == NULL || pt->ob == ob)
1098                 psys = BLI_findlink(&ob->particlesystem, pt->psys-1);
1099         else
1100                 psys = BLI_findlink(&pt->ob->particlesystem, pt->psys-1);
1101
1102         if (psys)
1103                 pt->flag |= PTARGET_VALID;
1104         else
1105                 pt->flag &= ~PTARGET_VALID;
1106
1107         return psys;
1108 }
1109 /************************************************/
1110 /*                      Keyed particles                                         */
1111 /************************************************/
1112 /* Counts valid keyed targets */
1113 void psys_count_keyed_targets(ParticleSimulationData *sim)
1114 {
1115         ParticleSystem *psys = sim->psys, *kpsys;
1116         ParticleTarget *pt = psys->targets.first;
1117         int keys_valid = 1;
1118         psys->totkeyed = 0;
1119
1120         for (; pt; pt=pt->next) {
1121                 kpsys = psys_get_target_system(sim->ob, pt);
1122
1123                 if (kpsys && kpsys->totpart) {
1124                         psys->totkeyed += keys_valid;
1125                         if (psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f)
1126                                 psys->totkeyed += 1;
1127                 }
1128                 else {
1129                         keys_valid = 0;
1130                 }
1131         }
1132
1133         psys->totkeyed *= psys->flag & PSYS_KEYED_TIMING ? 1 : psys->part->keyed_loops;
1134 }
1135
1136 static void set_keyed_keys(ParticleSimulationData *sim)
1137 {
1138         ParticleSystem *psys = sim->psys;
1139         ParticleSimulationData ksim= {0};
1140         ParticleTarget *pt;
1141         PARTICLE_P;
1142         ParticleKey *key;
1143         int totpart = psys->totpart, k, totkeys = psys->totkeyed;
1144         int keyed_flag = 0;
1145
1146         ksim.depsgraph = sim->depsgraph;
1147         ksim.scene = sim->scene;
1148
1149         /* no proper targets so let's clear and bail out */
1150         if (psys->totkeyed==0) {
1151                 free_keyed_keys(psys);
1152                 psys->flag &= ~PSYS_KEYED;
1153                 return;
1154         }
1155
1156         if (totpart && psys->particles->totkey != totkeys) {
1157                 free_keyed_keys(psys);
1158
1159                 key = MEM_callocN(totpart*totkeys*sizeof(ParticleKey), "Keyed keys");
1160
1161                 LOOP_PARTICLES {
1162                         pa->keys = key;
1163                         pa->totkey = totkeys;
1164                         key += totkeys;
1165                 }
1166         }
1167
1168         psys->flag &= ~PSYS_KEYED;
1169
1170
1171         pt = psys->targets.first;
1172         for (k=0; k<totkeys; k++) {
1173                 ksim.ob = pt->ob ? pt->ob : sim->ob;
1174                 ksim.psys = BLI_findlink(&ksim.ob->particlesystem, pt->psys - 1);
1175                 keyed_flag = (ksim.psys->flag & PSYS_KEYED);
1176                 ksim.psys->flag &= ~PSYS_KEYED;
1177
1178                 LOOP_PARTICLES {
1179                         key = pa->keys + k;
1180                         key->time = -1.0; /* use current time */
1181
1182                         psys_get_particle_state(&ksim, p%ksim.psys->totpart, key, 1);
1183
1184                         if (psys->flag & PSYS_KEYED_TIMING) {
1185                                 key->time = pa->time + pt->time;
1186                                 if (pt->duration != 0.0f && k+1 < totkeys) {
1187                                         copy_particle_key(key+1, key, 1);
1188                                         (key+1)->time = pa->time + pt->time + pt->duration;
1189                                 }
1190                         }
1191                         else if (totkeys > 1)
1192                                 key->time = pa->time + (float)k / (float)(totkeys - 1) * pa->lifetime;
1193                         else
1194                                 key->time = pa->time;
1195                 }
1196
1197                 if (psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f)
1198                         k++;
1199
1200                 ksim.psys->flag |= keyed_flag;
1201
1202                 pt = (pt->next && pt->next->flag & PTARGET_VALID) ? pt->next : psys->targets.first;
1203         }
1204
1205         psys->flag |= PSYS_KEYED;
1206 }
1207
1208 /************************************************/
1209 /*                      Point Cache                                                     */
1210 /************************************************/
1211 void psys_make_temp_pointcache(Object *ob, ParticleSystem *psys)
1212 {
1213         PointCache *cache = psys->pointcache;
1214
1215         if (cache->flag & PTCACHE_DISK_CACHE && BLI_listbase_is_empty(&cache->mem_cache)) {
1216                 PTCacheID pid;
1217                 BKE_ptcache_id_from_particles(&pid, ob, psys);
1218                 cache->flag &= ~PTCACHE_DISK_CACHE;
1219                 BKE_ptcache_disk_to_mem(&pid);
1220                 cache->flag |= PTCACHE_DISK_CACHE;
1221         }
1222 }
1223 static void psys_clear_temp_pointcache(ParticleSystem *psys)
1224 {
1225         if (psys->pointcache->flag & PTCACHE_DISK_CACHE)
1226                 BKE_ptcache_free_mem(&psys->pointcache->mem_cache);
1227 }
1228 void psys_get_pointcache_start_end(Scene *scene, ParticleSystem *psys, int *sfra, int *efra)
1229 {
1230         ParticleSettings *part = psys->part;
1231
1232         *sfra = max_ii(1, (int)part->sta);
1233         *efra = min_ii((int)(part->end + part->lifetime + 1.0f), max_ii(scene->r.pefra, scene->r.efra));
1234 }
1235
1236 /************************************************/
1237 /*                      Effectors                                                       */
1238 /************************************************/
1239 static void psys_update_particle_bvhtree(ParticleSystem *psys, float cfra)
1240 {
1241         if (psys) {
1242                 PARTICLE_P;
1243                 int totpart = 0;
1244                 bool need_rebuild;
1245
1246                 BLI_rw_mutex_lock(&psys_bvhtree_rwlock, THREAD_LOCK_READ);
1247                 need_rebuild = !psys->bvhtree || psys->bvhtree_frame != cfra;
1248                 BLI_rw_mutex_unlock(&psys_bvhtree_rwlock);
1249
1250                 if (need_rebuild) {
1251                         LOOP_SHOWN_PARTICLES {
1252                                 totpart++;
1253                         }
1254
1255                         BLI_rw_mutex_lock(&psys_bvhtree_rwlock, THREAD_LOCK_WRITE);
1256
1257                         BLI_bvhtree_free(psys->bvhtree);
1258                         psys->bvhtree = BLI_bvhtree_new(totpart, 0.0, 4, 6);
1259
1260                         LOOP_SHOWN_PARTICLES {
1261                                 if (pa->alive == PARS_ALIVE) {
1262                                         if (pa->state.time == cfra)
1263                                                 BLI_bvhtree_insert(psys->bvhtree, p, pa->prev_state.co, 1);
1264                                         else
1265                                                 BLI_bvhtree_insert(psys->bvhtree, p, pa->state.co, 1);
1266                                 }
1267                         }
1268                         BLI_bvhtree_balance(psys->bvhtree);
1269
1270                         psys->bvhtree_frame = cfra;
1271
1272                         BLI_rw_mutex_unlock(&psys_bvhtree_rwlock);
1273                 }
1274         }
1275 }
1276 void psys_update_particle_tree(ParticleSystem *psys, float cfra)
1277 {
1278         if (psys) {
1279                 PARTICLE_P;
1280                 int totpart = 0;
1281
1282                 if (!psys->tree || psys->tree_frame != cfra) {
1283                         LOOP_SHOWN_PARTICLES {
1284                                 totpart++;
1285                         }
1286
1287                         BLI_kdtree_free(psys->tree);
1288                         psys->tree = BLI_kdtree_new(psys->totpart);
1289
1290                         LOOP_SHOWN_PARTICLES {
1291                                 if (pa->alive == PARS_ALIVE) {
1292                                         if (pa->state.time == cfra)
1293                                                 BLI_kdtree_insert(psys->tree, p, pa->prev_state.co);
1294                                         else
1295                                                 BLI_kdtree_insert(psys->tree, p, pa->state.co);
1296                                 }
1297                         }
1298                         BLI_kdtree_balance(psys->tree);
1299
1300                         psys->tree_frame = cfra;
1301                 }
1302         }
1303 }
1304
1305 static void psys_update_effectors(ParticleSimulationData *sim)
1306 {
1307         BKE_effectors_free(sim->psys->effectors);
1308         sim->psys->effectors = BKE_effectors_create(sim->depsgraph,
1309                                                     sim->ob, sim->psys,
1310                                                     sim->psys->part->effector_weights);
1311         precalc_guides(sim, sim->psys->effectors);
1312 }
1313
1314 static void integrate_particle(ParticleSettings *part, ParticleData *pa, float dtime, float *external_acceleration,
1315                                void (*force_func)(void *forcedata, ParticleKey *state, float *force, float *impulse),
1316                                void *forcedata)
1317 {
1318 #define ZERO_F43 {{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}}
1319
1320         ParticleKey states[5];
1321         float force[3], acceleration[3], impulse[3], dx[4][3] = ZERO_F43, dv[4][3] = ZERO_F43, oldpos[3];
1322         float pa_mass= (part->flag & PART_SIZEMASS ? part->mass * pa->size : part->mass);
1323         int i, steps=1;
1324         int integrator = part->integrator;
1325
1326 #undef ZERO_F43
1327
1328         copy_v3_v3(oldpos, pa->state.co);
1329
1330         /* Verlet integration behaves strangely with moving emitters, so do first step with euler. */
1331         if (pa->prev_state.time < 0.f && integrator == PART_INT_VERLET)
1332                 integrator = PART_INT_EULER;
1333
1334         switch (integrator) {
1335                 case PART_INT_EULER:
1336                         steps=1;
1337                         break;
1338                 case PART_INT_MIDPOINT:
1339                         steps=2;
1340                         break;
1341                 case PART_INT_RK4:
1342                         steps=4;
1343                         break;
1344                 case PART_INT_VERLET:
1345                         steps=1;
1346                         break;
1347         }
1348
1349         for (i=0; i<steps; i++) {
1350                 copy_particle_key(states + i, &pa->state, 1);
1351         }
1352
1353         states->time = 0.f;
1354
1355         for (i=0; i<steps; i++) {
1356                 zero_v3(force);
1357                 zero_v3(impulse);
1358
1359                 force_func(forcedata, states+i, force, impulse);
1360
1361                 /* force to acceleration*/
1362                 mul_v3_v3fl(acceleration, force, 1.0f/pa_mass);
1363
1364                 if (external_acceleration)
1365                         add_v3_v3(acceleration, external_acceleration);
1366
1367                 /* calculate next state */
1368                 add_v3_v3(states[i].vel, impulse);
1369
1370                 switch (integrator) {
1371                         case PART_INT_EULER:
1372                                 madd_v3_v3v3fl(pa->state.co, states->co, states->vel, dtime);
1373                                 madd_v3_v3v3fl(pa->state.vel, states->vel, acceleration, dtime);
1374                                 break;
1375                         case PART_INT_MIDPOINT:
1376                                 if (i==0) {
1377                                         madd_v3_v3v3fl(states[1].co, states->co, states->vel, dtime*0.5f);
1378                                         madd_v3_v3v3fl(states[1].vel, states->vel, acceleration, dtime*0.5f);
1379                                         states[1].time = dtime*0.5f;
1380                                         /*fra=sim->psys->cfra+0.5f*dfra;*/
1381                                 }
1382                                 else {
1383                                         madd_v3_v3v3fl(pa->state.co, states->co, states[1].vel, dtime);
1384                                         madd_v3_v3v3fl(pa->state.vel, states->vel, acceleration, dtime);
1385                                 }
1386                                 break;
1387                         case PART_INT_RK4:
1388                                 switch (i) {
1389                                         case 0:
1390                                                 copy_v3_v3(dx[0], states->vel);
1391                                                 mul_v3_fl(dx[0], dtime);
1392                                                 copy_v3_v3(dv[0], acceleration);
1393                                                 mul_v3_fl(dv[0], dtime);
1394
1395                                                 madd_v3_v3v3fl(states[1].co, states->co, dx[0], 0.5f);
1396                                                 madd_v3_v3v3fl(states[1].vel, states->vel, dv[0], 0.5f);
1397                                                 states[1].time = dtime*0.5f;
1398                                                 /*fra=sim->psys->cfra+0.5f*dfra;*/
1399                                                 break;
1400                                         case 1:
1401                                                 madd_v3_v3v3fl(dx[1], states->vel, dv[0], 0.5f);
1402                                                 mul_v3_fl(dx[1], dtime);
1403                                                 copy_v3_v3(dv[1], acceleration);
1404                                                 mul_v3_fl(dv[1], dtime);
1405
1406                                                 madd_v3_v3v3fl(states[2].co, states->co, dx[1], 0.5f);
1407                                                 madd_v3_v3v3fl(states[2].vel, states->vel, dv[1], 0.5f);
1408                                                 states[2].time = dtime*0.5f;
1409                                                 break;
1410                                         case 2:
1411                                                 madd_v3_v3v3fl(dx[2], states->vel, dv[1], 0.5f);
1412                                                 mul_v3_fl(dx[2], dtime);
1413                                                 copy_v3_v3(dv[2], acceleration);
1414                                                 mul_v3_fl(dv[2], dtime);
1415
1416                                                 add_v3_v3v3(states[3].co, states->co, dx[2]);
1417                                                 add_v3_v3v3(states[3].vel, states->vel, dv[2]);
1418                                                 states[3].time = dtime;
1419                                                 /*fra=cfra;*/
1420                                                 break;
1421                                         case 3:
1422                                                 add_v3_v3v3(dx[3], states->vel, dv[2]);
1423                                                 mul_v3_fl(dx[3], dtime);
1424                                                 copy_v3_v3(dv[3], acceleration);
1425                                                 mul_v3_fl(dv[3], dtime);
1426
1427                                                 madd_v3_v3v3fl(pa->state.co, states->co, dx[0], 1.0f/6.0f);
1428                                                 madd_v3_v3fl(pa->state.co, dx[1], 1.0f/3.0f);
1429                                                 madd_v3_v3fl(pa->state.co, dx[2], 1.0f/3.0f);
1430                                                 madd_v3_v3fl(pa->state.co, dx[3], 1.0f/6.0f);
1431
1432                                                 madd_v3_v3v3fl(pa->state.vel, states->vel, dv[0], 1.0f/6.0f);
1433                                                 madd_v3_v3fl(pa->state.vel, dv[1], 1.0f/3.0f);
1434                                                 madd_v3_v3fl(pa->state.vel, dv[2], 1.0f/3.0f);
1435                                                 madd_v3_v3fl(pa->state.vel, dv[3], 1.0f/6.0f);
1436                                 }
1437                                 break;
1438                         case PART_INT_VERLET:   /* Verlet integration */
1439                                 madd_v3_v3v3fl(pa->state.vel, pa->prev_state.vel, acceleration, dtime);
1440                                 madd_v3_v3v3fl(pa->state.co, pa->prev_state.co, pa->state.vel, dtime);
1441
1442                                 sub_v3_v3v3(pa->state.vel, pa->state.co, oldpos);
1443                                 mul_v3_fl(pa->state.vel, 1.0f/dtime);
1444                                 break;
1445                 }
1446         }
1447 }
1448
1449 /*********************************************************************************************************
1450  *                    SPH fluid physics
1451  *
1452  * In theory, there could be unlimited implementation of SPH simulators
1453  *
1454  * This code uses in some parts adapted algorithms from the pseudo code as outlined in the Research paper:
1455  *
1456  * Titled: Particle-based Viscoelastic Fluid Simulation.
1457  * Authors: Simon Clavet, Philippe Beaudoin and Pierre Poulin
1458  * Website: http://www.iro.umontreal.ca/labs/infographie/papers/Clavet-2005-PVFS/
1459  *
1460  * Presented at Siggraph, (2005)
1461  *
1462  * ********************************************************************************************************/
1463 #define PSYS_FLUID_SPRINGS_INITIAL_SIZE 256
1464 static ParticleSpring *sph_spring_add(ParticleSystem *psys, ParticleSpring *spring)
1465 {
1466         /* Are more refs required? */
1467         if (psys->alloc_fluidsprings == 0 || psys->fluid_springs == NULL) {
1468                 psys->alloc_fluidsprings = PSYS_FLUID_SPRINGS_INITIAL_SIZE;
1469                 psys->fluid_springs = (ParticleSpring*)MEM_callocN(psys->alloc_fluidsprings * sizeof(ParticleSpring), "Particle Fluid Springs");
1470         }
1471         else if (psys->tot_fluidsprings == psys->alloc_fluidsprings) {
1472                 /* Double the number of refs allocated */
1473                 psys->alloc_fluidsprings *= 2;
1474                 psys->fluid_springs = (ParticleSpring*)MEM_reallocN(psys->fluid_springs, psys->alloc_fluidsprings * sizeof(ParticleSpring));
1475         }
1476
1477         memcpy(psys->fluid_springs + psys->tot_fluidsprings, spring, sizeof(ParticleSpring));
1478         psys->tot_fluidsprings++;
1479
1480         return psys->fluid_springs + psys->tot_fluidsprings - 1;
1481 }
1482 static void sph_spring_delete(ParticleSystem *psys, int j)
1483 {
1484         if (j != psys->tot_fluidsprings - 1)
1485                 psys->fluid_springs[j] = psys->fluid_springs[psys->tot_fluidsprings - 1];
1486
1487         psys->tot_fluidsprings--;
1488
1489         if (psys->tot_fluidsprings < psys->alloc_fluidsprings/2 && psys->alloc_fluidsprings > PSYS_FLUID_SPRINGS_INITIAL_SIZE) {
1490                 psys->alloc_fluidsprings /= 2;
1491                 psys->fluid_springs = (ParticleSpring*)MEM_reallocN(psys->fluid_springs,  psys->alloc_fluidsprings * sizeof(ParticleSpring));
1492         }
1493 }
1494 static void sph_springs_modify(ParticleSystem *psys, float dtime)
1495 {
1496         SPHFluidSettings *fluid = psys->part->fluid;
1497         ParticleData *pa1, *pa2;
1498         ParticleSpring *spring = psys->fluid_springs;
1499
1500         float h, d, Rij[3], rij, Lij;
1501         int i;
1502
1503         float yield_ratio = fluid->yield_ratio;
1504         float plasticity = fluid->plasticity_constant;
1505         /* scale things according to dtime */
1506         float timefix = 25.f * dtime;
1507
1508         if ((fluid->flag & SPH_VISCOELASTIC_SPRINGS)==0 || fluid->spring_k == 0.f)
1509                 return;
1510
1511         /* Loop through the springs */
1512         for (i=0; i<psys->tot_fluidsprings; i++, spring++) {
1513                 pa1 = psys->particles + spring->particle_index[0];
1514                 pa2 = psys->particles + spring->particle_index[1];
1515
1516                 sub_v3_v3v3(Rij, pa2->prev_state.co, pa1->prev_state.co);
1517                 rij = normalize_v3(Rij);
1518
1519                 /* adjust rest length */
1520                 Lij = spring->rest_length;
1521                 d = yield_ratio * timefix * Lij;
1522
1523                 if (rij > Lij + d) // Stretch
1524                         spring->rest_length += plasticity * (rij - Lij - d) * timefix;
1525                 else if (rij < Lij - d) // Compress
1526                         spring->rest_length -= plasticity * (Lij - d - rij) * timefix;
1527
1528                 h = 4.f*pa1->size;
1529
1530                 if (spring->rest_length > h)
1531                         spring->delete_flag = 1;
1532         }
1533
1534         /* Loop through springs backwaqrds - for efficient delete function */
1535         for (i=psys->tot_fluidsprings-1; i >= 0; i--) {
1536                 if (psys->fluid_springs[i].delete_flag)
1537                         sph_spring_delete(psys, i);
1538         }
1539 }
1540 static EdgeHash *sph_springhash_build(ParticleSystem *psys)
1541 {
1542         EdgeHash *springhash = NULL;
1543         ParticleSpring *spring;
1544         int i = 0;
1545
1546         springhash = BLI_edgehash_new_ex(__func__, psys->tot_fluidsprings);
1547
1548         for (i=0, spring=psys->fluid_springs; i<psys->tot_fluidsprings; i++, spring++)
1549                 BLI_edgehash_insert(springhash, spring->particle_index[0], spring->particle_index[1], POINTER_FROM_INT(i+1));
1550
1551         return springhash;
1552 }
1553
1554 #define SPH_NEIGHBORS 512
1555 typedef struct SPHNeighbor {
1556         ParticleSystem *psys;
1557         int index;
1558 } SPHNeighbor;
1559
1560 typedef struct SPHRangeData {
1561         SPHNeighbor neighbors[SPH_NEIGHBORS];
1562         int tot_neighbors;
1563
1564         float* data;
1565
1566         ParticleSystem *npsys;
1567         ParticleData *pa;
1568
1569         float h;
1570         float mass;
1571         float massfac;
1572         int use_size;
1573 } SPHRangeData;
1574
1575 static void sph_evaluate_func(BVHTree *tree, ParticleSystem **psys, float co[3], SPHRangeData *pfr, float interaction_radius, BVHTree_RangeQuery callback)
1576 {
1577         int i;
1578
1579         pfr->tot_neighbors = 0;
1580
1581         for (i=0; i < 10 && psys[i]; i++) {
1582                 pfr->npsys    = psys[i];
1583                 pfr->massfac  = psys[i]->part->mass / pfr->mass;
1584                 pfr->use_size = psys[i]->part->flag & PART_SIZEMASS;
1585
1586                 if (tree) {
1587                         BLI_bvhtree_range_query(tree, co, interaction_radius, callback, pfr);
1588                         break;
1589                 }
1590                 else {
1591                         BLI_rw_mutex_lock(&psys_bvhtree_rwlock, THREAD_LOCK_READ);
1592
1593                         BLI_bvhtree_range_query(psys[i]->bvhtree, co, interaction_radius, callback, pfr);
1594
1595                         BLI_rw_mutex_unlock(&psys_bvhtree_rwlock);
1596                 }
1597         }
1598 }
1599 static void sph_density_accum_cb(void *userdata, int index, const float co[3], float squared_dist)
1600 {
1601         SPHRangeData *pfr = (SPHRangeData *)userdata;
1602         ParticleData *npa = pfr->npsys->particles + index;
1603         float q;
1604         float dist;
1605
1606         UNUSED_VARS(co);
1607
1608         if (npa == pfr->pa || squared_dist < FLT_EPSILON)
1609                 return;
1610
1611         /* Ugh! One particle has too many neighbors! If some aren't taken into
1612          * account, the forces will be biased by the tree search order. This
1613          * effectively adds energy to the system, and results in a churning motion.
1614          * But, we have to stop somewhere, and it's not the end of the world.
1615          * - jahka and z0r
1616          */
1617         if (pfr->tot_neighbors >= SPH_NEIGHBORS)
1618                 return;
1619
1620         pfr->neighbors[pfr->tot_neighbors].index = index;
1621         pfr->neighbors[pfr->tot_neighbors].psys = pfr->npsys;
1622         pfr->tot_neighbors++;
1623
1624         dist = sqrtf(squared_dist);
1625         q = (1.f - dist/pfr->h) * pfr->massfac;
1626
1627         if (pfr->use_size)
1628                 q *= npa->size;
1629
1630         pfr->data[0] += q*q;
1631         pfr->data[1] += q*q*q;
1632 }
1633
1634 /*
1635  * Find the Courant number for an SPH particle (used for adaptive time step).
1636  */
1637 static void sph_particle_courant(SPHData *sphdata, SPHRangeData *pfr)
1638 {
1639         ParticleData *pa, *npa;
1640         int i;
1641         float flow[3], offset[3], dist;
1642
1643         zero_v3(flow);
1644
1645         dist = 0.0f;
1646         if (pfr->tot_neighbors > 0) {
1647                 pa = pfr->pa;
1648                 for (i=0; i < pfr->tot_neighbors; i++) {
1649                         npa = pfr->neighbors[i].psys->particles + pfr->neighbors[i].index;
1650                         sub_v3_v3v3(offset, pa->prev_state.co, npa->prev_state.co);
1651                         dist += len_v3(offset);
1652                         add_v3_v3(flow, npa->prev_state.vel);
1653                 }
1654                 dist += sphdata->psys[0]->part->fluid->radius; // TODO: remove this? - z0r
1655                 sphdata->element_size = dist / pfr->tot_neighbors;
1656                 mul_v3_v3fl(sphdata->flow, flow, 1.0f / pfr->tot_neighbors);
1657         }
1658         else {
1659                 sphdata->element_size = FLT_MAX;
1660                 copy_v3_v3(sphdata->flow, flow);
1661         }
1662 }
1663 static void sph_force_cb(void *sphdata_v, ParticleKey *state, float *force, float *UNUSED(impulse))
1664 {
1665         SPHData *sphdata = (SPHData *)sphdata_v;
1666         ParticleSystem **psys = sphdata->psys;
1667         ParticleData *pa = sphdata->pa;
1668         SPHFluidSettings *fluid = psys[0]->part->fluid;
1669         ParticleSpring *spring = NULL;
1670         SPHRangeData pfr;
1671         SPHNeighbor *pfn;
1672         float *gravity = sphdata->gravity;
1673         EdgeHash *springhash = sphdata->eh;
1674
1675         float q, u, rij, dv[3];
1676         float pressure, near_pressure;
1677
1678         float visc = fluid->viscosity_omega;
1679         float stiff_visc = fluid->viscosity_beta * (fluid->flag & SPH_FAC_VISCOSITY ? fluid->viscosity_omega : 1.f);
1680
1681         float inv_mass = 1.0f / sphdata->mass;
1682         float spring_constant = fluid->spring_k;
1683
1684         /* 4.0 seems to be a pretty good value */
1685         float interaction_radius = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * pa->size : 1.0f);
1686         float h = interaction_radius * sphdata->hfac;
1687         /* 4.77 is an experimentally determined density factor */
1688         float rest_density = fluid->rest_density * (fluid->flag & SPH_FAC_DENSITY ? 4.77f : 1.f);
1689         float rest_length = fluid->rest_length * (fluid->flag & SPH_FAC_REST_LENGTH ? 2.588f * pa->size : 1.f);
1690
1691         float stiffness = fluid->stiffness_k;
1692         float stiffness_near_fac = fluid->stiffness_knear * (fluid->flag & SPH_FAC_REPULSION ? fluid->stiffness_k : 1.f);
1693
1694         ParticleData *npa;
1695         float vec[3];
1696         float vel[3];
1697         float co[3];
1698         float data[2];
1699         float density, near_density;
1700
1701         int i, spring_index, index = pa - psys[0]->particles;
1702
1703         data[0] = data[1] = 0;
1704         pfr.data = data;
1705         pfr.h = h;
1706         pfr.pa = pa;
1707         pfr.mass = sphdata->mass;
1708
1709         sph_evaluate_func( NULL, psys, state->co, &pfr, interaction_radius, sph_density_accum_cb);
1710
1711         density = data[0];
1712         near_density = data[1];
1713
1714         pressure =  stiffness * (density - rest_density);
1715         near_pressure = stiffness_near_fac * near_density;
1716
1717         pfn = pfr.neighbors;
1718         for (i=0; i<pfr.tot_neighbors; i++, pfn++) {
1719                 npa = pfn->psys->particles + pfn->index;
1720
1721                 madd_v3_v3v3fl(co, npa->prev_state.co, npa->prev_state.vel, state->time);
1722
1723                 sub_v3_v3v3(vec, co, state->co);
1724                 rij = normalize_v3(vec);
1725
1726                 q = (1.f - rij/h) * pfn->psys->part->mass * inv_mass;
1727
1728                 if (pfn->psys->part->flag & PART_SIZEMASS)
1729                         q *= npa->size;
1730
1731                 copy_v3_v3(vel, npa->prev_state.vel);
1732
1733                 /* Double Density Relaxation */
1734                 madd_v3_v3fl(force, vec, -(pressure + near_pressure*q)*q);
1735
1736                 /* Viscosity */
1737                 if (visc > 0.f  || stiff_visc > 0.f) {
1738                         sub_v3_v3v3(dv, vel, state->vel);
1739                         u = dot_v3v3(vec, dv);
1740
1741                         if (u < 0.f && visc > 0.f)
1742                                 madd_v3_v3fl(force, vec, 0.5f * q * visc * u );
1743
1744                         if (u > 0.f && stiff_visc > 0.f)
1745                                 madd_v3_v3fl(force, vec, 0.5f * q * stiff_visc * u );
1746                 }
1747
1748                 if (spring_constant > 0.f) {
1749                         /* Viscoelastic spring force */
1750                         if (pfn->psys == psys[0] && fluid->flag & SPH_VISCOELASTIC_SPRINGS && springhash) {
1751                                 /* BLI_edgehash_lookup appears to be thread-safe. - z0r */
1752                                 spring_index = POINTER_AS_INT(BLI_edgehash_lookup(springhash, index, pfn->index));
1753
1754                                 if (spring_index) {
1755                                         spring = psys[0]->fluid_springs + spring_index - 1;
1756
1757                                         madd_v3_v3fl(force, vec, -10.f * spring_constant * (1.f - rij/h) * (spring->rest_length - rij));
1758                                 }
1759                                 else if (fluid->spring_frames == 0 || (pa->prev_state.time-pa->time) <= fluid->spring_frames) {
1760                                         ParticleSpring temp_spring;
1761                                         temp_spring.particle_index[0] = index;
1762                                         temp_spring.particle_index[1] = pfn->index;
1763                                         temp_spring.rest_length = (fluid->flag & SPH_CURRENT_REST_LENGTH) ? rij : rest_length;
1764                                         temp_spring.delete_flag = 0;
1765
1766                                         /* sph_spring_add is not thread-safe. - z0r */
1767                                         sph_spring_add(psys[0], &temp_spring);
1768                                 }
1769                         }
1770                         else {/* PART_SPRING_HOOKES - Hooke's spring force */
1771                                 madd_v3_v3fl(force, vec, -10.f * spring_constant * (1.f - rij/h) * (rest_length - rij));
1772                         }
1773                 }
1774         }
1775
1776         /* Artificial buoyancy force in negative gravity direction  */
1777         if (fluid->buoyancy > 0.f && gravity)
1778                 madd_v3_v3fl(force, gravity, fluid->buoyancy * (density-rest_density));
1779
1780         if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF)
1781                 sph_particle_courant(sphdata, &pfr);
1782         sphdata->pass++;
1783 }
1784
1785 static void sphclassical_density_accum_cb(void *userdata, int index, const float co[3], float UNUSED(squared_dist))
1786 {
1787         SPHRangeData *pfr = (SPHRangeData *)userdata;
1788         ParticleData *npa = pfr->npsys->particles + index;
1789         float q;
1790         float qfac = 21.0f / (256.f * (float)M_PI);
1791         float rij, rij_h;
1792         float vec[3];
1793
1794         /* Exclude particles that are more than 2h away. Can't use squared_dist here
1795          * because it is not accurate enough. Use current state, i.e. the output of
1796          * basic_integrate() - z0r */
1797         sub_v3_v3v3(vec, npa->state.co, co);
1798         rij = len_v3(vec);
1799         rij_h = rij / pfr->h;
1800         if (rij_h > 2.0f)
1801                 return;
1802
1803         /* Smoothing factor. Utilise the Wendland kernel. gnuplot:
1804          *     q1(x) = (2.0 - x)**4 * ( 1.0 + 2.0 * x)
1805          *     plot [0:2] q1(x) */
1806         q  = qfac / pow3f(pfr->h) * pow4f(2.0f - rij_h) * ( 1.0f + 2.0f * rij_h);
1807         q *= pfr->npsys->part->mass;
1808
1809         if (pfr->use_size)
1810                 q *= pfr->pa->size;
1811
1812         pfr->data[0] += q;
1813         pfr->data[1] += q / npa->sphdensity;
1814 }
1815
1816 static void sphclassical_neighbour_accum_cb(void *userdata, int index, const float co[3], float UNUSED(squared_dist))
1817 {
1818         SPHRangeData *pfr = (SPHRangeData *)userdata;
1819         ParticleData *npa = pfr->npsys->particles + index;
1820         float rij, rij_h;
1821         float vec[3];
1822
1823         if (pfr->tot_neighbors >= SPH_NEIGHBORS)
1824                 return;
1825
1826         /* Exclude particles that are more than 2h away. Can't use squared_dist here
1827          * because it is not accurate enough. Use current state, i.e. the output of
1828          * basic_integrate() - z0r */
1829         sub_v3_v3v3(vec, npa->state.co, co);
1830         rij = len_v3(vec);
1831         rij_h = rij / pfr->h;
1832         if (rij_h > 2.0f)
1833                 return;
1834
1835         pfr->neighbors[pfr->tot_neighbors].index = index;
1836         pfr->neighbors[pfr->tot_neighbors].psys = pfr->npsys;
1837         pfr->tot_neighbors++;
1838 }
1839 static void sphclassical_force_cb(void *sphdata_v, ParticleKey *state, float *force, float *UNUSED(impulse))
1840 {
1841         SPHData *sphdata = (SPHData *)sphdata_v;
1842         ParticleSystem **psys = sphdata->psys;
1843         ParticleData *pa = sphdata->pa;
1844         SPHFluidSettings *fluid = psys[0]->part->fluid;
1845         SPHRangeData pfr;
1846         SPHNeighbor *pfn;
1847         float *gravity = sphdata->gravity;
1848
1849         float dq, u, rij, dv[3];
1850         float pressure, npressure;
1851
1852         float visc = fluid->viscosity_omega;
1853
1854         float interaction_radius;
1855         float h, hinv;
1856         /* 4.77 is an experimentally determined density factor */
1857         float rest_density = fluid->rest_density * (fluid->flag & SPH_FAC_DENSITY ? 4.77f : 1.0f);
1858
1859         // Use speed of sound squared
1860         float stiffness = pow2f(fluid->stiffness_k);
1861
1862         ParticleData *npa;
1863         float vec[3];
1864         float co[3];
1865         float pressureTerm;
1866
1867         int i;
1868
1869         float qfac2 = 42.0f / (256.0f * (float)M_PI);
1870         float rij_h;
1871
1872         /* 4.0 here is to be consistent with previous formulation/interface */
1873         interaction_radius = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * pa->size : 1.0f);
1874         h = interaction_radius * sphdata->hfac;
1875         hinv = 1.0f / h;
1876
1877         pfr.h = h;
1878         pfr.pa = pa;
1879
1880         sph_evaluate_func(NULL, psys, state->co, &pfr, interaction_radius, sphclassical_neighbour_accum_cb);
1881         pressure =  stiffness * (pow7f(pa->sphdensity / rest_density) - 1.0f);
1882
1883         /* multiply by mass so that we return a force, not accel */
1884         qfac2 *= sphdata->mass / pow3f(pfr.h);
1885
1886         pfn = pfr.neighbors;
1887         for (i = 0; i < pfr.tot_neighbors; i++, pfn++) {
1888                 npa = pfn->psys->particles + pfn->index;
1889                 if (npa == pa) {
1890                         /* we do not contribute to ourselves */
1891                         continue;
1892                 }
1893
1894                 /* Find vector to neighbor. Exclude particles that are more than 2h
1895                  * away. Can't use current state here because it may have changed on
1896                  * another thread - so do own mini integration. Unlike basic_integrate,
1897                  * SPH integration depends on neighboring particles. - z0r */
1898                 madd_v3_v3v3fl(co, npa->prev_state.co, npa->prev_state.vel, state->time);
1899                 sub_v3_v3v3(vec, co, state->co);
1900                 rij = normalize_v3(vec);
1901                 rij_h = rij / pfr.h;
1902                 if (rij_h > 2.0f)
1903                         continue;
1904
1905                 npressure = stiffness * (pow7f(npa->sphdensity / rest_density) - 1.0f);
1906
1907                 /* First derivative of smoothing factor. Utilise the Wendland kernel.
1908                  * gnuplot:
1909                  *     q2(x) = 2.0 * (2.0 - x)**4 - 4.0 * (2.0 - x)**3 * (1.0 + 2.0 * x)
1910                  *     plot [0:2] q2(x)
1911                  * Particles > 2h away are excluded above. */
1912                 dq = qfac2 * (2.0f * pow4f(2.0f - rij_h) - 4.0f * pow3f(2.0f - rij_h) * (1.0f + 2.0f * rij_h)  );
1913
1914                 if (pfn->psys->part->flag & PART_SIZEMASS)
1915                         dq *= npa->size;
1916
1917                 pressureTerm = pressure / pow2f(pa->sphdensity) + npressure / pow2f(npa->sphdensity);
1918
1919                 /* Note that 'minus' is removed, because vec = vecBA, not vecAB.
1920                  * This applies to the viscosity calculation below, too. */
1921                 madd_v3_v3fl(force, vec, pressureTerm * dq);
1922
1923                 /* Viscosity */
1924                 if (visc > 0.0f) {
1925                         sub_v3_v3v3(dv, npa->prev_state.vel, pa->prev_state.vel);
1926                         u = dot_v3v3(vec, dv);
1927                         /* Apply parameters */
1928                         u *= -dq * hinv * visc / (0.5f * npa->sphdensity + 0.5f * pa->sphdensity);
1929                         madd_v3_v3fl(force, vec, u);
1930                 }
1931         }
1932
1933         /* Artificial buoyancy force in negative gravity direction  */
1934         if (fluid->buoyancy > 0.f && gravity)
1935                 madd_v3_v3fl(force, gravity, fluid->buoyancy * (pa->sphdensity - rest_density));
1936
1937         if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF)
1938                 sph_particle_courant(sphdata, &pfr);
1939         sphdata->pass++;
1940 }
1941
1942 static void sphclassical_calc_dens(ParticleData *pa, float UNUSED(dfra), SPHData *sphdata)
1943 {
1944         ParticleSystem **psys = sphdata->psys;
1945         SPHFluidSettings *fluid = psys[0]->part->fluid;
1946         /* 4.0 seems to be a pretty good value */
1947         float interaction_radius  = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * psys[0]->part->size : 1.0f);
1948         SPHRangeData pfr;
1949         float data[2];
1950
1951         data[0] = 0;
1952         data[1] = 0;
1953         pfr.data = data;
1954         pfr.h = interaction_radius * sphdata->hfac;
1955         pfr.pa = pa;
1956         pfr.mass = sphdata->mass;
1957
1958         sph_evaluate_func( NULL, psys, pa->state.co, &pfr, interaction_radius, sphclassical_density_accum_cb);
1959         pa->sphdensity = min_ff(max_ff(data[0], fluid->rest_density * 0.9f), fluid->rest_density * 1.1f);
1960 }
1961
1962 void psys_sph_init(ParticleSimulationData *sim, SPHData *sphdata)
1963 {
1964         ParticleTarget *pt;
1965         int i;
1966
1967         // Add other coupled particle systems.
1968         sphdata->psys[0] = sim->psys;
1969         for (i=1, pt=sim->psys->targets.first; i<10; i++, pt=(pt?pt->next:NULL))
1970                 sphdata->psys[i] = pt ? psys_get_target_system(sim->ob, pt) : NULL;
1971
1972         if (psys_uses_gravity(sim))
1973                 sphdata->gravity = sim->scene->physics_settings.gravity;
1974         else
1975                 sphdata->gravity = NULL;
1976         sphdata->eh = sph_springhash_build(sim->psys);
1977
1978         // These per-particle values should be overridden later, but just for
1979         // completeness we give them default values now.
1980         sphdata->pa = NULL;
1981         sphdata->mass = 1.0f;
1982
1983         if (sim->psys->part->fluid->solver == SPH_SOLVER_DDR) {
1984                 sphdata->force_cb = sph_force_cb;
1985                 sphdata->density_cb = sph_density_accum_cb;
1986                 sphdata->hfac = 1.0f;
1987         }
1988         else {
1989                 /* SPH_SOLVER_CLASSICAL */
1990                 sphdata->force_cb = sphclassical_force_cb;
1991                 sphdata->density_cb = sphclassical_density_accum_cb;
1992                 sphdata->hfac = 0.5f;
1993         }
1994
1995 }
1996
1997 void psys_sph_finalise(SPHData *sphdata)
1998 {
1999         if (sphdata->eh) {
2000                 BLI_edgehash_free(sphdata->eh, NULL);
2001                 sphdata->eh = NULL;
2002         }
2003 }
2004 /* Sample the density field at a point in space. */
2005 void psys_sph_density(BVHTree *tree, SPHData *sphdata, float co[3], float vars[2])
2006 {
2007         ParticleSystem **psys = sphdata->psys;
2008         SPHFluidSettings *fluid = psys[0]->part->fluid;
2009         /* 4.0 seems to be a pretty good value */
2010         float interaction_radius  = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * psys[0]->part->size : 1.0f);
2011         SPHRangeData pfr;
2012         float density[2];
2013
2014         density[0] = density[1] = 0.0f;
2015         pfr.data = density;
2016         pfr.h = interaction_radius * sphdata->hfac;
2017         pfr.mass = sphdata->mass;
2018
2019         sph_evaluate_func(tree, psys, co, &pfr, interaction_radius, sphdata->density_cb);
2020
2021         vars[0] = pfr.data[0];
2022         vars[1] = pfr.data[1];
2023 }
2024
2025 static void sph_integrate(ParticleSimulationData *sim, ParticleData *pa, float dfra, SPHData *sphdata)
2026 {
2027         ParticleSettings *part = sim->psys->part;
2028         // float timestep = psys_get_timestep(sim); // UNUSED
2029         float pa_mass = part->mass * (part->flag & PART_SIZEMASS ? pa->size : 1.f);
2030         float dtime = dfra*psys_get_timestep(sim);
2031         // int steps = 1; // UNUSED
2032         float effector_acceleration[3];
2033
2034         sphdata->pa = pa;
2035         sphdata->mass = pa_mass;
2036         sphdata->pass = 0;
2037         //sphdata.element_size and sphdata.flow are set in the callback.
2038
2039         /* restore previous state and treat gravity & effectors as external acceleration*/
2040         sub_v3_v3v3(effector_acceleration, pa->state.vel, pa->prev_state.vel);
2041         mul_v3_fl(effector_acceleration, 1.f/dtime);
2042
2043         copy_particle_key(&pa->state, &pa->prev_state, 0);
2044
2045         integrate_particle(part, pa, dtime, effector_acceleration, sphdata->force_cb, sphdata);
2046 }
2047
2048 /************************************************/
2049 /*                      Basic physics                                           */
2050 /************************************************/
2051 typedef struct EfData {
2052         ParticleTexture ptex;
2053         ParticleSimulationData *sim;
2054         ParticleData *pa;
2055 } EfData;
2056 static void basic_force_cb(void *efdata_v, ParticleKey *state, float *force, float *impulse)
2057 {
2058         EfData *efdata = (EfData *)efdata_v;
2059         ParticleSimulationData *sim = efdata->sim;
2060         ParticleSettings *part = sim->psys->part;
2061         ParticleData *pa = efdata->pa;
2062         EffectedPoint epoint;
2063         RNG *rng = sim->rng;
2064
2065         /* add effectors */
2066         pd_point_from_particle(efdata->sim, efdata->pa, state, &epoint);
2067         if (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR)
2068                 BKE_effectors_apply(sim->psys->effectors, sim->colliders, part->effector_weights, &epoint, force, impulse);
2069
2070         mul_v3_fl(force, efdata->ptex.field);
2071         mul_v3_fl(impulse, efdata->ptex.field);
2072
2073         /* calculate air-particle interaction */
2074         if (part->dragfac != 0.0f)
2075                 madd_v3_v3fl(force, state->vel, -part->dragfac * pa->size * pa->size * len_v3(state->vel));
2076
2077         /* brownian force */
2078         if (part->brownfac != 0.0f) {
2079                 force[0] += (BLI_rng_get_float(rng)-0.5f) * part->brownfac;
2080                 force[1] += (BLI_rng_get_float(rng)-0.5f) * part->brownfac;
2081                 force[2] += (BLI_rng_get_float(rng)-0.5f) * part->brownfac;
2082         }
2083
2084         if (part->flag & PART_ROT_DYN && epoint.ave)
2085                 copy_v3_v3(pa->state.ave, epoint.ave);
2086 }
2087 /* gathers all forces that effect particles and calculates a new state for the particle */
2088 static void basic_integrate(ParticleSimulationData *sim, int p, float dfra, float cfra)
2089 {
2090         ParticleSettings *part = sim->psys->part;
2091         ParticleData *pa = sim->psys->particles + p;
2092         ParticleKey tkey;
2093         float dtime=dfra*psys_get_timestep(sim), time;
2094         float *gravity = NULL, gr[3];
2095         EfData efdata;
2096
2097         psys_get_texture(sim, pa, &efdata.ptex, PAMAP_PHYSICS, cfra);
2098
2099         efdata.pa = pa;
2100         efdata.sim = sim;
2101
2102         /* add global acceleration (gravitation) */
2103         if (psys_uses_gravity(sim) &&
2104                 /* normal gravity is too strong for hair so it's disabled by default */
2105                 (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR))
2106         {
2107                 zero_v3(gr);
2108                 madd_v3_v3fl(gr, sim->scene->physics_settings.gravity, part->effector_weights->global_gravity * efdata.ptex.gravity);
2109                 gravity = gr;
2110         }
2111
2112         /* maintain angular velocity */
2113         copy_v3_v3(pa->state.ave, pa->prev_state.ave);
2114
2115         integrate_particle(part, pa, dtime, gravity, basic_force_cb, &efdata);
2116
2117         /* damp affects final velocity */
2118         if (part->dampfac != 0.f)
2119                 mul_v3_fl(pa->state.vel, 1.f - part->dampfac * efdata.ptex.damp * 25.f * dtime);
2120
2121         //copy_v3_v3(pa->state.ave, states->ave);
2122
2123         /* finally we do guides */
2124         time=(cfra-pa->time)/pa->lifetime;
2125         CLAMP(time, 0.0f, 1.0f);
2126
2127         copy_v3_v3(tkey.co,pa->state.co);
2128         copy_v3_v3(tkey.vel,pa->state.vel);
2129         tkey.time=pa->state.time;
2130
2131         if (part->type != PART_HAIR) {
2132                 if (do_guides(sim->depsgraph, sim->psys->part, sim->psys->effectors, &tkey, p, time)) {
2133                         copy_v3_v3(pa->state.co,tkey.co);
2134                         /* guides don't produce valid velocity */
2135                         sub_v3_v3v3(pa->state.vel, tkey.co, pa->prev_state.co);
2136                         mul_v3_fl(pa->state.vel,1.0f/dtime);
2137                         pa->state.time=tkey.time;
2138                 }
2139         }
2140 }
2141 static void basic_rotate(ParticleSettings *part, ParticleData *pa, float dfra, float timestep)
2142 {
2143         float rotfac, rot1[4], rot2[4] = {1.0,0.0,0.0,0.0}, dtime=dfra*timestep, extrotfac;
2144
2145         if ((part->flag & PART_ROTATIONS) == 0) {
2146                 unit_qt(pa->state.rot);
2147                 return;
2148         }
2149
2150         if (part->flag & PART_ROT_DYN) {
2151                 extrotfac = len_v3(pa->state.ave);
2152         }
2153         else {
2154                 extrotfac = 0.0f;
2155         }
2156
2157         if ((part->flag & PART_ROT_DYN) && ELEM(part->avemode, PART_AVE_VELOCITY, PART_AVE_HORIZONTAL, PART_AVE_VERTICAL)) {
2158                 float angle;
2159                 float len1 = len_v3(pa->prev_state.vel);
2160                 float len2 = len_v3(pa->state.vel);
2161                 float vec[3];
2162
2163                 if (len1 == 0.0f || len2 == 0.0f) {
2164                         zero_v3(pa->state.ave);
2165                 }
2166                 else {
2167                         cross_v3_v3v3(pa->state.ave, pa->prev_state.vel, pa->state.vel);
2168                         normalize_v3(pa->state.ave);
2169                         angle = dot_v3v3(pa->prev_state.vel, pa->state.vel) / (len1 * len2);
2170                         mul_v3_fl(pa->state.ave, saacos(angle) / dtime);
2171                 }
2172
2173                 get_angular_velocity_vector(part->avemode, &pa->state, vec);
2174                 axis_angle_to_quat(rot2, vec, dtime*part->avefac);
2175         }
2176
2177         rotfac = len_v3(pa->state.ave);
2178         if (rotfac == 0.0f || (part->flag & PART_ROT_DYN)==0 || extrotfac == 0.0f) {
2179                 unit_qt(rot1);
2180         }
2181         else {
2182                 axis_angle_to_quat(rot1,pa->state.ave,rotfac*dtime);
2183         }
2184         mul_qt_qtqt(pa->state.rot,rot1,pa->prev_state.rot);
2185         mul_qt_qtqt(pa->state.rot,rot2,pa->state.rot);
2186
2187         /* keep rotation quat in good health */
2188         normalize_qt(pa->state.rot);
2189 }
2190
2191 /************************************************
2192  * Collisions
2193  *
2194  * The algorithm is roughly:
2195  *  1. Use a BVH tree to search for faces that a particle may collide with.
2196  *  2. Use Newton's method to find the exact time at which the collision occurs.
2197  *     https://en.wikipedia.org/wiki/Newton's_method
2198  *
2199  ************************************************/
2200 #define COLLISION_MIN_RADIUS 0.001f
2201 #define COLLISION_MIN_DISTANCE 0.0001f
2202 #define COLLISION_ZERO 0.00001f
2203 #define COLLISION_INIT_STEP 0.00008f
2204 typedef float (*NRDistanceFunc)(float *p, float radius, ParticleCollisionElement *pce, float *nor);
2205 static float nr_signed_distance_to_plane(float *p, float radius, ParticleCollisionElement *pce, float *nor)
2206 {
2207         float p0[3], e1[3], e2[3], d;
2208
2209         sub_v3_v3v3(e1, pce->x1, pce->x0);
2210         sub_v3_v3v3(e2, pce->x2, pce->x0);
2211         sub_v3_v3v3(p0, p, pce->x0);
2212
2213         cross_v3_v3v3(nor, e1, e2);
2214         normalize_v3(nor);
2215
2216         d = dot_v3v3(p0, nor);
2217
2218         if (pce->inv_nor == -1) {
2219                 if (d < 0.f)
2220                         pce->inv_nor = 1;
2221                 else
2222                         pce->inv_nor = 0;
2223         }
2224
2225         if (pce->inv_nor == 1) {
2226                 negate_v3(nor);
2227                 d = -d;
2228         }
2229
2230         return d - radius;
2231 }
2232 static float nr_distance_to_edge(float *p, float radius, ParticleCollisionElement *pce, float *UNUSED(nor))
2233 {
2234         float v0[3], v1[3], v2[3], c[3];
2235
2236         sub_v3_v3v3(v0, pce->x1, pce->x0);
2237         sub_v3_v3v3(v1, p, pce->x0);
2238         sub_v3_v3v3(v2, p, pce->x1);
2239
2240         cross_v3_v3v3(c, v1, v2);
2241
2242         return fabsf(len_v3(c)/len_v3(v0)) - radius;
2243 }
2244 static float nr_distance_to_vert(float *p, float radius, ParticleCollisionElement *pce, float *UNUSED(nor))
2245 {
2246         return len_v3v3(p, pce->x0) - radius;
2247 }
2248 static void collision_interpolate_element(ParticleCollisionElement *pce, float t, float fac, ParticleCollision *col)
2249 {
2250         /* t is the current time for newton rhapson */
2251         /* fac is the starting factor for current collision iteration */
2252         /* the col->fac's are factors for the particle subframe step start and end during collision modifier step */
2253         float f = fac + t*(1.f-fac);
2254         float mul = col->fac1 + f * (col->fac2-col->fac1);
2255         if (pce->tot > 0) {
2256                 madd_v3_v3v3fl(pce->x0, pce->x[0], pce->v[0], mul);
2257
2258                 if (pce->tot > 1) {
2259                         madd_v3_v3v3fl(pce->x1, pce->x[1], pce->v[1], mul);
2260
2261                         if (pce->tot > 2)
2262                                 madd_v3_v3v3fl(pce->x2, pce->x[2], pce->v[2], mul);
2263                 }
2264         }
2265 }
2266 static void collision_point_velocity(ParticleCollisionElement *pce)
2267 {
2268         float v[3];
2269
2270         copy_v3_v3(pce->vel, pce->v[0]);
2271
2272         if (pce->tot > 1) {
2273                 sub_v3_v3v3(v, pce->v[1], pce->v[0]);
2274                 madd_v3_v3fl(pce->vel, v, pce->uv[0]);
2275
2276                 if (pce->tot > 2) {
2277                         sub_v3_v3v3(v, pce->v[2], pce->v[0]);
2278                         madd_v3_v3fl(pce->vel, v, pce->uv[1]);
2279                 }
2280         }
2281 }
2282 static float collision_point_distance_with_normal(float p[3], ParticleCollisionElement *pce, float fac, ParticleCollision *col, float *nor)
2283 {
2284         if (fac >= 0.f)
2285                 collision_interpolate_element(pce, 0.f, fac, col);
2286
2287         switch (pce->tot) {
2288                 case 1:
2289                 {
2290                         sub_v3_v3v3(nor, p, pce->x0);
2291                         return normalize_v3(nor);
2292                 }
2293                 case 2:
2294                 {
2295                         float u, e[3], vec[3];
2296                         sub_v3_v3v3(e, pce->x1, pce->x0);
2297                         sub_v3_v3v3(vec, p, pce->x0);
2298                         u = dot_v3v3(vec, e) / dot_v3v3(e, e);
2299
2300                         madd_v3_v3v3fl(nor, vec, e, -u);
2301                         return normalize_v3(nor);
2302                 }
2303                 case 3:
2304                         return nr_signed_distance_to_plane(p, 0.f, pce, nor);
2305         }
2306         return 0;
2307 }
2308 static void collision_point_on_surface(float p[3], ParticleCollisionElement *pce, float fac, ParticleCollision *col, float *co)
2309 {
2310         collision_interpolate_element(pce, 0.f, fac, col);
2311
2312         switch (pce->tot) {
2313                 case 1:
2314                 {
2315                         sub_v3_v3v3(co, p, pce->x0);
2316                         normalize_v3(co);
2317                         madd_v3_v3v3fl(co, pce->x0, co, col->radius);
2318                         break;
2319                 }
2320                 case 2:
2321                 {
2322                         float u, e[3], vec[3], nor[3];
2323                         sub_v3_v3v3(e, pce->x1, pce->x0);
2324                         sub_v3_v3v3(vec, p, pce->x0);
2325                         u = dot_v3v3(vec, e) / dot_v3v3(e, e);
2326
2327                         madd_v3_v3v3fl(nor, vec, e, -u);
2328                         normalize_v3(nor);
2329
2330                         madd_v3_v3v3fl(co, pce->x0, e, pce->uv[0]);
2331                         madd_v3_v3fl(co, nor, col->radius);
2332                         break;
2333                 }
2334                 case 3:
2335                 {
2336                         float p0[3], e1[3], e2[3], nor[3];
2337
2338                         sub_v3_v3v3(e1, pce->x1, pce->x0);
2339                         sub_v3_v3v3(e2, pce->x2, pce->x0);
2340                         sub_v3_v3v3(p0, p, pce->x0);
2341
2342                         cross_v3_v3v3(nor, e1, e2);
2343                         normalize_v3(nor);
2344
2345                         if (pce->inv_nor == 1)
2346                                 negate_v3(nor);
2347
2348                         madd_v3_v3v3fl(co, pce->x0, nor, col->radius);
2349                         madd_v3_v3fl(co, e1, pce->uv[0]);
2350                         madd_v3_v3fl(co, e2, pce->uv[1]);
2351                         break;
2352                 }
2353         }
2354 }
2355 /* find first root in range [0-1] starting from 0 */
2356 static float collision_newton_rhapson(ParticleCollision *col, float radius, ParticleCollisionElement *pce, NRDistanceFunc distance_func)
2357 {
2358         float t0, t1, dt_init, d0, d1, dd, n[3];
2359         int iter;
2360
2361         pce->inv_nor = -1;
2362
2363         if (col->inv_total_time > 0.0f) {
2364                 /* Initial step size should be small, but not too small or floating point
2365                  * precision errors will appear. - z0r */
2366                 dt_init = COLLISION_INIT_STEP * col->inv_total_time;
2367         }
2368         else {
2369                 dt_init = 0.001f;
2370         }
2371
2372         /* start from the beginning */
2373         t0 = 0.f;
2374         collision_interpolate_element(pce, t0, col->f, col);
2375         d0 = distance_func(col->co1, radius, pce, n);
2376         t1 = dt_init;
2377         d1 = 0.f;
2378
2379         for (iter=0; iter<10; iter++) {//, itersum++) {
2380                 /* get current location */
2381                 collision_interpolate_element(pce, t1, col->f, col);
2382                 interp_v3_v3v3(pce->p, col->co1, col->co2, t1);
2383
2384                 d1 = distance_func(pce->p, radius, pce, n);
2385
2386                 /* particle already inside face, so report collision */
2387                 if (iter == 0 && d0 < 0.f && d0 > -radius) {
2388                         copy_v3_v3(pce->p, col->co1);
2389                         copy_v3_v3(pce->nor, n);
2390                         pce->inside = 1;
2391                         return 0.f;
2392                 }
2393
2394                 /* Zero gradient (no movement relative to element). Can't step from
2395                  * here. */
2396                 if (d1 == d0) {
2397                         /* If first iteration, try from other end where the gradient may be
2398                          * greater. Note: code duplicated below. */
2399                         if (iter == 0) {
2400                                 t0 = 1.f;
2401                                 collision_interpolate_element(pce, t0, col->f, col);
2402                                 d0 = distance_func(col->co2, radius, pce, n);
2403                                 t1 = 1.0f - dt_init;
2404                                 d1 = 0.f;
2405                                 continue;
2406                         }
2407                         else
2408                                 return -1.f;
2409                 }
2410
2411                 dd = (t1-t0)/(d1-d0);
2412
2413                 t0 = t1;
2414                 d0 = d1;
2415
2416                 t1 -= d1*dd;
2417
2418                 /* Particle moving away from plane could also mean a strangely rotating
2419                  * face, so check from end. Note: code duplicated above. */
2420                 if (iter == 0 && t1 < 0.f) {
2421                         t0 = 1.f;
2422                         collision_interpolate_element(pce, t0, col->f, col);
2423                         d0 = distance_func(col->co2, radius, pce, n);
2424                         t1 = 1.0f - dt_init;
2425                         d1 = 0.f;
2426                         continue;
2427                 }
2428                 else if (iter == 1 && (t1 < -COLLISION_ZERO || t1 > 1.f))
2429                         return -1.f;
2430
2431                 if (d1 <= COLLISION_ZERO && d1 >= -COLLISION_ZERO) {
2432                         if (t1 >= -COLLISION_ZERO && t1 <= 1.f) {
2433                                 if (distance_func == nr_signed_distance_to_plane)
2434                                         copy_v3_v3(pce->nor, n);
2435
2436                                 CLAMP(t1, 0.f, 1.f);
2437
2438                                 return t1;
2439                         }
2440                         else
2441                                 return -1.f;
2442                 }
2443         }
2444         return -1.0;
2445 }
2446 static int collision_sphere_to_tri(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
2447 {
2448         ParticleCollisionElement *result = &col->pce;
2449         float ct, u, v;
2450
2451         pce->inv_nor = -1;
2452         pce->inside = 0;
2453
2454         ct = collision_newton_rhapson(col, radius, pce, nr_signed_distance_to_plane);
2455
2456         if (ct >= 0.f && ct < *t && (result->inside==0 || pce->inside==1) ) {
2457                 float e1[3], e2[3], p0[3];
2458                 float e1e1, e1e2, e1p0, e2e2, e2p0, inv;
2459
2460                 sub_v3_v3v3(e1, pce->x1, pce->x0);
2461                 sub_v3_v3v3(e2, pce->x2, pce->x0);
2462                 /* XXX: add radius correction here? */
2463                 sub_v3_v3v3(p0, pce->p, pce->x0);
2464
2465                 e1e1 = dot_v3v3(e1, e1);
2466                 e1e2 = dot_v3v3(e1, e2);
2467                 e1p0 = dot_v3v3(e1, p0);
2468                 e2e2 = dot_v3v3(e2, e2);
2469                 e2p0 = dot_v3v3(e2, p0);
2470
2471                 inv = 1.f/(e1e1 * e2e2 - e1e2 * e1e2);
2472                 u = (e2e2 * e1p0 - e1e2 * e2p0) * inv;
2473                 v = (e1e1 * e2p0 - e1e2 * e1p0) * inv;
2474
2475                 if (u>=0.f && u<=1.f && v>=0.f && u+v<=1.f) {
2476                         *result = *pce;
2477
2478                         /* normal already calculated in pce */
2479
2480                         result->uv[0] = u;
2481                         result->uv[1] = v;
2482
2483                         *t = ct;
2484                         return 1;
2485                 }
2486         }
2487         return 0;
2488 }
2489 static int collision_sphere_to_edges(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
2490 {
2491         ParticleCollisionElement edge[3], *cur = NULL, *hit = NULL;
2492         ParticleCollisionElement *result = &col->pce;
2493
2494         float ct;
2495         int i;
2496
2497         for (i=0; i<3; i++) {
2498                 cur = edge+i;
2499                 cur->x[0] = pce->x[i]; cur->x[1] = pce->x[(i+1)%3];
2500                 cur->v[0] = pce->v[i]; cur->v[1] = pce->v[(i+1)%3];
2501                 cur->tot = 2;
2502                 cur->inside = 0;
2503
2504                 ct = collision_newton_rhapson(col, radius, cur, nr_distance_to_edge);
2505
2506                 if (ct >= 0.f && ct < *t) {
2507                         float u, e[3], vec[3];
2508
2509                         sub_v3_v3v3(e, cur->x1, cur->x0);
2510                         sub_v3_v3v3(vec, cur->p, cur->x0);
2511                         u = dot_v3v3(vec, e) / dot_v3v3(e, e);
2512
2513                         if (u < 0.f || u > 1.f)
2514                                 break;
2515
2516                         *result = *cur;
2517
2518                         madd_v3_v3v3fl(result->nor, vec, e, -u);
2519                         normalize_v3(result->nor);
2520
2521                         result->uv[0] = u;
2522
2523
2524                         hit = cur;
2525                         *t = ct;
2526                 }
2527
2528         }
2529
2530         return hit != NULL;
2531 }
2532 static int collision_sphere_to_verts(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
2533 {
2534         ParticleCollisionElement vert[3], *cur = NULL, *hit = NULL;
2535         ParticleCollisionElement *result = &col->pce;
2536
2537         float ct;
2538         int i;
2539
2540         for (i=0; i<3; i++) {
2541                 cur = vert+i;
2542                 cur->x[0] = pce->x[i];
2543                 cur->v[0] = pce->v[i];
2544                 cur->tot = 1;
2545                 cur->inside = 0;
2546
2547                 ct = collision_newton_rhapson(col, radius, cur, nr_distance_to_vert);
2548
2549                 if (ct >= 0.f && ct < *t) {
2550                         *result = *cur;
2551
2552                         sub_v3_v3v3(result->nor, cur->p, cur->x0);
2553                         normalize_v3(result->nor);
2554
2555                         hit = cur;
2556                         *t = ct;
2557                 }
2558
2559         }
2560
2561         return hit != NULL;
2562 }
2563 /* Callback for BVHTree near test */
2564 void BKE_psys_collision_neartest_cb(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
2565 {
2566         ParticleCollision *col = (ParticleCollision *) userdata;
2567         ParticleCollisionElement pce;
2568         const MVertTri *vt = &col->md->tri[index];
2569         MVert *x = col->md->x;
2570         MVert *v = col->md->current_v;
2571         float t = hit->dist/col->original_ray_length;
2572         int collision = 0;
2573
2574         pce.x[0] = x[vt->tri[0]].co;
2575         pce.x[1] = x[vt->tri[1]].co;
2576         pce.x[2] = x[vt->tri[2]].co;
2577
2578         pce.v[0] = v[vt->tri[0]].co;
2579         pce.v[1] = v[vt->tri[1]].co;
2580         pce.v[2] = v[vt->tri[2]].co;
2581
2582         pce.tot = 3;
2583         pce.inside = 0;
2584         pce.index = index;
2585
2586         collision = collision_sphere_to_tri(col, ray->radius, &pce, &t);
2587         if (col->pce.inside == 0) {
2588                 collision += collision_sphere_to_edges(col, ray->radius, &pce, &t);
2589                 collision += collision_sphere_to_verts(col, ray->radius, &pce, &t);
2590         }
2591
2592         if (collision) {
2593                 hit->dist = col->original_ray_length * t;
2594                 hit->index = index;
2595
2596                 collision_point_velocity(&col->pce);
2597
2598                 col->hit = col->current;
2599         }
2600 }
2601 static int collision_detect(ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, ListBase *colliders)
2602 {
2603         const int raycast_flag = BVH_RAYCAST_DEFAULT & ~(BVH_RAYCAST_WATERTIGHT);
2604         ColliderCache *coll;
2605         float ray_dir[3];
2606
2607         if (BLI_listbase_is_empty(colliders))
2608                 return 0;
2609
2610         sub_v3_v3v3(ray_dir, col->co2, col->co1);
2611         hit->index = -1;
2612         hit->dist = col->original_ray_length = normalize_v3(ray_dir);
2613         col->pce.inside = 0;
2614
2615         /* even if particle is stationary we want to check for moving colliders */
2616         /* if hit.dist is zero the bvhtree_ray_cast will just ignore everything */
2617         if (hit->dist == 0.0f)
2618                 hit->dist = col->original_ray_length = 0.000001f;
2619
2620         for (coll = colliders->first; coll; coll=coll->next) {
2621                 /* for boids: don't check with current ground object; also skip if permeated */
2622                 bool skip = false;
2623
2624                 for (int i = 0; i < col->skip_count; i++) {
2625                         if (coll->ob == col->skip[i]) {
2626                                 skip = true;
2627                                 break;
2628                         }
2629                 }
2630
2631                 if (skip)
2632                         continue;
2633
2634                 /* particles should not collide with emitter at birth */
2635                 if (coll->ob == col->emitter && pa->time < col->cfra && pa->time >= col->old_cfra)
2636                         continue;
2637
2638                 col->current = coll->ob;
2639                 col->md = coll->collmd;
2640                 col->fac1 = (col->old_cfra - coll->collmd->time_x) / (coll->collmd->time_xnew - coll->collmd->time_x);
2641                 col->fac2 = (col->cfra - coll->collmd->time_x) / (coll->collmd->time_xnew - coll->collmd->time_x);
2642
2643                 if (col->md && col->md->bvhtree) {
2644                         BLI_bvhtree_ray_cast_ex(
2645                                 col->md->bvhtree, col->co1, ray_dir, col->radius, hit,
2646                                 BKE_psys_collision_neartest_cb, col, raycast_flag);
2647                 }
2648         }
2649
2650         return hit->index >= 0;
2651 }
2652 static int collision_response(ParticleSimulationData *sim, ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, int kill, int dynamic_rotation)
2653 {
2654         ParticleCollisionElement *pce = &col->pce;
2655         PartDeflect *pd = col->hit->pd;
2656         RNG *rng = sim->rng;
2657         /* point of collision */
2658         float co[3];
2659         /* location factor of collision between this iteration */
2660         float x = hit->dist/col->original_ray_length;
2661         /* time factor of collision between timestep */
2662         float f = col->f + x * (1.0f - col->f);
2663         /* time since previous collision (in seconds) */
2664         float dt1 = (f - col->f) * col->total_time;
2665         /* time left after collision (in seconds) */
2666         float dt2 = (1.0f - f) * col->total_time;
2667         /* did particle pass through the collision surface? */
2668         int through = (BLI_rng_get_float(rng) < pd->pdef_perm) ? 1 : 0;
2669
2670         /* calculate exact collision location */
2671         interp_v3_v3v3(co, col->co1, col->co2, x);
2672
2673         /* particle dies in collision */
2674         if (through == 0 && (kill || pd->flag & PDEFLE_KILL_PART)) {
2675                 pa->alive = PARS_DYING;
2676                 pa->dietime = col->old_cfra + (col->cfra - col->old_cfra) * f;
2677
2678                 copy_v3_v3(pa->state.co, co);
2679                 interp_v3_v3v3(pa->state.vel, pa->prev_state.vel, pa->state.vel, f);
2680                 interp_qt_qtqt(pa->state.rot, pa->prev_state.rot, pa->state.rot, f);
2681                 interp_v3_v3v3(pa->state.ave, pa->prev_state.ave, pa->state.ave, f);
2682
2683                 /* particle is dead so we don't need to calculate further */
2684                 return 0;
2685         }
2686         /* figure out velocity and other data after collision */
2687         else {
2688                 /* velocity directly before collision to be modified into velocity directly after collision */
2689                 float v0[3];
2690                 /* normal component of v0 */
2691                 float v0_nor[3];
2692                 /* tangential component of v0 */
2693                 float v0_tan[3];
2694                 /* tangential component of collision surface velocity */
2695                 float vc_tan[3];
2696                 float v0_dot, vc_dot;
2697                 float damp = pd->pdef_damp + pd->pdef_rdamp * 2 * (BLI_rng_get_float(rng) - 0.5f);
2698                 float frict = pd->pdef_frict + pd->pdef_rfrict * 2 * (BLI_rng_get_float(rng) - 0.5f);
2699                 float distance, nor[3], dot;
2700
2701                 CLAMP(damp,0.0f, 1.0f);
2702                 CLAMP(frict,0.0f, 1.0f);
2703
2704                 /* get exact velocity right before collision */
2705                 madd_v3_v3v3fl(v0, col->ve1, col->acc, dt1);
2706
2707                 /* convert collider velocity from 1/framestep to 1/s TODO: here we assume 1 frame step for collision modifier */
2708                 mul_v3_fl(pce->vel, col->inv_timestep);
2709
2710                 /* calculate tangential particle velocity */
2711                 v0_dot = dot_v3v3(pce->nor, v0);
2712                 madd_v3_v3v3fl(v0_tan, v0, pce->nor, -v0_dot);
2713
2714                 /* calculate tangential collider velocity */
2715                 vc_dot = dot_v3v3(pce->nor, pce->vel);
2716                 madd_v3_v3v3fl(vc_tan, pce->vel, pce->nor, -vc_dot);
2717
2718                 /* handle friction effects (tangential and angular velocity) */
2719                 if (frict > 0.0f) {
2720                         /* angular <-> linear velocity */
2721                         if (dynamic_rotation) {
2722                                 float vr_tan[3], v1_tan[3], ave[3];
2723
2724                                 /* linear velocity of particle surface */
2725                                 cross_v3_v3v3(vr_tan, pce->nor, pa->state.ave);
2726                                 mul_v3_fl(vr_tan, pa->size);
2727
2728                                 /* change to coordinates that move with the collision plane */
2729                                 sub_v3_v3v3(v1_tan, v0_tan, vc_tan);
2730
2731                                 /* The resulting velocity is a weighted average of particle cm & surface
2732                                  * velocity. This weight (related to particle's moment of inertia) could
2733                                  * be made a parameter for angular <-> linear conversion.
2734                                  */
2735                                 madd_v3_v3fl(v1_tan, vr_tan, -0.4);
2736                                 mul_v3_fl(v1_tan, 1.0f/1.4f); /* 1/(1+0.4) */
2737
2738                                 /* rolling friction is around 0.01 of sliding friction
2739                                  * (could be made a parameter) */
2740                                 mul_v3_fl(v1_tan, 1.0f - 0.01f * frict);
2741
2742                                 /* surface_velocity is opposite to cm velocity */
2743                                 negate_v3_v3(vr_tan, v1_tan);
2744
2745                                 /* get back to global coordinates */
2746                                 add_v3_v3(v1_tan, vc_tan);
2747
2748                                 /* convert to angular velocity*/
2749                                 cross_v3_v3v3(ave, vr_tan, pce->nor);
2750                                 mul_v3_fl(ave, 1.0f/MAX2(pa->size, 0.001f));
2751
2752                                 /* only friction will cause change in linear & angular velocity */
2753                                 interp_v3_v3v3(pa->state.ave, pa->state.ave, ave, frict);
2754                                 interp_v3_v3v3(v0_tan, v0_tan, v1_tan, frict);
2755                         }
2756                         else {
2757                                 /* just basic friction (unphysical due to the friction model used in Blender) */
2758                                 interp_v3_v3v3(v0_tan, v0_tan, vc_tan, frict);
2759                         }
2760                 }
2761
2762                 /* stickiness was possibly added before, so cancel that before calculating new normal velocity */
2763                 /* otherwise particles go flying out of the surface because of high reversed sticky velocity */
2764                 if (v0_dot < 0.0f) {
2765                         v0_dot += pd->pdef_stickness;
2766                         if (v0_dot > 0.0f)
2767                                 v0_dot = 0.0f;
2768                 }
2769
2770                 /* damping and flipping of velocity around normal */
2771                 v0_dot *= 1.0f - damp;
2772                 vc_dot *= through ? damp : 1.0f;
2773
2774                 /* calculate normal particle velocity */
2775                 /* special case for object hitting the particle from behind */
2776                 if (through==0 && ((vc_dot>0.0f && v0_dot>0.0f && vc_dot>v0_dot) || (vc_dot<0.0f && v0_dot<0.0f && vc_dot<v0_dot)))
2777                         mul_v3_v3fl(v0_nor, pce->nor, vc_dot);
2778                 else if (v0_dot > 0.f)
2779                         mul_v3_v3fl(v0_nor, pce->nor, vc_dot + v0_dot);
2780                 else
2781                         mul_v3_v3fl(v0_nor, pce->nor, vc_dot + (through ? 1.0f : -1.0f) * v0_dot);
2782
2783                 /* combine components together again */
2784                 add_v3_v3v3(v0, v0_nor, v0_tan);
2785
2786                 if (col->boid) {
2787                         /* keep boids above ground */
2788                         BoidParticle *bpa = pa->boid;
2789                         if (bpa->data.mode == eBoidMode_OnLand || co[2] <= col->boid_z) {
2790                                 co[2] = col->boid_z;
2791                                 v0[2] = 0.0f;
2792                         }
2793                 }
2794
2795                 /* re-apply acceleration to final location and velocity */
2796                 madd_v3_v3v3fl(pa->state.co, co, v0, dt2);
2797                 madd_v3_v3fl(pa->state.co, col->acc, 0.5f*dt2*dt2);
2798                 madd_v3_v3v3fl(pa->state.vel, v0, col->acc, dt2);
2799
2800                 /* make sure particle stays on the right side of the surface */
2801                 if (!through) {
2802                         distance = collision_point_distance_with_normal(co, pce, -1.f, col, nor);
2803
2804                         if (distance < col->radius + COLLISION_MIN_DISTANCE)
2805                                 madd_v3_v3fl(co, nor, col->radius + COLLISION_MIN_DISTANCE - distance);
2806
2807                         dot = dot_v3v3(nor, v0);
2808                         if (dot < 0.f)
2809                                 madd_v3_v3fl(v0, nor, -dot);
2810
2811                         distance = collision_point_distance_with_normal(pa->state.co, pce, 1.f, col, nor);
2812
2813                         if (distance < col->radius + COLLISION_MIN_DISTANCE)
2814                                 madd_v3_v3fl(pa->state.co, nor, col->radius + COLLISION_MIN_DISTANCE - distance);
2815
2816                         dot = dot_v3v3(nor, pa->state.vel);
2817                         if (dot < 0.f)
2818                                 madd_v3_v3fl(pa->state.vel, nor, -dot);
2819                 }
2820
2821                 /* add stickiness to surface */
2822                 madd_v3_v3fl(pa->state.vel, pce->nor, -pd->pdef_stickness);
2823
2824                 /* set coordinates for next iteration */
2825                 copy_v3_v3(col->co1, co);
2826                 copy_v3_v3(col->co2, pa->state.co);
2827
2828                 copy_v3_v3(col->ve1, v0);
2829                 copy_v3_v3(col->ve2, pa->state.vel);
2830
2831                 col->f = f;
2832         }
2833
2834         /* if permeability random roll succeeded, disable collider for this sim step */
2835         if (through) {
2836                 col->skip[col->skip_count++] = col->hit;
2837         }
2838
2839         return 1;
2840 }
2841 static void collision_fail(ParticleData *pa, ParticleCollision *col)
2842 {
2843         /* final chance to prevent total failure, so stick to the surface and hope for the best */
2844         collision_point_on_surface(col->co1, &col->pce, 1.f, col, pa->state.co);
2845
2846         copy_v3_v3(pa->state.vel, col->pce.vel);
2847         mul_v3_fl(pa->state.vel, col->inv_timestep);
2848
2849
2850         /* printf("max iterations\n"); */
2851 }
2852
2853 /* Particle - Mesh collision detection and response
2854  * Features:
2855  * -friction and damping
2856  * -angular momentum <-> linear momentum
2857  * -high accuracy by re-applying particle acceleration after collision
2858  * -handles moving, rotating and deforming meshes
2859  * -uses Newton-Rhapson iteration to find the collisions
2860  * -handles spherical particles and (nearly) point like particles
2861  */
2862 static void collision_check(ParticleSimulationData *sim, int p, float dfra, float cfra)
2863 {
2864         ParticleSettings *part = sim->psys->part;
2865         ParticleData *pa = sim->psys->particles + p;
2866         ParticleCollision col;
2867         BVHTreeRayHit hit;
2868         int collision_count=0;
2869
2870         float timestep = psys_get_timestep(sim);
2871
2872         memset(&col, 0, sizeof(ParticleCollision));
2873
2874         col.total_time = timestep * dfra;
2875         col.inv_total_time = 1.0f/col.total_time;
2876         col.inv_timestep = 1.0f/timestep;
2877
2878         col.cfra = cfra;
2879         col.old_cfra = sim->psys->cfra;
2880
2881         /* get acceleration (from gravity, forcefields etc. to be re-applied in collision response) */
2882         sub_v3_v3v3(col.acc, pa->state.vel, pa->prev_state.vel);
2883         mul_v3_fl(col.acc, 1.f/col.total_time);
2884
2885         /* set values for first iteration */
2886         copy_v3_v3(col.co1, pa->prev_state.co);
2887         copy_v3_v3(col.co2, pa->state.co);
2888         copy_v3_v3(col.ve1, pa->prev_state.vel);
2889         copy_v3_v3(col.ve2, pa->state.vel);
2890         col.f = 0.0f;
2891
2892         col.radius = ((part->flag & PART_SIZE_DEFL) || (part->phystype == PART_PHYS_BOIDS)) ? pa->size : COLLISION_MIN_RADIUS;
2893
2894         /* override for boids */
2895         if (part->phystype == PART_PHYS_BOIDS && part->boids->options & BOID_ALLOW_LAND) {
2896                 col.boid = 1;
2897                 col.boid_z = pa->state.co[2];
2898                 col.skip[col.skip_count++] = pa->boid->ground;
2899         }
2900
2901         /* 10 iterations to catch multiple collisions */
2902         while (collision_count < PARTICLE_COLLISION_MAX_COLLISIONS) {
2903                 if (collision_detect(pa, &col, &hit, sim->colliders)) {
2904
2905                         collision_count++;
2906
2907                         if (collision_count == PARTICLE_COLLISION_MAX_COLLISIONS)
2908                                 collision_fail(pa, &col);
2909                         else if (collision_response(sim, pa, &col, &hit, part->flag & PART_DIE_ON_COL, part->flag & PART_ROT_DYN)==0)
2910                                 return;
2911                 }
2912                 else
2913                         return;
2914         }
2915 }
2916 /************************************************/
2917 /*                      Hair                                                            */
2918 /************************************************/
2919 /* check if path cache or children need updating and do it if needed */
2920 static void psys_update_path_cache(ParticleSimulationData *sim, float cfra, const bool use_render_params)
2921 {
2922         ParticleSystem *psys = sim->psys;
2923         ParticleSettings *part = psys->part;
2924         ParticleEditSettings *pset = &sim->scene->toolsettings->particle;
2925         int distr=0, alloc=0, skip=0;
2926
2927         if ((psys->part->childtype && psys->totchild != psys_get_tot_child(sim->scene, psys, use_render_params)) || psys->recalc&ID_RECALC_PSYS_RESET)
2928                 alloc=1;
2929
2930         if (alloc || psys->recalc&ID_RECALC_PSYS_CHILD || (psys->vgroup[PSYS_VG_DENSITY] && (sim->ob && sim->ob->mode & OB_MODE_WEIGHT_PAINT)))
2931                 distr=1;
2932
2933         if (distr) {
2934                 if (alloc)
2935                         realloc_particles(sim, sim->psys->totpart);
2936
2937                 if (psys_get_tot_child(sim->scene, psys, use_render_params)) {
2938                         /* don't generate children while computing the hair keys */
2939                         if (!(psys->part->type == PART_HAIR) || (psys->flag & PSYS_HAIR_DONE)) {
2940                                 distribute_particles(sim, PART_FROM_CHILD);
2941
2942                                 if (part->childtype==PART_CHILD_FACES && part->parents != 0.0f)
2943                                         psys_find_parents(sim, use_render_params);
2944                         }
2945                 }
2946                 else
2947                         psys_free_children(psys);
2948         }
2949
2950         if ((part->type==PART_HAIR || psys->flag&PSYS_KEYED || psys->pointcache->flag & PTCACHE_BAKED)==0)
2951                 skip = 1; /* only hair, keyed and baked stuff can have paths */
2952         else if (part->ren_as != PART_DRAW_PATH && !(part->type==PART_HAIR && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR)))
2953                 skip = 1; /* particle visualization must be set as path */
2954         else if (DEG_get_mode(sim->depsgraph) != DAG_EVAL_RENDER) {
2955                 if (part->draw_as != PART_DRAW_REND)
2956                         skip = 1; /* draw visualization */
2957                 else if (psys->pointcache->flag & PTCACHE_BAKING)
2958                         skip = 1; /* no need to cache paths while baking dynamics */
2959
2960                 else if (psys_in_edit_mode(sim->depsgraph, psys)) {
2961                         if ((pset->flag & PE_DRAW_PART)==0)
2962                                 skip = 1;
2963                         else if (part->childtype==0 && (psys->flag & PSYS_HAIR_DYNAMICS && psys->pointcache->flag & PTCACHE_BAKED)==0)
2964                                 skip = 1; /* in edit mode paths are needed for child particles and dynamic hair */
2965                 }
2966         }
2967
2968         if (!skip) {
2969                 psys_cache_paths(sim, cfra, use_render_params);
2970
2971                 /* for render, child particle paths are computed on the fly */
2972                 if (part->childtype) {
2973                         if (!psys->totchild)
2974                                 skip = 1;
2975                         else if (psys->part->type == PART_HAIR && (psys->flag & PSYS_HAIR_DONE)==0)
2976                                 skip = 1;
2977
2978                         if (!skip)
2979                                 psys_cache_child_paths(sim, cfra, 0, use_render_params);
2980                 }
2981         }
2982         else if (psys->pathcache)
2983                 psys_free_path_cache(psys, NULL);
2984 }
2985
2986 static bool psys_hair_use_simulation(ParticleData *pa, float max_length)
2987 {
2988         /* Minimum segment length relative to average length.
2989          * Hairs with segments below this length will be excluded from the simulation,
2990          * because otherwise the solver will become unstable.
2991          * The hair system should always make sure the hair segments have reasonable length ratios,
2992          * but this can happen in old files when e.g. cutting hair.
2993          */
2994         const float min_length = 0.1f * max_length;
2995
2996         HairKey *key;
2997         int k;
2998
2999         if (pa->totkey < 2)
3000                 return false;
3001
3002         for (k=1, key=pa->hair+1; k<pa->totkey; k++,key++) {
3003                 float length = len_v3v3(key->co, (key-1)->co);
3004                 if (length < min_length)
3005                         return false;
3006         }
3007
3008         return true;
3009 }
3010
3011 static MDeformVert *hair_set_pinning(MDeformVert *dvert, float weight)
3012 {
3013         if (dvert) {
3014                 if (!dvert->totweight) {
3015                         dvert->dw = MEM_callocN(sizeof(MDeformWeight), "deformWeight");
3016                         dvert->totweight = 1;
3017                 }
3018
3019                 dvert->dw->weight = weight;
3020                 dvert++;
3021         }
3022         return dvert;
3023 }
3024
3025 static void hair_create_input_mesh(ParticleSimulationData *sim, int totpoint, int totedge, Mesh **r_mesh, ClothHairData **r_hairdata)
3026 {
3027         ParticleSystem *psys = sim->psys;
3028         ParticleSettings *part = psys->part;
3029         Mesh *mesh;
3030         ClothHairData *hairdata;
3031         MVert *mvert;
3032         MEdge *medge;
3033         MDeformVert *dvert;
3034         HairKey *key;
3035         PARTICLE_P;
3036         int k, hair_index;
3037         float hairmat[4][4];
3038         float max_length;
3039         float hair_radius;
3040
3041         mesh = *r_mesh;
3042         if (!mesh) {
3043                 *r_mesh = mesh = BKE_mesh_new_nomain(totpoint, totedge, 0, 0, 0);
3044                 CustomData_add_layer(&mesh->vdata, CD_MDEFORMVERT, CD_CALLOC, NULL, mesh->totvert);
3045                 BKE_mesh_update_customdata_pointers(mesh, false);
3046         }
3047         mvert = mesh->mvert;
3048         medge = mesh->medge;
3049         dvert = mesh->dvert;