bugfix [#24455] Scene is left at last rendered frame from rendering an animation
[blender.git] / source / blender / editors / physics / physics_fluid.c
1 /**
2  * fluidsim.c
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  *
22  * The Original Code is Copyright (C) Blender Foundation
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
33
34 #include <math.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <sys/stat.h>
38
39 #ifdef WIN32    /* Windos */
40 #ifndef snprintf
41 #define snprintf _snprintf
42 #endif
43 #endif
44
45 #include "MEM_guardedalloc.h"
46
47 /* types */
48 #include "DNA_anim_types.h"
49 #include "DNA_action_types.h"
50 #include "DNA_object_types.h"
51 #include "DNA_object_fluidsim.h"        
52
53 #include "BLI_blenlib.h"
54 #include "BLI_threads.h"
55 #include "BLI_math.h"
56
57 #include "BKE_animsys.h"
58 #include "BKE_armature.h"
59 #include "BKE_blender.h"
60 #include "BKE_context.h"
61 #include "BKE_customdata.h"
62 #include "BKE_DerivedMesh.h"
63 #include "BKE_displist.h"
64 #include "BKE_effect.h"
65 #include "BKE_fluidsim.h"
66 #include "BKE_global.h"
67 #include "BKE_ipo.h"
68 #include "BKE_key.h"
69 #include "BKE_main.h"
70 #include "BKE_modifier.h"
71 #include "BKE_object.h"
72 #include "BKE_report.h"
73 #include "BKE_scene.h"
74 #include "BKE_softbody.h"
75 #include "BKE_unit.h"
76
77
78 #include "LBM_fluidsim.h"
79
80
81 #include "ED_screen.h"
82
83 #include "WM_types.h"
84
85 #include "physics_intern.h" // own include
86
87 /* enable/disable overall compilation */
88 #ifndef DISABLE_ELBEEM
89
90 #include "WM_api.h"
91
92 #include "DNA_scene_types.h"
93 #include "DNA_ipo_types.h"
94 #include "DNA_mesh_types.h"
95
96 #include "PIL_time.h"
97
98
99 static float get_fluid_viscosity(FluidsimSettings *settings)
100 {
101         switch (settings->viscosityMode) {
102                 case 0:         /* unused */
103                         return -1.0;
104                 case 2:         /* water */
105                         return 1.0e-6;
106                 case 3:         /* some (thick) oil */
107                         return 5.0e-5;
108                 case 4:         /* ca. honey */
109                         return 2.0e-3;
110                 case 1:         /* manual */
111                 default:
112                         return (1.0/pow(10.0, settings->viscosityExponent)) * settings->viscosityValue;
113         }
114 }
115
116 static void get_fluid_gravity(float *gravity, Scene *scene, FluidsimSettings *fss)
117 {
118         if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
119                 copy_v3_v3(gravity, scene->physics_settings.gravity);
120         } else {
121                 copy_v3_v3(gravity, &fss->gravx);
122         }
123 }
124
125 static float get_fluid_size_m(Scene *scene, Object *domainob, FluidsimSettings *fss)
126 {
127         if (!scene->unit.system) {
128                 return fss->realsize;
129         } else {
130                 float dim[3];
131                 float longest_axis;
132                 
133                 object_get_dimensions(domainob, dim);
134                 longest_axis = MAX3(dim[0], dim[1], dim[2]);
135                 
136                 return longest_axis * scene->unit.scale_length;
137         }
138 }
139
140 static int fluid_is_animated_mesh(FluidsimSettings *fss)
141 {
142         return ((fss->type == OB_FLUIDSIM_CONTROL) || fss->domainNovecgen);
143 }
144
145 /* ********************** fluid sim settings struct functions ********************** */
146
147 #if 0
148 /* helper function */
149 void fluidsimGetGeometryObjFilename(Object *ob, char *dst) { //, char *srcname) {
150         //snprintf(dst,FILE_MAXFILE, "%s_cfgdata_%s.bobj.gz", srcname, ob->id.name);
151         snprintf(dst,FILE_MAXFILE, "fluidcfgdata_%s.bobj.gz", ob->id.name);
152 }
153 #endif
154
155
156 /* ********************** fluid sim channel helper functions ********************** */
157
158 typedef struct FluidAnimChannels {
159         int length;
160         
161         double aniFrameTime;
162         
163         float *timeAtFrame;
164         float *DomainTime;
165         float *DomainGravity;
166         float *DomainViscosity;
167 } FluidAnimChannels;
168
169 typedef struct FluidObject {
170         struct FluidObject *next, *prev;
171         
172         struct Object *object;
173         
174         float *Translation;
175         float *Rotation;
176         float *Scale;
177         float *Active;
178         
179         float *InitialVelocity;
180         
181         float *AttractforceStrength;
182         float *AttractforceRadius;
183         float *VelocityforceStrength;
184         float *VelocityforceRadius;
185         
186         float *VertexCache;
187         int numVerts, numTris;
188 } FluidObject;
189
190 // no. of entries for the two channel sizes
191 #define CHANNEL_FLOAT 1
192 #define CHANNEL_VEC   3
193
194 // simplify channels before printing
195 // for API this is done anyway upon init
196 #if 0
197 static void fluidsimPrintChannel(FILE *file, float *channel, int paramsize, char *str, int entries) 
198
199         int i,j; 
200         int channelSize = paramsize; 
201
202         if(entries==3) {
203                 elbeemSimplifyChannelVec3( channel, &channelSize); 
204         } else if(entries==1) {
205                 elbeemSimplifyChannelFloat( channel, &channelSize); 
206         } else {
207                 // invalid, cant happen?
208         }
209
210         fprintf(file, "      CHANNEL %s = \n", str); 
211         for(i=0; i<channelSize;i++) { 
212                 fprintf(file,"        ");  
213                 for(j=0;j<=entries;j++) {  // also print time value
214                         fprintf(file," %f ", channel[i*(entries+1)+j] ); 
215                         if(j==entries-1){ fprintf(file,"  "); }
216                 } 
217                 fprintf(file," \n");  
218         } 
219
220         fprintf(file,  "      ; \n" ); 
221 }
222 #endif
223
224
225 /* Note: fluid anim channel data layout
226  * ------------------------------------
227  * CHANNEL_FLOAT:
228  * frame 1     |frame 2
229  * [dataF][time][dataF][time]
230  *
231  * CHANNEL_VEC:
232  * frame 1                   |frame 2
233  * [dataX][dataY][dataZ][time][dataX][dataY][dataZ][time]
234  *
235  */
236
237 static void init_time(FluidsimSettings *domainSettings, FluidAnimChannels *channels)
238 {
239         int i;
240         
241         channels->timeAtFrame = MEM_callocN( (channels->length+1)*sizeof(float), "timeAtFrame channel");
242         
243         channels->timeAtFrame[0] = channels->timeAtFrame[1] = domainSettings->animStart; // start at index 1
244         
245         for(i=2; i<=channels->length; i++) {
246                 channels->timeAtFrame[i] = channels->timeAtFrame[i-1] + channels->aniFrameTime;
247         }
248 }
249
250 /* if this is slow, can replace with faster, less readable code */
251 static void set_channel(float *channel, float time, float *value, int i, int size)
252 {
253         if (size == CHANNEL_FLOAT) {
254                 channel[(i * 2) + 0] = value[0];
255                 channel[(i * 2) + 1] = time;
256         }
257         else if (size == CHANNEL_VEC) {
258                 channel[(i * 4) + 0] = value[0];
259                 channel[(i * 4) + 1] = value[1];
260                 channel[(i * 4) + 2] = value[2];
261                 channel[(i * 4) + 3] = time;
262         }
263 }
264
265 static void set_vertex_channel(float *channel, float time, struct Scene *scene, struct FluidObject *fobj, int i)
266 {
267         Object *ob = fobj->object;
268         FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
269         float *verts;
270         int *tris=NULL, numVerts=0, numTris=0;
271         int modifierIndex = modifiers_indexInObject(ob, (ModifierData *)fluidmd);
272         int framesize = (3*fobj->numVerts) + 1;
273         int j;
274         
275         if (channel == NULL)
276                 return;
277         
278         initElbeemMesh(scene, ob, &numVerts, &verts, &numTris, &tris, 1, modifierIndex);
279         
280         /* don't allow mesh to change number of verts in anim sequence */
281         if (numVerts != fobj->numVerts) {
282                 MEM_freeN(channel);
283                 channel = NULL;
284                 return;
285         }
286         
287         /* fill frame of channel with vertex locations */
288         for(j=0; j < (3*numVerts); j++) {
289                 channel[i*framesize + j] = verts[j];
290         }
291         channel[i*framesize + framesize-1] = time;
292         
293         MEM_freeN(verts);
294         MEM_freeN(tris);
295 }
296
297 static void free_domain_channels(FluidAnimChannels *channels)
298 {
299         if (!channels->timeAtFrame)
300                 return;
301         MEM_freeN(channels->timeAtFrame);
302         channels->timeAtFrame = NULL;
303         MEM_freeN(channels->DomainGravity);
304         channels->DomainGravity = NULL;
305         MEM_freeN(channels->DomainViscosity);
306         channels->DomainViscosity = NULL;
307 }
308
309 static void free_all_fluidobject_channels(ListBase *fobjects)
310 {
311         FluidObject *fobj;
312         
313         for (fobj=fobjects->first; fobj; fobj=fobj->next) {
314                 if (fobj->Translation) {
315                         MEM_freeN(fobj->Translation);
316                         fobj->Translation = NULL;
317                         MEM_freeN(fobj->Rotation);
318                         fobj->Rotation = NULL;
319                         MEM_freeN(fobj->Scale);
320                         fobj->Scale = NULL;
321                         MEM_freeN(fobj->Active);
322                         fobj->Active = NULL;
323                         MEM_freeN(fobj->InitialVelocity);
324                         fobj->InitialVelocity = NULL;
325                 }
326                 
327                 if (fobj->AttractforceStrength) {
328                         MEM_freeN(fobj->AttractforceStrength);
329                         fobj->AttractforceStrength = NULL;
330                         MEM_freeN(fobj->AttractforceRadius);
331                         fobj->AttractforceRadius = NULL;
332                         MEM_freeN(fobj->VelocityforceStrength);
333                         fobj->VelocityforceStrength = NULL;
334                         MEM_freeN(fobj->VelocityforceRadius);
335                         fobj->VelocityforceRadius = NULL;
336                 }
337                 
338                 if (fobj->VertexCache) {
339                         MEM_freeN(fobj->VertexCache);
340                         fobj->VertexCache = NULL;
341                 }
342         }
343 }
344
345 static void fluid_init_all_channels(bContext *C, Object *UNUSED(fsDomain), FluidsimSettings *domainSettings, FluidAnimChannels *channels, ListBase *fobjects)
346 {
347         Scene *scene = CTX_data_scene(C);
348         Base *base;
349         int i;
350         int length = channels->length;
351         float eval_time;
352         
353         /* XXX: first init time channel - temporary for now */
354         /* init time values (should be done after evaluating animated time curve) */
355         init_time(domainSettings, channels);
356         
357         /* allocate domain animation channels */
358         channels->DomainGravity = MEM_callocN( length * (CHANNEL_VEC+1) * sizeof(float), "channel DomainGravity");
359         channels->DomainViscosity = MEM_callocN( length * (CHANNEL_FLOAT+1) * sizeof(float), "channel DomainViscosity");
360         //channels->DomainTime = MEM_callocN( length * (CHANNEL_FLOAT+1) * sizeof(float), "channel DomainTime");
361         
362         /* allocate fluid objects */
363         for (base=scene->base.first; base; base= base->next) {
364                 Object *ob = base->object;
365                 FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
366                 
367                 if (fluidmd) {
368                         FluidObject *fobj = MEM_callocN(sizeof(FluidObject), "Fluid Object");
369                         fobj->object = ob;
370                         
371                         if (ELEM(fluidmd->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE)) {
372                                 BLI_addtail(fobjects, fobj);
373                                 continue;
374                         }
375                         
376                         fobj->Translation = MEM_callocN( length * (CHANNEL_VEC+1) * sizeof(float), "fluidobject Translation");
377                         fobj->Rotation = MEM_callocN( length * (CHANNEL_VEC+1) * sizeof(float), "fluidobject Rotation");
378                         fobj->Scale = MEM_callocN( length * (CHANNEL_VEC+1) * sizeof(float), "fluidobject Scale");
379                         fobj->Active = MEM_callocN( length * (CHANNEL_FLOAT+1) * sizeof(float), "fluidobject Active");
380                         fobj->InitialVelocity = MEM_callocN( length * (CHANNEL_VEC+1) * sizeof(float), "fluidobject InitialVelocity");
381                         
382                         if (fluidmd->fss->type == OB_FLUIDSIM_CONTROL) {
383                                 fobj->AttractforceStrength = MEM_callocN( length * (CHANNEL_FLOAT+1) * sizeof(float), "fluidobject AttractforceStrength");
384                                 fobj->AttractforceRadius = MEM_callocN( length * (CHANNEL_FLOAT+1) * sizeof(float), "fluidobject AttractforceRadius");
385                                 fobj->VelocityforceStrength = MEM_callocN( length * (CHANNEL_FLOAT+1) * sizeof(float), "fluidobject VelocityforceStrength");
386                                 fobj->VelocityforceRadius = MEM_callocN( length * (CHANNEL_FLOAT+1) * sizeof(float), "fluidobject VelocityforceRadius");
387                         }
388                         
389                         if (fluid_is_animated_mesh(fluidmd->fss)) {
390                                 float *verts=NULL;
391                                 int *tris=NULL, modifierIndex = modifiers_indexInObject(ob, (ModifierData *)fluidmd);
392
393                                 initElbeemMesh(scene, ob, &fobj->numVerts, &verts, &fobj->numTris, &tris, 0, modifierIndex);
394                                 fobj->VertexCache = MEM_callocN( length *((fobj->numVerts*CHANNEL_VEC)+1) * sizeof(float), "fluidobject VertexCache");
395                                 
396                                 MEM_freeN(verts);
397                                 MEM_freeN(tris);
398                         }
399                         
400                         BLI_addtail(fobjects, fobj);
401                 }
402         }
403         
404         /* now we loop over the frames and fill the allocated channels with data */
405         for (i=0; i<channels->length; i++) {
406                 FluidObject *fobj;
407                 float viscosity, gravity[3];
408                 float timeAtFrame;
409                 
410                 eval_time = domainSettings->bakeStart + i;
411                 timeAtFrame = channels->timeAtFrame[i+1];
412                 
413                 /* XXX: This can't be used due to an anim sys optimisation that ignores recalc object animation,
414                  * leaving it for the depgraph (this ignores object animation such as modifier properties though... :/ )
415                  * --> BKE_animsys_evaluate_all_animation(G.main, eval_time);
416                  * This doesn't work with drivers:
417                  * --> BKE_animsys_evaluate_animdata(&fsDomain->id, fsDomain->adt, eval_time, ADT_RECALC_ALL);
418                  */
419                 
420                 /* Modifying the global scene isn't nice, but we can do it in 
421                  * this part of the process before a threaded job is created */
422                 scene->r.cfra = (int)eval_time;
423                 ED_update_for_newframe(CTX_data_main(C), scene, CTX_wm_screen(C), 1);
424                 
425                 /* now scene data should be current according to animation system, so we fill the channels */
426                 
427                 /* Domain properties - gravity/viscosity/time */
428                 get_fluid_gravity(gravity, scene, domainSettings);
429                 set_channel(channels->DomainGravity, timeAtFrame, gravity, i, CHANNEL_VEC);
430                 viscosity = get_fluid_viscosity(domainSettings);
431                 set_channel(channels->DomainViscosity, timeAtFrame, &viscosity, i, CHANNEL_FLOAT);
432                 // XXX : set_channel(channels->DomainTime, timeAtFrame, &time, i, CHANNEL_VEC);
433                 
434                 /* object movement */
435                 for (fobj=fobjects->first; fobj; fobj=fobj->next) {
436                         Object *ob = fobj->object;
437                         FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
438                         float active= (float)(fluidmd->fss->flag & OB_FLUIDSIM_ACTIVE);
439                         float rot_d[3], rot_360[3] = {360.f, 360.f, 360.f};
440                         
441                         if (ELEM(fluidmd->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE))
442                                 continue;
443                         
444                         /* init euler rotation values and convert to elbeem format */
445                         BKE_rotMode_change_values(ob->quat, ob->rot, ob->rotAxis, &ob->rotAngle, ob->rotmode, ROT_MODE_EUL);
446                         mul_v3_v3fl(rot_d, ob->rot, 180.f/M_PI);
447                         sub_v3_v3v3(rot_d, rot_360, rot_d);
448                         
449                         set_channel(fobj->Translation, timeAtFrame, ob->loc, i, CHANNEL_VEC);
450                         set_channel(fobj->Rotation, timeAtFrame, rot_d, i, CHANNEL_VEC);
451                         set_channel(fobj->Scale, timeAtFrame, ob->size, i, CHANNEL_VEC);
452                         set_channel(fobj->Active, timeAtFrame, &active, i, CHANNEL_FLOAT);
453                         set_channel(fobj->InitialVelocity, timeAtFrame, &fluidmd->fss->iniVelx, i, CHANNEL_VEC);
454                         
455                         if (fluidmd->fss->type == OB_FLUIDSIM_CONTROL) {
456                                 set_channel(fobj->AttractforceStrength, timeAtFrame, &fluidmd->fss->attractforceStrength, i, CHANNEL_FLOAT);
457                                 set_channel(fobj->AttractforceRadius, timeAtFrame, &fluidmd->fss->attractforceRadius, i, CHANNEL_FLOAT);
458                                 set_channel(fobj->VelocityforceStrength, timeAtFrame, &fluidmd->fss->velocityforceStrength, i, CHANNEL_FLOAT);
459                                 set_channel(fobj->VelocityforceRadius, timeAtFrame, &fluidmd->fss->velocityforceRadius, i, CHANNEL_FLOAT);
460                         }
461                         
462                         if (fluid_is_animated_mesh(fluidmd->fss)) {
463                                 set_vertex_channel(fobj->VertexCache, timeAtFrame, scene, fobj, i);
464                         }
465                 }
466         }
467 }
468
469 static void export_fluid_objects(ListBase *fobjects, Scene *scene, int length)
470 {
471         FluidObject *fobj;
472         
473         for (fobj=fobjects->first; fobj; fobj=fobj->next) {
474                 Object *ob = fobj->object;
475                 FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
476                 int modifierIndex = modifiers_indexInObject(ob, (ModifierData *)fluidmd);
477                 
478                 float *verts=NULL;
479                 int *tris=NULL;
480                 int numVerts=0, numTris=0;
481                 int deform = fluid_is_animated_mesh(fluidmd->fss);
482                 
483                 elbeemMesh fsmesh;
484                 
485                 if (ELEM(fluidmd->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE))
486                         continue;
487                 
488                 elbeemResetMesh( &fsmesh );
489                 
490                 fsmesh.type = fluidmd->fss->type;
491                 fsmesh.name = ob->id.name;
492                 
493                 initElbeemMesh(scene, ob, &numVerts, &verts, &numTris, &tris, 0, modifierIndex);
494                 
495                 fsmesh.numVertices   = numVerts;
496                 fsmesh.numTriangles  = numTris;
497                 fsmesh.vertices      = verts;
498                 fsmesh.triangles     = tris;
499                 
500                 fsmesh.channelSizeTranslation  = 
501                 fsmesh.channelSizeRotation     = 
502                 fsmesh.channelSizeScale        = 
503                 fsmesh.channelSizeInitialVel   = 
504                 fsmesh.channelSizeActive       = length;
505                 
506                 fsmesh.channelTranslation      = fobj->Translation;
507                 fsmesh.channelRotation         = fobj->Rotation;
508                 fsmesh.channelScale            = fobj->Scale;
509                 fsmesh.channelActive           = fobj->Active;
510                 
511                 if( ELEM(fsmesh.type, OB_FLUIDSIM_FLUID, OB_FLUIDSIM_INFLOW)) {
512                         fsmesh.channelInitialVel = fobj->InitialVelocity;
513                         fsmesh.localInivelCoords = ((fluidmd->fss->typeFlags & OB_FSINFLOW_LOCALCOORD)?1:0);
514                 } 
515                 
516                 if(fluidmd->fss->typeFlags & OB_FSBND_NOSLIP)
517                         fsmesh.obstacleType = FLUIDSIM_OBSTACLE_NOSLIP;
518                 else if(fluidmd->fss->typeFlags & OB_FSBND_PARTSLIP)
519                         fsmesh.obstacleType = FLUIDSIM_OBSTACLE_PARTSLIP;
520                 else if(fluidmd->fss->typeFlags & OB_FSBND_FREESLIP)
521                         fsmesh.obstacleType = FLUIDSIM_OBSTACLE_FREESLIP;
522                 
523                 fsmesh.obstaclePartslip = fluidmd->fss->partSlipValue;
524                 fsmesh.volumeInitType = fluidmd->fss->volumeInitType;
525                 fsmesh.obstacleImpactFactor = fluidmd->fss->surfaceSmoothing; // misused value
526                 
527                 if (fsmesh.type == OB_FLUIDSIM_CONTROL) {
528                         fsmesh.cpsTimeStart = fluidmd->fss->cpsTimeStart;
529                         fsmesh.cpsTimeEnd = fluidmd->fss->cpsTimeEnd;
530                         fsmesh.cpsQuality = fluidmd->fss->cpsQuality;
531                         fsmesh.obstacleType = (fluidmd->fss->flag & OB_FLUIDSIM_REVERSE);
532                         
533                         fsmesh.channelSizeAttractforceRadius = 
534                         fsmesh.channelSizeVelocityforceStrength = 
535                         fsmesh.channelSizeVelocityforceRadius = 
536                         fsmesh.channelSizeAttractforceStrength = length;
537                         
538                         fsmesh.channelAttractforceStrength = fobj->AttractforceStrength;
539                         fsmesh.channelAttractforceRadius = fobj->AttractforceRadius;
540                         fsmesh.channelVelocityforceStrength = fobj->VelocityforceStrength;
541                         fsmesh.channelVelocityforceRadius = fobj->VelocityforceRadius;
542                 }
543                 else {
544                         fsmesh.channelAttractforceStrength =
545                         fsmesh.channelAttractforceRadius = 
546                         fsmesh.channelVelocityforceStrength = 
547                         fsmesh.channelVelocityforceRadius = NULL; 
548                 }
549                 
550                 /* animated meshes */
551                 if(deform) {
552                         fsmesh.channelSizeVertices = length;
553                         fsmesh.channelVertices = fobj->VertexCache;
554                                 
555                         // remove channels
556                         fsmesh.channelTranslation      = 
557                         fsmesh.channelRotation         = 
558                         fsmesh.channelScale            = NULL; 
559                 }
560                 
561                 elbeemAddMesh(&fsmesh);
562                 
563                 if(verts) MEM_freeN(verts);
564                 if(tris) MEM_freeN(tris);
565         }
566 }
567
568 static int fluid_validate_scene(ReportList *reports, Scene *scene, Object *fsDomain)
569 {
570         Base *base;
571         Object *newdomain = NULL;
572         int channelObjCount = 0;
573         int fluidInputCount = 0;
574
575         for(base=scene->base.first; base; base= base->next)
576         {
577                 Object *ob = base->object;
578                 FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);                    
579
580                 /* only find objects with fluid modifiers */
581                 if (!fluidmdtmp || ob->type != OB_MESH) continue;
582                         
583                 if(fluidmdtmp->fss->type == OB_FLUIDSIM_DOMAIN) {
584                         /* if no initial domain object given, find another potential domain */
585                         if (!fsDomain) {
586                                 newdomain = ob;
587                         }
588                         /* if there's more than one domain, cancel */
589                         else if (fsDomain && ob != fsDomain) {
590                                 BKE_report(reports, RPT_ERROR, "There should be only one domain object.");
591                                 return 0;
592                         }
593                 }
594                 
595                 /* count number of objects needed for animation channels */
596                 if ( !ELEM(fluidmdtmp->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE) )
597                         channelObjCount++;
598                 
599                 /* count number of fluid input objects */
600                 if (ELEM(fluidmdtmp->fss->type, OB_FLUIDSIM_FLUID, OB_FLUIDSIM_INFLOW))
601                         fluidInputCount++;
602         }
603
604         if (newdomain)
605                 fsDomain = newdomain;
606         
607         if (!fsDomain) {
608                 BKE_report(reports, RPT_ERROR, "No domain object found.");
609                 return 0;
610         }
611         
612         if (channelObjCount>=255) {
613                 BKE_report(reports, RPT_ERROR, "Cannot bake with more then 256 objects.");
614                 return 0;
615         }
616         
617         if (fluidInputCount == 0) {
618                 BKE_report(reports, RPT_ERROR, "No fluid input objects in the scene.");
619                 return 0;
620         }
621         
622         return 1;
623 }
624
625
626 #define FLUID_SUFFIX_CONFIG             "fluidsim.cfg"
627 #define FLUID_SUFFIX_SURFACE    "fluidsurface"
628
629 static int fluid_init_filepaths(Object *fsDomain, char *targetDir, char *targetFile, char *debugStrBuffer)
630 {
631         FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(fsDomain, eModifierType_Fluidsim);
632         FluidsimSettings *domainSettings= fluidmd->fss; 
633         FILE *fileCfg;
634         int dirExist = 0;
635         char newSurfdataPath[FILE_MAXDIR+FILE_MAXFILE]; // modified output settings
636         char *suffixConfig = FLUID_SUFFIX_CONFIG;
637         int outStringsChanged = 0;
638         
639         // prepare names...
640         strncpy(targetDir, domainSettings->surfdataPath, FILE_MAXDIR);
641         strncpy(newSurfdataPath, domainSettings->surfdataPath, FILE_MAXDIR);
642         BLI_path_abs(targetDir, G.main->name); // fixed #frame-no 
643         
644         strcpy(targetFile, targetDir);
645         strcat(targetFile, suffixConfig);
646         strcat(targetFile,".tmp"); // dont overwrite/delete original file
647         // make sure all directories exist
648         // as the bobjs use the same dir, this only needs to be checked
649         // for the cfg output
650         BLI_make_existing_file(targetFile);
651         
652         // check selected directory
653         // simply try to open cfg file for writing to test validity of settings
654         fileCfg = fopen(targetFile, "w");
655         if(fileCfg) { 
656                 dirExist = 1; fclose(fileCfg); 
657                 // remove cfg dummy from  directory test
658                 BLI_delete(targetFile, 0,0);
659         }
660         
661         if((strlen(targetDir)<1) || (!dirExist)) {
662                 char blendDir[FILE_MAXDIR+FILE_MAXFILE];
663                 char blendFile[FILE_MAXDIR+FILE_MAXFILE];
664                 
665                 // invalid dir, reset to current/previous
666                 strcpy(blendDir, G.main->name);
667                 BLI_splitdirstring(blendDir, blendFile);
668                 if(strlen(blendFile)>6){
669                         int len = strlen(blendFile);
670                         if( (blendFile[len-6]=='.')&& (blendFile[len-5]=='b')&& (blendFile[len-4]=='l')&&
671                            (blendFile[len-3]=='e')&& (blendFile[len-2]=='n')&& (blendFile[len-1]=='d') ){
672                                 blendFile[len-6] = '\0';
673                         }
674                 }
675                 // todo... strip .blend ?
676                 snprintf(newSurfdataPath,FILE_MAXFILE+FILE_MAXDIR,"//fluidsimdata/%s_%s_", blendFile, fsDomain->id.name);
677                 
678                 snprintf(debugStrBuffer,256,"fluidsimBake::error - warning resetting output dir to '%s'\n", newSurfdataPath);
679                 elbeemDebugOut(debugStrBuffer);
680                 outStringsChanged=1;
681         }
682         
683         // check if modified output dir is ok
684 #if 0
685         if(outStringsChanged) {
686                 char dispmsg[FILE_MAXDIR+FILE_MAXFILE+256];
687                 int  selection=0;
688                 strcpy(dispmsg,"Output settings set to: '");
689                 strcat(dispmsg, newSurfdataPath);
690                 strcat(dispmsg, "'%t|Continue with changed settings%x1|Discard and abort%x0");
691                 
692                 // ask user if thats what he/she wants...
693                 selection = pupmenu(dispmsg);
694                 if(selection<1) return 0; // 0 from menu, or -1 aborted
695                 strcpy(targetDir, newSurfdataPath);
696                 strncpy(domainSettings->surfdataPath, newSurfdataPath, FILE_MAXDIR);
697                 BLI_path_abs(targetDir, G.main->name); // fixed #frame-no 
698         }
699 #endif  
700         return outStringsChanged;
701 }
702
703 /* ******************************************************************************** */
704 /* ********************** write fluidsim config to file ************************* */
705 /* ******************************************************************************** */
706
707 typedef struct FluidBakeJob {
708         /* from wmJob */
709         void *owner;
710         short *stop, *do_update;
711         float *progress;
712         int current_frame;
713         elbeemSimulationSettings *settings;
714 } FluidBakeJob;
715
716 static void fluidbake_free(void *customdata)
717 {
718         FluidBakeJob *fb= customdata;
719         MEM_freeN(fb);
720 }
721
722 /* called by fluidbake, only to check job 'stop' value */
723 static int fluidbake_breakjob(void *UNUSED(customdata))
724 {
725         //FluidBakeJob *fb= (FluidBakeJob *)customdata;
726         //return *(fb->stop);
727         
728         /* this is not nice yet, need to make the jobs list template better 
729          * for identifying/acting upon various different jobs */
730         /* but for now we'll reuse the render break... */
731         return (G.afbreek);
732 }
733
734 /* called by fluidbake, wmJob sends notifier */
735 static void fluidbake_updatejob(void *customdata, float progress)
736 {
737         FluidBakeJob *fb= customdata;
738         
739         *(fb->do_update)= 1;
740         *(fb->progress)= progress;
741 }
742
743 static void fluidbake_startjob(void *customdata, short *stop, short *do_update, float *progress)
744 {
745         FluidBakeJob *fb= customdata;
746         
747         fb->stop= stop;
748         fb->do_update = do_update;
749         fb->progress = progress;
750         
751         G.afbreek= 0;   /* XXX shared with render - replace with job 'stop' switch */
752         
753         elbeemSimulate();
754         *do_update= 1;
755         *stop = 0;
756 }
757
758 static void fluidbake_endjob(void *customdata)
759 {
760         FluidBakeJob *fb= customdata;
761         
762         if (fb->settings) {
763                 MEM_freeN(fb->settings);
764                 fb->settings = NULL;
765         }
766 }
767
768 int runSimulationCallback(void *data, int status, int frame) {
769         FluidBakeJob *fb = (FluidBakeJob *)data;
770         elbeemSimulationSettings *settings = fb->settings;
771         
772         if (status == FLUIDSIM_CBSTATUS_NEWFRAME) {
773                 fluidbake_updatejob(fb, frame / (float)settings->noOfFrames);
774                 //printf("elbeem blender cb s%d, f%d, domainid:%d noOfFrames: %d \n", status,frame, settings->domainId, settings->noOfFrames ); // DEBUG
775         }
776         
777         if (fluidbake_breakjob(fb))  {
778                 return FLUIDSIM_CBRET_ABORT;
779         }
780         
781         return FLUIDSIM_CBRET_CONTINUE;
782 }
783
784 static void fluidbake_free_data(FluidAnimChannels *channels, ListBase *fobjects, elbeemSimulationSettings *fsset, FluidBakeJob *fb)
785 {
786         free_domain_channels(channels);
787         MEM_freeN(channels);
788         channels = NULL;
789
790         free_all_fluidobject_channels(fobjects);
791         BLI_freelistN(fobjects);
792         MEM_freeN(fobjects);
793         fobjects = NULL;
794         
795         if (fsset) {
796                 MEM_freeN(fsset);
797                 fsset = NULL;
798         }
799         
800         if (fb) {
801                 MEM_freeN(fb);
802                 fb = NULL;
803         }
804 }
805
806 int fluidsimBake(bContext *C, ReportList *reports, Object *fsDomain)
807 {
808         Scene *scene= CTX_data_scene(C);
809         int i;
810         FluidsimSettings *domainSettings;
811
812         char debugStrBuffer[256];
813         
814         int gridlevels = 0;
815         const char *strEnvName = "BLENDER_ELBEEMDEBUG"; // from blendercall.cpp
816         char *suffixConfig = FLUID_SUFFIX_CONFIG;
817         char *suffixSurface = FLUID_SUFFIX_SURFACE;
818
819         char targetDir[FILE_MAXDIR+FILE_MAXFILE];  // store & modify output settings
820         char targetFile[FILE_MAXDIR+FILE_MAXFILE]; // temp. store filename from targetDir for access
821         int  outStringsChanged = 0;             // modified? copy back before baking
822
823         float domainMat[4][4];
824         float invDomMat[4][4];
825
826         int noFrames;
827         int origFrame = scene->r.cfra;
828         
829         FluidAnimChannels *channels = MEM_callocN(sizeof(FluidAnimChannels), "fluid domain animation channels");
830         ListBase *fobjects = MEM_callocN(sizeof(ListBase), "fluid objects");
831         FluidsimModifierData *fluidmd = NULL;
832         Mesh *mesh = NULL;
833         
834         wmJob *steve;
835         FluidBakeJob *fb;
836         elbeemSimulationSettings *fsset= MEM_callocN(sizeof(elbeemSimulationSettings), "Fluid sim settings");
837         
838         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, "Fluid Simulation", WM_JOB_PROGRESS);
839         fb= MEM_callocN(sizeof(FluidBakeJob), "fluid bake job");
840         
841         if(getenv(strEnvName)) {
842                 int dlevel = atoi(getenv(strEnvName));
843                 elbeemSetDebugLevel(dlevel);
844                 snprintf(debugStrBuffer,256,"fluidsimBake::msg: Debug messages activated due to envvar '%s'\n",strEnvName); 
845                 elbeemDebugOut(debugStrBuffer);
846         }
847         
848         /* make sure it corresponds to startFrame setting (old: noFrames = scene->r.efra - scene->r.sfra +1) */;
849         noFrames = scene->r.efra - 0;
850         if(noFrames<=0) {
851                 BKE_report(reports, RPT_ERROR, "No frames to export - check your animation range settings.");
852                 fluidbake_free_data(channels, fobjects, fsset, fb);
853                 return 0;
854         }
855         
856         /* check scene for sane object/modifier settings */
857         if (!fluid_validate_scene(reports, scene, fsDomain)) {
858                 fluidbake_free_data(channels, fobjects, fsset, fb);
859                 return 0;
860         }
861         
862         /* these both have to be valid, otherwise we wouldnt be here */
863         fluidmd = (FluidsimModifierData *)modifiers_findByType(fsDomain, eModifierType_Fluidsim);
864         domainSettings = fluidmd->fss;
865         mesh = fsDomain->data;
866         
867         domainSettings->bakeStart = 1;
868         domainSettings->bakeEnd = scene->r.efra;
869         
870         // calculate bounding box
871         fluid_get_bb(mesh->mvert, mesh->totvert, fsDomain->obmat, domainSettings->bbStart, domainSettings->bbSize);
872         
873         // reset last valid frame
874         domainSettings->lastgoodframe = -1;
875         
876         /* rough check of settings... */
877         if(domainSettings->previewresxyz > domainSettings->resolutionxyz) {
878                 snprintf(debugStrBuffer,256,"fluidsimBake::warning - Preview (%d) >= Resolution (%d)... setting equal.\n", domainSettings->previewresxyz ,  domainSettings->resolutionxyz); 
879                 elbeemDebugOut(debugStrBuffer);
880                 domainSettings->previewresxyz = domainSettings->resolutionxyz;
881         }
882         // set adaptive coarsening according to resolutionxyz
883         // this should do as an approximation, with in/outflow
884         // doing this more accurate would be overkill
885         // perhaps add manual setting?
886         if(domainSettings->maxRefine <0) {
887                 if(domainSettings->resolutionxyz>128) {
888                         gridlevels = 2;
889                 } else
890                 if(domainSettings->resolutionxyz>64) {
891                         gridlevels = 1;
892                 } else {
893                         gridlevels = 0;
894                 }
895         } else {
896                 gridlevels = domainSettings->maxRefine;
897         }
898         snprintf(debugStrBuffer,256,"fluidsimBake::msg: Baking %s, refine: %d\n", fsDomain->id.name , gridlevels ); 
899         elbeemDebugOut(debugStrBuffer);
900         
901         
902         
903         /* ******** prepare output file paths ******** */
904         outStringsChanged = fluid_init_filepaths(fsDomain, targetDir, targetFile, debugStrBuffer);
905         channels->length = scene->r.efra;
906         channels->aniFrameTime = (domainSettings->animEnd - domainSettings->animStart)/(double)noFrames;
907         
908         /* ******** initialise and allocate animation channels ******** */
909         fluid_init_all_channels(C, fsDomain, domainSettings, channels, fobjects);
910
911         /* reset to original current frame */
912         scene->r.cfra = origFrame;
913         ED_update_for_newframe(CTX_data_main(C), scene, CTX_wm_screen(C), 1);
914         
915         
916         /* ---- XXX: No Time animation curve for now, leaving this code here for reference 
917          
918         { int timeIcu[1] = { FLUIDSIM_TIME };
919                 float timeDef[1] = { 1. };
920
921                 // time channel is a bit special, init by hand...
922                 timeAtIndex = MEM_callocN( (allchannelSize+1)*1*sizeof(float), "fluidsiminit_timeatindex");
923                 for(i=0; i<=scene->r.efra; i++) {
924                         timeAtIndex[i] = (float)(i-startFrame);
925                 }
926                 fluidsimInitChannel(scene, &channelDomainTime, allchannelSize, timeAtIndex, timeIcu,timeDef, domainSettings->ipo, CHANNEL_FLOAT ); // NDEB
927                 // time channel is a multiplicator for 
928                 if(channelDomainTime) {
929                         for(i=0; i<allchannelSize; i++) { 
930                                 channelDomainTime[i*2+0] = aniFrameTime * channelDomainTime[i*2+0]; 
931                                 if(channelDomainTime[i*2+0]<0.) channelDomainTime[i*2+0] = 0.;
932                         }
933                 }
934                 timeAtFrame = MEM_callocN( (allchannelSize+1)*1*sizeof(float), "fluidsiminit_timeatframe");
935                 timeAtFrame[0] = timeAtFrame[1] = domainSettings->animStart; // start at index 1
936                 if(channelDomainTime) {
937                         for(i=2; i<=allchannelSize; i++) {
938                                 timeAtFrame[i] = timeAtFrame[i-1]+channelDomainTime[(i-1)*2+0];
939                         }
940                 fsset->} else {
941                         for(i=2; i<=allchannelSize; i++) { timeAtFrame[i] = timeAtFrame[i-1]+aniFrameTime; }
942                 }
943
944         } // domain channel init
945         */
946                 
947         /* ******** init domain object's matrix ******** */
948         copy_m4_m4(domainMat, fsDomain->obmat);
949         if(!invert_m4_m4(invDomMat, domainMat)) {
950                 snprintf(debugStrBuffer,256,"fluidsimBake::error - Invalid obj matrix?\n"); 
951                 elbeemDebugOut(debugStrBuffer);
952                 BKE_report(reports, RPT_ERROR, "Invalid object matrix."); 
953
954                 fluidbake_free_data(channels, fobjects, fsset, fb);
955                 return 0;
956         }
957
958         /* ********  start writing / exporting ******** */
959         strcpy(targetFile, targetDir);
960         strcat(targetFile, suffixConfig);
961         strcat(targetFile,".tmp");  // dont overwrite/delete original file
962         
963         // make sure these directories exist as well
964         if(outStringsChanged) {
965                 BLI_make_existing_file(targetFile);
966         }
967
968         /* ******** export domain to elbeem ******** */
969         elbeemResetSettings(fsset);
970         fsset->version = 1;
971
972         // setup global settings
973         copy_v3_v3(fsset->geoStart, domainSettings->bbStart);
974         copy_v3_v3(fsset->geoSize, domainSettings->bbSize);
975         
976         // simulate with 50^3
977         fsset->resolutionxyz = (int)domainSettings->resolutionxyz;
978         fsset->previewresxyz = (int)domainSettings->previewresxyz;
979
980         fsset->realsize = get_fluid_size_m(scene, fsDomain, domainSettings);
981         fsset->viscosity = get_fluid_viscosity(domainSettings);
982         get_fluid_gravity(fsset->gravity, scene, domainSettings);
983
984         // simulate 5 frames, each 0.03 seconds, output to ./apitest_XXX.bobj.gz
985         fsset->animStart = domainSettings->animStart;
986         fsset->aniFrameTime = channels->aniFrameTime;
987         fsset->noOfFrames = noFrames; // is otherwise subtracted in parser
988
989         strcpy(targetFile, targetDir);
990         strcat(targetFile, suffixSurface);
991         // defaults for compressibility and adaptive grids
992         fsset->gstar = domainSettings->gstar;
993         fsset->maxRefine = domainSettings->maxRefine; // check <-> gridlevels
994         fsset->generateParticles = domainSettings->generateParticles; 
995         fsset->numTracerParticles = domainSettings->generateTracers; 
996         fsset->surfaceSmoothing = domainSettings->surfaceSmoothing; 
997         fsset->surfaceSubdivs = domainSettings->surfaceSubdivs; 
998         fsset->farFieldSize = domainSettings->farFieldSize; 
999         strcpy( fsset->outputPath, targetFile);
1000
1001         // domain channels
1002         fsset->channelSizeFrameTime = 
1003         fsset->channelSizeViscosity = 
1004         fsset->channelSizeGravity = channels->length;
1005         fsset->channelFrameTime = channels->DomainTime;
1006         fsset->channelViscosity = channels->DomainViscosity;
1007         fsset->channelGravity = channels->DomainGravity;
1008         
1009         fsset->runsimCallback = &runSimulationCallback;
1010         fsset->runsimUserData = fb;
1011
1012         if (domainSettings->typeFlags & OB_FSBND_NOSLIP)                fsset->domainobsType = FLUIDSIM_OBSTACLE_NOSLIP;
1013         else if (domainSettings->typeFlags&OB_FSBND_PARTSLIP)   fsset->domainobsType = FLUIDSIM_OBSTACLE_PARTSLIP;
1014         else if (domainSettings->typeFlags&OB_FSBND_FREESLIP)   fsset->domainobsType = FLUIDSIM_OBSTACLE_FREESLIP;
1015         fsset->domainobsPartslip = domainSettings->partSlipValue;
1016         fsset->generateVertexVectors = (domainSettings->domainNovecgen==0);
1017
1018         // init blender domain transform matrix
1019         { int j; 
1020         for(i=0; i<4; i++) {
1021                 for(j=0; j<4; j++) {
1022                         fsset->surfaceTrafo[i*4+j] = invDomMat[j][i];
1023                 }
1024         } }
1025
1026         /* ******** init solver with settings ******** */
1027         elbeemInit();
1028         elbeemAddDomain(fsset);
1029         
1030         /* ******** export all fluid objects to elbeem ******** */
1031         export_fluid_objects(fobjects, scene, channels->length);
1032         
1033         /* custom data for fluid bake job */
1034         fb->settings = fsset;
1035         
1036         /* setup job */
1037         WM_jobs_customdata(steve, fb, fluidbake_free);
1038         WM_jobs_timer(steve, 0.1, NC_SCENE|ND_FRAME, NC_SCENE|ND_FRAME);
1039         WM_jobs_callbacks(steve, fluidbake_startjob, NULL, NULL, fluidbake_endjob);
1040         
1041         WM_jobs_start(CTX_wm_manager(C), steve);
1042
1043         /* ******** free stored animation data ******** */
1044         fluidbake_free_data(channels, fobjects, NULL, NULL);
1045
1046         // elbeemFree();
1047         return 1;
1048 }
1049
1050 void fluidsimFreeBake(Object *UNUSED(ob))
1051 {
1052         /* not implemented yet */
1053 }
1054
1055 #else /* DISABLE_ELBEEM */
1056
1057 /* compile dummy functions for disabled fluid sim */
1058
1059 FluidsimSettings *fluidsimSettingsNew(Object *UNUSED(srcob))
1060 {
1061         return NULL;
1062 }
1063
1064 void fluidsimSettingsFree(FluidsimSettings *UNUSED(fss))
1065 {
1066 }
1067
1068 FluidsimSettings* fluidsimSettingsCopy(FluidsimSettings *UNUSED(fss))
1069 {
1070         return NULL;
1071 }
1072
1073 /* only compile dummy functions */
1074 int fluidsimBake(bContext *UNUSED(C), ReportList *UNUSED(reports), Object *UNUSED(ob))
1075 {
1076         return 0;
1077 }
1078
1079 void fluidsimFreeBake(Object *UNUSED(ob))
1080 {
1081 }
1082
1083 #endif /* DISABLE_ELBEEM */
1084
1085 /***************************** Operators ******************************/
1086
1087 static int fluid_bake_exec(bContext *C, wmOperator *op)
1088 {
1089         Object *ob= CTX_data_active_object(C);
1090
1091         if(!fluidsimBake(C, op->reports, ob))
1092                 return OPERATOR_CANCELLED;
1093
1094         return OPERATOR_FINISHED;
1095 }
1096
1097 void FLUID_OT_bake(wmOperatorType *ot)
1098 {
1099         /* identifiers */
1100         ot->name= "Fluid Simulation Bake";
1101         ot->description= "Bake fluid simulation";
1102         ot->idname= "FLUID_OT_bake";
1103         
1104         /* api callbacks */
1105         ot->exec= fluid_bake_exec;
1106         ot->poll= ED_operator_object_active_editable;
1107 }
1108