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