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