Fix T43427: Particle system children sometimes not generated on reload
[blender.git] / source / blender / blenkernel / intern / effect.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) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/effect.c
29  *  \ingroup bke
30  */
31
32 #include <stddef.h>
33 #include <stdarg.h>
34
35 #include <math.h>
36 #include <stdlib.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "DNA_curve_types.h"
41 #include "DNA_group_types.h"
42 #include "DNA_listBase.h"
43 #include "DNA_meshdata_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_object_force.h"
46 #include "DNA_particle_types.h"
47 #include "DNA_texture_types.h"
48 #include "DNA_scene_types.h"
49
50 #include "BLI_math.h"
51 #include "BLI_blenlib.h"
52 #include "BLI_noise.h"
53 #include "BLI_rand.h"
54 #include "BLI_utildefines.h"
55 #include "BLI_ghash.h"
56
57 #include "PIL_time.h"
58
59 #include "BKE_anim.h"           /* needed for where_on_path */
60 #include "BKE_collision.h"
61 #include "BKE_curve.h"
62 #include "BKE_displist.h"
63 #include "BKE_DerivedMesh.h"
64 #include "BKE_cdderivedmesh.h"
65 #include "BKE_effect.h"
66 #include "BKE_global.h"
67 #include "BKE_modifier.h"
68 #include "BKE_object.h"
69 #include "BKE_particle.h"
70 #include "BKE_scene.h"
71 #include "BKE_smoke.h"
72
73
74 #include "RE_render_ext.h"
75 #include "RE_shader_ext.h"
76
77 /* fluid sim particle import */
78 #ifdef WITH_MOD_FLUID
79 #include "LBM_fluidsim.h"
80 #include <zlib.h>
81 #include <string.h>
82 #endif // WITH_MOD_FLUID
83
84 EffectorWeights *BKE_add_effector_weights(Group *group)
85 {
86         EffectorWeights *weights = MEM_callocN(sizeof(EffectorWeights), "EffectorWeights");
87         int i;
88
89         for (i=0; i<NUM_PFIELD_TYPES; i++)
90                 weights->weight[i] = 1.0f;
91
92         weights->global_gravity = 1.0f;
93
94         weights->group = group;
95
96         return weights;
97 }
98 PartDeflect *object_add_collision_fields(int type)
99 {
100         PartDeflect *pd;
101
102         pd= MEM_callocN(sizeof(PartDeflect), "PartDeflect");
103
104         pd->forcefield = type;
105         pd->pdef_sbdamp = 0.1f;
106         pd->pdef_sbift  = 0.2f;
107         pd->pdef_sboft  = 0.02f;
108         pd->seed = ((unsigned int)(ceil(PIL_check_seconds_timer()))+1) % 128;
109         pd->f_strength = 1.0f;
110         pd->f_damp = 1.0f;
111
112         /* set sensible defaults based on type */
113         switch (type) {
114                 case PFIELD_VORTEX:
115                         pd->shape = PFIELD_SHAPE_PLANE;
116                         break;
117                 case PFIELD_WIND:
118                         pd->shape = PFIELD_SHAPE_PLANE;
119                         pd->f_flow = 1.0f; /* realistic wind behavior */
120                         break;
121                 case PFIELD_TEXTURE:
122                         pd->f_size = 1.0f;
123                         break;
124                 case PFIELD_SMOKEFLOW:
125                         pd->f_flow = 1.0f;
126                         break;
127         }
128         pd->flag = PFIELD_DO_LOCATION|PFIELD_DO_ROTATION;
129
130         return pd;
131 }
132
133 /* ***************** PARTICLES ***************** */
134
135 /* -------------------------- Effectors ------------------ */
136 void free_partdeflect(PartDeflect *pd)
137 {
138         if (!pd)
139                 return;
140
141         if (pd->tex)
142                 pd->tex->id.us--;
143
144         if (pd->rng)
145                 BLI_rng_free(pd->rng);
146
147         MEM_freeN(pd);
148 }
149
150 static EffectorCache *new_effector_cache(Scene *scene, Object *ob, ParticleSystem *psys, PartDeflect *pd)
151 {
152         EffectorCache *eff = MEM_callocN(sizeof(EffectorCache), "EffectorCache");
153         eff->scene = scene;
154         eff->ob = ob;
155         eff->psys = psys;
156         eff->pd = pd;
157         eff->frame = -1;
158         return eff;
159 }
160 static void add_object_to_effectors(ListBase **effectors, Scene *scene, EffectorWeights *weights, Object *ob, Object *ob_src)
161 {
162         EffectorCache *eff = NULL;
163
164         if ( ob == ob_src || weights->weight[ob->pd->forcefield] == 0.0f )
165                 return;
166
167         if (ob->pd->shape == PFIELD_SHAPE_POINTS && !ob->derivedFinal )
168                 return;
169
170         if (*effectors == NULL)
171                 *effectors = MEM_callocN(sizeof(ListBase), "effectors list");
172
173         eff = new_effector_cache(scene, ob, NULL, ob->pd);
174
175         /* make sure imat is up to date */
176         invert_m4_m4(ob->imat, ob->obmat);
177
178         BLI_addtail(*effectors, eff);
179 }
180 static void add_particles_to_effectors(ListBase **effectors, Scene *scene, EffectorWeights *weights, Object *ob, ParticleSystem *psys, ParticleSystem *psys_src)
181 {
182         ParticleSettings *part= psys->part;
183
184         if ( !psys_check_enabled(ob, psys) )
185                 return;
186
187         if ( psys == psys_src && (part->flag & PART_SELF_EFFECT) == 0)
188                 return;
189
190         if ( part->pd && part->pd->forcefield && weights->weight[part->pd->forcefield] != 0.0f) {
191                 if (*effectors == NULL)
192                         *effectors = MEM_callocN(sizeof(ListBase), "effectors list");
193
194                 BLI_addtail(*effectors, new_effector_cache(scene, ob, psys, part->pd));
195         }
196
197         if (part->pd2 && part->pd2->forcefield && weights->weight[part->pd2->forcefield] != 0.0f) {
198                 if (*effectors == NULL)
199                         *effectors = MEM_callocN(sizeof(ListBase), "effectors list");
200
201                 BLI_addtail(*effectors, new_effector_cache(scene, ob, psys, part->pd2));
202         }
203 }
204
205 /* returns ListBase handle with objects taking part in the effecting */
206 ListBase *pdInitEffectors(Scene *scene, Object *ob_src, ParticleSystem *psys_src,
207                           EffectorWeights *weights, bool precalc)
208 {
209         Base *base;
210         unsigned int layer= ob_src->lay;
211         ListBase *effectors = NULL;
212         
213         if (weights->group) {
214                 GroupObject *go;
215                 
216                 for (go= weights->group->gobject.first; go; go= go->next) {
217                         if ( (go->ob->lay & layer) ) {
218                                 if ( go->ob->pd && go->ob->pd->forcefield )
219                                         add_object_to_effectors(&effectors, scene, weights, go->ob, ob_src);
220
221                                 if ( go->ob->particlesystem.first ) {
222                                         ParticleSystem *psys= go->ob->particlesystem.first;
223
224                                         for ( ; psys; psys=psys->next )
225                                                 add_particles_to_effectors(&effectors, scene, weights, go->ob, psys, psys_src);
226                                 }
227                         }
228                 }
229         }
230         else {
231                 for (base = scene->base.first; base; base= base->next) {
232                         if ( (base->lay & layer) ) {
233                                 if ( base->object->pd && base->object->pd->forcefield )
234                                 add_object_to_effectors(&effectors, scene, weights, base->object, ob_src);
235
236                                 if ( base->object->particlesystem.first ) {
237                                         ParticleSystem *psys= base->object->particlesystem.first;
238
239                                         for ( ; psys; psys=psys->next )
240                                                 add_particles_to_effectors(&effectors, scene, weights, base->object, psys, psys_src);
241                                 }
242                         }
243                 }
244         }
245         
246         if (precalc)
247                 pdPrecalculateEffectors(effectors);
248         
249         return effectors;
250 }
251
252 void pdEndEffectors(ListBase **effectors)
253 {
254         if (*effectors) {
255                 EffectorCache *eff = (*effectors)->first;
256
257                 for (; eff; eff=eff->next) {
258                         if (eff->guide_data)
259                                 MEM_freeN(eff->guide_data);
260                 }
261
262                 BLI_freelistN(*effectors);
263                 MEM_freeN(*effectors);
264                 *effectors = NULL;
265         }
266 }
267
268 static void precalculate_effector(EffectorCache *eff)
269 {
270         unsigned int cfra = (unsigned int)(eff->scene->r.cfra >= 0 ? eff->scene->r.cfra : -eff->scene->r.cfra);
271         if (!eff->pd->rng)
272                 eff->pd->rng = BLI_rng_new(eff->pd->seed + cfra);
273         else
274                 BLI_rng_srandom(eff->pd->rng, eff->pd->seed + cfra);
275
276         if (eff->pd->forcefield == PFIELD_GUIDE && eff->ob->type==OB_CURVE) {
277                 Curve *cu= eff->ob->data;
278                 if (cu->flag & CU_PATH) {
279                         if (eff->ob->curve_cache == NULL || eff->ob->curve_cache->path==NULL || eff->ob->curve_cache->path->data==NULL)
280                                 BKE_displist_make_curveTypes(eff->scene, eff->ob, 0);
281
282                         if (eff->ob->curve_cache->path && eff->ob->curve_cache->path->data) {
283                                 where_on_path(eff->ob, 0.0, eff->guide_loc, eff->guide_dir, NULL, &eff->guide_radius, NULL);
284                                 mul_m4_v3(eff->ob->obmat, eff->guide_loc);
285                                 mul_mat3_m4_v3(eff->ob->obmat, eff->guide_dir);
286                         }
287                 }
288         }
289         else if (eff->pd->shape == PFIELD_SHAPE_SURFACE) {
290                 eff->surmd = (SurfaceModifierData *)modifiers_findByType( eff->ob, eModifierType_Surface );
291                 if (eff->ob->type == OB_CURVE)
292                         eff->flag |= PE_USE_NORMAL_DATA;
293         }
294         else if (eff->psys)
295                 psys_update_particle_tree(eff->psys, eff->scene->r.cfra);
296
297         /* Store object velocity */
298         if (eff->ob) {
299                 float old_vel[3];
300
301                 BKE_object_where_is_calc_time(eff->scene, eff->ob, cfra - 1.0f);
302                 copy_v3_v3(old_vel, eff->ob->obmat[3]);
303                 BKE_object_where_is_calc_time(eff->scene, eff->ob, cfra);
304                 sub_v3_v3v3(eff->velocity, eff->ob->obmat[3], old_vel);
305         }
306 }
307
308 void pdPrecalculateEffectors(ListBase *effectors)
309 {
310         if (effectors) {
311                 EffectorCache *eff = effectors->first;
312                 for (; eff; eff=eff->next)
313                         precalculate_effector(eff);
314         }
315 }
316
317
318 void pd_point_from_particle(ParticleSimulationData *sim, ParticleData *pa, ParticleKey *state, EffectedPoint *point)
319 {
320         ParticleSettings *part = sim->psys->part;
321         point->loc = state->co;
322         point->vel = state->vel;
323         point->index = pa - sim->psys->particles;
324         point->size = pa->size;
325         point->charge = 0.0f;
326         
327         if (part->pd && part->pd->forcefield == PFIELD_CHARGE)
328                 point->charge += part->pd->f_strength;
329
330         if (part->pd2 && part->pd2->forcefield == PFIELD_CHARGE)
331                 point->charge += part->pd2->f_strength;
332
333         point->vel_to_sec = 1.0f;
334         point->vel_to_frame = psys_get_timestep(sim);
335
336         point->flag = 0;
337
338         if (sim->psys->part->flag & PART_ROT_DYN) {
339                 point->ave = state->ave;
340                 point->rot = state->rot;
341         }
342         else
343                 point->ave = point->rot = NULL;
344
345         point->psys = sim->psys;
346 }
347
348 void pd_point_from_loc(Scene *scene, float *loc, float *vel, int index, EffectedPoint *point)
349 {
350         point->loc = loc;
351         point->vel = vel;
352         point->index = index;
353         point->size = 0.0f;
354
355         point->vel_to_sec = (float)scene->r.frs_sec;
356         point->vel_to_frame = 1.0f;
357
358         point->flag = 0;
359
360         point->ave = point->rot = NULL;
361         point->psys = NULL;
362 }
363 void pd_point_from_soft(Scene *scene, float *loc, float *vel, int index, EffectedPoint *point)
364 {
365         point->loc = loc;
366         point->vel = vel;
367         point->index = index;
368         point->size = 0.0f;
369
370         point->vel_to_sec = (float)scene->r.frs_sec;
371         point->vel_to_frame = 1.0f;
372
373         point->flag = PE_WIND_AS_SPEED;
374
375         point->ave = point->rot = NULL;
376
377         point->psys = NULL;
378 }
379 /************************************************/
380 /*                      Effectors               */
381 /************************************************/
382
383 // triangle - ray callback function
384 static void eff_tri_ray_hit(void *UNUSED(userData), int UNUSED(index), const BVHTreeRay *UNUSED(ray), BVHTreeRayHit *hit)
385 {       
386         /* whenever we hit a bounding box, we don't check further */
387         hit->dist = -1;
388         hit->index = 1;
389 }
390
391 // get visibility of a wind ray
392 static float eff_calc_visibility(ListBase *colliders, EffectorCache *eff, EffectorData *efd, EffectedPoint *point)
393 {
394         ListBase *colls = colliders;
395         ColliderCache *col;
396         float norm[3], len = 0.0;
397         float visibility = 1.0, absorption = 0.0;
398         
399         if (!(eff->pd->flag & PFIELD_VISIBILITY))
400                 return visibility;
401
402         if (!colls)
403                 colls = get_collider_cache(eff->scene, eff->ob, NULL);
404
405         if (!colls)
406                 return visibility;
407
408         negate_v3_v3(norm, efd->vec_to_point);
409         len = normalize_v3(norm);
410         
411         /* check all collision objects */
412         for (col = colls->first; col; col = col->next) {
413                 CollisionModifierData *collmd = col->collmd;
414
415                 if (col->ob == eff->ob)
416                         continue;
417
418                 if (collmd->bvhtree) {
419                         BVHTreeRayHit hit;
420
421                         hit.index = -1;
422                         hit.dist = len + FLT_EPSILON;
423
424                         /* check if the way is blocked */
425                         if (BLI_bvhtree_ray_cast(collmd->bvhtree, point->loc, norm, 0.0f, &hit, eff_tri_ray_hit, NULL)>=0) {
426                                 absorption= col->ob->pd->absorption;
427
428                                 /* visibility is only between 0 and 1, calculated from 1-absorption */
429                                 visibility *= CLAMPIS(1.0f-absorption, 0.0f, 1.0f);
430                                 
431                                 if (visibility <= 0.0f)
432                                         break;
433                         }
434                 }
435         }
436
437         if (!colliders)
438                 free_collider_cache(&colls);
439         
440         return visibility;
441 }
442
443 // noise function for wind e.g.
444 static float wind_func(struct RNG *rng, float strength)
445 {
446         int random = (BLI_rng_get_int(rng)+1) % 128; // max 2357
447         float force = BLI_rng_get_float(rng) + 1.0f;
448         float ret;
449         float sign = 0;
450         
451         sign = ((float)random > 64.0f) ? 1.0f: -1.0f; // dividing by 2 is not giving equal sign distribution
452         
453         ret = sign*((float)random / force)*strength/128.0f;
454         
455         return ret;
456 }
457
458 /* maxdist: zero effect from this distance outwards (if usemax) */
459 /* mindist: full effect up to this distance (if usemin) */
460 /* power: falloff with formula 1/r^power */
461 static float falloff_func(float fac, int usemin, float mindist, int usemax, float maxdist, float power)
462 {
463         /* first quick checks */
464         if (usemax && fac > maxdist)
465                 return 0.0f;
466
467         if (usemin && fac < mindist)
468                 return 1.0f;
469
470         if (!usemin)
471                 mindist = 0.0;
472
473         return pow((double)(1.0f+fac-mindist), (double)(-power));
474 }
475
476 static float falloff_func_dist(PartDeflect *pd, float fac)
477 {
478         return falloff_func(fac, pd->flag&PFIELD_USEMIN, pd->mindist, pd->flag&PFIELD_USEMAX, pd->maxdist, pd->f_power);
479 }
480
481 static float falloff_func_rad(PartDeflect *pd, float fac)
482 {
483         return falloff_func(fac, pd->flag&PFIELD_USEMINR, pd->minrad, pd->flag&PFIELD_USEMAXR, pd->maxrad, pd->f_power_r);
484 }
485
486 float effector_falloff(EffectorCache *eff, EffectorData *efd, EffectedPoint *UNUSED(point), EffectorWeights *weights)
487 {
488         float temp[3];
489         float falloff = weights ? weights->weight[0] * weights->weight[eff->pd->forcefield] : 1.0f;
490         float fac, r_fac;
491
492         fac = dot_v3v3(efd->nor, efd->vec_to_point2);
493
494         if (eff->pd->zdir == PFIELD_Z_POS && fac < 0.0f)
495                 falloff=0.0f;
496         else if (eff->pd->zdir == PFIELD_Z_NEG && fac > 0.0f)
497                 falloff=0.0f;
498         else {
499                 switch (eff->pd->falloff) {
500                 case PFIELD_FALL_SPHERE:
501                         falloff*= falloff_func_dist(eff->pd, efd->distance);
502                         break;
503
504                 case PFIELD_FALL_TUBE:
505                         falloff*= falloff_func_dist(eff->pd, ABS(fac));
506                         if (falloff == 0.0f)
507                                 break;
508
509                         madd_v3_v3v3fl(temp, efd->vec_to_point, efd->nor, -fac);
510                         r_fac= len_v3(temp);
511                         falloff*= falloff_func_rad(eff->pd, r_fac);
512                         break;
513                 case PFIELD_FALL_CONE:
514                         falloff*= falloff_func_dist(eff->pd, ABS(fac));
515                         if (falloff == 0.0f)
516                                 break;
517
518                         r_fac= RAD2DEGF(saacos(fac/len_v3(efd->vec_to_point)));
519                         falloff*= falloff_func_rad(eff->pd, r_fac);
520
521                         break;
522                 }
523         }
524
525         return falloff;
526 }
527
528 int closest_point_on_surface(SurfaceModifierData *surmd, const float co[3], float surface_co[3], float surface_nor[3], float surface_vel[3])
529 {
530         BVHTreeNearest nearest;
531
532         nearest.index = -1;
533         nearest.dist_sq = FLT_MAX;
534
535         BLI_bvhtree_find_nearest(surmd->bvhtree->tree, co, &nearest, surmd->bvhtree->nearest_callback, surmd->bvhtree);
536
537         if (nearest.index != -1) {
538                 copy_v3_v3(surface_co, nearest.co);
539
540                 if (surface_nor) {
541                         copy_v3_v3(surface_nor, nearest.no);
542                 }
543
544                 if (surface_vel) {
545                         MFace *mface = CDDM_get_tessface(surmd->dm, nearest.index);
546                         
547                         copy_v3_v3(surface_vel, surmd->v[mface->v1].co);
548                         add_v3_v3(surface_vel, surmd->v[mface->v2].co);
549                         add_v3_v3(surface_vel, surmd->v[mface->v3].co);
550                         if (mface->v4)
551                                 add_v3_v3(surface_vel, surmd->v[mface->v4].co);
552
553                         mul_v3_fl(surface_vel, mface->v4 ? 0.25f : (1.0f / 3.0f));
554                 }
555                 return 1;
556         }
557
558         return 0;
559 }
560 int get_effector_data(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, int real_velocity)
561 {
562         float cfra = eff->scene->r.cfra;
563         int ret = 0;
564
565         if (eff->pd && eff->pd->shape==PFIELD_SHAPE_SURFACE && eff->surmd) {
566                 /* closest point in the object surface is an effector */
567                 float vec[3];
568
569                 /* using velocity corrected location allows for easier sliding over effector surface */
570                 copy_v3_v3(vec, point->vel);
571                 mul_v3_fl(vec, point->vel_to_frame);
572                 add_v3_v3(vec, point->loc);
573
574                 ret = closest_point_on_surface(eff->surmd, vec, efd->loc, efd->nor, real_velocity ? efd->vel : NULL);
575
576                 efd->size = 0.0f;
577         }
578         else if (eff->pd && eff->pd->shape==PFIELD_SHAPE_POINTS) {
579
580                 if (eff->ob->derivedFinal) {
581                         DerivedMesh *dm = eff->ob->derivedFinal;
582
583                         dm->getVertCo(dm, *efd->index, efd->loc);
584                         dm->getVertNo(dm, *efd->index, efd->nor);
585
586                         mul_m4_v3(eff->ob->obmat, efd->loc);
587                         mul_mat3_m4_v3(eff->ob->obmat, efd->nor);
588
589                         normalize_v3(efd->nor);
590
591                         efd->size = 0.0f;
592
593                         /**/
594                         ret = 1;
595                 }
596         }
597         else if (eff->psys) {
598                 ParticleData *pa = eff->psys->particles + *efd->index;
599                 ParticleKey state;
600
601                 /* exclude the particle itself for self effecting particles */
602                 if (eff->psys == point->psys && *efd->index == point->index) {
603                         /* pass */
604                 }
605                 else {
606                         ParticleSimulationData sim= {NULL};
607                         sim.scene= eff->scene;
608                         sim.ob= eff->ob;
609                         sim.psys= eff->psys;
610
611                         /* TODO: time from actual previous calculated frame (step might not be 1) */
612                         state.time = cfra - 1.0f;
613                         ret = psys_get_particle_state(&sim, *efd->index, &state, 0);
614
615                         /* TODO */
616                         //if (eff->pd->forcefiled == PFIELD_HARMONIC && ret==0) {
617                         //      if (pa->dietime < eff->psys->cfra)
618                         //              eff->flag |= PE_VELOCITY_TO_IMPULSE;
619                         //}
620
621                         copy_v3_v3(efd->loc, state.co);
622
623                         /* rather than use the velocity use rotated x-axis (defaults to velocity) */
624                         efd->nor[0] = 1.f;
625                         efd->nor[1] = efd->nor[2] = 0.f;
626                         mul_qt_v3(state.rot, efd->nor);
627                 
628                         if (real_velocity)
629                                 copy_v3_v3(efd->vel, state.vel);
630
631                         efd->size = pa->size;
632                 }
633         }
634         else {
635                 /* use center of object for distance calculus */
636                 const Object *ob = eff->ob;
637
638                 /* use z-axis as normal*/
639                 normalize_v3_v3(efd->nor, ob->obmat[2]);
640
641                 if (eff->pd && eff->pd->shape == PFIELD_SHAPE_PLANE) {
642                         float temp[3], translate[3];
643                         sub_v3_v3v3(temp, point->loc, ob->obmat[3]);
644                         project_v3_v3v3(translate, temp, efd->nor);
645
646                         /* for vortex the shape chooses between old / new force */
647                         if (eff->pd->forcefield == PFIELD_VORTEX)
648                                 add_v3_v3v3(efd->loc, ob->obmat[3], translate);
649                         else /* normally efd->loc is closest point on effector xy-plane */
650                                 sub_v3_v3v3(efd->loc, point->loc, translate);
651                 }
652                 else {
653                         copy_v3_v3(efd->loc, ob->obmat[3]);
654                 }
655
656                 if (real_velocity)
657                         copy_v3_v3(efd->vel, eff->velocity);
658
659                 efd->size = 0.0f;
660
661                 ret = 1;
662         }
663
664         if (ret) {
665                 sub_v3_v3v3(efd->vec_to_point, point->loc, efd->loc);
666                 efd->distance = len_v3(efd->vec_to_point);
667
668                 /* rest length for harmonic effector, will have to see later if this could be extended to other effectors */
669                 if (eff->pd && eff->pd->forcefield == PFIELD_HARMONIC && eff->pd->f_size)
670                         mul_v3_fl(efd->vec_to_point, (efd->distance-eff->pd->f_size)/efd->distance);
671
672                 if (eff->flag & PE_USE_NORMAL_DATA) {
673                         copy_v3_v3(efd->vec_to_point2, efd->vec_to_point);
674                         copy_v3_v3(efd->nor2, efd->nor);
675                 }
676                 else {
677                         /* for some effectors we need the object center every time */
678                         sub_v3_v3v3(efd->vec_to_point2, point->loc, eff->ob->obmat[3]);
679                         normalize_v3_v3(efd->nor2, eff->ob->obmat[2]);
680                 }
681         }
682
683         return ret;
684 }
685 static void get_effector_tot(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, int *tot, int *p, int *step)
686 {
687         if (eff->pd->shape == PFIELD_SHAPE_POINTS) {
688                 efd->index = p;
689
690                 *p = 0;
691                 *tot = eff->ob->derivedFinal ? eff->ob->derivedFinal->numVertData : 1;
692
693                 if (*tot && eff->pd->forcefield == PFIELD_HARMONIC && point->index >= 0) {
694                         *p = point->index % *tot;
695                         *tot = *p+1;
696                 }
697         }
698         else if (eff->psys) {
699                 efd->index = p;
700
701                 *p = 0;
702                 *tot = eff->psys->totpart;
703                 
704                 if (eff->pd->forcefield == PFIELD_CHARGE) {
705                         /* Only the charge of the effected particle is used for 
706                          * interaction, not fall-offs. If the fall-offs aren't the
707                          * same this will be unphysical, but for animation this
708                          * could be the wanted behavior. If you want physical
709                          * correctness the fall-off should be spherical 2.0 anyways.
710                          */
711                         efd->charge = eff->pd->f_strength;
712                 }
713                 else if (eff->pd->forcefield == PFIELD_HARMONIC && (eff->pd->flag & PFIELD_MULTIPLE_SPRINGS)==0) {
714                         /* every particle is mapped to only one harmonic effector particle */
715                         *p= point->index % eff->psys->totpart;
716                         *tot= *p + 1;
717                 }
718
719                 if (eff->psys->part->effector_amount) {
720                         int totpart = eff->psys->totpart;
721                         int amount = eff->psys->part->effector_amount;
722
723                         *step = (totpart > amount) ? totpart/amount : 1;
724                 }
725         }
726         else {
727                 *p = 0;
728                 *tot = 1;
729         }
730 }
731 static void do_texture_effector(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, float *total_force)
732 {
733         TexResult result[4];
734         float tex_co[3], strength, force[3];
735         float nabla = eff->pd->tex_nabla;
736         int hasrgb;
737         short mode = eff->pd->tex_mode;
738         bool scene_color_manage;
739
740         if (!eff->pd->tex)
741                 return;
742
743         result[0].nor = result[1].nor = result[2].nor = result[3].nor = NULL;
744
745         strength= eff->pd->f_strength * efd->falloff;
746
747         copy_v3_v3(tex_co, point->loc);
748
749         if (eff->pd->flag & PFIELD_TEX_2D) {
750                 float fac=-dot_v3v3(tex_co, efd->nor);
751                 madd_v3_v3fl(tex_co, efd->nor, fac);
752         }
753
754         if (eff->pd->flag & PFIELD_TEX_OBJECT) {
755                 mul_m4_v3(eff->ob->imat, tex_co);
756         }
757
758         scene_color_manage = BKE_scene_check_color_management_enabled(eff->scene);
759
760         hasrgb = multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 0, result, NULL, scene_color_manage, false);
761
762         if (hasrgb && mode==PFIELD_TEX_RGB) {
763                 force[0] = (0.5f - result->tr) * strength;
764                 force[1] = (0.5f - result->tg) * strength;
765                 force[2] = (0.5f - result->tb) * strength;
766         }
767         else {
768                 strength/=nabla;
769
770                 tex_co[0] += nabla;
771                 multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 0, result+1, NULL, scene_color_manage, false);
772
773                 tex_co[0] -= nabla;
774                 tex_co[1] += nabla;
775                 multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 0, result+2, NULL, scene_color_manage, false);
776
777                 tex_co[1] -= nabla;
778                 tex_co[2] += nabla;
779                 multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 0, result+3, NULL, scene_color_manage, false);
780
781                 if (mode == PFIELD_TEX_GRAD || !hasrgb) { /* if we don't have rgb fall back to grad */
782                         /* generate intensity if texture only has rgb value */
783                         if (hasrgb & TEX_RGB) {
784                                 int i;
785                                 for (i=0; i<4; i++)
786                                         result[i].tin = (1.0f / 3.0f) * (result[i].tr + result[i].tg + result[i].tb);
787                         }
788                         force[0] = (result[0].tin - result[1].tin) * strength;
789                         force[1] = (result[0].tin - result[2].tin) * strength;
790                         force[2] = (result[0].tin - result[3].tin) * strength;
791                 }
792                 else { /*PFIELD_TEX_CURL*/
793                         float dbdy, dgdz, drdz, dbdx, dgdx, drdy;
794
795                         dbdy = result[2].tb - result[0].tb;
796                         dgdz = result[3].tg - result[0].tg;
797                         drdz = result[3].tr - result[0].tr;
798                         dbdx = result[1].tb - result[0].tb;
799                         dgdx = result[1].tg - result[0].tg;
800                         drdy = result[2].tr - result[0].tr;
801
802                         force[0] = (dbdy - dgdz) * strength;
803                         force[1] = (drdz - dbdx) * strength;
804                         force[2] = (dgdx - drdy) * strength;
805                 }
806         }
807
808         if (eff->pd->flag & PFIELD_TEX_2D) {
809                 float fac = -dot_v3v3(force, efd->nor);
810                 madd_v3_v3fl(force, efd->nor, fac);
811         }
812
813         add_v3_v3(total_force, force);
814 }
815 static void do_physical_effector(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, float *total_force)
816 {
817         PartDeflect *pd = eff->pd;
818         RNG *rng = pd->rng;
819         float force[3] = {0, 0, 0};
820         float temp[3];
821         float fac;
822         float strength = pd->f_strength;
823         float damp = pd->f_damp;
824         float noise_factor = pd->f_noise;
825
826         if (noise_factor > 0.0f) {
827                 strength += wind_func(rng, noise_factor);
828
829                 if (ELEM(pd->forcefield, PFIELD_HARMONIC, PFIELD_DRAG))
830                         damp += wind_func(rng, noise_factor);
831         }
832
833         copy_v3_v3(force, efd->vec_to_point);
834
835         switch (pd->forcefield) {
836                 case PFIELD_WIND:
837                         copy_v3_v3(force, efd->nor);
838                         mul_v3_fl(force, strength * efd->falloff);
839                         break;
840                 case PFIELD_FORCE:
841                         normalize_v3(force);
842                         mul_v3_fl(force, strength * efd->falloff);
843                         break;
844                 case PFIELD_VORTEX:
845                         /* old vortex force */
846                         if (pd->shape == PFIELD_SHAPE_POINT) {
847                                 cross_v3_v3v3(force, efd->nor, efd->vec_to_point);
848                                 normalize_v3(force);
849                                 mul_v3_fl(force, strength * efd->distance * efd->falloff);
850                         }
851                         else {
852                                 /* new vortex force */
853                                 cross_v3_v3v3(temp, efd->nor2, efd->vec_to_point2);
854                                 mul_v3_fl(temp, strength * efd->falloff);
855                                 
856                                 cross_v3_v3v3(force, efd->nor2, temp);
857                                 mul_v3_fl(force, strength * efd->falloff);
858                                 
859                                 madd_v3_v3fl(temp, point->vel, -point->vel_to_sec);
860                                 add_v3_v3(force, temp);
861                         }
862                         break;
863                 case PFIELD_MAGNET:
864                         if (eff->pd->shape == PFIELD_SHAPE_POINT)
865                                 /* magnetic field of a moving charge */
866                                 cross_v3_v3v3(temp, efd->nor, efd->vec_to_point);
867                         else
868                                 copy_v3_v3(temp, efd->nor);
869
870                         normalize_v3(temp);
871                         mul_v3_fl(temp, strength * efd->falloff);
872                         cross_v3_v3v3(force, point->vel, temp);
873                         mul_v3_fl(force, point->vel_to_sec);
874                         break;
875                 case PFIELD_HARMONIC:
876                         mul_v3_fl(force, -strength * efd->falloff);
877                         copy_v3_v3(temp, point->vel);
878                         mul_v3_fl(temp, -damp * 2.0f * sqrtf(fabsf(strength)) * point->vel_to_sec);
879                         add_v3_v3(force, temp);
880                         break;
881                 case PFIELD_CHARGE:
882                         mul_v3_fl(force, point->charge * strength * efd->falloff);
883                         break;
884                 case PFIELD_LENNARDJ:
885                         fac = pow((efd->size + point->size) / efd->distance, 6.0);
886                         
887                         fac = - fac * (1.0f - fac) / efd->distance;
888
889                         /* limit the repulsive term drastically to avoid huge forces */
890                         fac = ((fac>2.0f) ? 2.0f : fac);
891
892                         mul_v3_fl(force, strength * fac);
893                         break;
894                 case PFIELD_BOID:
895                         /* Boid field is handled completely in boids code. */
896                         return;
897                 case PFIELD_TURBULENCE:
898                         if (pd->flag & PFIELD_GLOBAL_CO) {
899                                 copy_v3_v3(temp, point->loc);
900                         }
901                         else {
902                                 add_v3_v3v3(temp, efd->vec_to_point2, efd->nor2);
903                         }
904                         force[0] = -1.0f + 2.0f * BLI_gTurbulence(pd->f_size, temp[0], temp[1], temp[2], 2, 0, 2);
905                         force[1] = -1.0f + 2.0f * BLI_gTurbulence(pd->f_size, temp[1], temp[2], temp[0], 2, 0, 2);
906                         force[2] = -1.0f + 2.0f * BLI_gTurbulence(pd->f_size, temp[2], temp[0], temp[1], 2, 0, 2);
907                         mul_v3_fl(force, strength * efd->falloff);
908                         break;
909                 case PFIELD_DRAG:
910                         copy_v3_v3(force, point->vel);
911                         fac = normalize_v3(force) * point->vel_to_sec;
912
913                         strength = MIN2(strength, 2.0f);
914                         damp = MIN2(damp, 2.0f);
915
916                         mul_v3_fl(force, -efd->falloff * fac * (strength * fac + damp));
917                         break;
918                 case PFIELD_SMOKEFLOW:
919                         zero_v3(force);
920                         if (pd->f_source) {
921                                 float density;
922                                 if ((density = smoke_get_velocity_at(pd->f_source, point->loc, force)) >= 0.0f) {
923                                         float influence = strength * efd->falloff;
924                                         if (pd->flag & PFIELD_SMOKE_DENSITY)
925                                                 influence *= density;
926                                         mul_v3_fl(force, influence);
927                                         /* apply flow */
928                                         madd_v3_v3fl(total_force, point->vel, -pd->f_flow * influence);
929                                 }
930                         }
931                         break;
932
933         }
934
935         if (pd->flag & PFIELD_DO_LOCATION) {
936                 madd_v3_v3fl(total_force, force, 1.0f/point->vel_to_sec);
937
938                 if (ELEM(pd->forcefield, PFIELD_HARMONIC, PFIELD_DRAG, PFIELD_SMOKEFLOW)==0 && pd->f_flow != 0.0f) {
939                         madd_v3_v3fl(total_force, point->vel, -pd->f_flow * efd->falloff);
940                 }
941         }
942
943         if (point->ave)
944                 zero_v3(point->ave);
945         if (pd->flag & PFIELD_DO_ROTATION && point->ave && point->rot) {
946                 float xvec[3] = {1.0f, 0.0f, 0.0f};
947                 float dave[3];
948                 mul_qt_v3(point->rot, xvec);
949                 cross_v3_v3v3(dave, xvec, force);
950                 if (pd->f_flow != 0.0f) {
951                         madd_v3_v3fl(dave, point->ave, -pd->f_flow * efd->falloff);
952                 }
953                 add_v3_v3(point->ave, dave);
954         }
955 }
956
957 /*  -------- pdDoEffectors() --------
958  * generic force/speed system, now used for particles and softbodies
959  * scene       = scene where it runs in, for time and stuff
960  * lb                   = listbase with objects that take part in effecting
961  * opco         = global coord, as input
962  * force                = force accumulator
963  * speed                = actual current speed which can be altered
964  * cur_time     = "external" time in frames, is constant for static particles
965  * loc_time     = "local" time in frames, range <0-1> for the lifetime of particle
966  * par_layer    = layer the caller is in
967  * flags                = only used for softbody wind now
968  * guide                = old speed of particle
969  */
970 void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *weights, EffectedPoint *point, float *force, float *impulse)
971 {
972 /*
973  * Modifies the force on a particle according to its
974  * relation with the effector object
975  * Different kind of effectors include:
976  *     Forcefields: Gravity-like attractor
977  *     (force power is related to the inverse of distance to the power of a falloff value)
978  *     Vortex fields: swirling effectors
979  *     (particles rotate around Z-axis of the object. otherwise, same relation as)
980  *     (Forcefields, but this is not done through a force/acceleration)
981  *     Guide: particles on a path
982  *     (particles are guided along a curve bezier or old nurbs)
983  *     (is independent of other effectors)
984  */
985         EffectorCache *eff;
986         EffectorData efd;
987         int p=0, tot = 1, step = 1;
988
989         /* Cycle through collected objects, get total of (1/(gravity_strength * dist^gravity_power)) */
990         /* Check for min distance here? (yes would be cool to add that, ton) */
991         
992         if (effectors) for (eff = effectors->first; eff; eff=eff->next) {
993                 /* object effectors were fully checked to be OK to evaluate! */
994
995                 get_effector_tot(eff, &efd, point, &tot, &p, &step);
996
997                 for (; p<tot; p+=step) {
998                         if (get_effector_data(eff, &efd, point, 0)) {
999                                 efd.falloff= effector_falloff(eff, &efd, point, weights);
1000                                 
1001                                 if (efd.falloff > 0.0f)
1002                                         efd.falloff *= eff_calc_visibility(colliders, eff, &efd, point);
1003
1004                                 if (efd.falloff <= 0.0f) {
1005                                         /* don't do anything */
1006                                 }
1007                                 else if (eff->pd->forcefield == PFIELD_TEXTURE) {
1008                                         do_texture_effector(eff, &efd, point, force);
1009                                 }
1010                                 else {
1011                                         float temp1[3] = {0, 0, 0}, temp2[3];
1012                                         copy_v3_v3(temp1, force);
1013
1014                                         do_physical_effector(eff, &efd, point, force);
1015                                         
1016                                         /* for softbody backward compatibility */
1017                                         if (point->flag & PE_WIND_AS_SPEED && impulse) {
1018                                                 sub_v3_v3v3(temp2, force, temp1);
1019                                                 sub_v3_v3v3(impulse, impulse, temp2);
1020                                         }
1021                                 }
1022                         }
1023                         else if (eff->flag & PE_VELOCITY_TO_IMPULSE && impulse) {
1024                                 /* special case for harmonic effector */
1025                                 add_v3_v3v3(impulse, impulse, efd.vel);
1026                         }
1027                 }
1028         }
1029 }
1030
1031 /* ======== Simulation Debugging ======== */
1032
1033 SimDebugData *_sim_debug_data = NULL;
1034
1035 unsigned int BKE_sim_debug_data_hash(int i)
1036 {
1037         return BLI_ghashutil_uinthash((unsigned int)i);
1038 }
1039
1040 unsigned int BKE_sim_debug_data_hash_combine(unsigned int kx, unsigned int ky)
1041 {
1042 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
1043
1044         unsigned int a, b, c;
1045
1046         a = b = c = 0xdeadbeef + (2 << 2) + 13;
1047         a += kx;
1048         b += ky;
1049
1050         c ^= b; c -= rot(b,14);
1051         a ^= c; a -= rot(c,11);
1052         b ^= a; b -= rot(a,25);
1053         c ^= b; c -= rot(b,16);
1054         a ^= c; a -= rot(c,4);
1055         b ^= a; b -= rot(a,14);
1056         c ^= b; c -= rot(b,24);
1057
1058         return c;
1059
1060 #undef rot
1061 }
1062
1063 static unsigned int debug_element_hash(const void *key)
1064 {
1065         const SimDebugElement *elem = key;
1066         return elem->hash;
1067 }
1068
1069 static bool debug_element_compare(const void *a, const void *b)
1070 {
1071         const SimDebugElement *elem1 = a;
1072         const SimDebugElement *elem2 = b;
1073
1074         if (elem1->hash == elem2->hash) {
1075                 return 0;
1076         }
1077         return 1;
1078 }
1079
1080 static void debug_element_free(void *val)
1081 {
1082         SimDebugElement *elem = val;
1083         MEM_freeN(elem);
1084 }
1085
1086 void BKE_sim_debug_data_set_enabled(bool enable)
1087 {
1088         if (enable) {
1089                 if (!_sim_debug_data) {
1090                         _sim_debug_data = MEM_callocN(sizeof(SimDebugData), "sim debug data");
1091                         _sim_debug_data->gh = BLI_ghash_new(debug_element_hash, debug_element_compare, "sim debug element hash");
1092                 }
1093         }
1094         else {
1095                 BKE_sim_debug_data_free();
1096         }
1097 }
1098
1099 bool BKE_sim_debug_data_get_enabled(void)
1100 {
1101         return _sim_debug_data != NULL;
1102 }
1103
1104 void BKE_sim_debug_data_free(void)
1105 {
1106         if (_sim_debug_data) {
1107                 if (_sim_debug_data->gh)
1108                         BLI_ghash_free(_sim_debug_data->gh, NULL, debug_element_free);
1109                 MEM_freeN(_sim_debug_data);
1110         }
1111 }
1112
1113 static void debug_data_insert(SimDebugData *debug_data, SimDebugElement *elem)
1114 {
1115         SimDebugElement *old_elem = BLI_ghash_lookup(debug_data->gh, elem);
1116         if (old_elem) {
1117                 *old_elem = *elem;
1118                 MEM_freeN(elem);
1119         }
1120         else
1121                 BLI_ghash_insert(debug_data->gh, elem, elem);
1122 }
1123
1124 void BKE_sim_debug_data_add_element(int type, const float v1[3], const float v2[3], float r, float g, float b, const char *category, unsigned int hash)
1125 {
1126         unsigned int category_hash = BLI_ghashutil_strhash_p(category);
1127         SimDebugElement *elem;
1128         
1129         if (!_sim_debug_data) {
1130                 if (G.debug & G_DEBUG_SIMDATA)
1131                         BKE_sim_debug_data_set_enabled(true);
1132                 else
1133                         return;
1134         }
1135         
1136         elem = MEM_callocN(sizeof(SimDebugElement), "sim debug data element");
1137         elem->type = type;
1138         elem->category_hash = category_hash;
1139         elem->hash = hash;
1140         elem->color[0] = r;
1141         elem->color[1] = g;
1142         elem->color[2] = b;
1143         copy_v3_v3(elem->v1, v1);
1144         copy_v3_v3(elem->v2, v2);
1145         
1146         debug_data_insert(_sim_debug_data, elem);
1147 }
1148
1149 void BKE_sim_debug_data_remove_element(unsigned int hash)
1150 {
1151         SimDebugElement dummy;
1152         if (!_sim_debug_data)
1153                 return;
1154         
1155         dummy.hash = hash;
1156         BLI_ghash_remove(_sim_debug_data->gh, &dummy, NULL, debug_element_free);
1157 }
1158
1159 void BKE_sim_debug_data_clear(void)
1160 {
1161         if (!_sim_debug_data)
1162                 return;
1163         
1164         if (_sim_debug_data->gh)
1165                 BLI_ghash_clear(_sim_debug_data->gh, NULL, debug_element_free);
1166 }
1167
1168 void BKE_sim_debug_data_clear_category(const char *category)
1169 {
1170         int category_hash = (int)BLI_ghashutil_strhash_p(category);
1171         
1172         if (!_sim_debug_data)
1173                 return;
1174         
1175         if (_sim_debug_data->gh) {
1176                 GHashIterator iter;
1177                 BLI_ghashIterator_init(&iter, _sim_debug_data->gh);
1178                 while (!BLI_ghashIterator_done(&iter)) {
1179                         SimDebugElement *elem = BLI_ghashIterator_getValue(&iter);
1180                         BLI_ghashIterator_step(&iter); /* removing invalidates the current iterator, so step before removing */
1181                         
1182                         if (elem->category_hash == category_hash)
1183                                 BLI_ghash_remove(_sim_debug_data->gh, elem, NULL, debug_element_free);
1184                 }
1185         }
1186 }