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