merge with 2.5 at r18679
[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 <math.h>
33 #include <stdlib.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_curve_types.h"
38 #include "DNA_effect_types.h"
39 #include "DNA_group_types.h"
40 #include "DNA_ipo_types.h"
41 #include "DNA_key_types.h"
42 #include "DNA_lattice_types.h"
43 #include "DNA_listBase.h"
44 #include "DNA_mesh_types.h"
45 #include "DNA_meshdata_types.h"
46 #include "DNA_material_types.h"
47 #include "DNA_object_types.h"
48 #include "DNA_object_force.h"
49 #include "DNA_texture_types.h"
50 #include "DNA_scene_types.h"
51
52 #include "BLI_arithb.h"
53 #include "BLI_blenlib.h"
54 #include "BLI_jitter.h"
55 #include "BLI_rand.h"
56
57 #include "BKE_action.h"
58 #include "BKE_anim.h"           /* needed for where_on_path */
59 #include "BKE_armature.h"
60 #include "BKE_blender.h"
61 #include "BKE_collision.h"
62 #include "BKE_constraint.h"
63 #include "BKE_deform.h"
64 #include "BKE_depsgraph.h"
65 #include "BKE_displist.h"
66 #include "BKE_DerivedMesh.h"
67 #include "BKE_effect.h"
68 #include "BKE_global.h"
69 #include "BKE_group.h"
70 #include "BKE_ipo.h"
71 #include "BKE_key.h"
72 #include "BKE_lattice.h"
73 #include "BKE_mesh.h"
74 #include "BKE_material.h"
75 #include "BKE_main.h"
76 #include "BKE_modifier.h"
77 #include "BKE_object.h"
78 #include "BKE_scene.h"
79 #include "BKE_screen.h"
80 #include "BKE_utildefines.h"
81
82 #include "PIL_time.h"
83 #include "RE_render_ext.h"
84
85 /* fluid sim particle import */
86 #ifndef DISABLE_ELBEEM
87 #include "DNA_object_fluidsim.h"
88 #include "LBM_fluidsim.h"
89 #include <zlib.h>
90 #include <string.h>
91 #endif // DISABLE_ELBEEM
92
93 //XXX #include "BIF_screen.h"
94
95 /* temporal struct, used for reading return of mesh_get_mapped_verts_nors() */
96
97 typedef struct VeNoCo {
98         float co[3], no[3];
99 } VeNoCo;
100
101 /* ***************** PARTICLES ***************** */
102
103 /* deprecated, only keep this for readfile.c */
104 PartEff *give_parteff(Object *ob)
105 {
106         PartEff *paf;
107         
108         paf= ob->effect.first;
109         while(paf) {
110                 if(paf->type==EFF_PARTICLE) return paf;
111                 paf= paf->next;
112         }
113         return 0;
114 }
115
116 void free_effect(Effect *eff)
117 {
118         PartEff *paf;
119         
120         if(eff->type==EFF_PARTICLE) {
121                 paf= (PartEff *)eff;
122                 if(paf->keys) MEM_freeN(paf->keys);
123         }
124         MEM_freeN(eff); 
125 }
126
127
128 void free_effects(ListBase *lb)
129 {
130         Effect *eff;
131         
132         eff= lb->first;
133         while(eff) {
134                 BLI_remlink(lb, eff);
135                 free_effect(eff);
136                 eff= lb->first;
137         }
138 }
139
140 /* -------------------------- Effectors ------------------ */
141
142 static void add_to_effectorcache(ListBase *lb, Scene *scene, Object *ob, Object *obsrc)
143 {
144         pEffectorCache *ec;
145         PartDeflect *pd= ob->pd;
146                         
147         if(pd->forcefield == PFIELD_GUIDE) {
148                 if(ob->type==OB_CURVE && obsrc->type==OB_MESH) {        /* guides only do mesh particles */
149                         Curve *cu= ob->data;
150                         if(cu->flag & CU_PATH) {
151                                 if(cu->path==NULL || cu->path->data==NULL)
152                                         makeDispListCurveTypes(scene, ob, 0);
153                                 if(cu->path && cu->path->data) {
154                                         ec= MEM_callocN(sizeof(pEffectorCache), "effector cache");
155                                         ec->ob= ob;
156                                         BLI_addtail(lb, ec);
157                                 }
158                         }
159                 }
160         }
161         else if(pd->forcefield) {
162                 
163                 if(pd->forcefield == PFIELD_WIND)
164                 {
165                         pd->rng = rng_new(1);
166                         rng_srandom(pd->rng, (unsigned int)(ceil(PIL_check_seconds_timer()))); // use better 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) % 65535; // max 2357
291         float force = rng_getFloat(rng) + 1.0f;
292         float ret;
293         float sign = 0;
294         
295         sign = (random > 32000.0) ? 1.0: -1.0; // dividing by 2 is not giving equal sign distribution
296         
297         ret = sign*((float)random / force)*strength/65535.0f;
298         
299         return ret;
300 }
301
302
303 static float falloff_func(float fac, int usemin, float mindist, int usemax, float maxdist, float power)
304 {
305         if(!usemin)
306                 mindist= 0.0f;
307
308         if(fac < mindist) {
309                 return 1.0f;
310         }
311         else if(usemax) {
312                 if(fac>maxdist || (maxdist-mindist)<=0.0f)
313                         return 0.0f;
314
315                 fac= (fac-mindist)/(maxdist-mindist);
316                 return 1.0f - (float)pow((double)fac, (double)power);
317         }
318         else
319                 return pow((double)1.0f+fac-mindist, (double)-power);
320 }
321
322 static float falloff_func_dist(PartDeflect *pd, float fac)
323 {
324         return falloff_func(fac, pd->flag&PFIELD_USEMIN, pd->mindist, pd->flag&PFIELD_USEMAX, pd->maxdist, pd->f_power);
325 }
326
327 static float falloff_func_rad(PartDeflect *pd, float fac)
328 {
329         return falloff_func(fac, pd->flag&PFIELD_USEMINR, pd->minrad, pd->flag&PFIELD_USEMAXR, pd->maxrad, pd->f_power_r);
330 }
331
332 float effector_falloff(PartDeflect *pd, float *eff_velocity, float *vec_to_part)
333 {
334         float eff_dir[3], temp[3];
335         float falloff=1.0, fac, r_fac;
336
337         if(pd->forcefield==PFIELD_LENNARDJ)
338                 return falloff; /* Lennard-Jones field has it's own falloff built in */
339
340         VecCopyf(eff_dir,eff_velocity);
341         Normalize(eff_dir);
342
343         if(pd->flag & PFIELD_POSZ && Inpf(eff_dir,vec_to_part)<0.0f)
344                 falloff=0.0f;
345         else switch(pd->falloff){
346                 case PFIELD_FALL_SPHERE:
347                         fac=VecLength(vec_to_part);
348                         falloff= falloff_func_dist(pd, fac);
349                         break;
350
351                 case PFIELD_FALL_TUBE:
352                         fac=Inpf(vec_to_part,eff_dir);
353                         falloff= falloff_func_dist(pd, ABS(fac));
354                         if(falloff == 0.0f)
355                                 break;
356
357                         VECADDFAC(temp,vec_to_part,eff_dir,-fac);
358                         r_fac=VecLength(temp);
359                         falloff*= falloff_func_rad(pd, r_fac);
360                         break;
361                 case PFIELD_FALL_CONE:
362                         fac=Inpf(vec_to_part,eff_dir);
363                         falloff= falloff_func_dist(pd, ABS(fac));
364                         if(falloff == 0.0f)
365                                 break;
366
367                         r_fac=saacos(fac/VecLength(vec_to_part))*180.0f/(float)M_PI;
368                         falloff*= falloff_func_rad(pd, r_fac);
369
370                         break;
371         }
372
373         return falloff;
374 }
375
376 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)
377 {
378         float mag_vec[3]={0,0,0};
379         float temp[3], temp2[3];
380         float eff_vel[3];
381         float noise = 0, visibility;
382         
383         // calculate visibility
384         visibility = eff_calc_visibility(scene, ob, opco, vec_to_part);
385         if(visibility <= 0.0)
386                 return;
387         falloff *= visibility;
388
389         VecCopyf(eff_vel,eff_velocity);
390         Normalize(eff_vel);
391
392         switch(type){
393                 case PFIELD_WIND:
394                         VECCOPY(mag_vec,eff_vel);
395                         
396                         // add wind noise here, only if we have wind
397                         if((noise_factor > 0.0f) && (force_val > FLT_EPSILON))
398                                 noise = wind_func(rng, noise_factor);
399                         
400                         VecMulf(mag_vec,(force_val+noise)*falloff);
401                         VecAddf(field,field,mag_vec);
402                         break;
403
404                 case PFIELD_FORCE:
405                         if(planar)
406                                 Projf(mag_vec,vec_to_part,eff_vel);
407                         else
408                                 VecCopyf(mag_vec,vec_to_part);
409
410                         Normalize(mag_vec);
411
412                         VecMulf(mag_vec,force_val*falloff);
413                         VecAddf(field,field,mag_vec);
414                         break;
415
416                 case PFIELD_VORTEX:
417                         Crossf(mag_vec,eff_vel,vec_to_part);
418
419                         Normalize(mag_vec);
420
421                         VecMulf(mag_vec,force_val*distance*falloff);
422                         VecAddf(field,field,mag_vec);
423
424                         break;
425                 case PFIELD_MAGNET:
426                         if(planar)
427                                 VecCopyf(temp,eff_vel);
428                         else
429                                 /* magnetic field of a moving charge */
430                                 Crossf(temp,eff_vel,vec_to_part);
431
432                         Normalize(temp);
433
434                         Crossf(temp2,velocity,temp);
435                         VecAddf(mag_vec,mag_vec,temp2);
436
437                         VecMulf(mag_vec,force_val*falloff);
438                         VecAddf(field,field,mag_vec);
439                         break;
440                 case PFIELD_HARMONIC:
441                         if(planar)
442                                 Projf(mag_vec,vec_to_part,eff_vel);
443                         else
444                                 VecCopyf(mag_vec,vec_to_part);
445
446                         Normalize(mag_vec);
447
448                         VecMulf(mag_vec,force_val*falloff);
449                         VecSubf(field,field,mag_vec);
450
451                         VecCopyf(mag_vec,velocity);
452                         /* 1.9 is an experimental value to get critical damping at damp=1.0 */
453                         VecMulf(mag_vec,damp*1.9f*(float)sqrt(force_val));
454                         VecSubf(field,field,mag_vec);
455                         break;
456                 case PFIELD_CHARGE:
457                         if(planar)
458                                 Projf(mag_vec,vec_to_part,eff_vel);
459                         else
460                                 VecCopyf(mag_vec,vec_to_part);
461
462                         Normalize(mag_vec);
463
464                         VecMulf(mag_vec,charge*force_val*falloff);
465                         VecAddf(field,field,mag_vec);
466                         break;
467                 case PFIELD_LENNARDJ:
468                 {
469                         float fac;
470
471                         if(planar) {
472                                 Projf(mag_vec,vec_to_part,eff_vel);
473                                 distance = VecLength(mag_vec);
474                         }
475                         else
476                                 VecCopyf(mag_vec,vec_to_part);
477
478                         /* at this distance the field is 60 times weaker than maximum */
479                         if(distance > 2.22 * (size+pa_size))
480                                 break;
481
482                         fac = pow((size+pa_size)/distance,6.0);
483                         
484                         fac = - fac * (1.0 - fac) / distance;
485
486                         /* limit the repulsive term drastically to avoid huge forces */
487                         fac = ((fac>2.0) ? 2.0 : fac);
488
489                         /* 0.003715 is the fac value at 2.22 times (size+pa_size),
490                            substracted to avoid discontinuity at the border
491                         */
492                         VecMulf(mag_vec, force_val * (fac-0.0037315));
493                         VecAddf(field,field,mag_vec);
494                         break;
495                 }
496         }
497 }
498
499 /*  -------- pdDoEffectors() --------
500     generic force/speed system, now used for particles and softbodies
501     scene       = scene where it runs in, for time and stuff
502         lb                      = listbase with objects that take part in effecting
503         opco            = global coord, as input
504     force               = force accumulator
505     speed               = actual current speed which can be altered
506         cur_time        = "external" time in frames, is constant for static particles
507         loc_time        = "local" time in frames, range <0-1> for the lifetime of particle
508     par_layer   = layer the caller is in
509         flags           = only used for softbody wind now
510         guide           = old speed of particle
511
512 */
513 void pdDoEffectors(Scene *scene, ListBase *lb, float *opco, float *force, float *speed, float cur_time, float loc_time, unsigned int flags)
514 {
515 /*
516         Modifies the force on a particle according to its
517         relation with the effector object
518         Different kind of effectors include:
519                 Forcefields: Gravity-like attractor
520                 (force power is related to the inverse of distance to the power of a falloff value)
521                 Vortex fields: swirling effectors
522                 (particles rotate around Z-axis of the object. otherwise, same relation as)
523                 (Forcefields, but this is not done through a force/acceleration)
524                 Guide: particles on a path
525                 (particles are guided along a curve bezier or old nurbs)
526                 (is independent of other effectors)
527 */
528         Object *ob;
529         pEffectorCache *ec;
530         PartDeflect *pd;
531         
532         float distance, vec_to_part[3];
533         float falloff;
534
535         /* Cycle through collected objects, get total of (1/(gravity_strength * dist^gravity_power)) */
536         /* Check for min distance here? (yes would be cool to add that, ton) */
537         
538         for(ec = lb->first; ec; ec= ec->next) {
539                 /* object effectors were fully checked to be OK to evaluate! */
540                 ob= ec->ob;
541                 pd= ob->pd;
542                         
543                 /* Get IPO force strength and fall off values here */
544                 where_is_object_time(scene, ob, cur_time);
545                         
546                 /* use center of object for distance calculus */
547                 VecSubf(vec_to_part, opco, ob->obmat[3]);
548                 distance = VecLength(vec_to_part);
549
550                 falloff=effector_falloff(pd,ob->obmat[2],vec_to_part);          
551                 
552                 if(falloff<=0.0f)
553                         ;       /* don't do anything */
554                 else {
555                         float field[3]={0,0,0}, tmp[3];
556                         VECCOPY(field, force);
557                         do_physical_effector(scene, ob, opco, pd->forcefield,pd->f_strength,distance,
558                                                                 falloff, pd->f_dist, pd->f_damp, ob->obmat[2], vec_to_part,
559                                                                 speed,force, pd->flag&PFIELD_PLANAR, pd->rng, pd->f_noise, 0.0f, 0.0f);
560                         
561                         // for softbody backward compatibility
562                         if(flags & PE_WIND_AS_SPEED){
563                                 VECSUB(tmp, force, field);
564                                 VECSUB(speed, speed, tmp);
565                         }
566                 }
567         }
568 }