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