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