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