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