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