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