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