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