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