Patch #34204: [Render Animation] Fails with "Error: Specified sample_fmt is not suppo...
[blender.git] / source / blender / blenkernel / intern / particle_system.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2007 by Janne Karhu.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Raul Fernandez Hernandez (Farsthary), Stephen Swhitehorn.
24  *
25  * Adaptive time step
26  * Classical SPH
27  * Copyright 2011-2012 AutoCRC
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 /** \file blender/blenkernel/intern/particle_system.c
33  *  \ingroup bke
34  */
35
36
37 #include <stddef.h>
38
39 #include <stdlib.h>
40 #include <math.h>
41 #include <string.h>
42
43 #ifdef _OPENMP
44 #include <omp.h>
45 #endif
46
47 #include "MEM_guardedalloc.h"
48
49 #include "DNA_anim_types.h"
50 #include "DNA_boid_types.h"
51 #include "DNA_particle_types.h"
52 #include "DNA_mesh_types.h"
53 #include "DNA_meshdata_types.h"
54 #include "DNA_modifier_types.h"
55 #include "DNA_object_force.h"
56 #include "DNA_object_types.h"
57 #include "DNA_material_types.h"
58 #include "DNA_curve_types.h"
59 #include "DNA_group_types.h"
60 #include "DNA_scene_types.h"
61 #include "DNA_texture_types.h"
62 #include "DNA_ipo_types.h" // XXX old animation system stuff... to be removed!
63 #include "DNA_listBase.h"
64
65 #include "BLI_edgehash.h"
66 #include "BLI_rand.h"
67 #include "BLI_jitter.h"
68 #include "BLI_math.h"
69 #include "BLI_blenlib.h"
70 #include "BLI_kdtree.h"
71 #include "BLI_kdopbvh.h"
72 #include "BLI_threads.h"
73 #include "BLI_utildefines.h"
74 #include "BLI_linklist.h"
75
76 #include "BKE_main.h"
77 #include "BKE_animsys.h"
78 #include "BKE_boids.h"
79 #include "BKE_cdderivedmesh.h"
80 #include "BKE_collision.h"
81 #include "BKE_displist.h"
82 #include "BKE_effect.h"
83 #include "BKE_particle.h"
84 #include "BKE_global.h"
85
86 #include "BKE_DerivedMesh.h"
87 #include "BKE_object.h"
88 #include "BKE_material.h"
89 #include "BKE_cloth.h"
90 #include "BKE_depsgraph.h"
91 #include "BKE_lattice.h"
92 #include "BKE_pointcache.h"
93 #include "BKE_mesh.h"
94 #include "BKE_modifier.h"
95 #include "BKE_scene.h"
96 #include "BKE_bvhutils.h"
97
98 #include "PIL_time.h"
99
100 #include "RE_shader_ext.h"
101
102 /* fluid sim particle import */
103 #ifdef WITH_MOD_FLUID
104 #include "DNA_object_fluidsim.h"
105 #include "LBM_fluidsim.h"
106 #include <zlib.h>
107 #include <string.h>
108
109 #endif // WITH_MOD_FLUID
110
111 /************************************************/
112 /*                      Reacting to system events                       */
113 /************************************************/
114
115 static int particles_are_dynamic(ParticleSystem *psys)
116 {
117         if (psys->pointcache->flag & PTCACHE_BAKED)
118                 return 0;
119
120         if (psys->part->type == PART_HAIR)
121                 return psys->flag & PSYS_HAIR_DYNAMICS;
122         else
123                 return ELEM3(psys->part->phystype, PART_PHYS_NEWTON, PART_PHYS_BOIDS, PART_PHYS_FLUID);
124 }
125
126 static int psys_get_current_display_percentage(ParticleSystem *psys)
127 {
128         ParticleSettings *part=psys->part;
129
130         if ((psys->renderdata && !particles_are_dynamic(psys)) ||  /* non-dynamic particles can be rendered fully */
131             (part->child_nbr && part->childtype)  ||    /* display percentage applies to children */
132             (psys->pointcache->flag & PTCACHE_BAKING))  /* baking is always done with full amount */
133         {
134                 return 100;
135         }
136
137         return psys->part->disp;
138 }
139
140 static int tot_particles(ParticleSystem *psys, PTCacheID *pid)
141 {
142         if (pid && psys->pointcache->flag & PTCACHE_EXTERNAL)
143                 return pid->cache->totpoint;
144         else if (psys->part->distr == PART_DISTR_GRID && psys->part->from != PART_FROM_VERT)
145                 return psys->part->grid_res * psys->part->grid_res * psys->part->grid_res - psys->totunexist;
146         else
147                 return psys->part->totpart - psys->totunexist;
148 }
149
150 void psys_reset(ParticleSystem *psys, int mode)
151 {
152         PARTICLE_P;
153
154         if (ELEM(mode, PSYS_RESET_ALL, PSYS_RESET_DEPSGRAPH)) {
155                 if (mode == PSYS_RESET_ALL || !(psys->flag & PSYS_EDITED)) {
156                         /* don't free if not absolutely necessary */
157                         if (psys->totpart != tot_particles(psys, NULL)) {
158                                 psys_free_particles(psys);
159                                 psys->totpart= 0;
160                         }
161
162                         psys->totkeyed= 0;
163                         psys->flag &= ~(PSYS_HAIR_DONE|PSYS_KEYED);
164
165                         if (psys->edit && psys->free_edit) {
166                                 psys->free_edit(psys->edit);
167                                 psys->edit = NULL;
168                                 psys->free_edit = NULL;
169                         }
170                 }
171         }
172         else if (mode == PSYS_RESET_CACHE_MISS) {
173                 /* set all particles to be skipped */
174                 LOOP_PARTICLES
175                         pa->flag |= PARS_NO_DISP;
176         }
177
178         /* reset children */
179         if (psys->child) {
180                 MEM_freeN(psys->child);
181                 psys->child= NULL;
182         }
183
184         psys->totchild= 0;
185
186         /* reset path cache */
187         psys_free_path_cache(psys, psys->edit);
188
189         /* reset point cache */
190         BKE_ptcache_invalidate(psys->pointcache);
191
192         if (psys->fluid_springs) {
193                 MEM_freeN(psys->fluid_springs);
194                 psys->fluid_springs = NULL;
195         }
196
197         psys->tot_fluidsprings = psys->alloc_fluidsprings = 0;
198 }
199
200 static void realloc_particles(ParticleSimulationData *sim, int new_totpart)
201 {
202         ParticleSystem *psys = sim->psys;
203         ParticleSettings *part = psys->part;
204         ParticleData *newpars = NULL;
205         BoidParticle *newboids = NULL;
206         PARTICLE_P;
207         int totpart, totsaved = 0;
208
209         if (new_totpart<0) {
210                 if ((part->distr == PART_DISTR_GRID) && (part->from != PART_FROM_VERT)) {
211                         totpart= part->grid_res;
212                         totpart*=totpart*totpart;
213                 }
214                 else
215                         totpart=part->totpart;
216         }
217         else
218                 totpart=new_totpart;
219
220         if (totpart != psys->totpart) {
221                 if (psys->edit && psys->free_edit) {
222                         psys->free_edit(psys->edit);
223                         psys->edit = NULL;
224                         psys->free_edit = NULL;
225                 }
226
227                 if (totpart) {
228                         newpars= MEM_callocN(totpart*sizeof(ParticleData), "particles");
229                         if (newpars == NULL)
230                                 return;
231
232                         if (psys->part->phystype == PART_PHYS_BOIDS) {
233                                 newboids= MEM_callocN(totpart*sizeof(BoidParticle), "boid particles");
234
235                                 if (newboids == NULL) {
236                                          /* allocation error! */
237                                         if (newpars)
238                                                 MEM_freeN(newpars);
239                                         return;
240                                 }
241                         }
242                 }
243         
244                 if (psys->particles) {
245                         totsaved=MIN2(psys->totpart,totpart);
246                         /*save old pars*/
247                         if (totsaved) {
248                                 memcpy(newpars,psys->particles,totsaved*sizeof(ParticleData));
249
250                                 if (psys->particles->boid)
251                                         memcpy(newboids, psys->particles->boid, totsaved*sizeof(BoidParticle));
252                         }
253
254                         if (psys->particles->keys)
255                                 MEM_freeN(psys->particles->keys);
256
257                         if (psys->particles->boid)
258                                 MEM_freeN(psys->particles->boid);
259
260                         for (p=0, pa=newpars; p<totsaved; p++, pa++) {
261                                 if (pa->keys) {
262                                         pa->keys= NULL;
263                                         pa->totkey= 0;
264                                 }
265                         }
266
267                         for (p=totsaved, pa=psys->particles+totsaved; p<psys->totpart; p++, pa++)
268                                 if (pa->hair) MEM_freeN(pa->hair);
269
270                         MEM_freeN(psys->particles);
271                         psys_free_pdd(psys);
272                 }
273                 
274                 psys->particles=newpars;
275                 psys->totpart=totpart;
276
277                 if (newboids) {
278                         LOOP_PARTICLES
279                                 pa->boid = newboids++;
280                 }
281         }
282
283         if (psys->child) {
284                 MEM_freeN(psys->child);
285                 psys->child=NULL;
286                 psys->totchild=0;
287         }
288 }
289
290 static int get_psys_child_number(struct Scene *scene, ParticleSystem *psys)
291 {
292         int nbr;
293
294         if (!psys->part->childtype)
295                 return 0;
296
297         if (psys->renderdata)
298                 nbr= psys->part->ren_child_nbr;
299         else
300                 nbr= psys->part->child_nbr;
301
302         return get_render_child_particle_number(&scene->r, nbr);
303 }
304
305 static int get_psys_tot_child(struct Scene *scene, ParticleSystem *psys)
306 {
307         return psys->totpart*get_psys_child_number(scene, psys);
308 }
309
310 static void alloc_child_particles(ParticleSystem *psys, int tot)
311 {
312         if (psys->child) {
313                 /* only re-allocate if we have to */
314                 if (psys->part->childtype && psys->totchild == tot) {
315                         memset(psys->child, 0, tot*sizeof(ChildParticle));
316                         return;
317                 }
318
319                 MEM_freeN(psys->child);
320                 psys->child=NULL;
321                 psys->totchild=0;
322         }
323
324         if (psys->part->childtype) {
325                 psys->totchild= tot;
326                 if (psys->totchild)
327                         psys->child= MEM_callocN(psys->totchild*sizeof(ChildParticle), "child_particles");
328         }
329 }
330
331 /************************************************/
332 /*                      Distribution                                            */
333 /************************************************/
334
335 void psys_calc_dmcache(Object *ob, DerivedMesh *dm, ParticleSystem *psys)
336 {
337         /* use for building derived mesh mapping info:
338          *
339          * node: the allocated links - total derived mesh element count 
340          * nodearray: the array of nodes aligned with the base mesh's elements, so
341          *            each original elements can reference its derived elements
342          */
343         Mesh *me= (Mesh*)ob->data;
344         PARTICLE_P;
345         
346         /* CACHE LOCATIONS */
347         if (!dm->deformedOnly) {
348                 /* Will use later to speed up subsurf/derivedmesh */
349                 LinkNode *node, *nodedmelem, **nodearray;
350                 int totdmelem, totelem, i, *origindex, *origindex_poly = NULL;
351
352                 if (psys->part->from == PART_FROM_VERT) {
353                         totdmelem= dm->getNumVerts(dm);
354                         totelem= me->totvert;
355                         origindex= dm->getVertDataArray(dm, CD_ORIGINDEX);
356                 }
357                 else { /* FROM_FACE/FROM_VOLUME */
358                         totdmelem= dm->getNumTessFaces(dm);
359                         totelem= me->totpoly;
360                         origindex = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
361                         /* for face lookups we need the poly origindex too */
362                         origindex_poly = dm->getPolyDataArray(dm, CD_ORIGINDEX);
363                         if (origindex_poly == NULL) {
364                                 origindex = NULL;
365                         }
366                 }
367         
368                 nodedmelem= MEM_callocN(sizeof(LinkNode)*totdmelem, "psys node elems");
369                 nodearray= MEM_callocN(sizeof(LinkNode *)*totelem, "psys node array");
370                 
371                 for (i=0, node=nodedmelem; i<totdmelem; i++, node++) {
372                         int origindex_final;
373                         node->link = SET_INT_IN_POINTER(i);
374
375                         /* may be vertex or face origindex */
376                         origindex_final = origindex ? origindex[i] : ORIGINDEX_NONE;
377
378                         /* if we have a poly source, do an index lookup */
379                         if (origindex_poly && origindex_final != ORIGINDEX_NONE) {
380                                 origindex_final = origindex_poly[origindex_final];
381                         }
382
383                         if (origindex_final != ORIGINDEX_NONE) {
384                                 if (nodearray[origindex_final]) {
385                                         /* prepend */
386                                         node->next = nodearray[origindex_final];
387                                         nodearray[origindex_final] = node;
388                                 }
389                                 else {
390                                         nodearray[origindex_final] = node;
391                                 }
392                         }
393                 }
394                 
395                 /* cache the verts/faces! */
396                 LOOP_PARTICLES {
397                         if (pa->num < 0) {
398                                 pa->num_dmcache = -1;
399                                 continue;
400                         }
401
402                         if (psys->part->from == PART_FROM_VERT) {
403                                 if (nodearray[pa->num])
404                                         pa->num_dmcache= GET_INT_FROM_POINTER(nodearray[pa->num]->link);
405                         }
406                         else { /* FROM_FACE/FROM_VOLUME */
407                                 /* Note that sometimes the pa->num is over the nodearray size, this is bad, maybe there is a better place to fix this,
408                                  * but for now passing NULL is OK. every face will be searched for the particle so its slower - Campbell */
409                                 pa->num_dmcache= psys_particle_dm_face_lookup(ob, dm, pa->num, pa->fuv, pa->num < totelem ? nodearray[pa->num] : NULL);
410                         }
411                 }
412
413                 MEM_freeN(nodearray);
414                 MEM_freeN(nodedmelem);
415         }
416         else {
417                 /* TODO PARTICLE, make the following line unnecessary, each function
418                  * should know to use the num or num_dmcache, set the num_dmcache to
419                  * an invalid value, just in case */
420                 
421                 LOOP_PARTICLES
422                         pa->num_dmcache = -1;
423         }
424 }
425
426 static void distribute_simple_children(Scene *scene, Object *ob, DerivedMesh *finaldm, ParticleSystem *psys)
427 {
428         ChildParticle *cpa = NULL;
429         int i, p;
430         int child_nbr= get_psys_child_number(scene, psys);
431         int totpart= get_psys_tot_child(scene, psys);
432
433         alloc_child_particles(psys, totpart);
434
435         cpa = psys->child;
436         for (i=0; i<child_nbr; i++) {
437                 for (p=0; p<psys->totpart; p++,cpa++) {
438                         float length=2.0;
439                         cpa->parent=p;
440                                         
441                         /* create even spherical distribution inside unit sphere */
442                         while (length>=1.0f) {
443                                 cpa->fuv[0]=2.0f*BLI_frand()-1.0f;
444                                 cpa->fuv[1]=2.0f*BLI_frand()-1.0f;
445                                 cpa->fuv[2]=2.0f*BLI_frand()-1.0f;
446                                 length=len_v3(cpa->fuv);
447                         }
448
449                         cpa->num=-1;
450                 }
451         }
452         /* dmcache must be updated for parent particles if children from faces is used */
453         psys_calc_dmcache(ob, finaldm, psys);
454 }
455 static void distribute_grid(DerivedMesh *dm, ParticleSystem *psys)
456 {
457         ParticleData *pa=NULL;
458         float min[3], max[3], delta[3], d;
459         MVert *mv, *mvert = dm->getVertDataArray(dm,0);
460         int totvert=dm->getNumVerts(dm), from=psys->part->from;
461         int i, j, k, p, res=psys->part->grid_res, size[3], axis;
462
463         mv=mvert;
464
465         /* find bounding box of dm */
466         copy_v3_v3(min, mv->co);
467         copy_v3_v3(max, mv->co);
468         mv++;
469
470         for (i=1; i<totvert; i++, mv++) {
471                 minmax_v3v3_v3(min, max, mv->co);
472         }
473
474         sub_v3_v3v3(delta, max, min);
475
476         /* determine major axis */
477         axis = (delta[0]>=delta[1]) ? 0 : ((delta[1]>=delta[2]) ? 1 : 2);
478          
479         d = delta[axis]/(float)res;
480
481         size[axis] = res;
482         size[(axis+1)%3] = (int)ceil(delta[(axis+1)%3]/d);
483         size[(axis+2)%3] = (int)ceil(delta[(axis+2)%3]/d);
484
485         /* float errors grrr.. */
486         size[(axis+1)%3] = MIN2(size[(axis+1)%3],res);
487         size[(axis+2)%3] = MIN2(size[(axis+2)%3],res);
488
489         size[0] = MAX2(size[0], 1);
490         size[1] = MAX2(size[1], 1);
491         size[2] = MAX2(size[2], 1);
492
493         /* no full offset for flat/thin objects */
494         min[0]+= d < delta[0] ? d/2.f : delta[0]/2.f;
495         min[1]+= d < delta[1] ? d/2.f : delta[1]/2.f;
496         min[2]+= d < delta[2] ? d/2.f : delta[2]/2.f;
497
498         for (i=0,p=0,pa=psys->particles; i<res; i++) {
499                 for (j=0; j<res; j++) {
500                         for (k=0; k<res; k++,p++,pa++) {
501                                 pa->fuv[0] = min[0] + (float)i*d;
502                                 pa->fuv[1] = min[1] + (float)j*d;
503                                 pa->fuv[2] = min[2] + (float)k*d;
504                                 pa->flag |= PARS_UNEXIST;
505                                 pa->hair_index = 0; /* abused in volume calculation */
506                         }
507                 }
508         }
509
510         /* enable particles near verts/edges/faces/inside surface */
511         if (from==PART_FROM_VERT) {
512                 float vec[3];
513
514                 pa=psys->particles;
515
516                 min[0] -= d/2.0f;
517                 min[1] -= d/2.0f;
518                 min[2] -= d/2.0f;
519
520                 for (i=0,mv=mvert; i<totvert; i++,mv++) {
521                         sub_v3_v3v3(vec,mv->co,min);
522                         vec[0]/=delta[0];
523                         vec[1]/=delta[1];
524                         vec[2]/=delta[2];
525                         pa[((int)(vec[0] * (size[0] - 1))  * res +
526                             (int)(vec[1] * (size[1] - 1))) * res +
527                             (int)(vec[2] * (size[2] - 1))].flag &= ~PARS_UNEXIST;
528                 }
529         }
530         else if (ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)) {
531                 float co1[3], co2[3];
532
533                 MFace *mface= NULL, *mface_array;
534                 float v1[3], v2[3], v3[3], v4[4], lambda;
535                 int a, a1, a2, a0mul, a1mul, a2mul, totface;
536                 int amax= from==PART_FROM_FACE ? 3 : 1;
537
538                 totface=dm->getNumTessFaces(dm);
539                 mface=mface_array=dm->getTessFaceDataArray(dm,CD_MFACE);
540                 
541                 for (a=0; a<amax; a++) {
542                         if (a==0) { a0mul=res*res; a1mul=res; a2mul=1; }
543                         else if (a==1) { a0mul=res; a1mul=1; a2mul=res*res; }
544                         else { a0mul=1; a1mul=res*res; a2mul=res; }
545
546                         for (a1=0; a1<size[(a+1)%3]; a1++) {
547                                 for (a2=0; a2<size[(a+2)%3]; a2++) {
548                                         mface= mface_array;
549
550                                         pa = psys->particles + a1*a1mul + a2*a2mul;
551                                         copy_v3_v3(co1, pa->fuv);
552                                         co1[a] -= d < delta[a] ? d/2.f : delta[a]/2.f;
553                                         copy_v3_v3(co2, co1);
554                                         co2[a] += delta[a] + 0.001f*d;
555                                         co1[a] -= 0.001f*d;
556                                         
557                                         /* lets intersect the faces */
558                                         for (i=0; i<totface; i++,mface++) {
559                                                 copy_v3_v3(v1, mvert[mface->v1].co);
560                                                 copy_v3_v3(v2, mvert[mface->v2].co);
561                                                 copy_v3_v3(v3, mvert[mface->v3].co);
562
563                                                 if (isect_axial_line_tri_v3(a, co1, co2, v2, v3, v1, &lambda)) {
564                                                         if (from==PART_FROM_FACE)
565                                                                 (pa+(int)(lambda*size[a])*a0mul)->flag &= ~PARS_UNEXIST;
566                                                         else /* store number of intersections */
567                                                                 (pa+(int)(lambda*size[a])*a0mul)->hair_index++;
568                                                 }
569                                                 else if (mface->v4) {
570                                                         copy_v3_v3(v4, mvert[mface->v4].co);
571
572                                                         if (isect_axial_line_tri_v3(a, co1, co2, v4, v1, v3, &lambda)) {
573                                                                 if (from==PART_FROM_FACE)
574                                                                         (pa+(int)(lambda*size[a])*a0mul)->flag &= ~PARS_UNEXIST;
575                                                                 else
576                                                                         (pa+(int)(lambda*size[a])*a0mul)->hair_index++;
577                                                         }
578                                                 }
579                                         }
580
581                                         if (from==PART_FROM_VOLUME) {
582                                                 int in=pa->hair_index%2;
583                                                 if (in) pa->hair_index++;
584                                                 for (i=0; i<size[0]; i++) {
585                                                         if (in || (pa+i*a0mul)->hair_index%2)
586                                                                 (pa+i*a0mul)->flag &= ~PARS_UNEXIST;
587                                                         /* odd intersections == in->out / out->in */
588                                                         /* even intersections -> in stays same */
589                                                         in=(in + (pa+i*a0mul)->hair_index) % 2;
590                                                 }
591                                         }
592                                 }
593                         }
594                 }
595         }
596
597         if (psys->part->flag & PART_GRID_HEXAGONAL) {
598                 for (i=0,p=0,pa=psys->particles; i<res; i++) {
599                         for (j=0; j<res; j++) {
600                                 for (k=0; k<res; k++,p++,pa++) {
601                                         if (j%2)
602                                                 pa->fuv[0] += d/2.f;
603
604                                         if (k%2) {
605                                                 pa->fuv[0] += d/2.f;
606                                                 pa->fuv[1] += d/2.f;
607                                         }
608                                 }
609                         }
610                 }
611         }
612
613         if (psys->part->flag & PART_GRID_INVERT) {
614                 for (i=0; i<size[0]; i++) {
615                         for (j=0; j<size[1]; j++) {
616                                 pa=psys->particles + res*(i*res + j);
617                                 for (k=0; k<size[2]; k++, pa++) {
618                                         pa->flag ^= PARS_UNEXIST;
619                                 }
620                         }
621                 }
622         }
623
624         if (psys->part->grid_rand > 0.f) {
625                 float rfac = d * psys->part->grid_rand;
626                 for (p=0,pa=psys->particles; p<psys->totpart; p++,pa++) {
627                         if (pa->flag & PARS_UNEXIST)
628                                 continue;
629
630                         pa->fuv[0] += rfac * (PSYS_FRAND(p + 31) - 0.5f);
631                         pa->fuv[1] += rfac * (PSYS_FRAND(p + 32) - 0.5f);
632                         pa->fuv[2] += rfac * (PSYS_FRAND(p + 33) - 0.5f);
633                 }
634         }
635 }
636
637 /* modified copy from rayshade.c */
638 static void hammersley_create(float *out, int n, int seed, float amount)
639 {
640         RNG *rng;
641         double p, t, offs[2];
642         int k, kk;
643
644         rng = BLI_rng_new(31415926 + n + seed);
645         offs[0] = BLI_rng_get_double(rng) + (double)amount;
646         offs[1] = BLI_rng_get_double(rng) + (double)amount;
647         BLI_rng_free(rng);
648
649         for (k = 0; k < n; k++) {
650                 t = 0;
651                 for (p = 0.5, kk = k; kk; p *= 0.5, kk >>= 1)
652                         if (kk & 1) /* kk mod 2 = 1 */
653                                 t += p;
654
655                 out[2*k + 0] = fmod((double)k/(double)n + offs[0], 1.0);
656                 out[2*k + 1] = fmod(t + offs[1], 1.0);
657         }
658 }
659
660 /* modified copy from effect.c */
661 static void init_mv_jit(float *jit, int num, int seed2, float amount)
662 {
663         RNG *rng;
664         float *jit2, x, rad1, rad2, rad3;
665         int i, num2;
666
667         if (num==0) return;
668
669         rad1= (float)(1.0f/sqrtf((float)num));
670         rad2= (float)(1.0f/((float)num));
671         rad3= (float)sqrt((float)num)/((float)num);
672
673         rng = BLI_rng_new(31415926 + num + seed2);
674         x= 0;
675                 num2 = 2 * num;
676         for (i=0; i<num2; i+=2) {
677         
678                 jit[i] = x + amount*rad1*(0.5f - BLI_rng_get_float(rng));
679                 jit[i+1] = i/(2.0f*num) + amount*rad1*(0.5f - BLI_rng_get_float(rng));
680                 
681                 jit[i]-= (float)floor(jit[i]);
682                 jit[i+1]-= (float)floor(jit[i+1]);
683                 
684                 x+= rad3;
685                 x -= (float)floor(x);
686         }
687
688         jit2= MEM_mallocN(12 + 2*sizeof(float)*num, "initjit");
689
690         for (i=0 ; i<4 ; i++) {
691                 BLI_jitterate1(jit, jit2, num, rad1);
692                 BLI_jitterate1(jit, jit2, num, rad1);
693                 BLI_jitterate2(jit, jit2, num, rad2);
694         }
695         MEM_freeN(jit2);
696         BLI_rng_free(rng);
697 }
698
699 static void psys_uv_to_w(float u, float v, int quad, float *w)
700 {
701         float vert[4][3], co[3];
702
703         if (!quad) {
704                 if (u+v > 1.0f)
705                         v= 1.0f-v;
706                 else
707                         u= 1.0f-u;
708         }
709
710         vert[0][0] = 0.0f; vert[0][1] = 0.0f; vert[0][2] = 0.0f;
711         vert[1][0] = 1.0f; vert[1][1] = 0.0f; vert[1][2] = 0.0f;
712         vert[2][0] = 1.0f; vert[2][1] = 1.0f; vert[2][2] = 0.0f;
713
714         co[0] = u;
715         co[1] = v;
716         co[2] = 0.0f;
717
718         if (quad) {
719                 vert[3][0] = 0.0f; vert[3][1] = 1.0f; vert[3][2] = 0.0f;
720                 interp_weights_poly_v3( w,vert, 4, co);
721         }
722         else {
723                 interp_weights_poly_v3( w,vert, 3, co);
724                 w[3] = 0.0f;
725         }
726 }
727
728 /* Find the index in "sum" array before "value" is crossed. */
729 static int distribute_binary_search(float *sum, int n, float value)
730 {
731         int mid, low=0, high=n;
732
733         if (value == 0.f)
734                 return 0;
735
736         while (low <= high) {
737                 mid= (low + high)/2;
738                 
739                 if (sum[mid] < value && value <= sum[mid+1])
740                         return mid;
741                 
742                 if (sum[mid] >= value)
743                         high= mid - 1;
744                 else if (sum[mid] < value)
745                         low= mid + 1;
746                 else
747                         return mid;
748         }
749
750         return low;
751 }
752
753 /* the max number if calls to rng_* funcs within psys_thread_distribute_particle
754  * be sure to keep up to date if this changes */
755 #define PSYS_RND_DIST_SKIP 2
756
757 /* note: this function must be thread safe, for from == PART_FROM_CHILD */
758 #define ONLY_WORKING_WITH_PA_VERTS 0
759 static void distribute_threads_exec(ParticleThread *thread, ParticleData *pa, ChildParticle *cpa, int p)
760 {
761         ParticleThreadContext *ctx= thread->ctx;
762         Object *ob= ctx->sim.ob;
763         DerivedMesh *dm= ctx->dm;
764         float *v1, *v2, *v3, *v4, nor[3], orco1[3], co1[3], co2[3], nor1[3];
765         float cur_d, min_d, randu, randv;
766         int from= ctx->from;
767         int cfrom= ctx->cfrom;
768         int distr= ctx->distr;
769         int i, intersect, tot;
770         int rng_skip_tot= PSYS_RND_DIST_SKIP; /* count how many rng_* calls wont need skipping */
771
772         if (from == PART_FROM_VERT) {
773                 /* TODO_PARTICLE - use original index */
774                 pa->num= ctx->index[p];
775                 pa->fuv[0] = 1.0f;
776                 pa->fuv[1] = pa->fuv[2] = pa->fuv[3] = 0.0;
777
778 #if ONLY_WORKING_WITH_PA_VERTS
779                 if (ctx->tree) {
780                         KDTreeNearest ptn[3];
781                         int w, maxw;
782
783                         psys_particle_on_dm(ctx->dm,from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co1,0,0,0,orco1,0);
784                         BKE_mesh_orco_verts_transform((Mesh*)ob->data, &orco1, 1, 1);
785                         maxw = BLI_kdtree_find_n_nearest(ctx->tree,3,orco1,NULL,ptn);
786
787                         for (w=0; w<maxw; w++) {
788                                 pa->verts[w]=ptn->num;
789                         }
790                 }
791 #endif
792         }
793         else if (from == PART_FROM_FACE || from == PART_FROM_VOLUME) {
794                 MFace *mface;
795
796                 pa->num = i = ctx->index[p];
797                 mface = dm->getTessFaceData(dm,i,CD_MFACE);
798                 
799                 switch (distr) {
800                 case PART_DISTR_JIT:
801                         if (ctx->jitlevel == 1) {
802                                 if (mface->v4)
803                                         psys_uv_to_w(0.5f, 0.5f, mface->v4, pa->fuv);
804                                 else
805                                         psys_uv_to_w(1.0f / 3.0f, 1.0f / 3.0f, mface->v4, pa->fuv);
806                         }
807                         else {
808                                 ctx->jitoff[i] = fmod(ctx->jitoff[i],(float)ctx->jitlevel);
809                                 if (!isnan(ctx->jitoff[i])) {
810                                         psys_uv_to_w(ctx->jit[2*(int)ctx->jitoff[i]], ctx->jit[2*(int)ctx->jitoff[i]+1], mface->v4, pa->fuv);
811                                         ctx->jitoff[i]++;
812                                 }
813                         }
814                         break;
815                 case PART_DISTR_RAND:
816                         randu= BLI_rng_get_float(thread->rng);
817                         randv= BLI_rng_get_float(thread->rng);
818                         rng_skip_tot -= 2;
819
820                         psys_uv_to_w(randu, randv, mface->v4, pa->fuv);
821                         break;
822                 }
823                 pa->foffset= 0.0f;
824                 
825                 /* experimental */
826                 if (from==PART_FROM_VOLUME) {
827                         MVert *mvert=dm->getVertDataArray(dm,CD_MVERT);
828
829                         tot=dm->getNumTessFaces(dm);
830
831                         psys_interpolate_face(mvert,mface,0,0,pa->fuv,co1,nor,0,0,0,0);
832
833                         normalize_v3(nor);
834                         mul_v3_fl(nor,-100.0);
835
836                         add_v3_v3v3(co2,co1,nor);
837
838                         min_d=2.0;
839                         intersect=0;
840
841                         for (i=0,mface=dm->getTessFaceDataArray(dm,CD_MFACE); i<tot; i++,mface++) {
842                                 if (i==pa->num) continue;
843
844                                 v1=mvert[mface->v1].co;
845                                 v2=mvert[mface->v2].co;
846                                 v3=mvert[mface->v3].co;
847
848                                 if (isect_line_tri_v3(co1, co2, v2, v3, v1, &cur_d, 0)) {
849                                         if (cur_d<min_d) {
850                                                 min_d=cur_d;
851                                                 pa->foffset=cur_d*50.0f; /* to the middle of volume */
852                                                 intersect=1;
853                                         }
854                                 }
855                                 if (mface->v4) {
856                                         v4=mvert[mface->v4].co;
857
858                                         if (isect_line_tri_v3(co1, co2, v4, v1, v3, &cur_d, 0)) {
859                                                 if (cur_d<min_d) {
860                                                         min_d=cur_d;
861                                                         pa->foffset=cur_d*50.0f; /* to the middle of volume */
862                                                         intersect=1;
863                                                 }
864                                         }
865                                 }
866                         }
867                         if (intersect==0)
868                                 pa->foffset=0.0;
869                         else {
870                                 switch (distr) {
871                                         case PART_DISTR_JIT:
872                                                 pa->foffset *= ctx->jit[p % (2 * ctx->jitlevel)];
873                                                 break;
874                                         case PART_DISTR_RAND:
875                                                 pa->foffset *= BLI_frand();
876                                                 break;
877                                 }
878                         }
879                 }
880         }
881         else if (from == PART_FROM_CHILD) {
882                 MFace *mf;
883
884                 if (ctx->index[p] < 0) {
885                         cpa->num=0;
886                         cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3]=0.0f;
887                         cpa->pa[0]=cpa->pa[1]=cpa->pa[2]=cpa->pa[3]=0;
888                         return;
889                 }
890
891                 mf= dm->getTessFaceData(dm, ctx->index[p], CD_MFACE);
892
893                 randu= BLI_rng_get_float(thread->rng);
894                 randv= BLI_rng_get_float(thread->rng);
895                 rng_skip_tot -= 2;
896
897                 psys_uv_to_w(randu, randv, mf->v4, cpa->fuv);
898
899                 cpa->num = ctx->index[p];
900
901                 if (ctx->tree) {
902                         KDTreeNearest ptn[10];
903                         int w,maxw;//, do_seams;
904                         float maxd /*, mind,dd */, totw= 0.0f;
905                         int parent[10];
906                         float pweight[10];
907
908                         psys_particle_on_dm(dm,cfrom,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co1,nor1,NULL,NULL,orco1,NULL);
909                         BKE_mesh_orco_verts_transform((Mesh*)ob->data, &orco1, 1, 1);
910                         maxw = BLI_kdtree_find_n_nearest(ctx->tree,4,orco1,NULL,ptn);
911
912                         maxd=ptn[maxw-1].dist;
913                         /* mind=ptn[0].dist; */ /* UNUSED */
914                         
915                         /* the weights here could be done better */
916                         for (w=0; w<maxw; w++) {
917                                 parent[w]=ptn[w].index;
918                                 pweight[w]=(float)pow(2.0,(double)(-6.0f*ptn[w].dist/maxd));
919                         }
920                         for (;w<10; w++) {
921                                 parent[w]=-1;
922                                 pweight[w]=0.0f;
923                         }
924
925                         for (w=0,i=0; w<maxw && i<4; w++) {
926                                 if (parent[w]>=0) {
927                                         cpa->pa[i]=parent[w];
928                                         cpa->w[i]=pweight[w];
929                                         totw+=pweight[w];
930                                         i++;
931                                 }
932                         }
933                         for (;i<4; i++) {
934                                 cpa->pa[i]=-1;
935                                 cpa->w[i]=0.0f;
936                         }
937
938                         if (totw>0.0f) for (w=0; w<4; w++)
939                                 cpa->w[w]/=totw;
940
941                         cpa->parent=cpa->pa[0];
942                 }
943         }
944
945         if (rng_skip_tot > 0) /* should never be below zero */
946                 BLI_rng_skip(thread->rng, rng_skip_tot);
947 }
948
949 static void *distribute_threads_exec_cb(void *data)
950 {
951         ParticleThread *thread= (ParticleThread*)data;
952         ParticleSystem *psys= thread->ctx->sim.psys;
953         ParticleData *pa;
954         ChildParticle *cpa;
955         int p, totpart;
956
957         if (thread->ctx->from == PART_FROM_CHILD) {
958                 totpart= psys->totchild;
959                 cpa= psys->child;
960
961                 for (p=0; p<totpart; p++, cpa++) {
962                         if (thread->ctx->skip) /* simplification skip */
963                                 BLI_rng_skip(thread->rng, PSYS_RND_DIST_SKIP * thread->ctx->skip[p]);
964
965                         if ((p+thread->num) % thread->tot == 0)
966                                 distribute_threads_exec(thread, NULL, cpa, p);
967                         else /* thread skip */
968                                 BLI_rng_skip(thread->rng, PSYS_RND_DIST_SKIP);
969                 }
970         }
971         else {
972                 totpart= psys->totpart;
973                 pa= psys->particles + thread->num;
974                 for (p=thread->num; p<totpart; p+=thread->tot, pa+=thread->tot)
975                         distribute_threads_exec(thread, pa, NULL, p);
976         }
977
978         return 0;
979 }
980
981 /* not thread safe, but qsort doesn't take userdata argument */
982 static int *COMPARE_ORIG_INDEX = NULL;
983 static int distribute_compare_orig_index(const void *p1, const void *p2)
984 {
985         int index1 = COMPARE_ORIG_INDEX[*(const int *)p1];
986         int index2 = COMPARE_ORIG_INDEX[*(const int *)p2];
987
988         if (index1 < index2)
989                 return -1;
990         else if (index1 == index2) {
991                 /* this pointer comparison appears to make qsort stable for glibc,
992                  * and apparently on solaris too, makes the renders reproducible */
993                 if (p1 < p2)
994                         return -1;
995                 else if (p1 == p2)
996                         return 0;
997                 else
998                         return 1;
999         }
1000         else
1001                 return 1;
1002 }
1003
1004 static void distribute_invalid(Scene *scene, ParticleSystem *psys, int from)
1005 {
1006         if (from == PART_FROM_CHILD) {
1007                 ChildParticle *cpa;
1008                 int p, totchild = get_psys_tot_child(scene, psys);
1009
1010                 if (psys->child && totchild) {
1011                         for (p=0,cpa=psys->child; p<totchild; p++,cpa++) {
1012                                 cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3] = 0.0;
1013                                 cpa->foffset= 0.0f;
1014                                 cpa->parent=0;
1015                                 cpa->pa[0]=cpa->pa[1]=cpa->pa[2]=cpa->pa[3]=0;
1016                                 cpa->num= -1;
1017                         }
1018                 }
1019         }
1020         else {
1021                 PARTICLE_P;
1022                 LOOP_PARTICLES {
1023                         pa->fuv[0] = pa->fuv[1] = pa->fuv[2] = pa->fuv[3] = 0.0;
1024                         pa->foffset= 0.0f;
1025                         pa->num= -1;
1026                 }
1027         }
1028 }
1029
1030 /* Creates a distribution of coordinates on a DerivedMesh       */
1031 /* This is to denote functionality that does not yet work with mesh - only derived mesh */
1032 static int distribute_threads_init_data(ParticleThread *threads, Scene *scene, DerivedMesh *finaldm, int from)
1033 {
1034         ParticleThreadContext *ctx= threads[0].ctx;
1035         Object *ob= ctx->sim.ob;
1036         ParticleSystem *psys= ctx->sim.psys;
1037         ParticleData *pa=0, *tpars= 0;
1038         ParticleSettings *part;
1039         ParticleSeam *seams= 0;
1040         KDTree *tree=0;
1041         DerivedMesh *dm= NULL;
1042         float *jit= NULL;
1043         int i, seed, p=0, totthread= threads[0].tot;
1044         int cfrom=0;
1045         int totelem=0, totpart, *particle_element=0, children=0, totseam=0;
1046         int jitlevel= 1, distr;
1047         float *element_weight=NULL,*element_sum=NULL,*jitter_offset=NULL, *vweight=NULL;
1048         float cur, maxweight=0.0, tweight, totweight, inv_totweight, co[3], nor[3], orco[3], ornor[3];
1049         
1050         if (ELEM3(NULL, ob, psys, psys->part))
1051                 return 0;
1052
1053         part=psys->part;
1054         totpart=psys->totpart;
1055         if (totpart==0)
1056                 return 0;
1057
1058         if (!finaldm->deformedOnly && !finaldm->getTessFaceDataArray(finaldm, CD_ORIGINDEX)) {
1059                 printf("Can't create particles with the current modifier stack, disable destructive modifiers\n");
1060 // XXX          error("Can't paint with the current modifier stack, disable destructive modifiers");
1061                 return 0;
1062         }
1063
1064         /* First handle special cases */
1065         if (from == PART_FROM_CHILD) {
1066                 /* Simple children */
1067                 if (part->childtype != PART_CHILD_FACES) {
1068                         BLI_srandom(31415926 + psys->seed + psys->child_seed);
1069                         distribute_simple_children(scene, ob, finaldm, psys);
1070                         return 0;
1071                 }
1072         }
1073         else {
1074                 /* Grid distribution */
1075                 if (part->distr==PART_DISTR_GRID && from != PART_FROM_VERT) {
1076                         BLI_srandom(31415926 + psys->seed);
1077                         dm= CDDM_from_mesh((Mesh*)ob->data, ob);
1078                         DM_ensure_tessface(dm);
1079                         distribute_grid(dm,psys);
1080                         dm->release(dm);
1081                         return 0;
1082                 }
1083         }
1084         
1085         /* Create trees and original coordinates if needed */
1086         if (from == PART_FROM_CHILD) {
1087                 distr=PART_DISTR_RAND;
1088                 BLI_srandom(31415926 + psys->seed + psys->child_seed);
1089                 dm= finaldm;
1090
1091                 /* BMESH ONLY */
1092                 DM_ensure_tessface(dm);
1093
1094                 children=1;
1095
1096                 tree=BLI_kdtree_new(totpart);
1097
1098                 for (p=0,pa=psys->particles; p<totpart; p++,pa++) {
1099                         psys_particle_on_dm(dm,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,nor,0,0,orco,ornor);
1100                         BKE_mesh_orco_verts_transform((Mesh*)ob->data, &orco, 1, 1);
1101                         BLI_kdtree_insert(tree, p, orco, ornor);
1102                 }
1103
1104                 BLI_kdtree_balance(tree);
1105
1106                 totpart = get_psys_tot_child(scene, psys);
1107                 cfrom = from = PART_FROM_FACE;
1108         }
1109         else {
1110                 distr = part->distr;
1111                 BLI_srandom(31415926 + psys->seed);
1112                 
1113                 dm= CDDM_from_mesh((Mesh*)ob->data, ob);
1114
1115                 /* BMESH ONLY, for verts we don't care about tessfaces */
1116                 if (from != PART_FROM_VERT) {
1117                         DM_ensure_tessface(dm);
1118                 }
1119
1120                 /* we need orco for consistent distributions */
1121                 DM_add_vert_layer(dm, CD_ORCO, CD_ASSIGN, BKE_mesh_orco_verts_get(ob));
1122
1123                 if (from == PART_FROM_VERT) {
1124                         MVert *mv= dm->getVertDataArray(dm, CD_MVERT);
1125                         float (*orcodata)[3] = dm->getVertDataArray(dm, CD_ORCO);
1126                         int totvert = dm->getNumVerts(dm);
1127
1128                         tree=BLI_kdtree_new(totvert);
1129
1130                         for (p=0; p<totvert; p++) {
1131                                 if (orcodata) {
1132                                         copy_v3_v3(co,orcodata[p]);
1133                                         BKE_mesh_orco_verts_transform((Mesh*)ob->data, &co, 1, 1);
1134                                 }
1135                                 else
1136                                         copy_v3_v3(co,mv[p].co);
1137                                 BLI_kdtree_insert(tree,p,co,NULL);
1138                         }
1139
1140                         BLI_kdtree_balance(tree);
1141                 }
1142         }
1143
1144         /* Get total number of emission elements and allocate needed arrays */
1145         totelem = (from == PART_FROM_VERT) ? dm->getNumVerts(dm) : dm->getNumTessFaces(dm);
1146
1147         if (totelem == 0) {
1148                 distribute_invalid(scene, psys, children ? PART_FROM_CHILD : 0);
1149
1150                 if (G.debug & G_DEBUG)
1151                         fprintf(stderr,"Particle distribution error: Nothing to emit from!\n");
1152
1153                 if (dm != finaldm) dm->release(dm);
1154
1155                 BLI_kdtree_free(tree);
1156
1157                 return 0;
1158         }
1159
1160         element_weight  = MEM_callocN(sizeof(float)*totelem, "particle_distribution_weights");
1161         particle_element= MEM_callocN(sizeof(int)*totpart, "particle_distribution_indexes");
1162         element_sum             = MEM_callocN(sizeof(float)*(totelem+1), "particle_distribution_sum");
1163         jitter_offset   = MEM_callocN(sizeof(float)*totelem, "particle_distribution_jitoff");
1164
1165         /* Calculate weights from face areas */
1166         if ((part->flag&PART_EDISTR || children) && from != PART_FROM_VERT) {
1167                 MVert *v1, *v2, *v3, *v4;
1168                 float totarea=0.f, co1[3], co2[3], co3[3], co4[3];
1169                 float (*orcodata)[3];
1170                 
1171                 orcodata= dm->getVertDataArray(dm, CD_ORCO);
1172
1173                 for (i=0; i<totelem; i++) {
1174                         MFace *mf=dm->getTessFaceData(dm,i,CD_MFACE);
1175
1176                         if (orcodata) {
1177                                 copy_v3_v3(co1, orcodata[mf->v1]);
1178                                 copy_v3_v3(co2, orcodata[mf->v2]);
1179                                 copy_v3_v3(co3, orcodata[mf->v3]);
1180                                 BKE_mesh_orco_verts_transform((Mesh*)ob->data, &co1, 1, 1);
1181                                 BKE_mesh_orco_verts_transform((Mesh*)ob->data, &co2, 1, 1);
1182                                 BKE_mesh_orco_verts_transform((Mesh*)ob->data, &co3, 1, 1);
1183                                 if (mf->v4) {
1184                                         copy_v3_v3(co4, orcodata[mf->v4]);
1185                                         BKE_mesh_orco_verts_transform((Mesh*)ob->data, &co4, 1, 1);
1186                                 }
1187                         }
1188                         else {
1189                                 v1= (MVert*)dm->getVertData(dm,mf->v1,CD_MVERT);
1190                                 v2= (MVert*)dm->getVertData(dm,mf->v2,CD_MVERT);
1191                                 v3= (MVert*)dm->getVertData(dm,mf->v3,CD_MVERT);
1192                                 copy_v3_v3(co1, v1->co);
1193                                 copy_v3_v3(co2, v2->co);
1194                                 copy_v3_v3(co3, v3->co);
1195                                 if (mf->v4) {
1196                                         v4= (MVert*)dm->getVertData(dm,mf->v4,CD_MVERT);
1197                                         copy_v3_v3(co4, v4->co);
1198                                 }
1199                         }
1200
1201                         cur = mf->v4 ? area_quad_v3(co1, co2, co3, co4) : area_tri_v3(co1, co2, co3);
1202                         
1203                         if (cur > maxweight)
1204                                 maxweight = cur;
1205
1206                         element_weight[i] = cur;
1207                         totarea += cur;
1208                 }
1209
1210                 for (i=0; i<totelem; i++)
1211                         element_weight[i] /= totarea;
1212
1213                 maxweight /= totarea;
1214         }
1215         else {
1216                 float min=1.0f/(float)(MIN2(totelem,totpart));
1217                 for (i=0; i<totelem; i++)
1218                         element_weight[i]=min;
1219                 maxweight=min;
1220         }
1221
1222         /* Calculate weights from vgroup */
1223         vweight = psys_cache_vgroup(dm,psys,PSYS_VG_DENSITY);
1224
1225         if (vweight) {
1226                 if (from==PART_FROM_VERT) {
1227                         for (i=0;i<totelem; i++)
1228                                 element_weight[i]*=vweight[i];
1229                 }
1230                 else { /* PART_FROM_FACE / PART_FROM_VOLUME */
1231                         for (i=0;i<totelem; i++) {
1232                                 MFace *mf=dm->getTessFaceData(dm,i,CD_MFACE);
1233                                 tweight = vweight[mf->v1] + vweight[mf->v2] + vweight[mf->v3];
1234                                 
1235                                 if (mf->v4) {
1236                                         tweight += vweight[mf->v4];
1237                                         tweight /= 4.0f;
1238                                 }
1239                                 else {
1240                                         tweight /= 3.0f;
1241                                 }
1242
1243                                 element_weight[i]*=tweight;
1244                         }
1245                 }
1246                 MEM_freeN(vweight);
1247         }
1248
1249         /* Calculate total weight of all elements */
1250         totweight= 0.0f;
1251         for (i=0;i<totelem; i++)
1252                 totweight += element_weight[i];
1253
1254         inv_totweight = (totweight > 0.f ? 1.f/totweight : 0.f);
1255
1256         /* Calculate cumulative weights */
1257         element_sum[0] = 0.0f;
1258         for (i=0; i<totelem; i++)
1259                 element_sum[i+1] = element_sum[i] + element_weight[i] * inv_totweight;
1260         
1261         /* Finally assign elements to particles */
1262         if ((part->flag&PART_TRAND) || (part->simplify_flag&PART_SIMPLIFY_ENABLE)) {
1263                 float pos;
1264
1265                 for (p=0; p<totpart; p++) {
1266                         /* In theory element_sum[totelem] should be 1.0, but due to float errors this is not necessarily always true, so scale pos accordingly. */
1267                         pos= BLI_frand() * element_sum[totelem];
1268                         particle_element[p] = distribute_binary_search(element_sum, totelem, pos);
1269                         particle_element[p] = MIN2(totelem-1, particle_element[p]);
1270                         jitter_offset[particle_element[p]] = pos;
1271                 }
1272         }
1273         else {
1274                 double step, pos;
1275                 
1276                 step= (totpart < 2) ? 0.5 : 1.0/(double)totpart;
1277                 pos= 1e-6; /* tiny offset to avoid zero weight face */
1278                 i= 0;
1279
1280                 for (p=0; p<totpart; p++, pos+=step) {
1281                         while ((i < totelem) && (pos > (double)element_sum[i + 1]))
1282                                 i++;
1283
1284                         particle_element[p] = MIN2(totelem-1, i);
1285
1286                         /* avoid zero weight face */
1287                         if (p == totpart-1 && element_weight[particle_element[p]] == 0.0f)
1288                                 particle_element[p] = particle_element[p-1];
1289
1290                         jitter_offset[particle_element[p]] = pos;
1291                 }
1292         }
1293
1294         MEM_freeN(element_sum);
1295
1296         /* For hair, sort by origindex (allows optimization's in rendering), */
1297         /* however with virtual parents the children need to be in random order. */
1298         if (part->type == PART_HAIR && !(part->childtype==PART_CHILD_FACES && part->parents!=0.0f)) {
1299                 COMPARE_ORIG_INDEX = NULL;
1300
1301                 if (from == PART_FROM_VERT) {
1302                         if (dm->numVertData)
1303                                 COMPARE_ORIG_INDEX= dm->getVertDataArray(dm, CD_ORIGINDEX);
1304                 }
1305                 else {
1306                         if (dm->numTessFaceData)
1307                                 COMPARE_ORIG_INDEX= dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
1308                 }
1309
1310                 if (COMPARE_ORIG_INDEX) {
1311                         qsort(particle_element, totpart, sizeof(int), distribute_compare_orig_index);
1312                         COMPARE_ORIG_INDEX = NULL;
1313                 }
1314         }
1315
1316         /* Create jittering if needed */
1317         if (distr==PART_DISTR_JIT && ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)) {
1318                 jitlevel= part->userjit;
1319                 
1320                 if (jitlevel == 0) {
1321                         jitlevel= totpart/totelem;
1322                         if (part->flag & PART_EDISTR) jitlevel*= 2;     /* looks better in general, not very scietific */
1323                         if (jitlevel<3) jitlevel= 3;
1324                 }
1325                 
1326                 jit= MEM_callocN((2+ jitlevel*2)*sizeof(float), "jit");
1327
1328                 /* for small amounts of particles we use regular jitter since it looks
1329                  * a bit better, for larger amounts we switch to hammersley sequence 
1330                  * because it is much faster */
1331                 if (jitlevel < 25)
1332                         init_mv_jit(jit, jitlevel, psys->seed, part->jitfac);
1333                 else
1334                         hammersley_create(jit, jitlevel+1, psys->seed, part->jitfac);
1335                 BLI_array_randomize(jit, 2*sizeof(float), jitlevel, psys->seed); /* for custom jit or even distribution */
1336         }
1337
1338         /* Setup things for threaded distribution */
1339         ctx->tree= tree;
1340         ctx->seams= seams;
1341         ctx->totseam= totseam;
1342         ctx->sim.psys= psys;
1343         ctx->index= particle_element;
1344         ctx->jit= jit;
1345         ctx->jitlevel= jitlevel;
1346         ctx->jitoff= jitter_offset;
1347         ctx->weight= element_weight;
1348         ctx->maxweight= maxweight;
1349         ctx->from= (children)? PART_FROM_CHILD: from;
1350         ctx->cfrom= cfrom;
1351         ctx->distr= distr;
1352         ctx->dm= dm;
1353         ctx->tpars= tpars;
1354
1355         if (children) {
1356                 totpart= psys_render_simplify_distribution(ctx, totpart);
1357                 alloc_child_particles(psys, totpart);
1358         }
1359
1360         if (!children || psys->totchild < 10000)
1361                 totthread= 1;
1362         
1363         seed= 31415926 + ctx->sim.psys->seed;
1364         for (i=0; i<totthread; i++) {
1365                 threads[i].rng= BLI_rng_new(seed);
1366                 threads[i].tot= totthread;
1367         }
1368
1369         return 1;
1370 }
1371
1372 static void distribute_particles_on_dm(ParticleSimulationData *sim, int from)
1373 {
1374         DerivedMesh *finaldm = sim->psmd->dm;
1375         ListBase threads;
1376         ParticleThread *pthreads;
1377         ParticleThreadContext *ctx;
1378         int i, totthread;
1379
1380         pthreads= psys_threads_create(sim);
1381
1382         if (!distribute_threads_init_data(pthreads, sim->scene, finaldm, from)) {
1383                 psys_threads_free(pthreads);
1384                 return;
1385         }
1386
1387         totthread= pthreads[0].tot;
1388         if (totthread > 1) {
1389                 BLI_init_threads(&threads, distribute_threads_exec_cb, totthread);
1390
1391                 for (i=0; i<totthread; i++)
1392                         BLI_insert_thread(&threads, &pthreads[i]);
1393
1394                 BLI_end_threads(&threads);
1395         }
1396         else
1397                 distribute_threads_exec_cb(&pthreads[0]);
1398
1399         psys_calc_dmcache(sim->ob, finaldm, sim->psys);
1400
1401         ctx= pthreads[0].ctx;
1402         if (ctx->dm != finaldm)
1403                 ctx->dm->release(ctx->dm);
1404
1405         psys_threads_free(pthreads);
1406 }
1407
1408 /* ready for future use, to emit particles without geometry */
1409 static void distribute_particles_on_shape(ParticleSimulationData *sim, int UNUSED(from))
1410 {
1411         distribute_invalid(sim->scene, sim->psys, 0);
1412
1413         fprintf(stderr,"Shape emission not yet possible!\n");
1414 }
1415
1416 static void distribute_particles(ParticleSimulationData *sim, int from)
1417 {
1418         PARTICLE_PSMD;
1419         int distr_error=0;
1420
1421         if (psmd) {
1422                 if (psmd->dm)
1423                         distribute_particles_on_dm(sim, from);
1424                 else
1425                         distr_error=1;
1426         }
1427         else
1428                 distribute_particles_on_shape(sim, from);
1429
1430         if (distr_error) {
1431                 distribute_invalid(sim->scene, sim->psys, from);
1432
1433                 fprintf(stderr,"Particle distribution error!\n");
1434         }
1435 }
1436
1437 /* threaded child particle distribution and path caching */
1438 ParticleThread *psys_threads_create(ParticleSimulationData *sim)
1439 {
1440         ParticleThread *threads;
1441         ParticleThreadContext *ctx;
1442         int i, totthread;
1443
1444         if (sim->scene->r.mode & R_FIXED_THREADS)
1445                 totthread= sim->scene->r.threads;
1446         else
1447                 totthread= BLI_system_thread_count();
1448         
1449         threads= MEM_callocN(sizeof(ParticleThread)*totthread, "ParticleThread");
1450         ctx= MEM_callocN(sizeof(ParticleThreadContext), "ParticleThreadContext");
1451
1452         ctx->sim = *sim;
1453         ctx->dm= ctx->sim.psmd->dm;
1454         ctx->ma= give_current_material(sim->ob, sim->psys->part->omat);
1455
1456         memset(threads, 0, sizeof(ParticleThread)*totthread);
1457
1458         for (i=0; i<totthread; i++) {
1459                 threads[i].ctx= ctx;
1460                 threads[i].num= i;
1461                 threads[i].tot= totthread;
1462         }
1463
1464         return threads;
1465 }
1466
1467 void psys_threads_free(ParticleThread *threads)
1468 {
1469         ParticleThreadContext *ctx= threads[0].ctx;
1470         int i, totthread= threads[0].tot;
1471
1472         /* path caching */
1473         if (ctx->vg_length)
1474                 MEM_freeN(ctx->vg_length);
1475         if (ctx->vg_clump)
1476                 MEM_freeN(ctx->vg_clump);
1477         if (ctx->vg_kink)
1478                 MEM_freeN(ctx->vg_kink);
1479         if (ctx->vg_rough1)
1480                 MEM_freeN(ctx->vg_rough1);
1481         if (ctx->vg_rough2)
1482                 MEM_freeN(ctx->vg_rough2);
1483         if (ctx->vg_roughe)
1484                 MEM_freeN(ctx->vg_roughe);
1485
1486         if (ctx->sim.psys->lattice) {
1487                 end_latt_deform(ctx->sim.psys->lattice);
1488                 ctx->sim.psys->lattice= NULL;
1489         }
1490
1491         /* distribution */
1492         if (ctx->jit) MEM_freeN(ctx->jit);
1493         if (ctx->jitoff) MEM_freeN(ctx->jitoff);
1494         if (ctx->weight) MEM_freeN(ctx->weight);
1495         if (ctx->index) MEM_freeN(ctx->index);
1496         if (ctx->skip) MEM_freeN(ctx->skip);
1497         if (ctx->seams) MEM_freeN(ctx->seams);
1498         //if (ctx->vertpart) MEM_freeN(ctx->vertpart);
1499         BLI_kdtree_free(ctx->tree);
1500
1501         /* threads */
1502         for (i=0; i<totthread; i++) {
1503                 if (threads[i].rng)
1504                         BLI_rng_free(threads[i].rng);
1505                 if (threads[i].rng_path)
1506                         BLI_rng_free(threads[i].rng_path);
1507         }
1508
1509         MEM_freeN(ctx);
1510         MEM_freeN(threads);
1511 }
1512
1513 /* set particle parameters that don't change during particle's life */
1514 void initialize_particle(ParticleSimulationData *sim, ParticleData *pa, int p)
1515 {
1516         ParticleSystem *psys = sim->psys;
1517         ParticleSettings *part = psys->part;
1518         ParticleTexture ptex;
1519
1520         pa->flag &= ~PARS_UNEXIST;
1521
1522         if (part->type != PART_FLUID) {
1523                 psys_get_texture(sim, pa, &ptex, PAMAP_INIT, 0.f);
1524                 
1525                 if (ptex.exist < PSYS_FRAND(p+125))
1526                         pa->flag |= PARS_UNEXIST;
1527
1528                 pa->time = (part->type == PART_HAIR) ? 0.f : part->sta + (part->end - part->sta)*ptex.time;
1529         }
1530
1531         pa->hair_index = 0;
1532         /* we can't reset to -1 anymore since we've figured out correct index in distribute_particles */
1533         /* usage other than straight after distribute has to handle this index by itself - jahka*/
1534         //pa->num_dmcache = DMCACHE_NOTFOUND; /* assume we don't have a derived mesh face */
1535 }
1536 static void initialize_all_particles(ParticleSimulationData *sim)
1537 {
1538         ParticleSystem *psys = sim->psys;
1539         PARTICLE_P;
1540
1541         psys->totunexist = 0;
1542
1543         LOOP_PARTICLES {
1544                 if ((pa->flag & PARS_UNEXIST)==0)
1545                         initialize_particle(sim, pa, p);
1546
1547                 if (pa->flag & PARS_UNEXIST)
1548                         psys->totunexist++;
1549         }
1550
1551         /* Free unexisting particles. */
1552         if (psys->totpart && psys->totunexist == psys->totpart) {
1553                 if (psys->particles->boid)
1554                         MEM_freeN(psys->particles->boid);
1555
1556                 MEM_freeN(psys->particles);
1557                 psys->particles = NULL;
1558                 psys->totpart = psys->totunexist = 0;
1559         }
1560
1561         if (psys->totunexist) {
1562                 int newtotpart = psys->totpart - psys->totunexist;
1563                 ParticleData *npa, *newpars;
1564                 
1565                 npa = newpars = MEM_callocN(newtotpart * sizeof(ParticleData), "particles");
1566
1567                 for (p=0, pa=psys->particles; p<newtotpart; p++, pa++, npa++) {
1568                         while (pa->flag & PARS_UNEXIST)
1569                                 pa++;
1570
1571                         memcpy(npa, pa, sizeof(ParticleData));
1572                 }
1573
1574                 if (psys->particles->boid)
1575                         MEM_freeN(psys->particles->boid);
1576                 MEM_freeN(psys->particles);
1577                 psys->particles = newpars;
1578                 psys->totpart -= psys->totunexist;
1579
1580                 if (psys->particles->boid) {
1581                         BoidParticle *newboids = MEM_callocN(psys->totpart * sizeof(BoidParticle), "boid particles");
1582
1583                         LOOP_PARTICLES
1584                                 pa->boid = newboids++;
1585
1586                 }
1587         }
1588 }
1589
1590 static void get_angular_velocity_vector(short avemode, ParticleKey *state, float vec[3])
1591 {
1592         switch (avemode) {
1593                 case PART_AVE_VELOCITY:
1594                         copy_v3_v3(vec, state->vel);
1595                         break;
1596                 case PART_AVE_HORIZONTAL:
1597                 {
1598                         float zvec[3];
1599                         zvec[0] = zvec[1] = 0;
1600                         zvec[2] = 1.f;
1601                         cross_v3_v3v3(vec, state->vel, zvec);
1602                         break;
1603                 }
1604                 case PART_AVE_VERTICAL:
1605                 {
1606                         float zvec[3], temp[3];
1607                         zvec[0] = zvec[1] = 0;
1608                         zvec[2] = 1.f;
1609                         cross_v3_v3v3(temp, state->vel, zvec);
1610                         cross_v3_v3v3(vec, temp, state->vel);
1611                         break;
1612                 }
1613                 case PART_AVE_GLOBAL_X:
1614                         vec[0] = 1.f;
1615                         vec[1] = vec[2] = 0;
1616                         break;
1617                 case PART_AVE_GLOBAL_Y:
1618                         vec[1] = 1.f;
1619                         vec[0] = vec[2] = 0;
1620                         break;
1621                 case PART_AVE_GLOBAL_Z:
1622                         vec[2] = 1.f;
1623                         vec[0] = vec[1] = 0;
1624                         break;
1625         }
1626 }
1627
1628 void psys_get_birth_coordinates(ParticleSimulationData *sim, ParticleData *pa, ParticleKey *state, float dtime, float cfra)
1629 {
1630         Object *ob = sim->ob;
1631         ParticleSystem *psys = sim->psys;
1632         ParticleSettings *part;
1633         ParticleTexture ptex;
1634         float fac, phasefac, nor[3] = {0,0,0},loc[3],vel[3] = {0.0,0.0,0.0},rot[4],q2[4];
1635         float r_vel[3],r_ave[3],r_rot[4],vec[3],p_vel[3] = {0.0,0.0,0.0};
1636         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};
1637         float q_phase[4];
1638         int p = pa - psys->particles;
1639         part=psys->part;
1640
1641         /* get birth location from object               */
1642         if (part->tanfac != 0.f)
1643                 psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,utan,vtan,0,0);
1644         else
1645                 psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,0,0,0,0);
1646                 
1647         /* get possible textural influence */
1648         psys_get_texture(sim, pa, &ptex, PAMAP_IVEL, cfra);
1649
1650         /* particles live in global space so    */
1651         /* let's convert:                                               */
1652         /* -location                                                    */
1653         mul_m4_v3(ob->obmat, loc);
1654                 
1655         /* -normal                                                              */
1656         mul_mat3_m4_v3(ob->obmat, nor);
1657         normalize_v3(nor);
1658
1659         /* -tangent                                                             */
1660         if (part->tanfac!=0.0f) {
1661                 //float phase=vg_rot?2.0f*(psys_particle_value_from_verts(sim->psmd->dm,part->from,pa,vg_rot)-0.5f):0.0f;
1662                 float phase=0.0f;
1663                 mul_v3_fl(vtan,-cosf((float)M_PI*(part->tanphase+phase)));
1664                 fac= -sinf((float)M_PI*(part->tanphase+phase));
1665                 madd_v3_v3fl(vtan, utan, fac);
1666
1667                 mul_mat3_m4_v3(ob->obmat,vtan);
1668
1669                 copy_v3_v3(utan, nor);
1670                 mul_v3_fl(utan,dot_v3v3(vtan,nor));
1671                 sub_v3_v3(vtan, utan);
1672                         
1673                 normalize_v3(vtan);
1674         }
1675                 
1676
1677         /* -velocity (boids need this even if there's no random velocity) */
1678         if (part->randfac != 0.0f || (part->phystype==PART_PHYS_BOIDS && pa->boid)) {
1679                 r_vel[0] = 2.0f * (PSYS_FRAND(p + 10) - 0.5f);
1680                 r_vel[1] = 2.0f * (PSYS_FRAND(p + 11) - 0.5f);
1681                 r_vel[2] = 2.0f * (PSYS_FRAND(p + 12) - 0.5f);
1682
1683                 mul_mat3_m4_v3(ob->obmat, r_vel);
1684                 normalize_v3(r_vel);
1685         }
1686
1687         /* -angular velocity                                    */
1688         if (part->avemode==PART_AVE_RAND) {
1689                 r_ave[0] = 2.0f * (PSYS_FRAND(p + 13) - 0.5f);
1690                 r_ave[1] = 2.0f * (PSYS_FRAND(p + 14) - 0.5f);
1691                 r_ave[2] = 2.0f * (PSYS_FRAND(p + 15) - 0.5f);
1692
1693                 mul_mat3_m4_v3(ob->obmat,r_ave);
1694                 normalize_v3(r_ave);
1695         }
1696                 
1697         /* -rotation                                                    */
1698         if (part->randrotfac != 0.0f) {
1699                 r_rot[0] = 2.0f * (PSYS_FRAND(p + 16) - 0.5f);
1700                 r_rot[1] = 2.0f * (PSYS_FRAND(p + 17) - 0.5f);
1701                 r_rot[2] = 2.0f * (PSYS_FRAND(p + 18) - 0.5f);
1702                 r_rot[3] = 2.0f * (PSYS_FRAND(p + 19) - 0.5f);
1703                 normalize_qt(r_rot);
1704
1705                 mat4_to_quat(rot,ob->obmat);
1706                 mul_qt_qtqt(r_rot,r_rot,rot);
1707         }
1708
1709         if (part->phystype==PART_PHYS_BOIDS && pa->boid) {
1710                 float dvec[3], q[4], mat[3][3];
1711
1712                 copy_v3_v3(state->co,loc);
1713
1714                 /* boids don't get any initial velocity  */
1715                 zero_v3(state->vel);
1716
1717                 /* boids store direction in ave */
1718                 if (fabsf(nor[2])==1.0f) {
1719                         sub_v3_v3v3(state->ave, loc, ob->obmat[3]);
1720                         normalize_v3(state->ave);
1721                 }
1722                 else {
1723                         copy_v3_v3(state->ave, nor);
1724                 }
1725
1726                 /* calculate rotation matrix */
1727                 project_v3_v3v3(dvec, r_vel, state->ave);
1728                 sub_v3_v3v3(mat[0], state->ave, dvec);
1729                 normalize_v3(mat[0]);
1730                 negate_v3_v3(mat[2], r_vel);
1731                 normalize_v3(mat[2]);
1732                 cross_v3_v3v3(mat[1], mat[2], mat[0]);
1733                 
1734                 /* apply rotation */
1735                 mat3_to_quat_is_ok( q,mat);
1736                 copy_qt_qt(state->rot, q);
1737         }
1738         else {
1739                 /* conversion done so now we apply new: */
1740                 /* -velocity from:                                              */
1741
1742                 /*              *reactions                                              */
1743                 if (dtime > 0.f) {
1744                         sub_v3_v3v3(vel, pa->state.vel, pa->prev_state.vel);
1745                 }
1746
1747                 /*              *emitter velocity                               */
1748                 if (dtime != 0.f && part->obfac != 0.f) {
1749                         sub_v3_v3v3(vel, loc, state->co);
1750                         mul_v3_fl(vel, part->obfac/dtime);
1751                 }
1752                 
1753                 /*              *emitter normal                                 */
1754                 if (part->normfac != 0.f)
1755                         madd_v3_v3fl(vel, nor, part->normfac);
1756                 
1757                 /*              *emitter tangent                                */
1758                 if (sim->psmd && part->tanfac != 0.f)
1759                         madd_v3_v3fl(vel, vtan, part->tanfac);
1760
1761                 /*              *emitter object orientation             */
1762                 if (part->ob_vel[0] != 0.f) {
1763                         normalize_v3_v3(vec, ob->obmat[0]);
1764                         madd_v3_v3fl(vel, vec, part->ob_vel[0]);
1765                 }
1766                 if (part->ob_vel[1] != 0.f) {
1767                         normalize_v3_v3(vec, ob->obmat[1]);
1768                         madd_v3_v3fl(vel, vec, part->ob_vel[1]);
1769                 }
1770                 if (part->ob_vel[2] != 0.f) {
1771                         normalize_v3_v3(vec, ob->obmat[2]);
1772                         madd_v3_v3fl(vel, vec, part->ob_vel[2]);
1773                 }
1774
1775                 /*              *texture                                                */
1776                 /* TODO */
1777
1778                 /*              *random                                                 */
1779                 if (part->randfac != 0.f)
1780                         madd_v3_v3fl(vel, r_vel, part->randfac);
1781
1782                 /*              *particle                                               */
1783                 if (part->partfac != 0.f)
1784                         madd_v3_v3fl(vel, p_vel, part->partfac);
1785                 
1786                 mul_v3_v3fl(state->vel, vel, ptex.ivel);
1787
1788                 /* -location from emitter                               */
1789                 copy_v3_v3(state->co,loc);
1790
1791                 /* -rotation                                                    */
1792                 unit_qt(state->rot);
1793
1794                 if (part->rotmode) {
1795                         /* create vector into which rotation is aligned */
1796                         switch (part->rotmode) {
1797                                 case PART_ROT_NOR:
1798                                         copy_v3_v3(rot_vec, nor);
1799                                         break;
1800                                 case PART_ROT_VEL:
1801                                         copy_v3_v3(rot_vec, vel);
1802                                         break;
1803                                 case PART_ROT_GLOB_X:
1804                                 case PART_ROT_GLOB_Y:
1805                                 case PART_ROT_GLOB_Z:
1806                                         rot_vec[part->rotmode - PART_ROT_GLOB_X] = 1.0f;
1807                                         break;
1808                                 case PART_ROT_OB_X:
1809                                 case PART_ROT_OB_Y:
1810                                 case PART_ROT_OB_Z:
1811                                         copy_v3_v3(rot_vec, ob->obmat[part->rotmode - PART_ROT_OB_X]);
1812                                         break;
1813                         }
1814                         
1815                         /* create rotation quat */
1816                         negate_v3(rot_vec);
1817                         vec_to_quat( q2,rot_vec, OB_POSX, OB_POSZ);
1818
1819                         /* randomize rotation quat */
1820                         if (part->randrotfac!=0.0f)
1821                                 interp_qt_qtqt(rot, q2, r_rot, part->randrotfac);
1822                         else
1823                                 copy_qt_qt(rot,q2);
1824
1825                         /* rotation phase */
1826                         phasefac = part->phasefac;
1827                         if (part->randphasefac != 0.0f)
1828                                 phasefac += part->randphasefac * PSYS_FRAND(p + 20);
1829                         axis_angle_to_quat( q_phase,x_vec, phasefac*(float)M_PI);
1830
1831                         /* combine base rotation & phase */
1832                         mul_qt_qtqt(state->rot, rot, q_phase);
1833                 }
1834
1835                 /* -angular velocity                                    */
1836
1837                 zero_v3(state->ave);
1838
1839                 if (part->avemode) {
1840                         if (part->avemode == PART_AVE_RAND)
1841                                 copy_v3_v3(state->ave, r_ave);
1842                         else
1843                                 get_angular_velocity_vector(part->avemode, state, state->ave);
1844
1845                         normalize_v3(state->ave);
1846                         mul_v3_fl(state->ave, part->avefac);
1847                 }
1848         }
1849 }
1850 /* sets particle to the emitter surface with initial velocity & rotation */
1851 void reset_particle(ParticleSimulationData *sim, ParticleData *pa, float dtime, float cfra)
1852 {
1853         Object *ob = sim->ob;
1854         ParticleSystem *psys = sim->psys;
1855         ParticleSettings *part;
1856         ParticleTexture ptex;
1857         int p = pa - psys->particles;
1858         part=psys->part;
1859         
1860         /* get precise emitter matrix if particle is born */
1861         if (part->type!=PART_HAIR && dtime > 0.f && pa->time < cfra && pa->time >= sim->psys->cfra) {
1862                 /* we have to force RECALC_ANIM here since where_is_objec_time only does drivers */
1863                 while (ob) {
1864                         BKE_animsys_evaluate_animdata(sim->scene, &ob->id, ob->adt, pa->time, ADT_RECALC_ANIM);
1865                         ob = ob->parent;
1866                 }
1867                 ob = sim->ob;
1868                 BKE_object_where_is_calc_time(sim->scene, ob, pa->time);
1869
1870                 psys->flag |= PSYS_OB_ANIM_RESTORE;
1871         }
1872
1873         psys_get_birth_coordinates(sim, pa, &pa->state, dtime, cfra);
1874
1875         if (part->phystype==PART_PHYS_BOIDS && pa->boid) {
1876                 BoidParticle *bpa = pa->boid;
1877
1878                 /* and gravity in r_ve */
1879                 bpa->gravity[0] = bpa->gravity[1] = 0.0f;
1880                 bpa->gravity[2] = -1.0f;
1881                 if ((sim->scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) &&
1882                     (sim->scene->physics_settings.gravity[2] != 0.0f))
1883                 {
1884                         bpa->gravity[2] = sim->scene->physics_settings.gravity[2];
1885                 }
1886
1887                 bpa->data.health = part->boids->health;
1888                 bpa->data.mode = eBoidMode_InAir;
1889                 bpa->data.state_id = ((BoidState*)part->boids->states.first)->id;
1890                 bpa->data.acc[0]=bpa->data.acc[1]=bpa->data.acc[2]=0.0f;
1891         }
1892
1893         if (part->type == PART_HAIR) {
1894                 pa->lifetime = 100.0f;
1895         }
1896         else {
1897                 /* get possible textural influence */
1898                 psys_get_texture(sim, pa, &ptex, PAMAP_LIFE, cfra);
1899
1900                 pa->lifetime = part->lifetime * ptex.life;
1901
1902                 if (part->randlife != 0.0f)
1903                         pa->lifetime *= 1.0f - part->randlife * PSYS_FRAND(p + 21);
1904         }
1905
1906         pa->dietime = pa->time + pa->lifetime;
1907
1908         if (sim->psys->pointcache && sim->psys->pointcache->flag & PTCACHE_BAKED &&
1909                 sim->psys->pointcache->mem_cache.first) {
1910                 float dietime = psys_get_dietime_from_cache(sim->psys->pointcache, p);
1911                 pa->dietime = MIN2(pa->dietime, dietime);
1912         }
1913
1914         if (pa->time > cfra)
1915                 pa->alive = PARS_UNBORN;
1916         else if (pa->dietime <= cfra)
1917                 pa->alive = PARS_DEAD;
1918         else
1919                 pa->alive = PARS_ALIVE;
1920
1921         pa->state.time = cfra;
1922 }
1923 static void reset_all_particles(ParticleSimulationData *sim, float dtime, float cfra, int from)
1924 {
1925         ParticleData *pa;
1926         int p, totpart=sim->psys->totpart;
1927         
1928         for (p=from, pa=sim->psys->particles+from; p<totpart; p++, pa++)
1929                 reset_particle(sim, pa, dtime, cfra);
1930 }
1931 /************************************************/
1932 /*                      Particle targets                                        */
1933 /************************************************/
1934 ParticleSystem *psys_get_target_system(Object *ob, ParticleTarget *pt)
1935 {
1936         ParticleSystem *psys = NULL;
1937
1938         if (pt->ob == NULL || pt->ob == ob)
1939                 psys = BLI_findlink(&ob->particlesystem, pt->psys-1);
1940         else
1941                 psys = BLI_findlink(&pt->ob->particlesystem, pt->psys-1);
1942
1943         if (psys)
1944                 pt->flag |= PTARGET_VALID;
1945         else
1946                 pt->flag &= ~PTARGET_VALID;
1947
1948         return psys;
1949 }
1950 /************************************************/
1951 /*                      Keyed particles                                         */
1952 /************************************************/
1953 /* Counts valid keyed targets */
1954 void psys_count_keyed_targets(ParticleSimulationData *sim)
1955 {
1956         ParticleSystem *psys = sim->psys, *kpsys;
1957         ParticleTarget *pt = psys->targets.first;
1958         int keys_valid = 1;
1959         psys->totkeyed = 0;
1960
1961         for (; pt; pt=pt->next) {
1962                 kpsys = psys_get_target_system(sim->ob, pt);
1963
1964                 if (kpsys && kpsys->totpart) {
1965                         psys->totkeyed += keys_valid;
1966                         if (psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f)
1967                                 psys->totkeyed += 1;
1968                 }
1969                 else {
1970                         keys_valid = 0;
1971                 }
1972         }
1973
1974         psys->totkeyed *= psys->flag & PSYS_KEYED_TIMING ? 1 : psys->part->keyed_loops;
1975 }
1976
1977 static void set_keyed_keys(ParticleSimulationData *sim)
1978 {
1979         ParticleSystem *psys = sim->psys;
1980         ParticleSimulationData ksim= {0};
1981         ParticleTarget *pt;
1982         PARTICLE_P;
1983         ParticleKey *key;
1984         int totpart = psys->totpart, k, totkeys = psys->totkeyed;
1985         int keyed_flag = 0;
1986
1987         ksim.scene= sim->scene;
1988         
1989         /* no proper targets so let's clear and bail out */
1990         if (psys->totkeyed==0) {
1991                 free_keyed_keys(psys);
1992                 psys->flag &= ~PSYS_KEYED;
1993                 return;
1994         }
1995
1996         if (totpart && psys->particles->totkey != totkeys) {
1997                 free_keyed_keys(psys);
1998                 
1999                 key = MEM_callocN(totpart*totkeys*sizeof(ParticleKey), "Keyed keys");
2000                 
2001                 LOOP_PARTICLES {
2002                         pa->keys = key;
2003                         pa->totkey = totkeys;
2004                         key += totkeys;
2005                 }
2006         }
2007         
2008         psys->flag &= ~PSYS_KEYED;
2009
2010
2011         pt = psys->targets.first;
2012         for (k=0; k<totkeys; k++) {
2013                 ksim.ob = pt->ob ? pt->ob : sim->ob;
2014                 ksim.psys = BLI_findlink(&ksim.ob->particlesystem, pt->psys - 1);
2015                 keyed_flag = (ksim.psys->flag & PSYS_KEYED);
2016                 ksim.psys->flag &= ~PSYS_KEYED;
2017
2018                 LOOP_PARTICLES {
2019                         key = pa->keys + k;
2020                         key->time = -1.0; /* use current time */
2021
2022                         psys_get_particle_state(&ksim, p%ksim.psys->totpart, key, 1);
2023
2024                         if (psys->flag & PSYS_KEYED_TIMING) {
2025                                 key->time = pa->time + pt->time;
2026                                 if (pt->duration != 0.0f && k+1 < totkeys) {
2027                                         copy_particle_key(key+1, key, 1);
2028                                         (key+1)->time = pa->time + pt->time + pt->duration;
2029                                 }
2030                         }
2031                         else if (totkeys > 1)
2032                                 key->time = pa->time + (float)k / (float)(totkeys - 1) * pa->lifetime;
2033                         else
2034                                 key->time = pa->time;
2035                 }
2036
2037                 if (psys->flag & PSYS_KEYED_TIMING && pt->duration!=0.0f)
2038                         k++;
2039
2040                 ksim.psys->flag |= keyed_flag;
2041
2042                 pt = (pt->next && pt->next->flag & PTARGET_VALID)? pt->next : psys->targets.first;
2043         }
2044
2045         psys->flag |= PSYS_KEYED;
2046 }
2047
2048 /************************************************/
2049 /*                      Point Cache                                                     */
2050 /************************************************/
2051 void psys_make_temp_pointcache(Object *ob, ParticleSystem *psys)
2052 {
2053         PointCache *cache = psys->pointcache;
2054
2055         if (cache->flag & PTCACHE_DISK_CACHE && cache->mem_cache.first == NULL) {
2056                 PTCacheID pid;
2057                 BKE_ptcache_id_from_particles(&pid, ob, psys);
2058                 cache->flag &= ~PTCACHE_DISK_CACHE;
2059                 BKE_ptcache_disk_to_mem(&pid);
2060                 cache->flag |= PTCACHE_DISK_CACHE;
2061         }
2062 }
2063 static void psys_clear_temp_pointcache(ParticleSystem *psys)
2064 {
2065         if (psys->pointcache->flag & PTCACHE_DISK_CACHE)
2066                 BKE_ptcache_free_mem(&psys->pointcache->mem_cache);
2067 }
2068 void psys_get_pointcache_start_end(Scene *scene, ParticleSystem *psys, int *sfra, int *efra)
2069 {
2070         ParticleSettings *part = psys->part;
2071
2072         *sfra = MAX2(1, (int)part->sta);
2073         *efra = MIN2((int)(part->end + part->lifetime + 1.0f), scene->r.efra);
2074 }
2075
2076 /************************************************/
2077 /*                      Effectors                                                       */
2078 /************************************************/
2079 static void psys_update_particle_bvhtree(ParticleSystem *psys, float cfra)
2080 {
2081         if (psys) {
2082                 PARTICLE_P;
2083                 int totpart = 0;
2084
2085                 if (!psys->bvhtree || psys->bvhtree_frame != cfra) {
2086                         LOOP_SHOWN_PARTICLES {
2087                                 totpart++;
2088                         }
2089                         
2090                         BLI_bvhtree_free(psys->bvhtree);
2091                         psys->bvhtree = BLI_bvhtree_new(totpart, 0.0, 4, 6);
2092
2093                         LOOP_SHOWN_PARTICLES {
2094                                 if (pa->alive == PARS_ALIVE) {
2095                                         if (pa->state.time == cfra)
2096                                                 BLI_bvhtree_insert(psys->bvhtree, p, pa->prev_state.co, 1);
2097                                         else
2098                                                 BLI_bvhtree_insert(psys->bvhtree, p, pa->state.co, 1);
2099                                 }
2100                         }
2101                         BLI_bvhtree_balance(psys->bvhtree);
2102
2103                         psys->bvhtree_frame = cfra;
2104                 }
2105         }
2106 }
2107 void psys_update_particle_tree(ParticleSystem *psys, float cfra)
2108 {
2109         if (psys) {
2110                 PARTICLE_P;
2111                 int totpart = 0;
2112
2113                 if (!psys->tree || psys->tree_frame != cfra) {
2114                         LOOP_SHOWN_PARTICLES {
2115                                 totpart++;
2116                         }
2117
2118                         BLI_kdtree_free(psys->tree);
2119                         psys->tree = BLI_kdtree_new(psys->totpart);
2120
2121                         LOOP_SHOWN_PARTICLES {
2122                                 if (pa->alive == PARS_ALIVE) {
2123                                         if (pa->state.time == cfra)
2124                                                 BLI_kdtree_insert(psys->tree, p, pa->prev_state.co, NULL);
2125                                         else
2126                                                 BLI_kdtree_insert(psys->tree, p, pa->state.co, NULL);
2127                                 }
2128                         }
2129                         BLI_kdtree_balance(psys->tree);
2130
2131                         psys->tree_frame = cfra;
2132                 }
2133         }
2134 }
2135
2136 static void psys_update_effectors(ParticleSimulationData *sim)
2137 {
2138         pdEndEffectors(&sim->psys->effectors);
2139         sim->psys->effectors = pdInitEffectors(sim->scene, sim->ob, sim->psys, sim->psys->part->effector_weights);
2140         precalc_guides(sim, sim->psys->effectors);
2141 }
2142
2143 static void integrate_particle(ParticleSettings *part, ParticleData *pa, float dtime, float *external_acceleration,
2144                                void (*force_func)(void *forcedata, ParticleKey *state, float *force, float *impulse),
2145                                void *forcedata)
2146 {
2147 #define ZERO_F43 {{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}}
2148
2149         ParticleKey states[5];
2150         float force[3], acceleration[3], impulse[3], dx[4][3] = ZERO_F43, dv[4][3] = ZERO_F43, oldpos[3];
2151         float pa_mass= (part->flag & PART_SIZEMASS ? part->mass * pa->size : part->mass);
2152         int i, steps=1;
2153         int integrator = part->integrator;
2154
2155 #undef ZERO_F43
2156
2157         copy_v3_v3(oldpos, pa->state.co);
2158
2159         /* Verlet integration behaves strangely with moving emitters, so do first step with euler. */
2160         if (pa->prev_state.time < 0.f && integrator == PART_INT_VERLET)
2161                 integrator = PART_INT_EULER;
2162
2163         switch (integrator) {
2164                 case PART_INT_EULER:
2165                         steps=1;
2166                         break;
2167                 case PART_INT_MIDPOINT:
2168                         steps=2;
2169                         break;
2170                 case PART_INT_RK4:
2171                         steps=4;
2172                         break;
2173                 case PART_INT_VERLET:
2174                         steps=1;
2175                         break;
2176         }
2177
2178         for (i=0; i<steps; i++) {
2179                 copy_particle_key(states + i, &pa->state, 1);
2180         }
2181
2182         states->time = 0.f;
2183
2184         for (i=0; i<steps; i++) {
2185                 zero_v3(force);
2186                 zero_v3(impulse);
2187
2188                 force_func(forcedata, states+i, force, impulse);
2189
2190                 /* force to acceleration*/
2191                 mul_v3_v3fl(acceleration, force, 1.0f/pa_mass);
2192
2193                 if (external_acceleration)
2194                         add_v3_v3(acceleration, external_acceleration);
2195                 
2196                 /* calculate next state */
2197                 add_v3_v3(states[i].vel, impulse);
2198
2199                 switch (integrator) {
2200                         case PART_INT_EULER:
2201                                 madd_v3_v3v3fl(pa->state.co, states->co, states->vel, dtime);
2202                                 madd_v3_v3v3fl(pa->state.vel, states->vel, acceleration, dtime);
2203                                 break;
2204                         case PART_INT_MIDPOINT:
2205                                 if (i==0) {
2206                                         madd_v3_v3v3fl(states[1].co, states->co, states->vel, dtime*0.5f);
2207                                         madd_v3_v3v3fl(states[1].vel, states->vel, acceleration, dtime*0.5f);
2208                                         states[1].time = dtime*0.5f;
2209                                         /*fra=sim->psys->cfra+0.5f*dfra;*/
2210                                 }
2211                                 else {
2212                                         madd_v3_v3v3fl(pa->state.co, states->co, states[1].vel, dtime);
2213                                         madd_v3_v3v3fl(pa->state.vel, states->vel, acceleration, dtime);
2214                                 }
2215                                 break;
2216                         case PART_INT_RK4:
2217                                 switch (i) {
2218                                         case 0:
2219                                                 copy_v3_v3(dx[0], states->vel);
2220                                                 mul_v3_fl(dx[0], dtime);
2221                                                 copy_v3_v3(dv[0], acceleration);
2222                                                 mul_v3_fl(dv[0], dtime);
2223
2224                                                 madd_v3_v3v3fl(states[1].co, states->co, dx[0], 0.5f);
2225                                                 madd_v3_v3v3fl(states[1].vel, states->vel, dv[0], 0.5f);
2226                                                 states[1].time = dtime*0.5f;
2227                                                 /*fra=sim->psys->cfra+0.5f*dfra;*/
2228                                                 break;
2229                                         case 1:
2230                                                 madd_v3_v3v3fl(dx[1], states->vel, dv[0], 0.5f);
2231                                                 mul_v3_fl(dx[1], dtime);
2232                                                 copy_v3_v3(dv[1], acceleration);
2233                                                 mul_v3_fl(dv[1], dtime);
2234
2235                                                 madd_v3_v3v3fl(states[2].co, states->co, dx[1], 0.5f);
2236                                                 madd_v3_v3v3fl(states[2].vel, states->vel, dv[1], 0.5f);
2237                                                 states[2].time = dtime*0.5f;
2238                                                 break;
2239                                         case 2:
2240                                                 madd_v3_v3v3fl(dx[2], states->vel, dv[1], 0.5f);
2241                                                 mul_v3_fl(dx[2], dtime);
2242                                                 copy_v3_v3(dv[2], acceleration);
2243                                                 mul_v3_fl(dv[2], dtime);
2244
2245                                                 add_v3_v3v3(states[3].co, states->co, dx[2]);
2246                                                 add_v3_v3v3(states[3].vel, states->vel, dv[2]);
2247                                                 states[3].time = dtime;
2248                                                 /*fra=cfra;*/
2249                                                 break;
2250                                         case 3:
2251                                                 add_v3_v3v3(dx[3], states->vel, dv[2]);
2252                                                 mul_v3_fl(dx[3], dtime);
2253                                                 copy_v3_v3(dv[3], acceleration);
2254                                                 mul_v3_fl(dv[3], dtime);
2255
2256                                                 madd_v3_v3v3fl(pa->state.co, states->co, dx[0], 1.0f/6.0f);
2257                                                 madd_v3_v3fl(pa->state.co, dx[1], 1.0f/3.0f);
2258                                                 madd_v3_v3fl(pa->state.co, dx[2], 1.0f/3.0f);
2259                                                 madd_v3_v3fl(pa->state.co, dx[3], 1.0f/6.0f);
2260
2261                                                 madd_v3_v3v3fl(pa->state.vel, states->vel, dv[0], 1.0f/6.0f);
2262                                                 madd_v3_v3fl(pa->state.vel, dv[1], 1.0f/3.0f);
2263                                                 madd_v3_v3fl(pa->state.vel, dv[2], 1.0f/3.0f);
2264                                                 madd_v3_v3fl(pa->state.vel, dv[3], 1.0f/6.0f);
2265                                 }
2266                                 break;
2267                         case PART_INT_VERLET:   /* Verlet integration */
2268                                 madd_v3_v3v3fl(pa->state.vel, pa->prev_state.vel, acceleration, dtime);
2269                                 madd_v3_v3v3fl(pa->state.co, pa->prev_state.co, pa->state.vel, dtime);
2270
2271                                 sub_v3_v3v3(pa->state.vel, pa->state.co, oldpos);
2272                                 mul_v3_fl(pa->state.vel, 1.0f/dtime);
2273                                 break;
2274                 }
2275         }
2276 }
2277
2278 /*********************************************************************************************************
2279  *                    SPH fluid physics 
2280  *
2281  * In theory, there could be unlimited implementation of SPH simulators
2282  *
2283  * This code uses in some parts adapted algorithms from the pseudo code as outlined in the Research paper:
2284  *
2285  * Titled: Particle-based Viscoelastic Fluid Simulation.
2286  * Authors: Simon Clavet, Philippe Beaudoin and Pierre Poulin
2287  * Website: http://www.iro.umontreal.ca/labs/infographie/papers/Clavet-2005-PVFS/
2288  *
2289  * Presented at Siggraph, (2005)
2290  *
2291  * ********************************************************************************************************/
2292 #define PSYS_FLUID_SPRINGS_INITIAL_SIZE 256
2293 static ParticleSpring *sph_spring_add(ParticleSystem *psys, ParticleSpring *spring)
2294 {
2295         /* Are more refs required? */
2296         if (psys->alloc_fluidsprings == 0 || psys->fluid_springs == NULL) {
2297                 psys->alloc_fluidsprings = PSYS_FLUID_SPRINGS_INITIAL_SIZE;
2298                 psys->fluid_springs = (ParticleSpring*)MEM_callocN(psys->alloc_fluidsprings * sizeof(ParticleSpring), "Particle Fluid Springs");
2299         }
2300         else if (psys->tot_fluidsprings == psys->alloc_fluidsprings) {
2301                 /* Double the number of refs allocated */
2302                 psys->alloc_fluidsprings *= 2;
2303                 psys->fluid_springs = (ParticleSpring*)MEM_reallocN(psys->fluid_springs, psys->alloc_fluidsprings * sizeof(ParticleSpring));
2304         }
2305
2306         memcpy(psys->fluid_springs + psys->tot_fluidsprings, spring, sizeof(ParticleSpring));
2307         psys->tot_fluidsprings++;
2308
2309         return psys->fluid_springs + psys->tot_fluidsprings - 1;
2310 }
2311 static void sph_spring_delete(ParticleSystem *psys, int j)
2312 {
2313         if (j != psys->tot_fluidsprings - 1)
2314                 psys->fluid_springs[j] = psys->fluid_springs[psys->tot_fluidsprings - 1];
2315
2316         psys->tot_fluidsprings--;
2317
2318         if (psys->tot_fluidsprings < psys->alloc_fluidsprings/2 && psys->alloc_fluidsprings > PSYS_FLUID_SPRINGS_INITIAL_SIZE) {
2319                 psys->alloc_fluidsprings /= 2;
2320                 psys->fluid_springs = (ParticleSpring*)MEM_reallocN(psys->fluid_springs,  psys->alloc_fluidsprings * sizeof(ParticleSpring));
2321         }
2322 }
2323 static void sph_springs_modify(ParticleSystem *psys, float dtime)
2324 {
2325         SPHFluidSettings *fluid = psys->part->fluid;
2326         ParticleData *pa1, *pa2;
2327         ParticleSpring *spring = psys->fluid_springs;
2328         
2329         float h, d, Rij[3], rij, Lij;
2330         int i;
2331
2332         float yield_ratio = fluid->yield_ratio;
2333         float plasticity = fluid->plasticity_constant;
2334         /* scale things according to dtime */
2335         float timefix = 25.f * dtime;
2336
2337         if ((fluid->flag & SPH_VISCOELASTIC_SPRINGS)==0 || fluid->spring_k == 0.f)
2338                 return;
2339
2340         /* Loop through the springs */
2341         for (i=0; i<psys->tot_fluidsprings; i++, spring++) {
2342                 pa1 = psys->particles + spring->particle_index[0];
2343                 pa2 = psys->particles + spring->particle_index[1];
2344
2345                 sub_v3_v3v3(Rij, pa2->prev_state.co, pa1->prev_state.co);
2346                 rij = normalize_v3(Rij);
2347
2348                 /* adjust rest length */
2349                 Lij = spring->rest_length;
2350                 d = yield_ratio * timefix * Lij;
2351
2352                 if (rij > Lij + d) // Stretch
2353                         spring->rest_length += plasticity * (rij - Lij - d) * timefix;
2354                 else if (rij < Lij - d) // Compress
2355                         spring->rest_length -= plasticity * (Lij - d - rij) * timefix;
2356
2357                 h = 4.f*pa1->size;
2358
2359                 if (spring->rest_length > h)
2360                         spring->delete_flag = 1;
2361         }
2362
2363         /* Loop through springs backwaqrds - for efficient delete function */
2364         for (i=psys->tot_fluidsprings-1; i >= 0; i--) {
2365                 if (psys->fluid_springs[i].delete_flag)
2366                         sph_spring_delete(psys, i);
2367         }
2368 }
2369 static EdgeHash *sph_springhash_build(ParticleSystem *psys)
2370 {
2371         EdgeHash *springhash = NULL;
2372         ParticleSpring *spring;
2373         int i = 0;
2374
2375         springhash = BLI_edgehash_new();
2376
2377         for (i=0, spring=psys->fluid_springs; i<psys->tot_fluidsprings; i++, spring++)
2378                 BLI_edgehash_insert(springhash, spring->particle_index[0], spring->particle_index[1], SET_INT_IN_POINTER(i+1));
2379
2380         return springhash;
2381 }
2382
2383 #define SPH_NEIGHBORS 512
2384 typedef struct SPHNeighbor {
2385         ParticleSystem *psys;
2386         int index;
2387 } SPHNeighbor;
2388
2389 typedef struct SPHRangeData {
2390         SPHNeighbor neighbors[SPH_NEIGHBORS];
2391         int tot_neighbors;
2392
2393         float* data;
2394
2395         ParticleSystem *npsys;
2396         ParticleData *pa;
2397
2398         float h;
2399         float mass;
2400         float massfac;
2401         int use_size;
2402 } SPHRangeData;
2403
2404 static void sph_evaluate_func(BVHTree *tree, ParticleSystem **psys, float co[3], SPHRangeData *pfr, float interaction_radius, BVHTree_RangeQuery callback)
2405 {
2406         int i;
2407
2408         pfr->tot_neighbors = 0;
2409
2410         for (i=0; i < 10 && psys[i]; i++) {
2411                 pfr->npsys    = psys[i];
2412                 pfr->massfac  = psys[i]->part->mass / pfr->mass;
2413                 pfr->use_size = psys[i]->part->flag & PART_SIZEMASS;
2414
2415                 if (tree) {
2416                         BLI_bvhtree_range_query(tree, co, interaction_radius, callback, pfr);
2417                         break;
2418                 }
2419                 else {
2420                         BLI_bvhtree_range_query(psys[i]->bvhtree, co, interaction_radius, callback, pfr);
2421                 }
2422         }
2423 }
2424 static void sph_density_accum_cb(void *userdata, int index, float squared_dist)
2425 {
2426         SPHRangeData *pfr = (SPHRangeData *)userdata;
2427         ParticleData *npa = pfr->npsys->particles + index;
2428         float q;
2429         float dist;
2430
2431         if (npa == pfr->pa || squared_dist < FLT_EPSILON)
2432                 return;
2433
2434         /* Ugh! One particle has too many neighbors! If some aren't taken into
2435          * account, the forces will be biased by the tree search order. This
2436          * effectively adds enery to the system, and results in a churning motion.
2437          * But, we have to stop somewhere, and it's not the end of the world.
2438          *  - jahka and z0r
2439          */
2440         if (pfr->tot_neighbors >= SPH_NEIGHBORS)
2441                 return;
2442
2443         pfr->neighbors[pfr->tot_neighbors].index = index;
2444         pfr->neighbors[pfr->tot_neighbors].psys = pfr->npsys;
2445         pfr->tot_neighbors++;
2446
2447         dist = sqrtf(squared_dist);
2448         q = (1.f - dist/pfr->h) * pfr->massfac;
2449
2450         if (pfr->use_size)
2451                 q *= npa->size;
2452
2453         pfr->data[0] += q*q;
2454         pfr->data[1] += q*q*q;
2455 }
2456
2457 /*
2458  * Find the Courant number for an SPH particle (used for adaptive time step).
2459  */
2460 static void sph_particle_courant(SPHData *sphdata, SPHRangeData *pfr)
2461 {
2462         ParticleData *pa, *npa;
2463         int i;
2464         float flow[3], offset[3], dist;
2465
2466         zero_v3(flow);
2467
2468         dist = 0.0f;
2469         if (pfr->tot_neighbors > 0) {
2470                 pa = pfr->pa;
2471                 for (i=0; i < pfr->tot_neighbors; i++) {
2472                         npa = pfr->neighbors[i].psys->particles + pfr->neighbors[i].index;
2473                         sub_v3_v3v3(offset, pa->prev_state.co, npa->prev_state.co);
2474                         dist += len_v3(offset);
2475                         add_v3_v3(flow, npa->prev_state.vel);
2476                 }
2477                 dist += sphdata->psys[0]->part->fluid->radius; // TODO: remove this? - z0r
2478                 sphdata->element_size = dist / pfr->tot_neighbors;
2479                 mul_v3_v3fl(sphdata->flow, flow, 1.0f / pfr->tot_neighbors);
2480         }
2481         else {
2482                 sphdata->element_size = MAXFLOAT;
2483                 copy_v3_v3(sphdata->flow, flow);
2484         }
2485 }
2486 static void sph_force_cb(void *sphdata_v, ParticleKey *state, float *force, float *UNUSED(impulse))
2487 {
2488         SPHData *sphdata = (SPHData *)sphdata_v;
2489         ParticleSystem **psys = sphdata->psys;
2490         ParticleData *pa = sphdata->pa;
2491         SPHFluidSettings *fluid = psys[0]->part->fluid;
2492         ParticleSpring *spring = NULL;
2493         SPHRangeData pfr;
2494         SPHNeighbor *pfn;
2495         float *gravity = sphdata->gravity;
2496         EdgeHash *springhash = sphdata->eh;
2497
2498         float q, u, rij, dv[3];
2499         float pressure, near_pressure;
2500
2501         float visc = fluid->viscosity_omega;
2502         float stiff_visc = fluid->viscosity_beta * (fluid->flag & SPH_FAC_VISCOSITY ? fluid->viscosity_omega : 1.f);
2503
2504         float inv_mass = 1.0f / sphdata->mass;
2505         float spring_constant = fluid->spring_k;
2506
2507         /* 4.0 seems to be a pretty good value */
2508         float interaction_radius = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * pa->size : 1.0f);
2509         float h = interaction_radius * sphdata->hfac;
2510         float rest_density = fluid->rest_density * (fluid->flag & SPH_FAC_DENSITY ? 4.77f : 1.f); /* 4.77 is an experimentally determined density factor */
2511         float rest_length = fluid->rest_length * (fluid->flag & SPH_FAC_REST_LENGTH ? 2.588f * pa->size : 1.f);
2512
2513         float stiffness = fluid->stiffness_k;
2514         float stiffness_near_fac = fluid->stiffness_knear * (fluid->flag & SPH_FAC_REPULSION ? fluid->stiffness_k : 1.f);
2515
2516         ParticleData *npa;
2517         float vec[3];
2518         float vel[3];
2519         float co[3];
2520         float data[2];
2521         float density, near_density;
2522
2523         int i, spring_index, index = pa - psys[0]->particles;
2524
2525         data[0] = data[1] = 0;
2526         pfr.data = data;
2527         pfr.h = h;
2528         pfr.pa = pa;
2529         pfr.mass = sphdata->mass;
2530
2531         sph_evaluate_func( NULL, psys, state->co, &pfr, interaction_radius, sph_density_accum_cb);
2532
2533         density = data[0];
2534         near_density = data[1];
2535
2536         pressure =  stiffness * (density - rest_density);
2537         near_pressure = stiffness_near_fac * near_density;
2538
2539         pfn = pfr.neighbors;
2540         for (i=0; i<pfr.tot_neighbors; i++, pfn++) {
2541                 npa = pfn->psys->particles + pfn->index;
2542
2543                 madd_v3_v3v3fl(co, npa->prev_state.co, npa->prev_state.vel, state->time);
2544
2545                 sub_v3_v3v3(vec, co, state->co);
2546                 rij = normalize_v3(vec);
2547
2548                 q = (1.f - rij/h) * pfn->psys->part->mass * inv_mass;
2549
2550                 if (pfn->psys->part->flag & PART_SIZEMASS)
2551                         q *= npa->size;
2552
2553                 copy_v3_v3(vel, npa->prev_state.vel);
2554
2555                 /* Double Density Relaxation */
2556                 madd_v3_v3fl(force, vec, -(pressure + near_pressure*q)*q);
2557
2558                 /* Viscosity */
2559                 if (visc > 0.f  || stiff_visc > 0.f) {
2560                         sub_v3_v3v3(dv, vel, state->vel);
2561                         u = dot_v3v3(vec, dv);
2562
2563                         if (u < 0.f && visc > 0.f)
2564                                 madd_v3_v3fl(force, vec, 0.5f * q * visc * u );
2565
2566                         if (u > 0.f && stiff_visc > 0.f)
2567                                 madd_v3_v3fl(force, vec, 0.5f * q * stiff_visc * u );
2568                 }
2569
2570                 if (spring_constant > 0.f) {
2571                         /* Viscoelastic spring force */
2572                         if (pfn->psys == psys[0] && fluid->flag & SPH_VISCOELASTIC_SPRINGS && springhash) {
2573                                 /* BLI_edgehash_lookup appears to be thread-safe. - z0r */
2574                                 spring_index = GET_INT_FROM_POINTER(BLI_edgehash_lookup(springhash, index, pfn->index));
2575
2576                                 if (spring_index) {
2577                                         spring = psys[0]->fluid_springs + spring_index - 1;
2578
2579                                         madd_v3_v3fl(force, vec, -10.f * spring_constant * (1.f - rij/h) * (spring->rest_length - rij));
2580                                 }
2581                                 else if (fluid->spring_frames == 0 || (pa->prev_state.time-pa->time) <= fluid->spring_frames) {
2582                                         ParticleSpring temp_spring;
2583                                         temp_spring.particle_index[0] = index;
2584                                         temp_spring.particle_index[1] = pfn->index;
2585                                         temp_spring.rest_length = (fluid->flag & SPH_CURRENT_REST_LENGTH) ? rij : rest_length;
2586                                         temp_spring.delete_flag = 0;
2587
2588                                         /* sph_spring_add is not thread-safe. - z0r */
2589                                         #pragma omp critical
2590                                         sph_spring_add(psys[0], &temp_spring);
2591                                 }
2592                         }
2593                         else {/* PART_SPRING_HOOKES - Hooke's spring force */
2594                                 madd_v3_v3fl(force, vec, -10.f * spring_constant * (1.f - rij/h) * (rest_length - rij));
2595                         }
2596                 }
2597         }
2598         
2599         /* Artificial buoyancy force in negative gravity direction  */
2600         if (fluid->buoyancy > 0.f && gravity)
2601                 madd_v3_v3fl(force, gravity, fluid->buoyancy * (density-rest_density));
2602
2603         if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF)
2604                 sph_particle_courant(sphdata, &pfr);
2605         sphdata->pass++;
2606 }
2607
2608 /* powf is really slow for raising to integer powers. */
2609 MINLINE float pow2(float x)
2610 {
2611         return x * x;
2612 }
2613 MINLINE float pow3(float x)
2614 {
2615         return pow2(x) * x;
2616 }
2617 MINLINE float pow4(float x)
2618 {
2619         return pow2(pow2(x));
2620 }
2621 MINLINE float pow7(float x)
2622 {
2623         return pow2(pow3(x)) * x;
2624 }
2625
2626 static void sphclassical_density_accum_cb(void *userdata, int index, float UNUSED(squared_dist))
2627 {
2628         SPHRangeData *pfr = (SPHRangeData *)userdata;
2629         ParticleData *npa = pfr->npsys->particles + index;
2630         float q;
2631         float qfac = 21.0f / (256.f * (float)M_PI);
2632         float rij, rij_h;
2633         float vec[3];
2634
2635         /* Exclude particles that are more than 2h away. Can't use squared_dist here
2636          * because it is not accurate enough. Use current state, i.e. the output of
2637          * basic_integrate() - z0r */
2638         sub_v3_v3v3(vec, npa->state.co, pfr->pa->state.co);
2639         rij = len_v3(vec);
2640         rij_h = rij / pfr->h;
2641         if (rij_h > 2.0f)
2642                 return;
2643
2644         /* Smoothing factor. Utilise the Wendland kernel. gnuplot:
2645          *     q1(x) = (2.0 - x)**4 * ( 1.0 + 2.0 * x)
2646          *     plot [0:2] q1(x) */
2647         q  = qfac / pow3(pfr->h) * pow4(2.0f - rij_h) * ( 1.0f + 2.0f * rij_h);
2648         q *= pfr->npsys->part->mass;
2649
2650         if (pfr->use_size)
2651                 q *= pfr->pa->size;
2652
2653         pfr->data[0] += q;
2654         pfr->data[1] += q / npa->sphdensity;
2655 }
2656
2657 static void sphclassical_neighbour_accum_cb(void *userdata, int index, float UNUSED(squared_dist))
2658 {
2659         SPHRangeData *pfr = (SPHRangeData *)userdata;
2660         ParticleData *npa = pfr->npsys->particles + index;
2661         float rij, rij_h;
2662         float vec[3];
2663
2664         if (pfr->tot_neighbors >= SPH_NEIGHBORS)
2665                 return;
2666
2667         /* Exclude particles that are more than 2h away. Can't use squared_dist here
2668          * because it is not accurate enough. Use current state, i.e. the output of
2669          * basic_integrate() - z0r */
2670         sub_v3_v3v3(vec, npa->state.co, pfr->pa->state.co);
2671         rij = len_v3(vec);
2672         rij_h = rij / pfr->h;
2673         if (rij_h > 2.0f)
2674                 return;
2675
2676         pfr->neighbors[pfr->tot_neighbors].index = index;
2677         pfr->neighbors[pfr->tot_neighbors].psys = pfr->npsys;
2678         pfr->tot_neighbors++;
2679 }
2680 static void sphclassical_force_cb(void *sphdata_v, ParticleKey *state, float *force, float *UNUSED(impulse))
2681 {
2682         SPHData *sphdata = (SPHData *)sphdata_v;
2683         ParticleSystem **psys = sphdata->psys;
2684         ParticleData *pa = sphdata->pa;
2685         SPHFluidSettings *fluid = psys[0]->part->fluid;
2686         SPHRangeData pfr;
2687         SPHNeighbor *pfn;
2688         float *gravity = sphdata->gravity;
2689
2690         float dq, u, rij, dv[3];
2691         float pressure, npressure;
2692
2693         float visc = fluid->viscosity_omega;
2694
2695         float interaction_radius;
2696         float h, hinv;
2697         /* 4.77 is an experimentally determined density factor */
2698         float rest_density = fluid->rest_density * (fluid->flag & SPH_FAC_DENSITY ? 4.77f : 1.0f);
2699
2700         // Use speed of sound squared
2701         float stiffness = pow2(fluid->stiffness_k);
2702
2703         ParticleData *npa;
2704         float vec[3];
2705         float co[3];
2706         float pressureTerm;
2707
2708         int i;
2709
2710         float qfac2 = 42.0f / (256.0f * (float)M_PI);
2711         float rij_h;
2712
2713         /* 4.0 here is to be consistent with previous formulation/interface */
2714         interaction_radius = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * pa->size : 1.0f);
2715         h = interaction_radius * sphdata->hfac;
2716         hinv = 1.0f / h;
2717
2718         pfr.h = h;
2719         pfr.pa = pa;
2720
2721         sph_evaluate_func(NULL, psys, state->co, &pfr, interaction_radius, sphclassical_neighbour_accum_cb);
2722         pressure =  stiffness * (pow7(pa->sphdensity / rest_density) - 1.0f);
2723
2724         /* multiply by mass so that we return a force, not accel */
2725         qfac2 *= sphdata->mass / pow3(pfr.h);
2726
2727         pfn = pfr.neighbors;
2728         for (i = 0; i < pfr.tot_neighbors; i++, pfn++) {
2729                 npa = pfn->psys->particles + pfn->index;
2730                 if (npa == pa) {
2731                         /* we do not contribute to ourselves */
2732                         continue;
2733                 }
2734
2735                 /* Find vector to neighbour. Exclude particles that are more than 2h
2736                  * away. Can't use current state here because it may have changed on
2737                  * another thread - so do own mini integration. Unlike basic_integrate,
2738                  * SPH integration depends on neighbouring particles. - z0r */
2739                 madd_v3_v3v3fl(co, npa->prev_state.co, npa->prev_state.vel, state->time);
2740                 sub_v3_v3v3(vec, co, state->co);
2741                 rij = normalize_v3(vec);
2742                 rij_h = rij / pfr.h;
2743                 if (rij_h > 2.0f)
2744                         continue;
2745
2746                 npressure = stiffness * (pow7(npa->sphdensity / rest_density) - 1.0f);
2747
2748                 /* First derivative of smoothing factor. Utilise the Wendland kernel.
2749                  * gnuplot:
2750                  *     q2(x) = 2.0 * (2.0 - x)**4 - 4.0 * (2.0 - x)**3 * (1.0 + 2.0 * x)
2751                  *     plot [0:2] q2(x)
2752                  * Particles > 2h away are excluded above. */
2753                 dq = qfac2 * (2.0f * pow4(2.0f - rij_h) - 4.0f * pow3(2.0f - rij_h) * (1.0f + 2.0f * rij_h)  );
2754
2755                 if (pfn->psys->part->flag & PART_SIZEMASS)
2756                         dq *= npa->size;
2757
2758                 pressureTerm = pressure / pow2(pa->sphdensity) + npressure / pow2(npa->sphdensity);
2759
2760                 /* Note that 'minus' is removed, because vec = vecBA, not vecAB.
2761                  * This applies to the viscosity calculation below, too. */
2762                 madd_v3_v3fl(force, vec, pressureTerm * dq);
2763
2764                 /* Viscosity */
2765                 if (visc > 0.0f) {
2766                         sub_v3_v3v3(dv, npa->prev_state.vel, pa->prev_state.vel);
2767                         u = dot_v3v3(vec, dv);
2768                         /* Apply parameters */
2769                         u *= -dq * hinv * visc / (0.5f * npa->sphdensity + 0.5f * pa->sphdensity);
2770                         madd_v3_v3fl(force, vec, u);
2771                 }
2772         }
2773
2774         /* Artificial buoyancy force in negative gravity direction  */
2775         if (fluid->buoyancy > 0.f && gravity)
2776                 madd_v3_v3fl(force, gravity, fluid->buoyancy * (pa->sphdensity - rest_density));
2777
2778         if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF)
2779                 sph_particle_courant(sphdata, &pfr);
2780         sphdata->pass++;
2781 }
2782
2783 static void sphclassical_calc_dens(ParticleData *pa, float UNUSED(dfra), SPHData *sphdata)
2784 {
2785         ParticleSystem **psys = sphdata->psys;
2786         SPHFluidSettings *fluid = psys[0]->part->fluid;
2787         /* 4.0 seems to be a pretty good value */
2788         float interaction_radius  = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * psys[0]->part->size : 1.0f);
2789         SPHRangeData pfr;
2790         float data[2];
2791
2792         data[0] = 0;
2793         data[1] = 0;
2794         pfr.data = data;
2795         pfr.h = interaction_radius * sphdata->hfac;
2796         pfr.pa = pa;
2797         pfr.mass = sphdata->mass;
2798
2799         sph_evaluate_func( NULL, psys, pa->state.co, &pfr, interaction_radius, sphclassical_density_accum_cb);
2800         pa->sphdensity = MIN2(MAX2(data[0], fluid->rest_density * 0.9f), fluid->rest_density * 1.1f);
2801 }
2802
2803 void psys_sph_init(ParticleSimulationData *sim, SPHData *sphdata)
2804 {
2805         ParticleTarget *pt;
2806         int i;
2807
2808         // Add other coupled particle systems.
2809         sphdata->psys[0] = sim->psys;
2810         for (i=1, pt=sim->psys->targets.first; i<10; i++, pt=(pt?pt->next:NULL))
2811                 sphdata->psys[i] = pt ? psys_get_target_system(sim->ob, pt) : NULL;
2812
2813         if (psys_uses_gravity(sim))
2814                 sphdata->gravity = sim->scene->physics_settings.gravity;
2815         else
2816                 sphdata->gravity = NULL;
2817         sphdata->eh = sph_springhash_build(sim->psys);
2818
2819         // These per-particle values should be overridden later, but just for
2820         // completeness we give them default values now.
2821         sphdata->pa = NULL;
2822         sphdata->mass = 1.0f;
2823
2824         if (sim->psys->part->fluid->solver == SPH_SOLVER_DDR) {
2825                 sphdata->force_cb = sph_force_cb;
2826                 sphdata->density_cb = sph_density_accum_cb;
2827                 sphdata->hfac = 1.0f;
2828         }
2829         else {
2830                 /* SPH_SOLVER_CLASSICAL */
2831                 sphdata->force_cb = sphclassical_force_cb;
2832                 sphdata->density_cb = sphclassical_density_accum_cb;
2833                 sphdata->hfac = 0.5f;
2834         }
2835
2836 }
2837
2838 void psys_sph_finalise(SPHData *sphdata)
2839 {
2840         if (sphdata->eh) {
2841                 BLI_edgehash_free(sphdata->eh, NULL);
2842                 sphdata->eh = NULL;
2843         }
2844 }
2845 /* Sample the density field at a point in space. */
2846 void psys_sph_density(BVHTree *tree, SPHData *sphdata, float co[3], float vars[2])
2847 {
2848         ParticleSystem **psys = sphdata->psys;
2849         SPHFluidSettings *fluid = psys[0]->part->fluid;
2850         /* 4.0 seems to be a pretty good value */
2851         float interaction_radius  = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * psys[0]->part->size : 1.0f);
2852         SPHRangeData pfr;
2853         float density[2];
2854
2855         density[0] = density[1] = 0.0f;
2856         pfr.data = density;
2857         pfr.h = interaction_radius * sphdata->hfac;
2858         pfr.mass = sphdata->mass;
2859
2860         sph_evaluate_func(tree, psys, co, &pfr, interaction_radius, sphdata->density_cb);
2861
2862         vars[0] = pfr.data[0];
2863         vars[1] = pfr.data[1];
2864 }
2865
2866 static void sph_integrate(ParticleSimulationData *sim, ParticleData *pa, float dfra, SPHData *sphdata)
2867 {
2868         ParticleSettings *part = sim->psys->part;
2869         // float timestep = psys_get_timestep(sim); // UNUSED
2870         float pa_mass = part->mass * (part->flag & PART_SIZEMASS ? pa->size : 1.f);
2871         float dtime = dfra*psys_get_timestep(sim);
2872         // int steps = 1; // UNUSED
2873         float effector_acceleration[3];
2874
2875         sphdata->pa = pa;
2876         sphdata->mass = pa_mass;
2877         sphdata->pass = 0;
2878         //sphdata.element_size and sphdata.flow are set in the callback.
2879
2880         /* restore previous state and treat gravity & effectors as external acceleration*/
2881         sub_v3_v3v3(effector_acceleration, pa->state.vel, pa->prev_state.vel);
2882         mul_v3_fl(effector_acceleration, 1.f/dtime);
2883
2884         copy_particle_key(&pa->state, &pa->prev_state, 0);
2885
2886         integrate_particle(part, pa, dtime, effector_acceleration, sphdata->force_cb, sphdata);
2887 }
2888
2889 /************************************************/
2890 /*                      Basic physics                                           */
2891 /************************************************/
2892 typedef struct EfData {
2893         ParticleTexture ptex;
2894         ParticleSimulationData *sim;
2895         ParticleData *pa;
2896 } EfData;
2897 static void basic_force_cb(void *efdata_v, ParticleKey *state, float *force, float *impulse)
2898 {
2899         EfData *efdata = (EfData *)efdata_v;
2900         ParticleSimulationData *sim = efdata->sim;
2901         ParticleSettings *part = sim->psys->part;
2902         ParticleData *pa = efdata->pa;
2903         EffectedPoint epoint;
2904
2905         /* add effectors */
2906         pd_point_from_particle(efdata->sim, efdata->pa, state, &epoint);
2907         if (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR)
2908                 pdDoEffectors(sim->psys->effectors, sim->colliders, part->effector_weights, &epoint, force, impulse);
2909
2910         mul_v3_fl(force, efdata->ptex.field);
2911         mul_v3_fl(impulse, efdata->ptex.field);
2912
2913         /* calculate air-particle interaction */
2914         if (part->dragfac != 0.0f)
2915                 madd_v3_v3fl(force, state->vel, -part->dragfac * pa->size * pa->size * len_v3(state->vel));
2916
2917         /* brownian force */
2918         if (part->brownfac != 0.0f) {
2919                 force[0] += (BLI_frand()-0.5f) * part->brownfac;
2920                 force[1] += (BLI_frand()-0.5f) * part->brownfac;
2921                 force[2] += (BLI_frand()-0.5f) * part->brownfac;
2922         }
2923
2924         if (part->flag & PART_ROT_DYN && epoint.ave)
2925                 copy_v3_v3(pa->state.ave, epoint.ave);
2926 }
2927 /* gathers all forces that effect particles and calculates a new state for the particle */
2928 static void basic_integrate(ParticleSimulationData *sim, int p, float dfra, float cfra)
2929 {
2930         ParticleSettings *part = sim->psys->part;
2931         ParticleData *pa = sim->psys->particles + p;
2932         ParticleKey tkey;
2933         float dtime=dfra*psys_get_timestep(sim), time;
2934         float *gravity = NULL, gr[3];
2935         EfData efdata;
2936
2937         psys_get_texture(sim, pa, &efdata.ptex, PAMAP_PHYSICS, cfra);
2938
2939         efdata.pa = pa;
2940         efdata.sim = sim;
2941
2942         /* add global acceleration (gravitation) */
2943         if (psys_uses_gravity(sim) &&
2944                 /* normal gravity is too strong for hair so it's disabled by default */
2945                 (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR))
2946         {
2947                 zero_v3(gr);
2948                 madd_v3_v3fl(gr, sim->scene->physics_settings.gravity, part->effector_weights->global_gravity * efdata.ptex.gravity);
2949                 gravity = gr;
2950         }
2951
2952         /* maintain angular velocity */
2953         copy_v3_v3(pa->state.ave, pa->prev_state.ave);
2954
2955         integrate_particle(part, pa, dtime, gravity, basic_force_cb, &efdata);
2956
2957         /* damp affects final velocity */
2958         if (part->dampfac != 0.f)
2959                 mul_v3_fl(pa->state.vel, 1.f - part->dampfac * efdata.ptex.damp * 25.f * dtime);
2960
2961         //copy_v3_v3(pa->state.ave, states->ave);
2962
2963         /* finally we do guides */
2964         time=(cfra-pa->time)/pa->lifetime;
2965         CLAMP(time, 0.0f, 1.0f);
2966
2967         copy_v3_v3(tkey.co,pa->state.co);
2968         copy_v3_v3(tkey.vel,pa->state.vel);
2969         tkey.time=pa->state.time;
2970
2971         if (part->type != PART_HAIR) {
2972                 if (do_guides(sim->psys->effectors, &tkey, p, time)) {
2973                         copy_v3_v3(pa->state.co,tkey.co);
2974                         /* guides don't produce valid velocity */
2975                         sub_v3_v3v3(pa->state.vel, tkey.co, pa->prev_state.co);
2976                         mul_v3_fl(pa->state.vel,1.0f/dtime);
2977                         pa->state.time=tkey.time;
2978                 }
2979         }
2980 }
2981 static void basic_rotate(ParticleSettings *part, ParticleData *pa, float dfra, float timestep)
2982 {
2983         float rotfac, rot1[4], rot2[4] = {1.0,0.0,0.0,0.0}, dtime=dfra*timestep, extrotfac;
2984
2985         if ((part->flag & PART_ROTATIONS) == 0) {
2986                 unit_qt(pa->state.rot);
2987                 return;
2988         }
2989
2990         if (part->flag & PART_ROT_DYN) {
2991                 extrotfac = len_v3(pa->state.ave);
2992         }
2993         else {
2994                 extrotfac = 0.0f;
2995         }
2996
2997         if ((part->flag & PART_ROT_DYN) && ELEM3(part->avemode, PART_AVE_VELOCITY, PART_AVE_HORIZONTAL, PART_AVE_VERTICAL)) {
2998                 float angle;
2999                 float len1 = len_v3(pa->prev_state.vel);
3000                 float len2 = len_v3(pa->state.vel);
3001                 float vec[3];
3002
3003                 if (len1 == 0.0f || len2 == 0.0f) {
3004                         zero_v3(pa->state.ave);
3005                 }
3006                 else {
3007                         cross_v3_v3v3(pa->state.ave, pa->prev_state.vel, pa->state.vel);
3008                         normalize_v3(pa->state.ave);
3009                         angle = dot_v3v3(pa->prev_state.vel, pa->state.vel) / (len1 * len2);
3010                         mul_v3_fl(pa->state.ave, saacos(angle) / dtime);
3011                 }
3012
3013                 get_angular_velocity_vector(part->avemode, &pa->state, vec);
3014                 axis_angle_to_quat(rot2, vec, dtime*part->avefac);
3015         }
3016
3017         rotfac = len_v3(pa->state.ave);
3018         if (rotfac == 0.0f || (part->flag & PART_ROT_DYN)==0 || extrotfac == 0.0f) {
3019                 unit_qt(rot1);
3020         }
3021         else {
3022                 axis_angle_to_quat(rot1,pa->state.ave,rotfac*dtime);
3023         }
3024         mul_qt_qtqt(pa->state.rot,rot1,pa->prev_state.rot);