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