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