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