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