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