05e82921e92ae6fda48dc0c13ad60ccc4e85f5a1
[blender.git] / source / blender / src / fluidsim.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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, 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
38
39 #include "MEM_guardedalloc.h"
40
41 /* types */
42 #include "DNA_curve_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_object_fluidsim.h"        
45 #include "DNA_key_types.h"
46 #include "DNA_mesh_types.h"
47 #include "DNA_meshdata_types.h"
48 #include "DNA_lattice_types.h"
49 #include "DNA_scene_types.h"
50 #include "DNA_camera_types.h"
51 #include "DNA_screen_types.h"
52 #include "DNA_space_types.h"
53 #include "DNA_userdef_types.h"
54 #include "DNA_ipo_types.h"
55 #include "DNA_key_types.h" 
56
57 #include "BLI_blenlib.h"
58 #include "BLI_arithb.h"
59 #include "MTC_matrixops.h"
60
61 #include "BKE_customdata.h"
62 #include "BKE_displist.h"
63 #include "BKE_effect.h"
64 #include "BKE_fluidsim.h"
65 #include "BKE_global.h"
66 #include "BKE_modifier.h"
67 #include "BKE_main.h"
68 #include "BKE_key.h"
69 #include "BKE_scene.h"
70 #include "BKE_object.h"
71 #include "BKE_softbody.h"
72 #include "BKE_DerivedMesh.h"
73 #include "BKE_ipo.h"
74 #include "LBM_fluidsim.h"
75 // warning - double elbeem.h in intern/extern...
76 #include "elbeem.h"
77
78 #include "BLI_editVert.h"
79 #include "BIF_editdeform.h"
80 #include "BIF_gl.h"
81 #include "BIF_screen.h"
82 #include "BIF_space.h"
83 #include "BIF_cursors.h"
84 #include "BIF_interface.h"
85 #include "BSE_headerbuttons.h"
86
87 #include "mydevice.h"
88 #include "blendef.h"
89 #include "SDL.h"
90 #include "SDL_thread.h"
91 #include "SDL_mutex.h"
92 #include <sys/stat.h>
93
94 #ifdef WIN32    /* Windos */
95 //#include "BLI_winstuff.h"
96 #ifndef snprintf
97 #define snprintf _snprintf
98 #endif
99 #endif
100 // SDL redefines main for SDL_main, not needed here...
101 #undef main
102
103 #ifdef __APPLE__        /* MacOS X */
104 #undef main
105 #endif
106
107 /* from header info.c */
108 extern int start_progress_bar(void);
109 extern void end_progress_bar(void);
110 extern int progress_bar(float done, char *busy_info);
111
112 double fluidsimViscosityPreset[6] = {
113         -1.0,   /* unused */
114         -1.0,   /* manual */
115         1.0e-6, /* water */
116         5.0e-5, /* some (thick) oil */
117         2.0e-3, /* ca. honey */
118         -1.0    /* end */
119 };
120
121 char* fluidsimViscosityPresetString[6] = {
122         "UNUSED",       /* unused */
123         "UNUSED",       /* manual */
124         "  = 1.0 * 10^-6", /* water */
125         "  = 5.0 * 10^-5", /* some (thick) oil */
126         "  = 2.0 * 10^-3", /* ca. honey */
127         "INVALID"       /* end */
128 };
129
130 /* enable/disable overall compilation */
131 #ifndef DISABLE_ELBEEM
132
133
134 /* ********************** fluid sim settings struct functions ********************** */
135
136 /* helper function */
137 void fluidsimGetGeometryObjFilename(struct Object *ob, char *dst) { //, char *srcname) {
138         //snprintf(dst,FILE_MAXFILE, "%s_cfgdata_%s.bobj.gz", srcname, ob->id.name);
139         snprintf(dst,FILE_MAXFILE, "fluidcfgdata_%s.bobj.gz", ob->id.name);
140 }
141
142
143
144
145 /* ******************************************************************************** */
146 /* ********************** fluid sim channel helper functions ********************** */
147 /* ******************************************************************************** */
148
149 // no. of entries for the two channel sizes
150 #define CHANNEL_FLOAT 1
151 #define CHANNEL_VEC   3
152
153 #define FS_FREE_ONECHANNEL(c,str) { \
154         if(c){ MEM_freeN(c); c=NULL; } \
155 } // end ONE CHANN, debug: fprintf(stderr,"freeing " str " \n"); 
156
157 #define FS_FREE_CHANNELS { \
158         FS_FREE_ONECHANNEL(timeAtIndex,"timeAtIndex");\
159         FS_FREE_ONECHANNEL(timeAtFrame,"timeAtFrame");\
160         FS_FREE_ONECHANNEL(channelDomainTime,"channelDomainTime"); \
161         FS_FREE_ONECHANNEL(channelDomainGravity,"channelDomainGravity");\
162         FS_FREE_ONECHANNEL(channelDomainViscosity,"channelDomainViscosity");\
163         for(i=0;i<256;i++) { \
164                 FS_FREE_ONECHANNEL(channelObjMove[i][0],"channelObjMove0"); \
165                 FS_FREE_ONECHANNEL(channelObjMove[i][1],"channelObjMove1"); \
166                 FS_FREE_ONECHANNEL(channelObjMove[i][2],"channelObjMove2"); \
167                 FS_FREE_ONECHANNEL(channelObjInivel[i],"channelObjInivel"); \
168                 FS_FREE_ONECHANNEL(channelObjActive[i],"channelObjActive"); \
169                 FS_FREE_ONECHANNEL(channelAttractforceStrength[i],"channelAttractforceStrength"); \
170                 FS_FREE_ONECHANNEL(channelAttractforceRadius[i],"channelAttractforceRadius"); \
171                 FS_FREE_ONECHANNEL(channelVelocityforceStrength[i],"channelVelocityforceStrength"); \
172                 FS_FREE_ONECHANNEL(channelVelocityforceRadius[i],"channelVelocityforceRadius"); \
173         }  \
174 } // end FS FREE CHANNELS
175
176
177 // simplify channels before printing
178 // for API this is done anyway upon init
179 #if 0
180 static void fluidsimPrintChannel(FILE *file, float *channel, int paramsize, char *str, int entries) 
181
182         int i,j; 
183         int channelSize = paramsize; 
184
185         if(entries==3) {
186                 elbeemSimplifyChannelVec3( channel, &channelSize); 
187         } else if(entries==1) {
188                 elbeemSimplifyChannelFloat( channel, &channelSize); 
189         } else {
190                 // invalid, cant happen?
191         }
192
193         fprintf(file, "      CHANNEL %s = \n", str); 
194         for(i=0; i<channelSize;i++) { 
195                 fprintf(file,"        ");  
196                 for(j=0;j<=entries;j++) {  // also print time value
197                         fprintf(file," %f ", channel[i*(entries+1)+j] ); 
198                         if(j==entries-1){ fprintf(file,"  "); }
199                 } 
200                 fprintf(file," \n");  
201         } 
202
203         fprintf(file,  "      ; \n" ); 
204 }
205 #endif
206
207 static void fluidsimInitChannel(float **setchannel, int size, float *time, 
208                 int *icuIds, float *defaults, Ipo* ipo, int entries) {
209         int i,j;
210         IpoCurve* icus[3];
211         char *cstr = NULL;
212         float *channel = NULL;
213         float aniFrlen = G.scene->r.framelen;
214         int current_frame = G.scene->r.cfra;
215         if((entries<1) || (entries>3)) {
216                 printf("fluidsimInitChannel::Error - invalid no. of entries: %d\n",entries);
217                 entries = 1;
218         }
219
220         cstr = "fluidsiminit_channelfloat";
221         if(entries>1) cstr = "fluidsiminit_channelvec";
222         channel = MEM_callocN( size* (entries+1)* sizeof(float), cstr );
223         
224         if(ipo) {
225                 for(j=0; j<entries; j++) icus[j]  = find_ipocurve(ipo, icuIds[j] );
226         } else {
227                 for(j=0; j<entries; j++) icus[j]  = NULL; 
228         }
229         
230         for(j=0; j<entries; j++) {
231                 if(icus[j]) { 
232                         for(i=1; i<=size; i++) {
233                                 /* Bugfix to make python drivers working
234                                 // which uses Blender.get("curframe") 
235                                 */
236                                 G.scene->r.cfra = floor(aniFrlen*((float)i));
237                                 
238                                 calc_icu(icus[j], aniFrlen*((float)i) );
239                                 channel[(i-1)*(entries+1) + j] = icus[j]->curval;
240                         }
241                 }  else {
242                         for(i=1; i<=size; i++) { channel[(i-1)*(entries+1) + j] = defaults[j]; }
243                 }
244                 //printf("fluidsimInitChannel entry:%d , ",j); for(i=1; i<=size; i++) { printf(" val%d:%f ",i, channel[(i-1)*(entries+1) + j] ); } printf(" \n"); // DEBUG
245         }
246         // set time values
247         for(i=1; i<=size; i++) {
248                 channel[(i-1)*(entries+1) + entries] = time[i];
249         }
250         G.scene->r.cfra = current_frame;
251         *setchannel = channel;
252 }
253
254 static void fluidsimInitMeshChannel(float **setchannel, int size, Object *obm, int vertices, float *time, int modifierIndex) {
255         float *channel = NULL;
256         int mallsize = size* (3*vertices+1);
257         int frame,i;
258         int numVerts=0, numTris=0;
259         int setsize = 3*vertices+1;
260
261         channel = MEM_callocN( mallsize* sizeof(float), "fluidsim_meshchannel" );
262
263         //fprintf(stderr,"\n\nfluidsimInitMeshChannel size%d verts%d mallsize%d \n\n\n",size,vertices,mallsize);
264         for(frame=1; frame<=size; frame++) {
265                 float *verts=NULL;
266                 int *tris=NULL;
267                 G.scene->r.cfra = frame;
268                 scene_update_for_newframe(G.scene, G.scene->lay);
269
270                 initElbeemMesh(obm, &numVerts, &verts, &numTris, &tris, 1, modifierIndex);
271                 //fprintf(stderr,"\nfluidsimInitMeshChannel frame%d verts%d/%d \n\n",frame,vertices,numVerts);
272                 for(i=0; i<3*vertices;i++) {
273                         channel[(frame-1)*setsize + i] = verts[i];
274                         //fprintf(stdout," frame%d vert%d=%f \n",frame,i,verts[i]);
275                         //if(i%3==2) fprintf(stdout,"\n");
276                 }
277                 channel[(frame-1)*setsize + setsize-1] = time[frame];
278
279                 MEM_freeN(verts);
280                 MEM_freeN(tris);
281         }
282         *setchannel = channel;
283 }
284
285
286 /* ******************************************************************************** */
287 /* ********************** simulation thread             ************************* */
288 /* ******************************************************************************** */
289
290 SDL_mutex       *globalBakeLock=NULL;
291 int                     globalBakeState = 0; // 0 everything ok, -1 abort simulation, -2 sim error, 1 sim done
292 int                     globalBakeFrame = 0;
293
294 // run simulation in seperate thread
295 static int fluidsimSimulateThread(void *unused) { // *ptr) {
296         //char* fnameCfgPath = (char*)(ptr);
297         int ret=0;
298         
299         ret = elbeemSimulate();
300         SDL_mutexP(globalBakeLock);
301         if(globalBakeState==0) {
302                 if(ret==0) {
303                         // if no error, set to normal exit
304                         globalBakeState = 1;
305                 } else {
306                         // simulation failed, display error
307                         globalBakeState = -2;
308                 }
309         }
310         SDL_mutexV(globalBakeLock);
311         return ret;
312 }
313
314
315 int runSimulationCallback(void *data, int status, int frame) {
316         //elbeemSimulationSettings *settings = (elbeemSimulationSettings*)data;
317         //printf("elbeem blender cb s%d, f%d, domainid:%d \n", status,frame, settings->domainId ); // DEBUG
318         
319         if(!globalBakeLock) return FLUIDSIM_CBRET_ABORT;
320         if(status==FLUIDSIM_CBSTATUS_NEWFRAME) {
321                 SDL_mutexP(globalBakeLock);
322                 globalBakeFrame = frame-1;
323                 SDL_mutexV(globalBakeLock);
324         }
325         
326         //if((frameCounter==3) && (!frameStop)) { frameStop=1; return 1; }
327                 
328         SDL_mutexP(globalBakeLock);
329         if(globalBakeState!=0) {
330                 return FLUIDSIM_CBRET_ABORT;
331         }
332         SDL_mutexV(globalBakeLock);
333         return FLUIDSIM_CBRET_CONTINUE;
334 }
335
336
337 /* ******************************************************************************** */
338 /* ********************** write fluidsim config to file ************************* */
339 /* ******************************************************************************** */
340
341 void fluidsimBake(struct Object *ob)
342 {
343         FILE *fileCfg;
344         int i;
345         struct Object *fsDomain = NULL;
346         FluidsimSettings *domainSettings;
347         struct Object *obit = NULL; /* object iterator */
348         Base *base;
349         int origFrame = G.scene->r.cfra;
350         char debugStrBuffer[256];
351         int dirExist = 0;
352         int gridlevels = 0;
353         int simAborted = 0; // was the simulation aborted by user?
354         int  doExportOnly = 0;
355         char *exportEnvStr = "BLENDER_ELBEEMEXPORTONLY";
356         const char *strEnvName = "BLENDER_ELBEEMDEBUG"; // from blendercall.cpp
357         //char *channelNames[3] = { "translation","rotation","scale" };
358
359         char *suffixConfig = "fluidsim.cfg";
360         char *suffixSurface = "fluidsurface";
361         char newSurfdataPath[FILE_MAXDIR+FILE_MAXFILE]; // modified output settings
362         char targetDir[FILE_MAXDIR+FILE_MAXFILE];  // store & modify output settings
363         char targetFile[FILE_MAXDIR+FILE_MAXFILE]; // temp. store filename from targetDir for access
364         int  outStringsChanged = 0;             // modified? copy back before baking
365         int  haveSomeFluid = 0;                 // check if any fluid objects are set
366
367         // config vars, inited before either export or run...
368         double calcViscosity = 0.0;
369         int noFrames;
370         double aniFrameTime;
371         float aniFrlen;
372         int   channelObjCount;
373         float *bbStart = NULL;
374         float *bbSize = NULL;
375         float domainMat[4][4];
376         float invDomMat[4][4];
377         // channel data
378         int   allchannelSize; // fixed by no. of frames
379         int   startFrame = 1;  // dont use G.scene->r.sfra here, always start with frame 1
380         // easy frame -> sim time calc
381         float *timeAtFrame=NULL, *timeAtIndex=NULL;
382         // domain
383         float *channelDomainTime = NULL;
384         float *channelDomainViscosity = NULL; 
385         float *channelDomainGravity = NULL;
386         // objects (currently max. 256 objs)
387         float *channelObjMove[256][3]; // object movments , 0=trans, 1=rot, 2=scale
388         float *channelObjInivel[256];    // initial velocities
389         float *channelObjActive[256];    // obj active channel
390         
391         /* fluid control channels */
392         float *channelAttractforceStrength[256];
393         float *channelAttractforceRadius[256];
394         float *channelVelocityforceStrength[256];
395         float *channelVelocityforceRadius[256];
396         FluidsimModifierData *fluidmd = NULL;
397         Mesh *mesh = NULL;
398         
399         if(getenv(strEnvName)) {
400                 int dlevel = atoi(getenv(strEnvName));
401                 elbeemSetDebugLevel(dlevel);
402                 snprintf(debugStrBuffer,256,"fluidsimBake::msg: Debug messages activated due to envvar '%s'\n",strEnvName); 
403                 elbeemDebugOut(debugStrBuffer);
404         }
405         if(getenv(exportEnvStr)) {
406                 doExportOnly = atoi(getenv(exportEnvStr));
407                 snprintf(debugStrBuffer,256,"fluidsimBake::msg: Exporting mode set to '%d' due to envvar '%s'\n",doExportOnly, exportEnvStr); 
408                 elbeemDebugOut(debugStrBuffer);
409         }
410
411         // make sure it corresponds to startFrame setting
412         // old: noFrames = G.scene->r.efra - G.scene->r.sfra +1;
413         noFrames = G.scene->r.efra - 0;
414         if(noFrames<=0) {
415                 pupmenu("Fluidsim Bake Error%t|No frames to export - check your animation range settings. Aborted%x0");
416                 return;
417         }
418
419         /* no object pointer, find in selected ones.. */
420         if(!ob) {
421                 for(base=G.scene->base.first; base; base= base->next) {
422                         if ((base)->flag & SELECT) 
423                         {
424                                 FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(base->object, eModifierType_Fluidsim);
425                                 
426                                 if(fluidmdtmp && (base->object->type==OB_MESH)) 
427                                 {
428                                         if(fluidmdtmp->fss->type == OB_FLUIDSIM_DOMAIN) 
429                                         {
430                                                 ob = base->object;
431                                                 break;
432                                         }
433                                 }
434                         }
435                 }
436                 // no domains found?
437                 if(!ob) return;
438         }
439         
440         channelObjCount = 0;
441         for(base=G.scene->base.first; base; base= base->next) 
442         {
443                 FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(base->object, eModifierType_Fluidsim);
444                 obit = base->object;
445                 if( fluidmdtmp && 
446                         (obit->type==OB_MESH) &&
447                         (fluidmdtmp->fss->type != OB_FLUIDSIM_DOMAIN) &&  // if has to match 3 places! // CHECKMATCH
448                         (fluidmdtmp->fss->type != OB_FLUIDSIM_PARTICLE) ) 
449                 {
450                         channelObjCount++;
451                 }
452         }
453         
454         if (channelObjCount>=255) {
455                 pupmenu("Fluidsim Bake Error%t|Cannot bake with more then 256 objects");
456                 return;
457         }
458
459         /* check if there's another domain... */
460         for(base=G.scene->base.first; base; base= base->next) 
461         {
462                 FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(base->object, eModifierType_Fluidsim);
463                 obit = base->object;
464                 if( fluidmdtmp &&(obit->type==OB_MESH)) 
465                 {
466                         if(fluidmdtmp->fss->type == OB_FLUIDSIM_DOMAIN) 
467                         {
468                                 if(obit != ob) 
469                                 {
470                                         pupmenu("Fluidsim Bake Error%t|There should be only one domain object! Aborted%x0");
471                                         return;
472                                 }
473                         }
474                 }
475         }
476         
477         // check if theres any fluid
478         // abort baking if not...
479         for(base=G.scene->base.first; base; base= base->next) 
480         {
481                 FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(base->object, eModifierType_Fluidsim);
482                 obit = base->object;
483                 if( fluidmdtmp && 
484                         (obit->type==OB_MESH) && 
485                         ((fluidmdtmp->fss->type == OB_FLUIDSIM_FLUID) ||
486                         (fluidmdtmp->fss->type == OB_FLUIDSIM_INFLOW) ))
487                 {
488                         haveSomeFluid = 1;
489                         break;
490                 }
491         }
492         if(!haveSomeFluid) {
493                 pupmenu("Fluidsim Bake Error%t|No fluid objects in scene... Aborted%x0");
494                 return;
495         }
496         
497         /* these both have to be valid, otherwise we wouldnt be here */
498         /* dont use ob here after...*/
499         fsDomain = ob;
500         fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
501         domainSettings = fluidmd->fss;
502         ob = NULL;
503         mesh = fsDomain->data;
504         
505         // calculate bounding box
506         fluid_get_bb(mesh->mvert, mesh->totvert, fsDomain->obmat, domainSettings->bbStart, domainSettings->bbSize);
507         
508         // reset last valid frame
509         domainSettings->lastgoodframe = -1;
510         
511         /* rough check of settings... */
512         if(domainSettings->previewresxyz > domainSettings->resolutionxyz) {
513                 snprintf(debugStrBuffer,256,"fluidsimBake::warning - Preview (%d) >= Resolution (%d)... setting equal.\n", domainSettings->previewresxyz ,  domainSettings->resolutionxyz); 
514                 elbeemDebugOut(debugStrBuffer);
515                 domainSettings->previewresxyz = domainSettings->resolutionxyz;
516         }
517         // set adaptive coarsening according to resolutionxyz
518         // this should do as an approximation, with in/outflow
519         // doing this more accurate would be overkill
520         // perhaps add manual setting?
521         if(domainSettings->maxRefine <0) {
522                 if(domainSettings->resolutionxyz>128) {
523                         gridlevels = 2;
524                 } else
525                 if(domainSettings->resolutionxyz>64) {
526                         gridlevels = 1;
527                 } else {
528                         gridlevels = 0;
529                 }
530         } else {
531                 gridlevels = domainSettings->maxRefine;
532         }
533         snprintf(debugStrBuffer,256,"fluidsimBake::msg: Baking %s, refine: %d\n", fsDomain->id.name , gridlevels ); 
534         elbeemDebugOut(debugStrBuffer);
535
536         // prepare names...
537         strncpy(targetDir, domainSettings->surfdataPath, FILE_MAXDIR);
538         strncpy(newSurfdataPath, domainSettings->surfdataPath, FILE_MAXDIR);
539         BLI_convertstringcode(targetDir, G.sce); // fixed #frame-no 
540
541         strcpy(targetFile, targetDir);
542         strcat(targetFile, suffixConfig);
543         if(!doExportOnly) { strcat(targetFile,".tmp"); }  // dont overwrite/delete original file
544         // make sure all directories exist
545         // as the bobjs use the same dir, this only needs to be checked
546         // for the cfg output
547         BLI_make_existing_file(targetFile);
548
549         // check selected directory
550         // simply try to open cfg file for writing to test validity of settings
551         fileCfg = fopen(targetFile, "w");
552         if(fileCfg) { 
553                 dirExist = 1; fclose(fileCfg); 
554                 // remove cfg dummy from  directory test
555                 if(!doExportOnly) { BLI_delete(targetFile, 0,0); }
556         }
557
558         if((strlen(targetDir)<1) || (!dirExist)) {
559                 char blendDir[FILE_MAXDIR+FILE_MAXFILE], blendFile[FILE_MAXDIR+FILE_MAXFILE];
560                 // invalid dir, reset to current/previous
561                 strcpy(blendDir, G.sce);
562                 BLI_splitdirstring(blendDir, blendFile);
563                 if(strlen(blendFile)>6){
564                         int len = strlen(blendFile);
565                         if( (blendFile[len-6]=='.')&& (blendFile[len-5]=='b')&& (blendFile[len-4]=='l')&&
566                                         (blendFile[len-3]=='e')&& (blendFile[len-2]=='n')&& (blendFile[len-1]=='d') ){
567                                 blendFile[len-6] = '\0';
568                         }
569                 }
570                 // todo... strip .blend ?
571                 snprintf(newSurfdataPath,FILE_MAXFILE+FILE_MAXDIR,"//fluidsimdata/%s_%s_", blendFile, fsDomain->id.name);
572
573                 snprintf(debugStrBuffer,256,"fluidsimBake::error - warning resetting output dir to '%s'\n", newSurfdataPath);
574                 elbeemDebugOut(debugStrBuffer);
575                 outStringsChanged=1;
576         }
577
578         // check if modified output dir is ok
579         if(outStringsChanged) {
580                 char dispmsg[FILE_MAXDIR+FILE_MAXFILE+256];
581                 int  selection=0;
582                 strcpy(dispmsg,"Output settings set to: '");
583                 strcat(dispmsg, newSurfdataPath);
584                 strcat(dispmsg, "'%t|Continue with changed settings%x1|Discard and abort%x0");
585
586                 // ask user if thats what he/she wants...
587                 selection = pupmenu(dispmsg);
588                 if(selection<1) return; // 0 from menu, or -1 aborted
589                 strcpy(targetDir, newSurfdataPath);
590                 strncpy(domainSettings->surfdataPath, newSurfdataPath, FILE_MAXDIR);
591                 BLI_convertstringcode(targetDir, G.sce); // fixed #frame-no 
592         }
593         
594         // --------------------------------------------------------------------------------------------
595         // dump data for start frame 
596         // CHECK more reasonable to number frames according to blender?
597         // dump data for frame 0
598         G.scene->r.cfra = startFrame;
599         scene_update_for_newframe(G.scene, G.scene->lay);
600         
601         // init common export vars for both file export and run
602         for(i=0; i<256; i++) {
603                 channelObjMove[i][0] = channelObjMove[i][1] = channelObjMove[i][2] = NULL;
604                 channelObjInivel[i] = NULL;
605                 channelObjActive[i] = NULL;
606                 channelAttractforceStrength[i] = NULL;
607                 channelAttractforceRadius[i] = NULL;
608                 channelVelocityforceStrength[i] = NULL;
609                 channelVelocityforceRadius[i] = NULL;
610         }
611         allchannelSize = G.scene->r.efra; // always use till last frame
612         aniFrameTime = (domainSettings->animEnd - domainSettings->animStart)/(double)noFrames;
613         // blender specific - scale according to map old/new settings in anim panel:
614         aniFrlen = G.scene->r.framelen;
615         if(domainSettings->viscosityMode==1) {
616                 /* manual mode, visc=value/(10^-vexp) */
617                 calcViscosity = (1.0/pow(10.0,domainSettings->viscosityExponent)) * domainSettings->viscosityValue;
618         } else {
619                 calcViscosity = fluidsimViscosityPreset[ domainSettings->viscosityMode ];
620         }
621
622         bbStart = domainSettings->bbStart;
623         bbSize = domainSettings->bbSize;
624
625         // always init
626         { int timeIcu[1] = { FLUIDSIM_TIME };
627                 float timeDef[1] = { 1. };
628                 int gravIcu[3] = { FLUIDSIM_GRAV_X, FLUIDSIM_GRAV_Y, FLUIDSIM_GRAV_Z };
629                 float gravDef[3];
630                 int viscIcu[1] = { FLUIDSIM_VISC };
631                 float viscDef[1] = { 1. };
632
633                 gravDef[0] = domainSettings->gravx;
634                 gravDef[1] = domainSettings->gravy;
635                 gravDef[2] = domainSettings->gravz;
636
637                 // time channel is a bit special, init by hand...
638                 timeAtIndex = MEM_callocN( (allchannelSize+1)*1*sizeof(float), "fluidsiminit_timeatindex");
639                 for(i=0; i<=G.scene->r.efra; i++) {
640                         timeAtIndex[i] = (float)(i-startFrame);
641                 }
642                 fluidsimInitChannel( &channelDomainTime, allchannelSize, timeAtIndex, timeIcu,timeDef, domainSettings->ipo, CHANNEL_FLOAT ); // NDEB
643                 // time channel is a multiplicator for aniFrameTime
644                 if(channelDomainTime) {
645                         for(i=0; i<allchannelSize; i++) { 
646                                 channelDomainTime[i*2+0] = aniFrameTime * channelDomainTime[i*2+0]; 
647                                 if(channelDomainTime[i*2+0]<0.) channelDomainTime[i*2+0] = 0.;
648                         }
649                 }
650                 timeAtFrame = MEM_callocN( (allchannelSize+1)*1*sizeof(float), "fluidsiminit_timeatframe");
651                 timeAtFrame[0] = timeAtFrame[1] = domainSettings->animStart; // start at index 1
652                 if(channelDomainTime) {
653                         for(i=2; i<=allchannelSize; i++) {
654                                 timeAtFrame[i] = timeAtFrame[i-1]+channelDomainTime[(i-1)*2+0];
655                         }
656                 } else {
657                         for(i=2; i<=allchannelSize; i++) { timeAtFrame[i] = timeAtFrame[i-1]+aniFrameTime; }
658                 }
659
660                 fluidsimInitChannel( &channelDomainViscosity, allchannelSize, timeAtFrame, viscIcu,viscDef, domainSettings->ipo, CHANNEL_FLOAT ); // NDEB
661                 if(channelDomainViscosity) {
662                         for(i=0; i<allchannelSize; i++) { channelDomainViscosity[i*2+0] = calcViscosity * channelDomainViscosity[i*2+0]; }
663                 }
664                 fluidsimInitChannel( &channelDomainGravity, allchannelSize, timeAtFrame, gravIcu,gravDef, domainSettings->ipo, CHANNEL_VEC );
665         } // domain channel init
666         
667         // init obj movement channels
668         channelObjCount=0;
669         for(base=G.scene->base.first; base; base= base->next) 
670         {
671                 FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(base->object, eModifierType_Fluidsim);
672                 obit = base->object;
673                 
674                 if( fluidmdtmp && 
675                         (obit->type==OB_MESH) &&
676                         (fluidmdtmp->fss->type != OB_FLUIDSIM_DOMAIN) &&  // if has to match 3 places! // CHECKMATCH
677                         (fluidmdtmp->fss->type != OB_FLUIDSIM_PARTICLE) ) {
678
679                         //  cant use fluidsimInitChannel for obj channels right now, due
680                         //  to the special DXXX channels, and the rotation specialities
681                         IpoCurve *icuex[3][3];
682                         //IpoCurve *par_icuex[3][3];
683                         int icuIds[3][3] = { 
684                                 {OB_LOC_X,  OB_LOC_Y,  OB_LOC_Z},
685                                 {OB_ROT_X,  OB_ROT_Y,  OB_ROT_Z},
686                                 {OB_SIZE_X, OB_SIZE_Y, OB_SIZE_Z} 
687                         };
688                         // relative ipos
689                         IpoCurve *icudex[3][3];
690                         //IpoCurve *par_icudex[3][3];
691                         int icudIds[3][3] = { 
692                                 {OB_DLOC_X,  OB_DLOC_Y,  OB_DLOC_Z},
693                                 {OB_DROT_X,  OB_DROT_Y,  OB_DROT_Z},
694                                 {OB_DSIZE_X, OB_DSIZE_Y, OB_DSIZE_Z} 
695                         };
696                         int j,k;
697                         float vals[3] = {0.0,0.0,0.0}; 
698                         int o = channelObjCount;
699                         int   inivelIcu[3] =  { FLUIDSIM_VEL_X, FLUIDSIM_VEL_Y, FLUIDSIM_VEL_Z };
700                         float inivelDefs[3];
701                         int   activeIcu[1] =  { FLUIDSIM_ACTIVE };
702                         float activeDefs[1] = { 1 }; // default to on
703
704                         inivelDefs[0] = fluidmdtmp->fss->iniVelx;
705                         inivelDefs[1] = fluidmdtmp->fss->iniVely;
706                         inivelDefs[2] = fluidmdtmp->fss->iniVelz;
707
708                         // check & init loc,rot,size
709                         for(j=0; j<3; j++) {
710                                 for(k=0; k<3; k++) {
711                                         icuex[j][k]  = find_ipocurve(obit->ipo, icuIds[j][k] );
712                                         icudex[j][k] = find_ipocurve(obit->ipo, icudIds[j][k] );
713                                         //if(obit->parent) {
714                                                 //par_icuex[j][k]  = find_ipocurve(obit->parent->ipo, icuIds[j][k] );
715                                                 //par_icudex[j][k] = find_ipocurve(obit->parent->ipo, icudIds[j][k] );
716                                         //}
717                                 }
718                         }
719
720                         for(j=0; j<3; j++) {
721                                 channelObjMove[o][j] = MEM_callocN( allchannelSize*4*sizeof(float), "fluidsiminit_objmovchannel");
722                                 for(i=1; i<=allchannelSize; i++) {
723
724                                         for(k=0; k<3; k++) {
725                                                 if(icuex[j][k]) { 
726                                                         // IPO exists, use it ...
727                                                         calc_icu(icuex[j][k], aniFrlen*((float)i) );
728                                                         vals[k] = icuex[j][k]->curval; 
729                                                         if(obit->parent) {
730                                                                 // add parent transform, multiply scaling, add trafo&rot
731                                                                 //calc_icu(par_icuex[j][k], aniFrlen*((float)i) );
732                                                                 //if(j==2) { vals[k] *= par_icuex[j][k]->curval; }
733                                                                 //else { vals[k] += par_icuex[j][k]->curval; }
734                                                         }
735                                                 } else {
736                                                         // use defaults from static values
737                                                         float setval=0.0;
738                                                         if(j==0) { 
739                                                                 setval = obit->loc[k];
740                                                                 if(obit->parent){ setval += obit->parent->loc[k]; }
741                                                         } else if(j==1) { 
742                                                                 setval = ( 180.0*obit->rot[k] )/( 10.0*M_PI );
743                                                                 if(obit->parent){ setval = ( 180.0*(obit->rot[k]+obit->parent->rot[k]) )/( 10.0*M_PI ); }
744                                                         } else { 
745                                                                 setval = obit->size[k]; 
746                                                                 if(obit->parent){ setval *= obit->parent->size[k]; }
747                                                         }
748                                                         vals[k] = setval;
749                                                 }
750                                                 if(icudex[j][k]) { 
751                                                         calc_icu(icudex[j][k], aniFrlen*((float)i) );
752                                                         //vals[k] += icudex[j][k]->curval; 
753                                                         // add transform, multiply scaling, add trafo&rot
754                                                         if(j==2) { vals[k] *= icudex[j][k]->curval; }
755                                                         else { vals[k] += icudex[j][k]->curval; }
756                                                         if(obit->parent) {
757                                                                 // add parent transform, multiply scaling, add trafo&rot
758                                                                 //calc_icu(par_icuex[j][k], aniFrlen*((float)i) );
759                                                                 //if(j==2) { vals[k] *= par_icudex[j][k]->curval; }
760                                                                 //else { vals[k] += par_icudex[j][k]->curval; }
761                                                         }
762                                                 } 
763                                         } // k
764
765                                         for(k=0; k<3; k++) {
766                                                 float set = vals[k];
767                                                 if(j==1) { // rot is downscaled by 10 for ipo !?
768                                                         set = 360.0 - (10.0*set);
769                                                 }
770                                                 channelObjMove[o][j][(i-1)*4 + k] = set;
771                                         } // k
772                                         channelObjMove[o][j][(i-1)*4 + 3] = timeAtFrame[i];
773                                 }
774                         }
775                         
776                         {
777                                 int   attrFSIcu[1] =  { FLUIDSIM_ATTR_FORCE_STR };
778                                 int   attrFRIcu[1] =  { FLUIDSIM_ATTR_FORCE_RADIUS };
779                                 int   velFSIcu[1] =  { FLUIDSIM_VEL_FORCE_STR };
780                                 int   velFRIcu[1] =  { FLUIDSIM_VEL_FORCE_RADIUS };
781
782                                 float attrFSDefs[1];
783                                 float attrFRDefs[1];
784                                 float velFSDefs[1];
785                                 float velFRDefs[1];
786                                 
787                                 attrFSDefs[0] = fluidmdtmp->fss->attractforceStrength;
788                                 attrFRDefs[0] = fluidmdtmp->fss->attractforceRadius;
789                                 velFSDefs[0] = fluidmdtmp->fss->velocityforceStrength;
790                                 velFRDefs[0] = fluidmdtmp->fss->velocityforceRadius;
791                                 
792                                 fluidsimInitChannel( &channelAttractforceStrength[o], allchannelSize, timeAtFrame, attrFSIcu,attrFSDefs, fluidmdtmp->fss->ipo, CHANNEL_FLOAT );
793                                 fluidsimInitChannel( &channelAttractforceRadius[o], allchannelSize, timeAtFrame, attrFRIcu,attrFRDefs, fluidmdtmp->fss->ipo, CHANNEL_FLOAT );
794                                 fluidsimInitChannel( &channelVelocityforceStrength[o], allchannelSize, timeAtFrame, velFSIcu,velFSDefs, fluidmdtmp->fss->ipo, CHANNEL_FLOAT );
795                                 fluidsimInitChannel( &channelVelocityforceRadius[o], allchannelSize, timeAtFrame, velFRIcu,velFRDefs, fluidmdtmp->fss->ipo, CHANNEL_FLOAT );
796                         }
797                         
798                         fluidsimInitChannel( &channelObjInivel[o], allchannelSize, timeAtFrame, inivelIcu,inivelDefs, fluidmdtmp->fss->ipo, CHANNEL_VEC );
799                         fluidsimInitChannel( &channelObjActive[o], allchannelSize, timeAtFrame, activeIcu,activeDefs, fluidmdtmp->fss->ipo, CHANNEL_FLOAT );
800                 
801
802                         channelObjCount++;
803
804                 }
805         }
806
807         // init trafo matrix
808         MTC_Mat4CpyMat4(domainMat, fsDomain->obmat);
809         if(!Mat4Invert(invDomMat, domainMat)) {
810                 snprintf(debugStrBuffer,256,"fluidsimBake::error - Invalid obj matrix?\n"); 
811                 elbeemDebugOut(debugStrBuffer);
812                 // FIXME add fatal msg
813                 FS_FREE_CHANNELS;
814                 return;
815         }
816
817
818         // --------------------------------------------------------------------------------------------
819         // start writing / exporting
820         strcpy(targetFile, targetDir);
821         strcat(targetFile, suffixConfig);
822         if(!doExportOnly) { strcat(targetFile,".tmp"); }  // dont overwrite/delete original file
823         // make sure these directories exist as well
824         if(outStringsChanged) {
825                 BLI_make_existing_file(targetFile);
826         }
827
828         if(!doExportOnly) {
829                 SDL_Thread *simthr = NULL;
830
831                 // perform simulation with El'Beem api and SDL threads
832                 elbeemSimulationSettings fsset;
833                 elbeemResetSettings(&fsset);
834                 fsset.version = 1;
835
836                 // setup global settings
837                 for(i=0 ; i<3; i++) fsset.geoStart[i] = bbStart[i];
838                 for(i=0 ; i<3; i++) fsset.geoSize[i] = bbSize[i];
839                 
840                 // simulate with 50^3
841                 fsset.resolutionxyz = (int)domainSettings->resolutionxyz;
842                 fsset.previewresxyz = (int)domainSettings->previewresxyz;
843                 // 10cm water domain
844                 fsset.realsize = domainSettings->realsize;
845                 fsset.viscosity = calcViscosity;
846                 // earth gravity
847                 fsset.gravity[0] = domainSettings->gravx;
848                 fsset.gravity[1] = domainSettings->gravy;
849                 fsset.gravity[2] = domainSettings->gravz;
850                 // simulate 5 frames, each 0.03 seconds, output to ./apitest_XXX.bobj.gz
851                 fsset.animStart = domainSettings->animStart;
852                 fsset.aniFrameTime = aniFrameTime;
853                 fsset.noOfFrames = noFrames - 1; // is otherwise subtracted in parser
854                 strcpy(targetFile, targetDir);
855                 strcat(targetFile, suffixSurface);
856                 // defaults for compressibility and adaptive grids
857                 fsset.gstar = domainSettings->gstar;
858                 fsset.maxRefine = domainSettings->maxRefine; // check <-> gridlevels
859                 fsset.generateParticles = domainSettings->generateParticles; 
860                 fsset.numTracerParticles = domainSettings->generateTracers; 
861                 fsset.surfaceSmoothing = domainSettings->surfaceSmoothing; 
862                 fsset.surfaceSubdivs = domainSettings->surfaceSubdivs; 
863                 fsset.farFieldSize = domainSettings->farFieldSize; 
864                 strcpy( fsset.outputPath, targetFile);
865
866                 // domain channels
867                 fsset.channelSizeFrameTime = 
868                 fsset.channelSizeViscosity = 
869                 fsset.channelSizeGravity =  allchannelSize;
870                 fsset.channelFrameTime = channelDomainTime;
871                 fsset.channelViscosity = channelDomainViscosity;
872                 fsset.channelGravity = channelDomainGravity;
873
874                 fsset.runsimCallback = &runSimulationCallback;
875                 fsset.runsimUserData = &fsset;
876
877                 if(     (domainSettings->typeFlags&OB_FSBND_NOSLIP))   fsset.domainobsType = FLUIDSIM_OBSTACLE_NOSLIP;
878                 else if((domainSettings->typeFlags&OB_FSBND_PARTSLIP)) fsset.domainobsType = FLUIDSIM_OBSTACLE_PARTSLIP;
879                 else if((domainSettings->typeFlags&OB_FSBND_FREESLIP)) fsset.domainobsType = FLUIDSIM_OBSTACLE_FREESLIP;
880                 fsset.domainobsPartslip = domainSettings->partSlipValue;
881                 fsset.generateVertexVectors = (domainSettings->domainNovecgen==0);
882
883                 // init blender trafo matrix
884                 // fprintf(stderr,"elbeemInit - mpTrafo:\n");
885                 { int j; 
886                 for(i=0; i<4; i++) {
887                         for(j=0; j<4; j++) {
888                                 fsset.surfaceTrafo[i*4+j] = invDomMat[j][i];
889                                 // fprintf(stderr,"elbeemInit - mpTrafo %d %d = %f (%d) \n", i,j, fsset.surfaceTrafo[i*4+j] , (i*4+j) );
890                         }
891                 } }
892
893           // init solver with settings
894                 elbeemInit();
895                 elbeemAddDomain(&fsset);
896                 
897                 // init objects
898                 channelObjCount = 0;
899                 for(base=G.scene->base.first; base; base= base->next) {
900                         FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(base->object, eModifierType_Fluidsim);
901                         obit = base->object;
902                         //{ snprintf(debugStrBuffer,256,"DEBUG object name=%s, type=%d ...\n", obit->id.name, obit->type); elbeemDebugOut(debugStrBuffer); } // DEBUG
903                         if( fluidmdtmp &&  // if has to match 3 places! // CHECKMATCH
904                                 (obit->type==OB_MESH) &&
905                                 (fluidmdtmp->fss->type != OB_FLUIDSIM_DOMAIN) &&
906                                 (fluidmdtmp->fss->type != OB_FLUIDSIM_PARTICLE)) 
907                         {
908                                 float *verts=NULL;
909                                 int *tris=NULL;
910                                 int numVerts=0, numTris=0;
911                                 int o = channelObjCount;
912                                 int     deform = (fluidmdtmp->fss->domainNovecgen); // misused value
913                                 // todo - use blenderInitElbeemMesh
914                                 int modifierIndex = modifiers_indexInObject(obit, (ModifierData *)fluidmdtmp);
915                                 
916                                 elbeemMesh fsmesh;
917                                 elbeemResetMesh( &fsmesh );
918                                 fsmesh.type = fluidmdtmp->fss->type;
919                                 // get name of object for debugging solver
920                                 fsmesh.name = obit->id.name; 
921
922                                 initElbeemMesh(obit, &numVerts, &verts, &numTris, &tris, 0, modifierIndex);
923                                 fsmesh.numVertices   = numVerts;
924                                 fsmesh.numTriangles  = numTris;
925                                 fsmesh.vertices      = verts;
926                                 fsmesh.triangles     = tris;
927
928                                 fsmesh.channelSizeTranslation  = 
929                                 fsmesh.channelSizeRotation     = 
930                                 fsmesh.channelSizeScale        = 
931                                 fsmesh.channelSizeInitialVel   = 
932                                 fsmesh.channelSizeActive       = allchannelSize;
933
934                                 fsmesh.channelTranslation      = channelObjMove[o][0];
935                                 fsmesh.channelRotation         = channelObjMove[o][1];
936                                 fsmesh.channelScale            = channelObjMove[o][2];
937                                 fsmesh.channelActive           = channelObjActive[o];
938                                 if( (fsmesh.type == OB_FLUIDSIM_FLUID) ||
939                                 (fsmesh.type == OB_FLUIDSIM_INFLOW)) {
940                                         fsmesh.channelInitialVel       = channelObjInivel[o];
941                                         fsmesh.localInivelCoords = ((fluidmdtmp->fss->typeFlags&OB_FSINFLOW_LOCALCOORD)?1:0);
942                                 } 
943
944                                 if(     (fluidmdtmp->fss->typeFlags&OB_FSBND_NOSLIP))   fsmesh.obstacleType = FLUIDSIM_OBSTACLE_NOSLIP;
945                                 else if((fluidmdtmp->fss->typeFlags&OB_FSBND_PARTSLIP)) fsmesh.obstacleType = FLUIDSIM_OBSTACLE_PARTSLIP;
946                                 else if((fluidmdtmp->fss->typeFlags&OB_FSBND_FREESLIP)) fsmesh.obstacleType = FLUIDSIM_OBSTACLE_FREESLIP;
947                                 fsmesh.obstaclePartslip = fluidmdtmp->fss->partSlipValue;
948                                 fsmesh.volumeInitType = fluidmdtmp->fss->volumeInitType;
949                                 fsmesh.obstacleImpactFactor = fluidmdtmp->fss->surfaceSmoothing; // misused value
950                                 
951                                 if(fsmesh.type == OB_FLUIDSIM_CONTROL)
952                                 {
953                                         // control fluids will get exported as whole
954                                         deform = 1;
955                                         
956                                         fsmesh.cpsTimeStart = fluidmdtmp->fss->cpsTimeStart;
957                                         fsmesh.cpsTimeEnd = fluidmdtmp->fss->cpsTimeEnd;
958                                         fsmesh.cpsQuality = fluidmdtmp->fss->cpsQuality;
959                                         fsmesh.obstacleType = (fluidmdtmp->fss->flag & OB_FLUIDSIM_REVERSE);
960                                         
961                                         fsmesh.channelSizeAttractforceRadius = 
962                                         fsmesh.channelSizeVelocityforceStrength = 
963                                         fsmesh.channelSizeVelocityforceRadius = 
964                                         fsmesh.channelSizeAttractforceStrength = allchannelSize;
965                                         
966                                         fsmesh.channelAttractforceStrength = channelAttractforceStrength[o];
967                                         fsmesh.channelAttractforceRadius = channelAttractforceRadius[o];
968                                         fsmesh.channelVelocityforceStrength = channelVelocityforceStrength[o];
969                                         fsmesh.channelVelocityforceRadius = channelVelocityforceRadius[o];
970                                 }
971                                 else 
972                                 {
973                                         // set channels to 0
974                                         fsmesh.channelAttractforceStrength =
975                                         fsmesh.channelAttractforceRadius = 
976                                         fsmesh.channelVelocityforceStrength = 
977                                         fsmesh.channelVelocityforceRadius = NULL; 
978                                 }
979
980                                 // animated meshes
981                                 if(deform) {
982                                         fsmesh.channelSizeVertices = allchannelSize;
983                                         fluidsimInitMeshChannel( &fsmesh.channelVertices, allchannelSize, obit, numVerts, timeAtFrame, modifierIndex);
984                                         G.scene->r.cfra = startFrame;
985                                         scene_update_for_newframe(G.scene, G.scene->lay);
986                                         // remove channels
987                                         fsmesh.channelTranslation      = 
988                                         fsmesh.channelRotation         = 
989                                         fsmesh.channelScale            = NULL; 
990                                 } 
991
992                                 elbeemAddMesh(&fsmesh);
993
994                                 if(verts) MEM_freeN(verts);
995                                 if(tris) MEM_freeN(tris);
996                                 if(fsmesh.channelVertices) MEM_freeN(fsmesh.channelVertices);
997                                 channelObjCount++;
998                         } // valid mesh
999                 } // objects
1000                 //domainSettings->type = OB_FLUIDSIM_DOMAIN; // enable for bake display again
1001                 //fsDomain->fluidsimFlag = OB_FLUIDSIM_ENABLE; // disable during bake
1002                 
1003                 globalBakeLock = SDL_CreateMutex();
1004                 // set to neutral, -1 means user abort, -2 means init error
1005                 globalBakeState = 0;
1006                 globalBakeFrame = 0;
1007                 simthr = SDL_CreateThread(fluidsimSimulateThread, targetFile);
1008
1009                 if(!simthr) {
1010                         snprintf(debugStrBuffer,256,"fluidsimBake::error: Unable to create thread... running without one.\n"); 
1011                         elbeemDebugOut(debugStrBuffer);
1012                         set_timecursor(0);
1013                         elbeemSimulate();
1014                 } else {
1015                         int done = 0;
1016                         unsigned short event=0;
1017                         short val;
1018                         float noFramesf = (float)noFrames;
1019                         float percentdone = 0.0;
1020                         int lastRedraw = -1;
1021                         
1022                         start_progress_bar();
1023
1024                         while(done==0) {            
1025                                 char busy_mess[80];
1026                                 
1027                                 waitcursor(1);
1028                                 
1029                                 // lukep we add progress bar as an interim mesure
1030                                 percentdone = globalBakeFrame / noFramesf;
1031                                 sprintf(busy_mess, "baking fluids %d / %d       |||", globalBakeFrame, (int) noFramesf);
1032                                 progress_bar(percentdone, busy_mess );
1033                                 
1034                                 SDL_Delay(2000); // longer delay to prevent frequent redrawing
1035                                 SDL_mutexP(globalBakeLock);
1036                                 if(globalBakeState != 0) done = 1; // 1=ok, <0=error/abort
1037                                 SDL_mutexV(globalBakeLock);
1038
1039                                 while(qtest()) {
1040                                         event = extern_qread(&val);
1041                                         if(event == ESCKEY) {
1042                                                 // abort...
1043                                                 SDL_mutexP(globalBakeLock);
1044                                                 
1045                                                 if(domainSettings)
1046                                                         domainSettings->lastgoodframe = startFrame+globalBakeFrame;
1047                                                 
1048                                                 done = -1;
1049                                                 globalBakeFrame = 0;
1050                                                 globalBakeState = -1;
1051                                                 simAborted = 1;
1052                                                 SDL_mutexV(globalBakeLock);
1053                                                 break;
1054                                         }
1055                                 } 
1056
1057                                 // redraw the 3D for showing progress once in a while...
1058                                 if(lastRedraw!=globalBakeFrame) {
1059                                         ScrArea *sa;
1060                                         G.scene->r.cfra = startFrame+globalBakeFrame;
1061                                         lastRedraw = globalBakeFrame;
1062                                         update_for_newframe_muted();
1063                                         sa= G.curscreen->areabase.first;
1064                                         while(sa) {
1065                                                 if(sa->spacetype == SPACE_VIEW3D) { scrarea_do_windraw(sa); }
1066                                                 sa= sa->next;   
1067                                         } 
1068                                         screen_swapbuffers();
1069                                 } // redraw
1070                         }
1071                         SDL_WaitThread(simthr,NULL);
1072                         end_progress_bar();
1073                 }
1074                 SDL_DestroyMutex(globalBakeLock);
1075                 globalBakeLock = NULL;
1076         } // El'Beem API init, thread creation 
1077         // --------------------------------------------------------------------------------------------
1078         else
1079         { // write config file to be run with command line simulator
1080                 pupmenu("Fluidsim Bake Message%t|Config file export not supported.%x0");
1081         } // config file export done!
1082
1083         // --------------------------------------------------------------------------------------------
1084         FS_FREE_CHANNELS;
1085
1086         // go back to "current" blender time
1087         waitcursor(0);
1088         
1089         if(globalBakeState >= 0)
1090         {
1091                 if(domainSettings)
1092                         domainSettings->lastgoodframe = startFrame+globalBakeFrame;
1093         }
1094         
1095   G.scene->r.cfra = origFrame;
1096   scene_update_for_newframe(G.scene, G.scene->lay);
1097         allqueue(REDRAWVIEW3D, 0);
1098         allqueue(REDRAWBUTSOBJECT, 0);
1099
1100         if(!simAborted) {
1101                 char fsmessage[512];
1102                 char elbeemerr[256];
1103                 strcpy(fsmessage,"Fluidsim Bake Error: ");
1104                 // check if some error occurred
1105                 if(globalBakeState==-2) {
1106                         strcat(fsmessage,"Failed to initialize [Msg: ");
1107
1108                         elbeemGetErrorString(elbeemerr);
1109                         strcat(fsmessage,elbeemerr);
1110
1111                         strcat(fsmessage,"] |OK%x0");
1112                         pupmenu(fsmessage);
1113                 } // init error
1114         }
1115         
1116         // elbeemFree();
1117 }
1118
1119 void fluidsimFreeBake(struct Object *ob)
1120 {
1121         /* not implemented yet */
1122 }
1123
1124
1125 #else /* DISABLE_ELBEEM */
1126
1127 /* compile dummy functions for disabled fluid sim */
1128
1129 FluidsimSettings *fluidsimSettingsNew(struct Object *srcob) {
1130         return NULL;
1131 }
1132
1133 void fluidsimSettingsFree(FluidsimSettings *fss) {
1134 }
1135
1136 FluidsimSettings* fluidsimSettingsCopy(FluidsimSettings *fss) {
1137         return NULL;
1138 }
1139
1140 /* only compile dummy functions */
1141 void fluidsimBake(struct Object *ob) {
1142 }
1143
1144 void fluidsimFreeBake(struct Object *ob) {
1145 }
1146
1147 #endif /* DISABLE_ELBEEM */
1148