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