svn merge https://svn.blender.org/svnroot/bf-blender/trunk/blender -r21908:22075
[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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, 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 "BLI_storage.h" /* _LARGEFILE_SOURCE */
33
34 #include <math.h>
35 #include <stdlib.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_curve_types.h"
40 #include "DNA_effect_types.h"
41 #include "DNA_group_types.h"
42 #include "DNA_ipo_types.h"
43 #include "DNA_key_types.h"
44 #include "DNA_lattice_types.h"
45 #include "DNA_listBase.h"
46 #include "DNA_mesh_types.h"
47 #include "DNA_meshdata_types.h"
48 #include "DNA_material_types.h"
49 #include "DNA_object_types.h"
50 #include "DNA_object_force.h"
51 #include "DNA_texture_types.h"
52 #include "DNA_scene_types.h"
53
54 #include "BLI_arithb.h"
55 #include "BLI_blenlib.h"
56 #include "BLI_jitter.h"
57 #include "BLI_rand.h"
58
59 #include "PIL_time.h"
60
61 #include "BKE_action.h"
62 #include "BKE_anim.h"           /* needed for where_on_path */
63 #include "BKE_armature.h"
64 #include "BKE_blender.h"
65 #include "BKE_collision.h"
66 #include "BKE_constraint.h"
67 #include "BKE_deform.h"
68 #include "BKE_depsgraph.h"
69 #include "BKE_displist.h"
70 #include "BKE_DerivedMesh.h"
71 #include "BKE_effect.h"
72 #include "BKE_global.h"
73 #include "BKE_group.h"
74 #include "BKE_ipo.h"
75 #include "BKE_key.h"
76 #include "BKE_lattice.h"
77 #include "BKE_mesh.h"
78 #include "BKE_material.h"
79 #include "BKE_main.h"
80 #include "BKE_modifier.h"
81 #include "BKE_object.h"
82 #include "BKE_scene.h"
83 #include "BKE_screen.h"
84 #include "BKE_utildefines.h"
85
86 #include "RE_render_ext.h"
87
88 /* fluid sim particle import */
89 #ifndef DISABLE_ELBEEM
90 #include "DNA_object_fluidsim.h"
91 #include "LBM_fluidsim.h"
92 #include <zlib.h>
93 #include <string.h>
94 #endif // DISABLE_ELBEEM
95
96 //XXX #include "BIF_screen.h"
97
98 PartDeflect *object_add_collision_fields(void)
99 {
100         PartDeflect *pd;
101
102         pd= MEM_callocN(sizeof(PartDeflect), "PartDeflect");
103
104         pd->pdef_sbdamp = 0.1f;
105         pd->pdef_sbift  = 0.2f;
106         pd->pdef_sboft  = 0.02f;
107         pd->seed = ((unsigned int)(ceil(PIL_check_seconds_timer()))+1) % 128;
108         pd->f_strength = 1.0f;
109
110         return pd;
111 }
112
113 /* temporal struct, used for reading return of mesh_get_mapped_verts_nors() */
114
115 typedef struct VeNoCo {
116         float co[3], no[3];
117 } VeNoCo;
118
119 /* ***************** PARTICLES ***************** */
120
121 /* deprecated, only keep this for readfile.c */
122 PartEff *give_parteff(Object *ob)
123 {
124         PartEff *paf;
125         
126         paf= ob->effect.first;
127         while(paf) {
128                 if(paf->type==EFF_PARTICLE) return paf;
129                 paf= paf->next;
130         }
131         return 0;
132 }
133
134 void free_effect(Effect *eff)
135 {
136         PartEff *paf;
137         
138         if(eff->type==EFF_PARTICLE) {
139                 paf= (PartEff *)eff;
140                 if(paf->keys) MEM_freeN(paf->keys);
141         }
142         MEM_freeN(eff); 
143 }
144
145
146 void free_effects(ListBase *lb)
147 {
148         Effect *eff;
149         
150         eff= lb->first;
151         while(eff) {
152                 BLI_remlink(lb, eff);
153                 free_effect(eff);
154                 eff= lb->first;
155         }
156 }
157
158 /* -------------------------- Effectors ------------------ */
159
160 static void add_to_effectorcache(ListBase *lb, Scene *scene, Object *ob, Object *obsrc)
161 {
162         pEffectorCache *ec;
163         PartDeflect *pd= ob->pd;
164                         
165         if(pd->forcefield == PFIELD_GUIDE) {
166                 if(ob->type==OB_CURVE && obsrc->type==OB_MESH) {        /* guides only do mesh particles */
167                         Curve *cu= ob->data;
168                         if(cu->flag & CU_PATH) {
169                                 if(cu->path==NULL || cu->path->data==NULL)
170                                         makeDispListCurveTypes(scene, ob, 0);
171                                 if(cu->path && cu->path->data) {
172                                         ec= MEM_callocN(sizeof(pEffectorCache), "effector cache");
173                                         ec->ob= ob;
174                                         BLI_addtail(lb, ec);
175                                 }
176                         }
177                 }
178         }
179         else if(pd->forcefield) {
180                 
181                 if(pd->forcefield == PFIELD_WIND)
182                 {
183                         pd->rng = rng_new(pd->seed);
184                 }
185         
186                 ec= MEM_callocN(sizeof(pEffectorCache), "effector cache");
187                 ec->ob= ob;
188                 BLI_addtail(lb, ec);
189         }
190 }
191
192 /* returns ListBase handle with objects taking part in the effecting */
193 ListBase *pdInitEffectors(Scene *scene, Object *obsrc, Group *group)
194 {
195         static ListBase listb={NULL, NULL};
196         pEffectorCache *ec;
197         Base *base;
198         unsigned int layer= obsrc->lay;
199         
200         if(group) {
201                 GroupObject *go;
202                 
203                 for(go= group->gobject.first; go; go= go->next) {
204                         if( (go->ob->lay & layer) && go->ob->pd && go->ob!=obsrc) {
205                                 add_to_effectorcache(&listb, scene, go->ob, obsrc);
206                         }
207                 }
208         }
209         else {
210                 for(base = scene->base.first; base; base= base->next) {
211                         if( (base->lay & layer) && base->object->pd && base->object!=obsrc) {
212                                 add_to_effectorcache(&listb, scene, base->object, obsrc);
213                         }
214                 }
215         }
216         
217         /* make a full copy */
218         for(ec= listb.first; ec; ec= ec->next) {
219                 ec->obcopy= *(ec->ob);
220         }
221
222         if(listb.first)
223                 return &listb;
224         
225         return NULL;
226 }
227
228 void pdEndEffectors(ListBase *lb)
229 {
230         if(lb) {
231                 pEffectorCache *ec;
232                 /* restore full copy */
233                 for(ec= lb->first; ec; ec= ec->next)
234                 {
235                         if(ec->ob->pd && (ec->ob->pd->forcefield == PFIELD_WIND))
236                                 rng_free(ec->ob->pd->rng);
237                         
238                         *(ec->ob)= ec->obcopy;
239                 }
240
241                 BLI_freelistN(lb);
242         }
243 }
244
245
246 /************************************************/
247 /*                      Effectors               */
248 /************************************************/
249
250 // triangle - ray callback function
251 static void eff_tri_ray_hit(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
252 {       
253         // whenever we hit a bounding box, we don't check further
254         hit->dist = -1;
255         hit->index = 1;
256 }
257
258 // get visibility of a wind ray
259 static float eff_calc_visibility(Scene *scene, Object *ob, float *co, float *dir)
260 {
261         CollisionModifierData **collobjs = NULL;
262         int numcollobj = 0, i;
263         float norm[3], len = 0.0;
264         float visibility = 1.0;
265         
266         collobjs = get_collisionobjects(scene, ob, &numcollobj);
267         
268         if(!collobjs)
269                 return 0;
270         
271         VECCOPY(norm, dir);
272         VecNegf(norm);
273         len = Normalize(norm);
274         
275         // check all collision objects
276         for(i = 0; i < numcollobj; i++)
277         {
278                 CollisionModifierData *collmd = collobjs[i];
279                 
280                 if(collmd->bvhtree)
281                 {
282                         BVHTreeRayHit hit;
283                         
284                         hit.index = -1;
285                         hit.dist = len + FLT_EPSILON;
286                         
287                         // check if the way is blocked
288                         if(BLI_bvhtree_ray_cast(collmd->bvhtree, co, norm, 0.0f, &hit, eff_tri_ray_hit, NULL)>=0)
289                         {
290                                 // visibility is only between 0 and 1, calculated from 1-absorption
291                                 visibility *= MAX2(0.0, MIN2(1.0, (1.0-((float)collmd->absorption)*0.01)));
292                                 
293                                 if(visibility <= 0.0f)
294                                         break;
295                         }
296                 }
297         }
298         
299         MEM_freeN(collobjs);
300         
301         return visibility;
302 }
303
304 // noise function for wind e.g.
305 static float wind_func(struct RNG *rng, float strength)
306 {
307         int random = (rng_getInt(rng)+1) % 128; // max 2357
308         float force = rng_getFloat(rng) + 1.0f;
309         float ret;
310         float sign = 0;
311         
312         sign = ((float)random > 64.0) ? 1.0: -1.0; // dividing by 2 is not giving equal sign distribution
313         
314         ret = sign*((float)random / force)*strength/128.0f;
315         
316         return ret;
317 }
318
319 /* maxdist: zero effect from this distance outwards (if usemax) */
320 /* mindist: full effect up to this distance (if usemin) */
321 /* power: falloff with formula 1/r^power */
322 static float falloff_func(float fac, int usemin, float mindist, int usemax, float maxdist, float power)
323 {
324         /* first quick checks */
325         if(usemax && fac > maxdist)
326                 return 0.0f;
327
328         if(usemin && fac < mindist)
329                 return 1.0f;
330
331         if(!usemin)
332                 mindist = 0.0;
333
334         return pow((double)1.0+fac-mindist, (double)-power);
335 }
336
337 static float falloff_func_dist(PartDeflect *pd, float fac)
338 {
339         return falloff_func(fac, pd->flag&PFIELD_USEMIN, pd->mindist, pd->flag&PFIELD_USEMAX, pd->maxdist, pd->f_power);
340 }
341
342 static float falloff_func_rad(PartDeflect *pd, float fac)
343 {
344         return falloff_func(fac, pd->flag&PFIELD_USEMINR, pd->minrad, pd->flag&PFIELD_USEMAXR, pd->maxrad, pd->f_power_r);
345 }
346
347 float effector_falloff(PartDeflect *pd, float *eff_velocity, float *vec_to_part)
348 {
349         float eff_dir[3], temp[3];
350         float falloff=1.0, fac, r_fac;
351
352         if(pd->forcefield==PFIELD_LENNARDJ)
353                 return falloff; /* Lennard-Jones field has it's own falloff built in */
354
355         VecCopyf(eff_dir,eff_velocity);
356         Normalize(eff_dir);
357
358         if(pd->flag & PFIELD_POSZ && Inpf(eff_dir,vec_to_part)<0.0f)
359                 falloff=0.0f;
360         else switch(pd->falloff){
361                 case PFIELD_FALL_SPHERE:
362                         fac=VecLength(vec_to_part);
363                         falloff= falloff_func_dist(pd, fac);
364                         break;
365
366                 case PFIELD_FALL_TUBE:
367                         fac=Inpf(vec_to_part,eff_dir);
368                         falloff= falloff_func_dist(pd, ABS(fac));
369                         if(falloff == 0.0f)
370                                 break;
371
372                         VECADDFAC(temp,vec_to_part,eff_dir,-fac);
373                         r_fac=VecLength(temp);
374                         falloff*= falloff_func_rad(pd, r_fac);
375                         break;
376                 case PFIELD_FALL_CONE:
377                         fac=Inpf(vec_to_part,eff_dir);
378                         falloff= falloff_func_dist(pd, ABS(fac));
379                         if(falloff == 0.0f)
380                                 break;
381
382                         r_fac=saacos(fac/VecLength(vec_to_part))*180.0f/(float)M_PI;
383                         falloff*= falloff_func_rad(pd, r_fac);
384
385                         break;
386         }
387
388         return falloff;
389 }
390
391 void do_physical_effector(Scene *scene, Object *ob, float *opco, short type, float force_val, float distance, float falloff, float size, float damp, float *eff_velocity, float *vec_to_part, float *velocity, float *field, int planar, struct RNG *rng, float noise_factor, float charge, float pa_size)
392 {
393         float mag_vec[3]={0,0,0};
394         float temp[3], temp2[3];
395         float eff_vel[3];
396         float noise = 0, visibility;
397         
398         // calculate visibility
399         visibility = eff_calc_visibility(scene, ob, opco, vec_to_part);
400         if(visibility <= 0.0)
401                 return;
402         falloff *= visibility;
403
404         VecCopyf(eff_vel,eff_velocity);
405         Normalize(eff_vel);
406
407         switch(type){
408                 case PFIELD_WIND:
409                         VECCOPY(mag_vec,eff_vel);
410                         
411                         // add wind noise here, only if we have wind
412                         if((noise_factor > 0.0f) && (force_val > FLT_EPSILON))
413                                 noise = wind_func(rng, noise_factor);
414                         
415                         VecMulf(mag_vec,(force_val+noise)*falloff);
416                         VecAddf(field,field,mag_vec);
417                         break;
418
419                 case PFIELD_FORCE:
420                         if(planar)
421                                 Projf(mag_vec,vec_to_part,eff_vel);
422                         else
423                                 VecCopyf(mag_vec,vec_to_part);
424
425                         Normalize(mag_vec);
426
427                         VecMulf(mag_vec,force_val*falloff);
428                         VecAddf(field,field,mag_vec);
429                         break;
430
431                 case PFIELD_VORTEX:
432                         Crossf(mag_vec,eff_vel,vec_to_part);
433
434                         Normalize(mag_vec);
435
436                         VecMulf(mag_vec,force_val*distance*falloff);
437                         VecAddf(field,field,mag_vec);
438
439                         break;
440                 case PFIELD_MAGNET:
441                         if(planar)
442                                 VecCopyf(temp,eff_vel);
443                         else
444                                 /* magnetic field of a moving charge */
445                                 Crossf(temp,eff_vel,vec_to_part);
446
447                         Normalize(temp);
448
449                         Crossf(temp2,velocity,temp);
450                         VecAddf(mag_vec,mag_vec,temp2);
451
452                         VecMulf(mag_vec,force_val*falloff);
453                         VecAddf(field,field,mag_vec);
454                         break;
455                 case PFIELD_HARMONIC:
456                         if(planar)
457                                 Projf(mag_vec,vec_to_part,eff_vel);
458                         else
459                                 VecCopyf(mag_vec,vec_to_part);
460
461                         VecMulf(mag_vec,force_val*falloff);
462                         VecSubf(field,field,mag_vec);
463
464                         VecCopyf(mag_vec,velocity);
465                         VecMulf(mag_vec,damp*2.0f*(float)sqrt(force_val));
466                         VecSubf(field,field,mag_vec);
467                         break;
468                 case PFIELD_CHARGE:
469                         if(planar)
470                                 Projf(mag_vec,vec_to_part,eff_vel);
471                         else
472                                 VecCopyf(mag_vec,vec_to_part);
473
474                         Normalize(mag_vec);
475
476                         VecMulf(mag_vec,charge*force_val*falloff);
477                         VecAddf(field,field,mag_vec);
478                         break;
479                 case PFIELD_LENNARDJ:
480                 {
481                         float fac;
482
483                         if(planar) {
484                                 Projf(mag_vec,vec_to_part,eff_vel);
485                                 distance = VecLength(mag_vec);
486                         }
487                         else
488                                 VecCopyf(mag_vec,vec_to_part);
489
490                         /* at this distance the field is 60 times weaker than maximum */
491                         if(distance > 2.22 * (size+pa_size))
492                                 break;
493
494                         fac = pow((size+pa_size)/distance,6.0);
495                         
496                         fac = - fac * (1.0 - fac) / distance;
497
498                         /* limit the repulsive term drastically to avoid huge forces */
499                         fac = ((fac>2.0) ? 2.0 : fac);
500
501                         /* 0.003715 is the fac value at 2.22 times (size+pa_size),
502                            substracted to avoid discontinuity at the border
503                         */
504                         VecMulf(mag_vec, force_val * (fac-0.0037315));
505                         VecAddf(field,field,mag_vec);
506                         break;
507                 }
508                 case PFIELD_BOID:
509                         /* Boid field is handled completely in boids code. */
510                         break;
511         }
512 }
513
514 /*  -------- pdDoEffectors() --------
515     generic force/speed system, now used for particles and softbodies
516     scene       = scene where it runs in, for time and stuff
517         lb                      = listbase with objects that take part in effecting
518         opco            = global coord, as input
519     force               = force accumulator
520     speed               = actual current speed which can be altered
521         cur_time        = "external" time in frames, is constant for static particles
522         loc_time        = "local" time in frames, range <0-1> for the lifetime of particle
523     par_layer   = layer the caller is in
524         flags           = only used for softbody wind now
525         guide           = old speed of particle
526
527 */
528 void pdDoEffectors(Scene *scene, ListBase *lb, float *opco, float *force, float *speed, float cur_time, float loc_time, unsigned int flags)
529 {
530 /*
531         Modifies the force on a particle according to its
532         relation with the effector object
533         Different kind of effectors include:
534                 Forcefields: Gravity-like attractor
535                 (force power is related to the inverse of distance to the power of a falloff value)
536                 Vortex fields: swirling effectors
537                 (particles rotate around Z-axis of the object. otherwise, same relation as)
538                 (Forcefields, but this is not done through a force/acceleration)
539                 Guide: particles on a path
540                 (particles are guided along a curve bezier or old nurbs)
541                 (is independent of other effectors)
542 */
543         Object *ob;
544         pEffectorCache *ec;
545         PartDeflect *pd;
546         
547         float distance, vec_to_part[3];
548         float falloff;
549
550         /* Cycle through collected objects, get total of (1/(gravity_strength * dist^gravity_power)) */
551         /* Check for min distance here? (yes would be cool to add that, ton) */
552         
553         for(ec = lb->first; ec; ec= ec->next) {
554                 /* object effectors were fully checked to be OK to evaluate! */
555                 ob= ec->ob;
556                 pd= ob->pd;
557                         
558                 /* Get IPO force strength and fall off values here */
559                 where_is_object_time(scene, ob, cur_time);
560                         
561                 /* use center of object for distance calculus */
562                 VecSubf(vec_to_part, opco, ob->obmat[3]);
563                 distance = VecLength(vec_to_part);
564
565                 falloff=effector_falloff(pd,ob->obmat[2],vec_to_part);          
566                 
567                 if(falloff<=0.0f)
568                         ;       /* don't do anything */
569                 else {
570                         float field[3]={0,0,0}, tmp[3];
571                         VECCOPY(field, force);
572                         do_physical_effector(scene, ob, opco, pd->forcefield,pd->f_strength,distance,
573                                                                 falloff, pd->f_dist, pd->f_damp, ob->obmat[2], vec_to_part,
574                                                                 speed,force, pd->flag&PFIELD_PLANAR, pd->rng, pd->f_noise, 0.0f, 0.0f);
575                         
576                         // for softbody backward compatibility
577                         if(flags & PE_WIND_AS_SPEED){
578                                 VECSUB(tmp, force, field);
579                                 VECSUB(speed, speed, tmp);
580                         }
581                 }
582         }
583 }