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