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