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