Unified effector functionality for particles, cloth and softbody
[blender-staging.git] / source / blender / blenkernel / intern / effect.c
1 /*  effect.c
2  * 
3  * 
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include "BLI_storage.h" /* _LARGEFILE_SOURCE */
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_arithb.h"
56 #include "BLI_blenlib.h"
57 #include "BLI_jitter.h"
58 #include "BLI_listbase.h"
59 #include "BLI_noise.h"
60 #include "BLI_rand.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 #include "BKE_screen.h"
89 #include "BKE_utildefines.h"
90
91 #include "RE_render_ext.h"
92 #include "RE_shader_ext.h"
93
94 /* fluid sim particle import */
95 #ifndef DISABLE_ELBEEM
96 #include "DNA_object_fluidsim.h"
97 #include "LBM_fluidsim.h"
98 #include <zlib.h>
99 #include <string.h>
100 #endif // DISABLE_ELBEEM
101
102 //XXX #include "BIF_screen.h"
103
104 EffectorWeights *BKE_add_effector_weights(Group *group)
105 {
106         EffectorWeights *weights = MEM_callocN(sizeof(EffectorWeights), "EffectorWeights");
107         int i;
108
109         for(i=0; i<NUM_PFIELD_TYPES; i++)
110                 weights->weight[i] = 1.0f;
111
112         weights->global_gravity = 1.0f;
113
114         weights->group = group;
115
116         return weights;
117 }
118 PartDeflect *object_add_collision_fields(int type)
119 {
120         PartDeflect *pd;
121
122         pd= MEM_callocN(sizeof(PartDeflect), "PartDeflect");
123
124         pd->forcefield = type;
125         pd->pdef_sbdamp = 0.1f;
126         pd->pdef_sbift  = 0.2f;
127         pd->pdef_sboft  = 0.02f;
128         pd->seed = ((unsigned int)(ceil(PIL_check_seconds_timer()))+1) % 128;
129         pd->f_strength = 1.0f;
130         pd->f_damp = 1.0f;
131         pd->f_size = 1.0f;
132
133         /* set sensible defaults based on type */
134         switch(type) {
135                 case PFIELD_VORTEX:
136                         pd->shape = PFIELD_SHAPE_PLANE;
137                         break;
138                 case PFIELD_WIND:
139                         pd->shape = PFIELD_SHAPE_PLANE;
140                         pd->f_flow = 1.0f; /* realistic wind behavior */
141                         break;
142         }
143         pd->flag = PFIELD_DO_LOCATION|PFIELD_DO_ROTATION;
144
145         return pd;
146 }
147
148 /* temporal struct, used for reading return of mesh_get_mapped_verts_nors() */
149
150 typedef struct VeNoCo {
151         float co[3], no[3];
152 } VeNoCo;
153
154 /* ***************** PARTICLES ***************** */
155
156 /* deprecated, only keep this for readfile.c */
157 PartEff *give_parteff(Object *ob)
158 {
159         PartEff *paf;
160         
161         paf= ob->effect.first;
162         while(paf) {
163                 if(paf->type==EFF_PARTICLE) return paf;
164                 paf= paf->next;
165         }
166         return 0;
167 }
168
169 void free_effect(Effect *eff)
170 {
171         PartEff *paf;
172         
173         if(eff->type==EFF_PARTICLE) {
174                 paf= (PartEff *)eff;
175                 if(paf->keys) MEM_freeN(paf->keys);
176         }
177         MEM_freeN(eff); 
178 }
179
180
181 void free_effects(ListBase *lb)
182 {
183         Effect *eff;
184         
185         eff= lb->first;
186         while(eff) {
187                 BLI_remlink(lb, eff);
188                 free_effect(eff);
189                 eff= lb->first;
190         }
191 }
192
193 /* -------------------------- Effectors ------------------ */
194 void free_partdeflect(PartDeflect *pd)
195 {
196         if(!pd)
197                 return;
198
199         if(pd->tex)
200                 pd->tex->id.us--;
201
202         if(pd->rng)
203                 rng_free(pd->rng);
204
205         MEM_freeN(pd);
206 }
207
208 static void precalculate_effector(EffectorCache *eff)
209 {
210         unsigned int cfra = (unsigned int)(eff->scene->r.cfra >= 0 ? eff->scene->r.cfra : -eff->scene->r.cfra);
211         if(!eff->pd->rng)
212                 eff->pd->rng = rng_new(eff->pd->seed + cfra);
213         else
214                 rng_srandom(eff->pd->rng, eff->pd->seed + cfra);
215
216         if(eff->pd->forcefield == PFIELD_GUIDE && eff->ob->type==OB_CURVE) {
217                 Curve *cu= eff->ob->data;
218                 if(cu->flag & CU_PATH) {
219                         if(cu->path==NULL || cu->path->data==NULL)
220                                 makeDispListCurveTypes(eff->scene, eff->ob, 0);
221
222                         if(cu->path && cu->path->data) {
223                                 where_on_path(eff->ob, 0.0, eff->guide_loc, eff->guide_dir, NULL, &eff->guide_radius);
224                                 Mat4MulVecfl(eff->ob->obmat, eff->guide_loc);
225                                 Mat4Mul3Vecfl(eff->ob->obmat, eff->guide_dir);
226                         }
227                 }
228         }
229         else if(eff->pd->shape == PFIELD_SHAPE_SURFACE) {
230                 eff->surmd = (SurfaceModifierData *)modifiers_findByType ( eff->ob, eModifierType_Surface );
231         }
232         else if(eff->psys)
233                 psys_update_particle_tree(eff->psys, eff->scene->r.cfra);
234 }
235 static EffectorCache *new_effector_cache(Scene *scene, Object *ob, ParticleSystem *psys, PartDeflect *pd)
236 {
237         EffectorCache *eff = MEM_callocN(sizeof(EffectorCache), "EffectorCache");
238         eff->scene = scene;
239         eff->ob = ob;
240         eff->psys = psys;
241         eff->pd = pd;
242         eff->frame = -1;
243
244         precalculate_effector(eff);
245
246         return eff;
247 }
248 static void add_object_to_effectors(ListBase **effectors, Scene *scene, EffectorWeights *weights, Object *ob, Object *ob_src)
249 {
250         EffectorCache *eff = NULL;
251
252         if( ob == ob_src || weights->weight[ob->pd->forcefield] == 0.0f )
253                 return;
254
255         if (ob->pd->shape == PFIELD_SHAPE_POINTS && !ob->derivedFinal )
256                 return;
257
258         if(*effectors == NULL)
259                 *effectors = MEM_callocN(sizeof(ListBase), "effectors list");
260
261         eff = new_effector_cache(scene, ob, NULL, ob->pd);
262
263         BLI_addtail(*effectors, eff);
264 }
265 static void add_particles_to_effectors(ListBase **effectors, Scene *scene, EffectorWeights *weights, Object *ob, ParticleSystem *psys, ParticleSystem *psys_src)
266 {
267         ParticleSettings *part= psys->part;
268
269         if( !psys_check_enabled(ob, psys) )
270                 return;
271
272         if( psys == psys_src && (part->flag & PART_SELF_EFFECT) == 0)
273                 return;
274
275         if( part->pd && part->pd->forcefield && weights->weight[part->pd->forcefield] != 0.0f) {
276                 if(*effectors == NULL)
277                         *effectors = MEM_callocN(sizeof(ListBase), "effectors list");
278
279                 BLI_addtail(*effectors, new_effector_cache(scene, ob, psys, part->pd));
280         }
281
282         if (part->pd2 && part->pd2->forcefield && weights->weight[part->pd2->forcefield] != 0.0f) {
283                 if(*effectors == NULL)
284                         *effectors = MEM_callocN(sizeof(ListBase), "effectors list");
285
286                 BLI_addtail(*effectors, new_effector_cache(scene, ob, psys, part->pd2));
287         }
288 }
289
290 /* returns ListBase handle with objects taking part in the effecting */
291 ListBase *pdInitEffectors(Scene *scene, Object *ob_src, ParticleSystem *psys_src, EffectorWeights *weights)
292 {
293         Base *base;
294         unsigned int layer= ob_src->lay;
295         ListBase *effectors = NULL;
296         
297         if(weights->group) {
298                 GroupObject *go;
299                 
300                 for(go= weights->group->gobject.first; go; go= go->next) {
301                         if( (go->ob->lay & layer) ) {
302                                 if( go->ob->pd && go->ob->pd->forcefield )
303                                         add_object_to_effectors(&effectors, scene, weights, go->ob, ob_src);
304
305                                 if( go->ob->particlesystem.first ) {
306                                         ParticleSystem *psys= go->ob->particlesystem.first;
307
308                                         for( ; psys; psys=psys->next )
309                                                 add_particles_to_effectors(&effectors, scene, weights, go->ob, psys, psys_src);
310                                 }
311                         }
312                 }
313         }
314         else {
315                 for(base = scene->base.first; base; base= base->next) {
316                         if( (base->lay & layer) ) {
317                                 if( base->object->pd && base->object->pd->forcefield )
318                                 add_object_to_effectors(&effectors, scene, weights, base->object, ob_src);
319
320                                 if( base->object->particlesystem.first ) {
321                                         ParticleSystem *psys= base->object->particlesystem.first;
322
323                                         for( ; psys; psys=psys->next )
324                                                 add_particles_to_effectors(&effectors, scene, weights, base->object, psys, psys_src);
325                                 }
326                         }
327                 }
328         }
329         return effectors;
330 }
331
332 void pdEndEffectors(ListBase **effectors)
333 {
334         if(*effectors) {
335                 EffectorCache *eff = (*effectors)->first;
336
337                 for(; eff; eff=eff->next) {
338                         if(eff->guide_data)
339                                 MEM_freeN(eff->guide_data);
340                 }
341
342                 BLI_freelistN(*effectors);
343                 MEM_freeN(*effectors);
344                 *effectors = NULL;
345         }
346 }
347
348
349 void pd_point_from_particle(ParticleSimulationData *sim, ParticleData *pa, ParticleKey *state, EffectedPoint *point)
350 {
351         point->loc = state->co;
352         point->vel = state->vel;
353         point->index = pa - sim->psys->particles;
354         point->size = pa->size;
355         /* TODO: point->charge */
356         point->charge = 1.0f;
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 *userdata, int index, const BVHTreeRay *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         ListBase *colls = colliders;
420         ColliderCache *col;
421         float norm[3], len = 0.0;
422         float visibility = 1.0, absorption = 0.0;
423         
424         if(!(eff->pd->flag & PFIELD_VISIBILITY))
425                 return visibility;
426
427         if(!colls)
428                 colls = get_collider_cache(eff->scene, NULL);
429
430         if(!colls)
431                 return visibility;
432         
433         VECCOPY(norm, efd->vec_to_point);
434         VecNegf(norm);
435         len = Normalize(norm);
436         
437         // check all collision objects
438         for(col = colls->first; col; col = col->next)
439         {
440                 CollisionModifierData *collmd = col->collmd;
441
442                 if(col->ob == eff->ob)
443                         continue;
444                 
445                 if(collmd->bvhtree)
446                 {
447                         BVHTreeRayHit hit;
448                         
449                         hit.index = -1;
450                         hit.dist = len + FLT_EPSILON;
451                         
452                         // check if the way is blocked
453                         if(BLI_bvhtree_ray_cast(collmd->bvhtree, point->loc, norm, 0.0f, &hit, eff_tri_ray_hit, NULL)>=0)
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                 free_collider_cache(&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 = (rng_getInt(rng)+1) % 128; // max 2357
476         float force = rng_getFloat(rng) + 1.0f;
477         float ret;
478         float sign = 0;
479         
480         sign = ((float)random > 64.0) ? 1.0: -1.0; // 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.0+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 *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 = Inpf(efd->nor, efd->vec_to_point);
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 switch(eff->pd->falloff){
528                 case PFIELD_FALL_SPHERE:
529                         falloff*= falloff_func_dist(eff->pd, efd->distance);
530                         break;
531
532                 case PFIELD_FALL_TUBE:
533                         falloff*= falloff_func_dist(eff->pd, ABS(fac));
534                         if(falloff == 0.0f)
535                                 break;
536
537                         VECADDFAC(temp, efd->vec_to_point, efd->nor, -fac);
538                         r_fac= VecLength(temp);
539                         falloff*= falloff_func_rad(eff->pd, r_fac);
540                         break;
541                 case PFIELD_FALL_CONE:
542                         falloff*= falloff_func_dist(eff->pd, ABS(fac));
543                         if(falloff == 0.0f)
544                                 break;
545
546                         r_fac=saacos(fac/VecLength(efd->vec_to_point))*180.0f/(float)M_PI;
547                         falloff*= falloff_func_rad(eff->pd, r_fac);
548
549                         break;
550         }
551
552         return falloff;
553 }
554
555 int closest_point_on_surface(SurfaceModifierData *surmd, float *co, float *surface_co, float *surface_nor, float *surface_vel)
556 {
557         BVHTreeNearest nearest;
558
559         nearest.index = -1;
560         nearest.dist = FLT_MAX;
561
562         BLI_bvhtree_find_nearest(surmd->bvhtree->tree, co, &nearest, surmd->bvhtree->nearest_callback, surmd->bvhtree);
563
564         if(nearest.index != -1) {
565                 VECCOPY(surface_co, nearest.co);
566
567                 if(surface_nor) {
568                         VECCOPY(surface_nor, nearest.no);
569                 }
570
571                 if(surface_vel) {
572                         MFace *mface = CDDM_get_face(surmd->dm, nearest.index);
573                         
574                         VECCOPY(surface_vel, surmd->v[mface->v1].co);
575                         VecAddf(surface_vel, surface_vel, surmd->v[mface->v2].co);
576                         VecAddf(surface_vel, surface_vel, surmd->v[mface->v3].co);
577                         if(mface->v4)
578                                 VecAddf(surface_vel, surface_vel, surmd->v[mface->v4].co);
579
580                         VecMulf(surface_vel, mface->v4 ? 0.25f : 0.333f);
581                 }
582                 return 1;
583         }
584
585         return 0;
586 }
587 int get_effector_data(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, int real_velocity)
588 {
589         float cfra = eff->scene->r.cfra;
590         int ret = 0;
591
592         if(eff->pd->shape==PFIELD_SHAPE_SURFACE && eff->surmd) {
593                 /* closest point in the object surface is an effector */
594                 float vec[3];
595
596                 /* using velocity corrected location allows for easier sliding over effector surface */
597                 VecCopyf(vec, point->vel);
598                 VecMulf(vec, point->vel_to_frame);
599                 VecAddf(vec, vec, point->loc);
600
601                 ret = closest_point_on_surface(eff->surmd, vec, efd->loc, efd->nor, real_velocity ? efd->vel : NULL);
602
603                 efd->size = 0.0f;
604         }
605         else if(eff->pd->shape==PFIELD_SHAPE_POINTS) {
606
607                 if(eff->ob->derivedFinal) {
608                         DerivedMesh *dm = eff->ob->derivedFinal;
609
610                         dm->getVertCo(dm, *efd->index, efd->loc);
611                         dm->getVertNo(dm, *efd->index, efd->nor);
612
613                         Mat4MulVecfl(eff->ob->obmat, efd->loc);
614                         Mat4Mul3Vecfl(eff->ob->obmat, efd->nor);
615
616                         Normalize(efd->nor);
617
618                         efd->size = 0.0f;
619
620                         /**/
621                         ret = 1;
622                 }
623         }
624         else if(eff->psys) {
625                 ParticleSimulationData sim = {eff->scene, eff->ob, eff->psys, NULL, NULL};
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                         ;
632                 else {
633                         /* TODO: time from actual previous calculated frame (step might not be 1) */
634                         state.time = cfra - 1.0;
635                         ret = psys_get_particle_state(&sim, *efd->index, &state, 0);
636
637                         /* TODO */
638                         //if(eff->pd->forcefiled == PFIELD_HARMONIC && ret==0) {
639                         //      if(pa->dietime < eff->psys->cfra)
640                         //              eff->flag |= PE_VELOCITY_TO_IMPULSE;
641                         //}
642
643                         VECCOPY(efd->loc, state.co);
644                         VECCOPY(efd->nor, state.vel);
645                         if(real_velocity) {
646                                 VECCOPY(efd->vel, state.vel);
647                         }
648
649                         efd->size = pa->size;
650                 }
651         }
652         else {
653                 /* use center of object for distance calculus */
654                 Object *ob = eff->ob;
655                 Object obcopy = *ob;
656
657                 where_is_object_time(eff->scene, ob, cfra);
658
659                 /* use z-axis as normal*/
660                 VECCOPY(efd->nor, ob->obmat[2]);
661                 Normalize(efd->nor);
662
663                 /* for vortex the shape chooses between old / new force */
664                 if(eff->pd->shape == PFIELD_SHAPE_PLANE) {
665                         /* efd->loc is closes point on effector xy-plane */
666                         float temp[3];
667                         VecSubf(temp, point->loc, ob->obmat[3]);
668                         Projf(efd->loc, temp, efd->nor);
669                         VecSubf(efd->loc, point->loc, efd->loc);
670                 }
671                 else {
672                         VECCOPY(efd->loc, ob->obmat[3]);
673                 }
674
675                 if(real_velocity) {
676                         VECCOPY(efd->vel, ob->obmat[3]);
677
678                         where_is_object_time(eff->scene, ob, cfra - 1.0);
679
680                         VecSubf(efd->vel, efd->vel, ob->obmat[3]);
681                 }
682
683                 *eff->ob = obcopy;
684
685                 efd->size = 0.0f;
686
687                 ret = 1;
688         }
689
690         if(ret) {
691                 VecSubf(efd->vec_to_point, point->loc, efd->loc);
692                 efd->distance = VecLength(efd->vec_to_point);
693
694                 /* for some effectors we need the object center every time */
695                 VecSubf(efd->vec_to_point2, point->loc, eff->ob->obmat[3]);
696                 VECCOPY(efd->nor2, eff->ob->obmat[2]);
697                 Normalize(efd->nor2);
698         }
699
700         return ret;
701 }
702 static void get_effector_tot(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, int *tot, int *p)
703 {
704         if(eff->pd->shape == PFIELD_SHAPE_POINTS) {
705                 efd->index = p;
706
707                 *p = 0;
708                 *tot = eff->ob->derivedFinal ? eff->ob->derivedFinal->numVertData : 1;
709
710                 if(*tot && eff->pd->forcefield == PFIELD_HARMONIC && point->index >= 0) {
711                         *p = point->index % *tot;
712                         *tot = *p+1;
713                 }
714         }
715         else if(eff->psys) {
716                 efd->index = p;
717
718                 *p = 0;
719                 *tot = eff->psys->totpart;
720                 
721                 if(eff->pd->forcefield == PFIELD_CHARGE) {
722                         /* Only the charge of the effected particle is used for 
723                         interaction, not fall-offs. If the fall-offs aren't the 
724                         same this will be unphysical, but for animation this            
725                         could be the wanted behavior. If you want physical
726                         correctness the fall-off should be spherical 2.0 anyways.
727                         */
728                         efd->charge = eff->pd->f_strength;
729                 }
730                 else if(eff->pd->forcefield == PFIELD_HARMONIC) {
731                         /* every particle is mapped to only one harmonic effector particle */
732                         *p= point->index % eff->psys->totpart;
733                         *tot= *p + 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 = 0;
753
754         strength= eff->pd->f_strength * efd->falloff;
755
756         VECCOPY(tex_co,point->loc);
757
758         if(eff->pd->flag & PFIELD_TEX_2D) {
759                 float fac=-Inpf(tex_co, efd->nor);
760                 VECADDFAC(tex_co, tex_co, efd->nor, fac);
761         }
762
763         if(eff->pd->flag & PFIELD_TEX_OBJECT) {
764                 Mat4Mul3Vecfl(eff->ob->obmat, tex_co);
765         }
766
767         hasrgb = multitex_ext(eff->pd->tex, tex_co, NULL,NULL, 1, 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, 1, result+1);
779
780                 tex_co[0] -= nabla;
781                 tex_co[1] += nabla;
782                 multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 1, result+2);
783
784                 tex_co[1] -= nabla;
785                 tex_co[2] += nabla;
786                 multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 1, result+3);
787
788                 if(mode == PFIELD_TEX_GRAD || !hasrgb) { /* if we dont have rgb fall back to grad */
789                         force[0] = (result[0].tin - result[1].tin) * strength;
790                         force[1] = (result[0].tin - result[2].tin) * strength;
791                         force[2] = (result[0].tin - result[3].tin) * strength;
792                 }
793                 else { /*PFIELD_TEX_CURL*/
794                         float dbdy, dgdz, drdz, dbdx, dgdx, drdy;
795
796                         dbdy = result[2].tb - result[0].tb;
797                         dgdz = result[3].tg - result[0].tg;
798                         drdz = result[3].tr - result[0].tr;
799                         dbdx = result[1].tb - result[0].tb;
800                         dgdx = result[1].tg - result[0].tg;
801                         drdy = result[2].tr - result[0].tr;
802
803                         force[0] = (dbdy - dgdz) * strength;
804                         force[1] = (drdz - dbdx) * strength;
805                         force[2] = (dgdx - drdy) * strength;
806                 }
807         }
808
809         if(eff->pd->flag & PFIELD_TEX_2D){
810                 float fac = -Inpf(force, efd->nor);
811                 VECADDFAC(force, force, efd->nor, fac);
812         }
813
814         VecAddf(total_force, total_force, force);
815 }
816 void do_physical_effector(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, float *total_force)
817 {
818         PartDeflect *pd = eff->pd;
819         RNG *rng = pd->rng;
820         float force[3]={0,0,0};
821         float temp[3];
822         float fac;
823         float strength = pd->f_strength;
824         float damp = pd->f_damp;
825         float noise_factor = pd->f_noise;
826
827         if(noise_factor > 0.0f) {
828                 strength += wind_func(rng, noise_factor);
829
830                 if(ELEM(pd->forcefield, PFIELD_HARMONIC, PFIELD_DRAG))
831                         damp += wind_func(rng, noise_factor);
832         }
833
834         VECCOPY(force, efd->vec_to_point);
835
836         switch(pd->forcefield){
837                 case PFIELD_WIND:
838                         Normalize(force);
839                         strength *= (Inpf(force, efd->nor) >= 0.0f ? 1.0f : -1.0f);
840                         VecMulf(force, strength * efd->falloff);
841                         break;
842                 case PFIELD_FORCE:
843                         Normalize(force);
844                         VecMulf(force, strength * efd->falloff);
845                         break;
846                 case PFIELD_VORTEX:
847                         /* old vortex force */
848                         if(pd->shape == PFIELD_SHAPE_POINT) {
849                                 Crossf(force, efd->nor, efd->vec_to_point);
850                                 Normalize(force);
851                                 VecMulf(force, strength * efd->distance * efd->falloff);
852                         }
853                         else {
854                                 /* new vortex force */
855                                 Crossf(temp, efd->nor2, efd->vec_to_point2);
856                                 VecMulf(temp, strength * efd->falloff);
857                                 
858                                 Crossf(force, efd->nor2, temp);
859                                 VecMulf(force, strength * efd->falloff);
860                                 
861                                 VECADDFAC(temp, temp, point->vel, -point->vel_to_sec);
862                                 VecAddf(force, force, temp);
863                         }
864                         break;
865                 case PFIELD_MAGNET:
866                         if(eff->pd->shape == PFIELD_SHAPE_POINT)
867                                 /* magnetic field of a moving charge */
868                                 Crossf(temp, efd->nor, efd->vec_to_point);
869                         else
870                                 VecCopyf(temp, efd->nor);
871
872                         Normalize(temp);
873                         VecMulf(temp, strength * efd->falloff);
874                         Crossf(force, point->vel, temp);
875                         VecMulf(force, point->vel_to_sec);
876                         break;
877                 case PFIELD_HARMONIC:
878                         VecMulf(force, -strength * efd->falloff);
879                         VecCopyf(temp, point->vel);
880                         VecMulf(temp, -damp * 2.0f * (float)sqrt(fabs(strength)) * point->vel_to_sec);
881                         VecAddf(force, force, temp);
882                         break;
883                 case PFIELD_CHARGE:
884                         VecMulf(force, point->charge * strength * efd->falloff);
885                         break;
886                 case PFIELD_LENNARDJ:
887                         fac = pow((efd->size + point->size) / efd->distance, 6.0);
888                         
889                         fac = - fac * (1.0 - fac) / efd->distance;
890
891                         /* limit the repulsive term drastically to avoid huge forces */
892                         fac = ((fac>2.0) ? 2.0 : fac);
893
894                         VecMulf(force, strength * fac);
895                         break;
896                 case PFIELD_BOID:
897                         /* Boid field is handled completely in boids code. */
898                         return;
899                 case PFIELD_TURBULENCE:
900                         if(pd->flag & PFIELD_GLOBAL_CO) {
901                                 VECCOPY(temp, point->loc);
902                         }
903                         else {
904                                 VECADD(temp, efd->vec_to_point2, efd->nor2);
905                         }
906                         force[0] = -1.0f + 2.0f * BLI_gTurbulence(pd->f_size, temp[0], temp[1], temp[2], 2,0,2);
907                         force[1] = -1.0f + 2.0f * BLI_gTurbulence(pd->f_size, temp[1], temp[2], temp[0], 2,0,2);
908                         force[2] = -1.0f + 2.0f * BLI_gTurbulence(pd->f_size, temp[2], temp[0], temp[1], 2,0,2);
909                         VecMulf(force, strength * efd->falloff);
910                         break;
911                 case PFIELD_DRAG:
912                         VECCOPY(force, point->vel);
913                         fac = Normalize(force) * point->vel_to_sec;
914
915                         strength = MIN2(strength, 2.0f);
916                         damp = MIN2(damp, 2.0f);
917
918                         VecMulf(force, -efd->falloff * fac * (strength * fac + damp));
919                         break;
920         }
921
922         if(pd->flag & PFIELD_DO_LOCATION) {
923                 VECADDFAC(total_force, total_force, force, 1.0f/point->vel_to_sec);
924
925                 if(ELEM(pd->forcefield, PFIELD_HARMONIC, PFIELD_DRAG)==0 && pd->f_flow != 0.0f) {
926                         VECADDFAC(total_force, total_force, point->vel, -pd->f_flow * efd->falloff);
927                 }
928         }
929
930         if(pd->flag & PFIELD_DO_ROTATION && point->ave && point->rot) {
931                 float xvec[3] = {1.0f, 0.0f, 0.0f};
932                 float dave[3];
933                 QuatMulVecf(point->rot, xvec);
934                 Crossf(dave, xvec, force);
935                 if(pd->f_flow != 0.0f) {
936                         VECADDFAC(dave, dave, point->ave, -pd->f_flow * efd->falloff);
937                 }
938                 VecAddf(point->ave, point->ave, dave);
939         }
940 }
941
942 /*  -------- pdDoEffectors() --------
943     generic force/speed system, now used for particles and softbodies
944     scene       = scene where it runs in, for time and stuff
945         lb                      = listbase with objects that take part in effecting
946         opco            = global coord, as input
947     force               = force accumulator
948     speed               = actual current speed which can be altered
949         cur_time        = "external" time in frames, is constant for static particles
950         loc_time        = "local" time in frames, range <0-1> for the lifetime of particle
951     par_layer   = layer the caller is in
952         flags           = only used for softbody wind now
953         guide           = old speed of particle
954
955 */
956 void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *weights, EffectedPoint *point, float *force, float *impulse)
957 {
958 /*
959         Modifies the force on a particle according to its
960         relation with the effector object
961         Different kind of effectors include:
962                 Forcefields: Gravity-like attractor
963                 (force power is related to the inverse of distance to the power of a falloff value)
964                 Vortex fields: swirling effectors
965                 (particles rotate around Z-axis of the object. otherwise, same relation as)
966                 (Forcefields, but this is not done through a force/acceleration)
967                 Guide: particles on a path
968                 (particles are guided along a curve bezier or old nurbs)
969                 (is independent of other effectors)
970 */
971         EffectorCache *eff;
972         EffectorData efd;
973         int p=0, tot = 1;
974
975         /* Cycle through collected objects, get total of (1/(gravity_strength * dist^gravity_power)) */
976         /* Check for min distance here? (yes would be cool to add that, ton) */
977         
978         if(effectors) for(eff = effectors->first; eff; eff=eff->next) {
979                 /* object effectors were fully checked to be OK to evaluate! */
980
981                 get_effector_tot(eff, &efd, point, &tot, &p);
982
983                 for(; p<tot; p++) {
984                         if(get_effector_data(eff, &efd, point, 0)) {
985                                 efd.falloff= effector_falloff(eff, &efd, point, weights);
986                                 
987                                 if(efd.falloff > 0.0f)
988                                         efd.falloff *= eff_calc_visibility(colliders, eff, &efd, point);
989
990                                 if(efd.falloff <= 0.0f)
991                                         ;       /* don't do anything */
992                                 else if(eff->pd->forcefield == PFIELD_TEXTURE)
993                                         do_texture_effector(eff, &efd, point, force);
994                                 else {
995                                         float temp1[3]={0,0,0}, temp2[3];
996                                         VECCOPY(temp1, force);
997
998                                         do_physical_effector(eff, &efd, point, force);
999                                         
1000                                         // for softbody backward compatibility
1001                                         if(point->flag & PE_WIND_AS_SPEED && impulse){
1002                                                 VECSUB(temp2, force, temp1);
1003                                                 VECSUB(impulse, impulse, temp2);
1004                                         }
1005                                 }
1006                         }
1007                         else if(eff->flag & PE_VELOCITY_TO_IMPULSE && impulse) {
1008                                 /* special case for harmonic effector */
1009                                 VECADD(impulse, impulse, efd.vel);
1010                         }
1011                 }
1012         }
1013 }