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