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