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