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