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