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