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