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