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