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