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