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