Fix T46249: Boid goal object that has a force field set to 'Every Point' shape causes...
[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         const int raycast_flag = BVH_RAYCAST_DEFAULT & ~(BVH_RAYCAST_WATERTIGHT);
395         ListBase *colls = colliders;
396         ColliderCache *col;
397         float norm[3], len = 0.0;
398         float visibility = 1.0, absorption = 0.0;
399         
400         if (!(eff->pd->flag & PFIELD_VISIBILITY))
401                 return visibility;
402
403         if (!colls)
404                 colls = get_collider_cache(eff->scene, eff->ob, NULL);
405
406         if (!colls)
407                 return visibility;
408
409         negate_v3_v3(norm, efd->vec_to_point);
410         len = normalize_v3(norm);
411         
412         /* check all collision objects */
413         for (col = colls->first; col; col = col->next) {
414                 CollisionModifierData *collmd = col->collmd;
415
416                 if (col->ob == eff->ob)
417                         continue;
418
419                 if (collmd->bvhtree) {
420                         BVHTreeRayHit hit;
421
422                         hit.index = -1;
423                         hit.dist = len + FLT_EPSILON;
424
425                         /* check if the way is blocked */
426                         if (BLI_bvhtree_ray_cast_ex(
427                                 collmd->bvhtree, point->loc, norm, 0.0f, &hit,
428                                 eff_tri_ray_hit, NULL, raycast_flag) != -1)
429                         {
430                                 absorption= col->ob->pd->absorption;
431
432                                 /* visibility is only between 0 and 1, calculated from 1-absorption */
433                                 visibility *= CLAMPIS(1.0f-absorption, 0.0f, 1.0f);
434                                 
435                                 if (visibility <= 0.0f)
436                                         break;
437                         }
438                 }
439         }
440
441         if (!colliders)
442                 free_collider_cache(&colls);
443         
444         return visibility;
445 }
446
447 // noise function for wind e.g.
448 static float wind_func(struct RNG *rng, float strength)
449 {
450         int random = (BLI_rng_get_int(rng)+1) % 128; // max 2357
451         float force = BLI_rng_get_float(rng) + 1.0f;
452         float ret;
453         float sign = 0;
454         
455         sign = ((float)random > 64.0f) ? 1.0f: -1.0f; // dividing by 2 is not giving equal sign distribution
456         
457         ret = sign*((float)random / force)*strength/128.0f;
458         
459         return ret;
460 }
461
462 /* maxdist: zero effect from this distance outwards (if usemax) */
463 /* mindist: full effect up to this distance (if usemin) */
464 /* power: falloff with formula 1/r^power */
465 static float falloff_func(float fac, int usemin, float mindist, int usemax, float maxdist, float power)
466 {
467         /* first quick checks */
468         if (usemax && fac > maxdist)
469                 return 0.0f;
470
471         if (usemin && fac < mindist)
472                 return 1.0f;
473
474         if (!usemin)
475                 mindist = 0.0;
476
477         return pow((double)(1.0f+fac-mindist), (double)(-power));
478 }
479
480 static float falloff_func_dist(PartDeflect *pd, float fac)
481 {
482         return falloff_func(fac, pd->flag&PFIELD_USEMIN, pd->mindist, pd->flag&PFIELD_USEMAX, pd->maxdist, pd->f_power);
483 }
484
485 static float falloff_func_rad(PartDeflect *pd, float fac)
486 {
487         return falloff_func(fac, pd->flag&PFIELD_USEMINR, pd->minrad, pd->flag&PFIELD_USEMAXR, pd->maxrad, pd->f_power_r);
488 }
489
490 float effector_falloff(EffectorCache *eff, EffectorData *efd, EffectedPoint *UNUSED(point), EffectorWeights *weights)
491 {
492         float temp[3];
493         float falloff = weights ? weights->weight[0] * weights->weight[eff->pd->forcefield] : 1.0f;
494         float fac, r_fac;
495
496         fac = dot_v3v3(efd->nor, efd->vec_to_point2);
497
498         if (eff->pd->zdir == PFIELD_Z_POS && fac < 0.0f)
499                 falloff=0.0f;
500         else if (eff->pd->zdir == PFIELD_Z_NEG && fac > 0.0f)
501                 falloff=0.0f;
502         else {
503                 switch (eff->pd->falloff) {
504                 case PFIELD_FALL_SPHERE:
505                         falloff*= falloff_func_dist(eff->pd, efd->distance);
506                         break;
507
508                 case PFIELD_FALL_TUBE:
509                         falloff*= falloff_func_dist(eff->pd, ABS(fac));
510                         if (falloff == 0.0f)
511                                 break;
512
513                         madd_v3_v3v3fl(temp, efd->vec_to_point2, efd->nor, -fac);
514                         r_fac= len_v3(temp);
515                         falloff*= falloff_func_rad(eff->pd, r_fac);
516                         break;
517                 case PFIELD_FALL_CONE:
518                         falloff*= falloff_func_dist(eff->pd, ABS(fac));
519                         if (falloff == 0.0f)
520                                 break;
521
522                         r_fac= RAD2DEGF(saacos(fac/len_v3(efd->vec_to_point)));
523                         falloff*= falloff_func_rad(eff->pd, r_fac);
524
525                         break;
526                 }
527         }
528
529         return falloff;
530 }
531
532 int closest_point_on_surface(SurfaceModifierData *surmd, const float co[3], float surface_co[3], float surface_nor[3], float surface_vel[3])
533 {
534         BVHTreeNearest nearest;
535
536         nearest.index = -1;
537         nearest.dist_sq = FLT_MAX;
538
539         BLI_bvhtree_find_nearest(surmd->bvhtree->tree, co, &nearest, surmd->bvhtree->nearest_callback, surmd->bvhtree);
540
541         if (nearest.index != -1) {
542                 copy_v3_v3(surface_co, nearest.co);
543
544                 if (surface_nor) {
545                         copy_v3_v3(surface_nor, nearest.no);
546                 }
547
548                 if (surface_vel) {
549                         const MLoop *mloop = surmd->bvhtree->loop;
550                         const MLoopTri *lt = &surmd->bvhtree->looptri[nearest.index];
551                         
552                         copy_v3_v3(surface_vel, surmd->v[mloop[lt->tri[0]].v].co);
553                         add_v3_v3(surface_vel, surmd->v[mloop[lt->tri[1]].v].co);
554                         add_v3_v3(surface_vel, surmd->v[mloop[lt->tri[2]].v].co);
555
556                         mul_v3_fl(surface_vel, (1.0f / 3.0f));
557                 }
558                 return 1;
559         }
560
561         return 0;
562 }
563 int get_effector_data(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, int real_velocity)
564 {
565         float cfra = eff->scene->r.cfra;
566         int ret = 0;
567
568         if (eff->pd && eff->pd->shape==PFIELD_SHAPE_SURFACE && eff->surmd) {
569                 /* closest point in the object surface is an effector */
570                 float vec[3];
571
572                 /* using velocity corrected location allows for easier sliding over effector surface */
573                 copy_v3_v3(vec, point->vel);
574                 mul_v3_fl(vec, point->vel_to_frame);
575                 add_v3_v3(vec, point->loc);
576
577                 ret = closest_point_on_surface(eff->surmd, vec, efd->loc, efd->nor, real_velocity ? efd->vel : NULL);
578
579                 efd->size = 0.0f;
580         }
581         else if (eff->pd && eff->pd->shape==PFIELD_SHAPE_POINTS) {
582
583                 if (eff->ob->derivedFinal) {
584                         DerivedMesh *dm = eff->ob->derivedFinal;
585
586                         dm->getVertCo(dm, *efd->index, efd->loc);
587                         dm->getVertNo(dm, *efd->index, efd->nor);
588
589                         mul_m4_v3(eff->ob->obmat, efd->loc);
590                         mul_mat3_m4_v3(eff->ob->obmat, efd->nor);
591
592                         normalize_v3(efd->nor);
593
594                         efd->size = 0.0f;
595
596                         /**/
597                         ret = 1;
598                 }
599         }
600         else if (eff->psys) {
601                 ParticleData *pa = eff->psys->particles + *efd->index;
602                 ParticleKey state;
603
604                 /* exclude the particle itself for self effecting particles */
605                 if (eff->psys == point->psys && *efd->index == point->index) {
606                         /* pass */
607                 }
608                 else {
609                         ParticleSimulationData sim= {NULL};
610                         sim.scene= eff->scene;
611                         sim.ob= eff->ob;
612                         sim.psys= eff->psys;
613
614                         /* TODO: time from actual previous calculated frame (step might not be 1) */
615                         state.time = cfra - 1.0f;
616                         ret = psys_get_particle_state(&sim, *efd->index, &state, 0);
617
618                         /* TODO */
619                         //if (eff->pd->forcefiled == PFIELD_HARMONIC && ret==0) {
620                         //      if (pa->dietime < eff->psys->cfra)
621                         //              eff->flag |= PE_VELOCITY_TO_IMPULSE;
622                         //}
623
624                         copy_v3_v3(efd->loc, state.co);
625
626                         /* rather than use the velocity use rotated x-axis (defaults to velocity) */
627                         efd->nor[0] = 1.f;
628                         efd->nor[1] = efd->nor[2] = 0.f;
629                         mul_qt_v3(state.rot, efd->nor);
630                 
631                         if (real_velocity)
632                                 copy_v3_v3(efd->vel, state.vel);
633
634                         efd->size = pa->size;
635                 }
636         }
637         else {
638                 /* use center of object for distance calculus */
639                 const Object *ob = eff->ob;
640
641                 /* use z-axis as normal*/
642                 normalize_v3_v3(efd->nor, ob->obmat[2]);
643
644                 if (eff->pd && eff->pd->shape == PFIELD_SHAPE_PLANE) {
645                         float temp[3], translate[3];
646                         sub_v3_v3v3(temp, point->loc, ob->obmat[3]);
647                         project_v3_v3v3(translate, temp, efd->nor);
648
649                         /* for vortex the shape chooses between old / new force */
650                         if (eff->pd->forcefield == PFIELD_VORTEX)
651                                 add_v3_v3v3(efd->loc, ob->obmat[3], translate);
652                         else /* normally efd->loc is closest point on effector xy-plane */
653                                 sub_v3_v3v3(efd->loc, point->loc, translate);
654                 }
655                 else {
656                         copy_v3_v3(efd->loc, ob->obmat[3]);
657                 }
658
659                 if (real_velocity)
660                         copy_v3_v3(efd->vel, eff->velocity);
661
662                 efd->size = 0.0f;
663
664                 ret = 1;
665         }
666
667         if (ret) {
668                 sub_v3_v3v3(efd->vec_to_point, point->loc, efd->loc);
669                 efd->distance = len_v3(efd->vec_to_point);
670
671                 /* rest length for harmonic effector, will have to see later if this could be extended to other effectors */
672                 if (eff->pd && eff->pd->forcefield == PFIELD_HARMONIC && eff->pd->f_size)
673                         mul_v3_fl(efd->vec_to_point, (efd->distance-eff->pd->f_size)/efd->distance);
674
675                 if (eff->flag & PE_USE_NORMAL_DATA) {
676                         copy_v3_v3(efd->vec_to_point2, efd->vec_to_point);
677                         copy_v3_v3(efd->nor2, efd->nor);
678                 }
679                 else {
680                         /* for some effectors we need the object center every time */
681                         sub_v3_v3v3(efd->vec_to_point2, point->loc, eff->ob->obmat[3]);
682                         normalize_v3_v3(efd->nor2, eff->ob->obmat[2]);
683                 }
684         }
685
686         return ret;
687 }
688 static void get_effector_tot(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, int *tot, int *p, int *step)
689 {
690         *p = 0;
691         efd->index = p;
692
693         if (eff->pd->shape == PFIELD_SHAPE_POINTS) {
694                 *tot = eff->ob->derivedFinal ? eff->ob->derivedFinal->numVertData : 1;
695
696                 if (*tot && eff->pd->forcefield == PFIELD_HARMONIC && point->index >= 0) {
697                         *p = point->index % *tot;
698                         *tot = *p+1;
699                 }
700         }
701         else if (eff->psys) {
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                 *tot = 1;
728         }
729 }
730 static void do_texture_effector(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, float *total_force)
731 {
732         TexResult result[4];
733         float tex_co[3], strength, force[3];
734         float nabla = eff->pd->tex_nabla;
735         int hasrgb;
736         short mode = eff->pd->tex_mode;
737         bool scene_color_manage;
738
739         if (!eff->pd->tex)
740                 return;
741
742         result[0].nor = result[1].nor = result[2].nor = result[3].nor = NULL;
743
744         strength= eff->pd->f_strength * efd->falloff;
745
746         copy_v3_v3(tex_co, point->loc);
747
748         if (eff->pd->flag & PFIELD_TEX_2D) {
749                 float fac=-dot_v3v3(tex_co, efd->nor);
750                 madd_v3_v3fl(tex_co, efd->nor, fac);
751         }
752
753         if (eff->pd->flag & PFIELD_TEX_OBJECT) {
754                 mul_m4_v3(eff->ob->imat, tex_co);
755         }
756
757         scene_color_manage = BKE_scene_check_color_management_enabled(eff->scene);
758
759         hasrgb = multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 0, result, NULL, scene_color_manage, false);
760
761         if (hasrgb && mode==PFIELD_TEX_RGB) {
762                 force[0] = (0.5f - result->tr) * strength;
763                 force[1] = (0.5f - result->tg) * strength;
764                 force[2] = (0.5f - result->tb) * strength;
765         }
766         else {
767                 strength/=nabla;
768
769                 tex_co[0] += nabla;
770                 multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 0, result+1, NULL, scene_color_manage, false);
771
772                 tex_co[0] -= nabla;
773                 tex_co[1] += nabla;
774                 multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 0, result+2, NULL, scene_color_manage, false);
775
776                 tex_co[1] -= nabla;
777                 tex_co[2] += nabla;
778                 multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 0, result+3, NULL, scene_color_manage, false);
779
780                 if (mode == PFIELD_TEX_GRAD || !hasrgb) { /* if we don't have rgb fall back to grad */
781                         /* generate intensity if texture only has rgb value */
782                         if (hasrgb & TEX_RGB) {
783                                 int i;
784                                 for (i=0; i<4; i++)
785                                         result[i].tin = (1.0f / 3.0f) * (result[i].tr + result[i].tg + result[i].tb);
786                         }
787                         force[0] = (result[0].tin - result[1].tin) * strength;
788                         force[1] = (result[0].tin - result[2].tin) * strength;
789                         force[2] = (result[0].tin - result[3].tin) * strength;
790                 }
791                 else { /*PFIELD_TEX_CURL*/
792                         float dbdy, dgdz, drdz, dbdx, dgdx, drdy;
793
794                         dbdy = result[2].tb - result[0].tb;
795                         dgdz = result[3].tg - result[0].tg;
796                         drdz = result[3].tr - result[0].tr;
797                         dbdx = result[1].tb - result[0].tb;
798                         dgdx = result[1].tg - result[0].tg;
799                         drdy = result[2].tr - result[0].tr;
800
801                         force[0] = (dbdy - dgdz) * strength;
802                         force[1] = (drdz - dbdx) * strength;
803                         force[2] = (dgdx - drdy) * strength;
804                 }
805         }
806
807         if (eff->pd->flag & PFIELD_TEX_2D) {
808                 float fac = -dot_v3v3(force, efd->nor);
809                 madd_v3_v3fl(force, efd->nor, fac);
810         }
811
812         add_v3_v3(total_force, force);
813 }
814 static void do_physical_effector(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, float *total_force)
815 {
816         PartDeflect *pd = eff->pd;
817         RNG *rng = pd->rng;
818         float force[3] = {0, 0, 0};
819         float temp[3];
820         float fac;
821         float strength = pd->f_strength;
822         float damp = pd->f_damp;
823         float noise_factor = pd->f_noise;
824
825         if (noise_factor > 0.0f) {
826                 strength += wind_func(rng, noise_factor);
827
828                 if (ELEM(pd->forcefield, PFIELD_HARMONIC, PFIELD_DRAG))
829                         damp += wind_func(rng, noise_factor);
830         }
831
832         copy_v3_v3(force, efd->vec_to_point);
833
834         switch (pd->forcefield) {
835                 case PFIELD_WIND:
836                         copy_v3_v3(force, efd->nor);
837                         mul_v3_fl(force, strength * efd->falloff);
838                         break;
839                 case PFIELD_FORCE:
840                         normalize_v3(force);
841                         mul_v3_fl(force, strength * efd->falloff);
842                         break;
843                 case PFIELD_VORTEX:
844                         /* old vortex force */
845                         if (pd->shape == PFIELD_SHAPE_POINT) {
846                                 cross_v3_v3v3(force, efd->nor, efd->vec_to_point);
847                                 normalize_v3(force);
848                                 mul_v3_fl(force, strength * efd->distance * efd->falloff);
849                         }
850                         else {
851                                 /* new vortex force */
852                                 cross_v3_v3v3(temp, efd->nor2, efd->vec_to_point2);
853                                 mul_v3_fl(temp, strength * efd->falloff);
854                                 
855                                 cross_v3_v3v3(force, efd->nor2, temp);
856                                 mul_v3_fl(force, strength * efd->falloff);
857                                 
858                                 madd_v3_v3fl(temp, point->vel, -point->vel_to_sec);
859                                 add_v3_v3(force, temp);
860                         }
861                         break;
862                 case PFIELD_MAGNET:
863                         if (eff->pd->shape == PFIELD_SHAPE_POINT)
864                                 /* magnetic field of a moving charge */
865                                 cross_v3_v3v3(temp, efd->nor, efd->vec_to_point);
866                         else
867                                 copy_v3_v3(temp, efd->nor);
868
869                         normalize_v3(temp);
870                         mul_v3_fl(temp, strength * efd->falloff);
871                         cross_v3_v3v3(force, point->vel, temp);
872                         mul_v3_fl(force, point->vel_to_sec);
873                         break;
874                 case PFIELD_HARMONIC:
875                         mul_v3_fl(force, -strength * efd->falloff);
876                         copy_v3_v3(temp, point->vel);
877                         mul_v3_fl(temp, -damp * 2.0f * sqrtf(fabsf(strength)) * point->vel_to_sec);
878                         add_v3_v3(force, temp);
879                         break;
880                 case PFIELD_CHARGE:
881                         mul_v3_fl(force, point->charge * strength * efd->falloff);
882                         break;
883                 case PFIELD_LENNARDJ:
884                         fac = pow((efd->size + point->size) / efd->distance, 6.0);
885                         
886                         fac = - fac * (1.0f - fac) / efd->distance;
887
888                         /* limit the repulsive term drastically to avoid huge forces */
889                         fac = ((fac>2.0f) ? 2.0f : fac);
890
891                         mul_v3_fl(force, strength * fac);
892                         break;
893                 case PFIELD_BOID:
894                         /* Boid field is handled completely in boids code. */
895                         return;
896                 case PFIELD_TURBULENCE:
897                         if (pd->flag & PFIELD_GLOBAL_CO) {
898                                 copy_v3_v3(temp, point->loc);
899                         }
900                         else {
901                                 add_v3_v3v3(temp, efd->vec_to_point2, efd->nor2);
902                         }
903                         force[0] = -1.0f + 2.0f * BLI_gTurbulence(pd->f_size, temp[0], temp[1], temp[2], 2, 0, 2);
904                         force[1] = -1.0f + 2.0f * BLI_gTurbulence(pd->f_size, temp[1], temp[2], temp[0], 2, 0, 2);
905                         force[2] = -1.0f + 2.0f * BLI_gTurbulence(pd->f_size, temp[2], temp[0], temp[1], 2, 0, 2);
906                         mul_v3_fl(force, strength * efd->falloff);
907                         break;
908                 case PFIELD_DRAG:
909                         copy_v3_v3(force, point->vel);
910                         fac = normalize_v3(force) * point->vel_to_sec;
911
912                         strength = MIN2(strength, 2.0f);
913                         damp = MIN2(damp, 2.0f);
914
915                         mul_v3_fl(force, -efd->falloff * fac * (strength * fac + damp));
916                         break;
917                 case PFIELD_SMOKEFLOW:
918                         zero_v3(force);
919                         if (pd->f_source) {
920                                 float density;
921                                 if ((density = smoke_get_velocity_at(pd->f_source, point->loc, force)) >= 0.0f) {
922                                         float influence = strength * efd->falloff;
923                                         if (pd->flag & PFIELD_SMOKE_DENSITY)
924                                                 influence *= density;
925                                         mul_v3_fl(force, influence);
926                                         /* apply flow */
927                                         madd_v3_v3fl(total_force, point->vel, -pd->f_flow * influence);
928                                 }
929                         }
930                         break;
931
932         }
933
934         if (pd->flag & PFIELD_DO_LOCATION) {
935                 madd_v3_v3fl(total_force, force, 1.0f/point->vel_to_sec);
936
937                 if (ELEM(pd->forcefield, PFIELD_HARMONIC, PFIELD_DRAG, PFIELD_SMOKEFLOW)==0 && pd->f_flow != 0.0f) {
938                         madd_v3_v3fl(total_force, point->vel, -pd->f_flow * efd->falloff);
939                 }
940         }
941
942         if (point->ave)
943                 zero_v3(point->ave);
944         if (pd->flag & PFIELD_DO_ROTATION && point->ave && point->rot) {
945                 float xvec[3] = {1.0f, 0.0f, 0.0f};
946                 float dave[3];
947                 mul_qt_v3(point->rot, xvec);
948                 cross_v3_v3v3(dave, xvec, force);
949                 if (pd->f_flow != 0.0f) {
950                         madd_v3_v3fl(dave, point->ave, -pd->f_flow * efd->falloff);
951                 }
952                 add_v3_v3(point->ave, dave);
953         }
954 }
955
956 /*  -------- pdDoEffectors() --------
957  * generic force/speed system, now used for particles and softbodies
958  * scene       = scene where it runs in, for time and stuff
959  * lb                   = listbase with objects that take part in effecting
960  * opco         = global coord, as input
961  * force                = force accumulator
962  * speed                = actual current speed which can be altered
963  * cur_time     = "external" time in frames, is constant for static particles
964  * loc_time     = "local" time in frames, range <0-1> for the lifetime of particle
965  * par_layer    = layer the caller is in
966  * flags                = only used for softbody wind now
967  * guide                = old speed of particle
968  */
969 void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *weights, EffectedPoint *point, float *force, float *impulse)
970 {
971 /*
972  * Modifies the force on a particle according to its
973  * relation with the effector object
974  * Different kind of effectors include:
975  *     Forcefields: Gravity-like attractor
976  *     (force power is related to the inverse of distance to the power of a falloff value)
977  *     Vortex fields: swirling effectors
978  *     (particles rotate around Z-axis of the object. otherwise, same relation as)
979  *     (Forcefields, but this is not done through a force/acceleration)
980  *     Guide: particles on a path
981  *     (particles are guided along a curve bezier or old nurbs)
982  *     (is independent of other effectors)
983  */
984         EffectorCache *eff;
985         EffectorData efd;
986         int p=0, tot = 1, step = 1;
987
988         /* Cycle through collected objects, get total of (1/(gravity_strength * dist^gravity_power)) */
989         /* Check for min distance here? (yes would be cool to add that, ton) */
990         
991         if (effectors) for (eff = effectors->first; eff; eff=eff->next) {
992                 /* object effectors were fully checked to be OK to evaluate! */
993
994                 get_effector_tot(eff, &efd, point, &tot, &p, &step);
995
996                 for (; p<tot; p+=step) {
997                         if (get_effector_data(eff, &efd, point, 0)) {
998                                 efd.falloff= effector_falloff(eff, &efd, point, weights);
999                                 
1000                                 if (efd.falloff > 0.0f)
1001                                         efd.falloff *= eff_calc_visibility(colliders, eff, &efd, point);
1002
1003                                 if (efd.falloff <= 0.0f) {
1004                                         /* don't do anything */
1005                                 }
1006                                 else if (eff->pd->forcefield == PFIELD_TEXTURE) {
1007                                         do_texture_effector(eff, &efd, point, force);
1008                                 }
1009                                 else {
1010                                         float temp1[3] = {0, 0, 0}, temp2[3];
1011                                         copy_v3_v3(temp1, force);
1012
1013                                         do_physical_effector(eff, &efd, point, force);
1014                                         
1015                                         /* for softbody backward compatibility */
1016                                         if (point->flag & PE_WIND_AS_SPEED && impulse) {
1017                                                 sub_v3_v3v3(temp2, force, temp1);
1018                                                 sub_v3_v3v3(impulse, impulse, temp2);
1019                                         }
1020                                 }
1021                         }
1022                         else if (eff->flag & PE_VELOCITY_TO_IMPULSE && impulse) {
1023                                 /* special case for harmonic effector */
1024                                 add_v3_v3v3(impulse, impulse, efd.vel);
1025                         }
1026                 }
1027         }
1028 }
1029
1030 /* ======== Simulation Debugging ======== */
1031
1032 SimDebugData *_sim_debug_data = NULL;
1033
1034 unsigned int BKE_sim_debug_data_hash(int i)
1035 {
1036         return BLI_ghashutil_uinthash((unsigned int)i);
1037 }
1038
1039 unsigned int BKE_sim_debug_data_hash_combine(unsigned int kx, unsigned int ky)
1040 {
1041 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
1042
1043         unsigned int a, b, c;
1044
1045         a = b = c = 0xdeadbeef + (2 << 2) + 13;
1046         a += kx;
1047         b += ky;
1048
1049         c ^= b; c -= rot(b,14);
1050         a ^= c; a -= rot(c,11);
1051         b ^= a; b -= rot(a,25);
1052         c ^= b; c -= rot(b,16);
1053         a ^= c; a -= rot(c,4);
1054         b ^= a; b -= rot(a,14);
1055         c ^= b; c -= rot(b,24);
1056
1057         return c;
1058
1059 #undef rot
1060 }
1061
1062 static unsigned int debug_element_hash(const void *key)
1063 {
1064         const SimDebugElement *elem = key;
1065         return elem->hash;
1066 }
1067
1068 static bool debug_element_compare(const void *a, const void *b)
1069 {
1070         const SimDebugElement *elem1 = a;
1071         const SimDebugElement *elem2 = b;
1072
1073         if (elem1->hash == elem2->hash) {
1074                 return 0;
1075         }
1076         return 1;
1077 }
1078
1079 static void debug_element_free(void *val)
1080 {
1081         SimDebugElement *elem = val;
1082         MEM_freeN(elem);
1083 }
1084
1085 void BKE_sim_debug_data_set_enabled(bool enable)
1086 {
1087         if (enable) {
1088                 if (!_sim_debug_data) {
1089                         _sim_debug_data = MEM_callocN(sizeof(SimDebugData), "sim debug data");
1090                         _sim_debug_data->gh = BLI_ghash_new(debug_element_hash, debug_element_compare, "sim debug element hash");
1091                 }
1092         }
1093         else {
1094                 BKE_sim_debug_data_free();
1095         }
1096 }
1097
1098 bool BKE_sim_debug_data_get_enabled(void)
1099 {
1100         return _sim_debug_data != NULL;
1101 }
1102
1103 void BKE_sim_debug_data_free(void)
1104 {
1105         if (_sim_debug_data) {
1106                 if (_sim_debug_data->gh)
1107                         BLI_ghash_free(_sim_debug_data->gh, NULL, debug_element_free);
1108                 MEM_freeN(_sim_debug_data);
1109         }
1110 }
1111
1112 static void debug_data_insert(SimDebugData *debug_data, SimDebugElement *elem)
1113 {
1114         SimDebugElement *old_elem = BLI_ghash_lookup(debug_data->gh, elem);
1115         if (old_elem) {
1116                 *old_elem = *elem;
1117                 MEM_freeN(elem);
1118         }
1119         else
1120                 BLI_ghash_insert(debug_data->gh, elem, elem);
1121 }
1122
1123 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)
1124 {
1125         unsigned int category_hash = BLI_ghashutil_strhash_p(category);
1126         SimDebugElement *elem;
1127         
1128         if (!_sim_debug_data) {
1129                 if (G.debug & G_DEBUG_SIMDATA)
1130                         BKE_sim_debug_data_set_enabled(true);
1131                 else
1132                         return;
1133         }
1134         
1135         elem = MEM_callocN(sizeof(SimDebugElement), "sim debug data element");
1136         elem->type = type;
1137         elem->category_hash = category_hash;
1138         elem->hash = hash;
1139         elem->color[0] = r;
1140         elem->color[1] = g;
1141         elem->color[2] = b;
1142         copy_v3_v3(elem->v1, v1);
1143         copy_v3_v3(elem->v2, v2);
1144         
1145         debug_data_insert(_sim_debug_data, elem);
1146 }
1147
1148 void BKE_sim_debug_data_remove_element(unsigned int hash)
1149 {
1150         SimDebugElement dummy;
1151         if (!_sim_debug_data)
1152                 return;
1153         
1154         dummy.hash = hash;
1155         BLI_ghash_remove(_sim_debug_data->gh, &dummy, NULL, debug_element_free);
1156 }
1157
1158 void BKE_sim_debug_data_clear(void)
1159 {
1160         if (!_sim_debug_data)
1161                 return;
1162         
1163         if (_sim_debug_data->gh)
1164                 BLI_ghash_clear(_sim_debug_data->gh, NULL, debug_element_free);
1165 }
1166
1167 void BKE_sim_debug_data_clear_category(const char *category)
1168 {
1169         int category_hash = (int)BLI_ghashutil_strhash_p(category);
1170         
1171         if (!_sim_debug_data)
1172                 return;
1173         
1174         if (_sim_debug_data->gh) {
1175                 GHashIterator iter;
1176                 BLI_ghashIterator_init(&iter, _sim_debug_data->gh);
1177                 while (!BLI_ghashIterator_done(&iter)) {
1178                         const SimDebugElement *elem = BLI_ghashIterator_getValue(&iter);
1179                         BLI_ghashIterator_step(&iter); /* removing invalidates the current iterator, so step before removing */
1180                         
1181                         if (elem->category_hash == category_hash)
1182                                 BLI_ghash_remove(_sim_debug_data->gh, elem, NULL, debug_element_free);
1183                 }
1184         }
1185 }