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