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