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