- another minor solver update to fix
[blender.git] / intern / elbeem / intern / simulation_object.cpp
1 /******************************************************************************
2  *
3  * El'Beem - Free Surface Fluid Simulation with the Lattice Boltzmann Method
4  * Copyright 2003,2004 Nils Thuerey
5  *
6  * Basic interface for all simulation modules
7  *
8  *****************************************************************************/
9
10 #include "simulation_object.h"
11 #include "solver_interface.h"
12 #include "ntl_bsptree.h"
13 #include "ntl_ray.h"
14 #include "ntl_world.h"
15 #include "solver_interface.h"
16 #include "particletracer.h"
17 #include "elbeem.h"
18
19 #ifdef _WIN32
20 #else
21 #include <sys/time.h>
22 #endif
23
24
25 //! lbm factory functions
26 LbmSolverInterface* createSolver();
27
28
29 /******************************************************************************
30  * Constructor
31  *****************************************************************************/
32 SimulationObject::SimulationObject() :
33         ntlGeometryShader(),
34         mGeoStart(-100.0), mGeoEnd(100.0),
35         mpGiTree(NULL), mpGiObjects(NULL),
36         mpGlob(NULL),
37         mPanic( false ),
38         mDebugType( 1 /* =FLUIDDISPNothing*/ ),
39         mpLbm(NULL), mpParam( NULL ),
40         mShowSurface(true), mShowParticles(false),
41         mSelectedCid( NULL ),
42         mpElbeemSettings( NULL )
43
44 {
45         mpParam = new Parametrizer();
46         //for(int i=0; i<MAX_DEBDISPSET; i++) { mDebDispSet[i].type  = (i); mDebDispSet[i].on    = false; mDebDispSet[i].scale = 1.0; }
47
48         // reset time
49         mTime                                           = 0.0;
50 }
51
52
53 /******************************************************************************
54  * Destructor
55  *****************************************************************************/
56 SimulationObject::~SimulationObject()
57 {
58         if(mpGiTree)         delete mpGiTree;
59         if(mpElbeemSettings) delete mpElbeemSettings;
60         if(mpLbm)            delete mpLbm;
61   if(mpParam)          delete mpParam;
62         debMsgStd("SimulationObject",DM_MSG,"El'Beem Done!\n",10);
63 }
64
65
66
67 /*****************************************************************************/
68 /*! init tree for certain geometry init */
69 /*****************************************************************************/
70 void SimulationObject::initGeoTree() {
71         if(mpGlob == NULL) { 
72                 errFatal("SimulationObject::initGeoTree error","Requires globals!", SIMWORLD_INITERROR); 
73                 return;
74         }
75         ntlScene *scene = mpGlob->getSimScene();
76         mpGiObjects = scene->getObjects();
77
78         if(mpGiTree != NULL) delete mpGiTree;
79         char treeFlag = (1<<(mGeoInitId+4));
80         mpGiTree = new ntlTree( 20, 4, // warning - fixed values for depth & maxtriangles here...
81                                                                                                 scene, treeFlag );
82 }
83
84 /*****************************************************************************/
85 /*! destroy tree etc. when geometry init done */
86 /*****************************************************************************/
87 void SimulationObject::freeGeoTree() {
88         if(mpGiTree != NULL) delete mpGiTree;
89 }
90
91
92
93 // copy & remember settings for later use
94 void SimulationObject::copyElbeemSettings(elbeemSimulationSettings *settings) {
95         mpElbeemSettings = new elbeemSimulationSettings;
96         *mpElbeemSettings = *settings;
97
98         mGeoInitId = settings->domainId+1;
99         debMsgStd("SimulationObject",DM_MSG,"mGeoInitId="<<mGeoInitId<<", domainId="<<settings->domainId, 8);
100 }
101
102 /******************************************************************************
103  * simluation interface: initialize simulation using the given configuration file 
104  *****************************************************************************/
105 int SimulationObject::initializeLbmSimulation(ntlRenderGlobals *glob)
106 {
107         if(! isSimworldOk() ) return 1;
108         
109         // already inited?
110         if(mpLbm) return 0;
111         
112         mpGlob = glob;
113         if(!getVisible()) {
114                 mpAttrs->setAllUsed();
115                 return 0;
116         }
117
118
119         mGeoInitId = mpAttrs->readInt("geoinitid", mGeoInitId,"LbmSolverInterface", "mGeoInitId", false);
120         //mDimension, mSolverType are deprecated
121         string mSolverType(""); 
122         mSolverType = mpAttrs->readString("solver", mSolverType, "SimulationObject","mSolverType", false ); 
123
124         mpLbm = createSolver(); 
125   /* check lbm pointer */
126         if(mpLbm == NULL) {
127                 errFatal("SimulationObject::initializeLbmSimulation","Unable to init LBM solver! ", SIMWORLD_INITERROR);
128                 return 2;
129         }
130         debMsgStd("SimulationObject::initialized",DM_MSG,"IdStr:"<<mpLbm->getIdString() <<" LBM solver! ", 2);
131
132         // for non-param simulations
133         mpLbm->setParametrizer( mpParam );
134         mpParam->setAttrList( getAttributeList() );
135         // not needed.. done in solver_init: mpParam->setSize ... in solver_interface
136         mpParam->parseAttrList();
137
138         mpLbm->setAttrList( getAttributeList() );
139         mpLbm->parseAttrList();
140         mpParts = new ParticleTracer();
141         mpParts->parseAttrList( getAttributeList() );
142
143         if(! isSimworldOk() ) return 3;
144         mpParts->setName( getName() + "_part" );
145         mpParts->initialize( glob );
146         if(! isSimworldOk() ) return 4;
147         
148         // init material settings
149         string matMc("default");
150         matMc = mpAttrs->readString("material_surf", matMc, "SimulationObject","matMc", false );
151         mShowSurface   = mpAttrs->readInt("showsurface", mShowSurface, "SimulationObject","mShowSurface", false ); 
152         mShowParticles = mpAttrs->readInt("showparticles", mShowParticles, "SimulationObject","mShowParticles", false ); 
153
154         checkBoundingBox( mGeoStart, mGeoEnd, "SimulationObject::initializeSimulation" );
155         mpLbm->setLbmInitId( mGeoInitId );
156         mpLbm->setGeoStart( mGeoStart );
157         mpLbm->setGeoEnd( mGeoEnd );
158         mpLbm->setRenderGlobals( mpGlob );
159         mpLbm->setName( getName() + "_lbm" );
160         mpLbm->setParticleTracer( mpParts );
161         if(mpElbeemSettings) {
162                 // set further settings from API struct init
163                 if(mpElbeemSettings->outputPath) this->mOutFilename = string(mpElbeemSettings->outputPath);
164                 mpLbm->initDomainTrafo( mpElbeemSettings->surfaceTrafo );
165                 mpLbm->setSmoothing(1.0 * mpElbeemSettings->surfaceSmoothing, 1.0 * mpElbeemSettings->surfaceSmoothing);
166                 mpLbm->setSizeX(mpElbeemSettings->resolutionxyz);
167                 mpLbm->setSizeY(mpElbeemSettings->resolutionxyz);
168                 mpLbm->setSizeZ(mpElbeemSettings->resolutionxyz);
169                 mpLbm->setPreviewSize(mpElbeemSettings->previewresxyz);
170                 mpLbm->setRefinementDesired(mpElbeemSettings->maxRefine);
171                 mpLbm->setGenerateParticles(mpElbeemSettings->generateParticles);
172                 // set initial particles
173                 mpParts->setNumInitialParticles(mpElbeemSettings->numTracerParticles);
174
175                 string dinitType = string("no");
176                 if     (mpElbeemSettings->obstacleType==FLUIDSIM_OBSTACLE_PARTSLIP) dinitType = string("part"); 
177                 else if(mpElbeemSettings->obstacleType==FLUIDSIM_OBSTACLE_FREESLIP) dinitType = string("free"); 
178                 else /*if(mpElbeemSettings->obstacleType==FLUIDSIM_OBSTACLE_NOSLIP)*/ dinitType = string("no"); 
179                 mpLbm->setDomainBound(dinitType);
180                 mpLbm->setDomainPartSlip(mpElbeemSettings->obstaclePartslip);
181                 mpLbm->setDumpVelocities(mpElbeemSettings->generateVertexVectors);
182                 mpLbm->setFarFieldSize(mpElbeemSettings->farFieldSize);
183                 debMsgStd("SimulationObject::initialize",DM_MSG,"Added domain bound: "<<dinitType<<" ps="<<mpElbeemSettings->obstaclePartslip<<" vv"<<mpElbeemSettings->generateVertexVectors<<","<<mpLbm->getDumpVelocities(), 9 );
184
185                 debMsgStd("SimulationObject::initialize",DM_MSG,"Set ElbeemSettings values "<<mpLbm->getGenerateParticles(),10);
186         }
187
188         if(! mpLbm->initializeSolverMemory()   )         { errMsg("SimulationObject::initialize","initializeSolverMemory failed"); mPanic=true; return 10; }
189         if(checkCallerStatus(FLUIDSIM_CBSTATUS_STEP, 0)) { errMsg("SimulationObject::initialize","initializeSolverMemory status"); mPanic=true; return 11; } 
190         if(! mpLbm->initializeSolverGrids()    )         { errMsg("SimulationObject::initialize","initializeSolverGrids  failed"); mPanic=true; return 12; }
191         if(checkCallerStatus(FLUIDSIM_CBSTATUS_STEP, 0)) { errMsg("SimulationObject::initialize","initializeSolverGrids  status"); mPanic=true; return 13; } 
192         if(! mpLbm->initializeSolverPostinit() )         { errMsg("SimulationObject::initialize","initializeSolverPostin failed"); mPanic=true; return 14; }
193         if(checkCallerStatus(FLUIDSIM_CBSTATUS_STEP, 0)) { errMsg("SimulationObject::initialize","initializeSolverPostin status"); mPanic=true; return 15; } 
194
195         // print cell type stats
196         const int jmax = sizeof(CellFlagType)*8;
197         int totalCells = 0;
198         int flagCount[jmax];
199         for(int j=0; j<jmax ; j++) flagCount[j] = 0;
200         int diffInits = 0;
201         LbmSolverInterface::CellIdentifier cid = mpLbm->getFirstCell();
202         for(; mpLbm->noEndCell( cid );
203               mpLbm->advanceCell( cid ) ) {
204                 int flag = mpLbm->getCellFlag(cid,0);
205                 int flag2 = mpLbm->getCellFlag(cid,1);
206                 if(flag != flag2) {
207                         diffInits++;
208                 }
209                 for(int j=0; j<jmax ; j++) {
210                         if( flag&(1<<j) ) flagCount[j]++;
211                 }
212                 totalCells++;
213         }
214         mpLbm->deleteCellIterator( &cid );
215
216         char charNl = '\n';
217         debugOutNnl("SimulationObject::initializeLbmSimulation celltype stats: " <<charNl, 5);
218         debugOutNnl("no. of cells = "<<totalCells<<", "<<charNl ,5);
219         for(int j=0; j<jmax ; j++) {
220                 std::ostringstream out;
221                 if(flagCount[j]>0) {
222                         out<<"\t" << flagCount[j] <<" x "<< convertCellFlagType2String( (CellFlagType)(1<<j) ) <<", " << charNl;
223                         debugOutNnl(out.str(), 5);
224                 }
225         }
226         // compute dist. of empty/bnd - fluid - if
227         // cfEmpty   = (1<<0), cfBnd  = (1<< 2), cfFluid   = (1<<10), cfInter   = (1<<11),
228         if(1){
229                 std::ostringstream out;
230                 out.precision(2); out.width(4);
231                 int totNum = flagCount[1]+flagCount[2]+flagCount[7]+flagCount[8];
232                 double ebFrac = (double)(flagCount[1]+flagCount[2]) / totNum;
233                 double flFrac = (double)(flagCount[7]) / totNum;
234                 double ifFrac = (double)(flagCount[8]) / totNum;
235                 //???
236                 out<<"\tFractions: [empty/bnd - fluid - interface - ext. if]  =  [" << ebFrac<<" - " << flFrac<<" - " << ifFrac<<"] "<< charNl;
237
238                 if(diffInits > 0) {
239                         debMsgStd("SimulationObject::initializeLbmSimulation",DM_MSG,"celltype Warning: Diffinits="<<diffInits<<"!" , 5);
240                 }
241                 debugOutNnl(out.str(), 5);
242         }
243
244         // might be modified by mpLbm
245         mpParts->setStart( mGeoStart );
246         mpParts->setEnd( mGeoEnd );
247         mpParts->setCastShadows( false );
248         mpParts->setReceiveShadows( false );
249         mpParts->searchMaterial( glob->getMaterials() );
250
251         // this has to be inited here - before, the values might be unknown
252         ntlGeometryObject *surf = mpLbm->getSurfaceGeoObj();
253         if(surf) {
254                 surf->setName( "final" ); // final surface mesh 
255                 // warning - this might cause overwriting effects for multiple sims and geom dump...
256                 surf->setCastShadows( true );
257                 surf->setReceiveShadows( false );
258                 surf->searchMaterial( glob->getMaterials() );
259                 if(mShowSurface) mObjects.push_back( surf );
260         }
261         
262 #ifdef ELBEEM_PLUGIN
263         mShowParticles=1;
264 #endif // ELBEEM_PLUGIN
265         if((mpLbm->getGenerateParticles()>0.0)||(mpParts->getNumInitialParticles()>0)) {
266                 mShowParticles=1;
267                 mpParts->setDumpParts(true);
268         }
269                 //debMsgStd("SimulationObject::init",DM_NOTIFY,"Using envvar ELBEEM_DUMPPARTICLE to set mShowParticles, DEBUG!",1);
270         //}  // DEBUG ENABLE!!!!!!!!!!
271         if(mShowParticles) {
272                 mObjects.push_back(mpParts);
273         }
274
275         // add objects to display for debugging (e.g. levelset particles)
276         vector<ntlGeometryObject *> debugObjs = mpLbm->getDebugObjects();
277         for(size_t i=0;i<debugObjs.size(); i++) {
278                 debugObjs[i]->setCastShadows( false );
279                 debugObjs[i]->setReceiveShadows( false );
280                 debugObjs[i]->searchMaterial( glob->getMaterials() );
281                 mObjects.push_back( debugObjs[i] );
282         }
283         return 0;
284 }
285
286 /*! set current frame */
287 void SimulationObject::setFrameNum(int num) {
288         // advance parametrizer
289         mpParam->setFrameNum(num);
290 }
291
292 /******************************************************************************
293  * simluation interface: advance simulation another step (whatever delta time that might be) 
294  *****************************************************************************/
295 void SimulationObject::step( void )
296 {
297         if(mpParam->getCurrentAniFrameTime()>0.0) {
298                 // dont advance for stopped time
299                 mpLbm->step();
300                 mTime += mpParam->getTimestep();
301 //if(mTime>0.001) { errMsg("DEBUG!!!!!!!!","quit mlsu..."); exit(1); } // PROFILE DEBUG TEST!
302         }
303         if(mpLbm->getPanic()) mPanic = true;
304
305         checkCallerStatus(FLUIDSIM_CBSTATUS_STEP, 0);
306         //if((mpElbeemSettings)&&(mpElbeemSettings->runsimCallback)) {
307                 //int ret = (mpElbeemSettings->runsimCallback)(mpElbeemSettings->runsimUserData, FLUIDSIM_CBSTATUS_STEP, 0);
308                 //errMsg("runSimulationCallback cbtest1"," "<<this->getName()<<" ret="<<ret);
309         //}
310   //debMsgStd("SimulationObject::step",DM_MSG," Sim '"<<mName<<"' stepped to "<<mTime<<" (stept="<<(mpParam->getTimestep())<<", framet="<<getFrameTime()<<") ", 10);
311 }
312 /*! prepare visualization of simulation for e.g. raytracing */
313 void SimulationObject::prepareVisualization( void ) {
314         if(mPanic) return;
315         mpLbm->prepareVisualization();
316 }
317
318
319 /******************************************************************************/
320 /* get current start simulation time */
321 double SimulationObject::getStartTime( void ) {
322         //return mpParam->calculateAniStart();
323         return mpParam->getAniStart();
324 }
325 /* get time for a single animation frame */
326 double SimulationObject::getFrameTime( int frame ) {
327         return mpParam->getAniFrameTime(frame);
328 }
329 /* get time for a single time step  */
330 double SimulationObject::getTimestep( void ) {
331         return mpParam->getTimestep();
332 }
333
334
335 /******************************************************************************
336  * return a pointer to the geometry object of this simulation 
337  *****************************************************************************/
338 //ntlGeometryObject *SimulationObject::getGeometry() { return mpMC; }
339 vector<ntlGeometryObject *>::iterator 
340 SimulationObject::getObjectsBegin()
341 {
342         return mObjects.begin();
343 }
344 vector<ntlGeometryObject *>::iterator 
345 SimulationObject::getObjectsEnd()
346 {
347         return mObjects.end();
348 }
349
350
351
352
353
354 /******************************************************************************
355  * GUI - display debug info 
356  *****************************************************************************/
357
358 void SimulationObject::drawDebugDisplay() {
359 #ifndef NOGUI
360         if(!getVisible()) return;
361
362         //if( mDebugType > (MAX_DEBDISPSET-1) ){ errFatal("SimulationObject::drawDebugDisplay","Invalid debug type!", SIMWORLD_GENERICERROR); return; }
363         //mDebDispSet[ mDebugType ].on = true;
364         //errorOut( mDebugType <<"//"<< mDebDispSet[mDebugType].type );
365         mpLbm->debugDisplay( mDebugType );
366
367         //::lbmMarkedCellDisplay<>( mpLbm );
368         mpLbm->lbmMarkedCellDisplay();
369 #endif
370 }
371
372 /* GUI - display interactive info  */
373 void SimulationObject::drawInteractiveDisplay()
374 {
375 #ifndef NOGUI
376         if(!getVisible()) return;
377         if(mSelectedCid) {
378                 // in debugDisplayNode if dispset is on is ignored...
379                 mpLbm->debugDisplayNode( FLUIDDISPGrid, mSelectedCid );
380         }
381 #endif
382 }
383
384
385 /*******************************************************************************/
386 // GUI - handle mouse movement for selection 
387 /*******************************************************************************/
388 void SimulationObject::setMousePos(int x,int y, ntlVec3Gfx org, ntlVec3Gfx dir)
389 {
390         normalize( dir );
391         // assume 2D sim is in XY plane...
392         
393         double zplane = (mGeoEnd[2]-mGeoStart[2])*0.5;
394         double zt = (zplane-org[2]) / dir[2];
395         ntlVec3Gfx pos(
396                         org[0]+ dir[0] * zt,
397                         org[1]+ dir[1] * zt, 0.0);
398
399         mSelectedCid = mpLbm->getCellAt( pos );
400         //errMsg("SMP ", mName<< x<<" "<<y<<" - "<<dir );
401         x = y = 0; // remove warning
402 }
403                         
404
405 void SimulationObject::setMouseClick()
406 {
407         if(mSelectedCid) {
408                 //::debugPrintNodeInfo<>( mpLbm, mSelectedCid, mpLbm->getNodeInfoString() );
409                 mpLbm->debugPrintNodeInfo( mSelectedCid );
410         }
411 }
412
413 /*! notify object that dump is in progress (e.g. for field dump) */
414 void SimulationObject::notifyShaderOfDump(int dumptype, int frameNr,char *frameNrStr,string outfilename) {
415         if(!mpLbm) return;
416
417         mpLbm->notifySolverOfDump(dumptype, frameNr,frameNrStr,outfilename);
418         checkCallerStatus(FLUIDSIM_CBSTATUS_NEWFRAME, frameNr);
419 }
420
421 /*! check status (e.g. stop/abort) from calling program, returns !=0 if sth. happened... */
422 int SimulationObject::checkCallerStatus(int status, int frame) {
423         //return 0; // DEBUG
424         int ret = 0;
425         if((mpElbeemSettings)&&(mpElbeemSettings->runsimCallback)) {
426                 ret = (mpElbeemSettings->runsimCallback)(mpElbeemSettings->runsimUserData, status,frame);
427                 if(ret!=FLUIDSIM_CBRET_CONTINUE) {
428                         if(ret==FLUIDSIM_CBRET_STOP) {
429                                 debMsgStd("SimulationObject::notifySolverOfDump",DM_NOTIFY,"Got stop signal from caller",1);
430                                 setElbeemState( SIMWORLD_STOP );
431                         }
432                         else if(ret==FLUIDSIM_CBRET_ABORT) {
433                                 errFatal("SimulationObject::notifySolverOfDump","Got abort signal from caller, aborting...", SIMWORLD_GENERICERROR );
434                                 mPanic = 1;
435                         }
436                         else {
437                                 errMsg("SimulationObject::notifySolverOfDump","Invalid callback return value: "<<ret<<", ignoring... ");
438                         }
439                 }
440         }
441
442         errMsg("SimulationObject::checkCallerStatus","s="<<status<<",f="<<frame<<" "<<this->getName()<<" ret="<<ret);
443         if(isSimworldOk()) return 0;
444         return 1;
445 }
446