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