Fix #28416: setting fluid simulation start time to anything other than zero
[blender.git] / intern / elbeem / intern / ntl_world.cpp
1 /** \file elbeem/intern/ntl_world.cpp
2  *  \ingroup elbeem
3  */
4 /******************************************************************************
5  *
6  * El'Beem - Free Surface Fluid Simulation with the Lattice Boltzmann Method
7  * Copyright 2003-2006 Nils Thuerey
8  *
9  * Main renderer class
10  *
11  *****************************************************************************/
12
13
14 #include <sys/stat.h>
15 #include <sstream>
16 #include "utilities.h"
17 #include "ntl_world.h"
18 #include "parametrizer.h"
19
20 // for non-threaded renderViz
21 #ifndef NOGUI
22 #include "../gui/ntl_openglrenderer.h"
23 #include "../gui/guifuncs.h"
24 #include "../gui/frame.h"
25 #endif
26
27
28 /* external parser functions from cfgparser.cxx */
29 #ifndef ELBEEM_PLUGIN
30 /* parse given file as config file */
31 void parseFile(string filename);
32 /* set pointers for parsing */
33 void setPointers( ntlRenderGlobals *setglob);
34 #endif // ELBEEM_PLUGIN
35
36
37 /******************************************************************************
38  * Constructor
39  *****************************************************************************/
40
41 ntlWorld::ntlWorld() {
42         initDefaults();
43 }
44
45 ntlWorld::ntlWorld(string filename, bool commandlineMode) 
46 {
47 #ifndef ELBEEM_PLUGIN
48
49                 initDefaults();
50 #       ifdef NOGUI
51                 commandlineMode = true; // remove warning...
52 #       endif // NOGUI
53
54                 // load config
55                 setPointers( getRenderGlobals() );
56                 parseFile( filename.c_str() );
57 #       ifndef NOGUI
58                 // setup opengl display, save first animation step for start time 
59                 // init after parsing file...
60                 if(!commandlineMode) {
61                         mpOpenGLRenderer = new ntlOpenGLRenderer( mpGlob );
62                 }
63 #       endif // NOGUI
64                 finishWorldInit();
65
66 #else // ELBEEM_PLUGIN
67         errFatal("ntlWorld::init","Cfg file parsing not supported for API version! "<<filename<<" "<<commandlineMode, SIMWORLD_INITERROR);
68 #endif // ELBEEM_PLUGIN
69 }
70
71
72 int globalDomainCounter = 1;
73 int ntlWorld::addDomain(elbeemSimulationSettings *settings)
74 {
75         // create domain obj
76         SimulationObject *sim = new SimulationObject();
77         char simname[100];
78         snprintf(simname,100,"domain%04d",globalDomainCounter);
79         globalDomainCounter++;
80         sim->setName(string(simname));
81         mpGlob->getSims()->push_back( sim );
82
83         // important - add to both, only render scene objects are free'd 
84         mpGlob->getRenderScene()->addGeoClass( sim );
85         mpGlob->getSimScene()->addGeoClass( sim );
86         sim->setGeoStart(ntlVec3Gfx(settings->geoStart[0],settings->geoStart[1],settings->geoStart[2]));
87         sim->setGeoEnd(ntlVec3Gfx(
88                         settings->geoStart[0]+settings->geoSize[0],
89                         settings->geoStart[1]+settings->geoSize[1],
90                         settings->geoStart[2]+settings->geoSize[2] ));
91         // further init in postGeoConstrInit/initializeLbmSimulation of SimulationObject
92         sim->copyElbeemSettings(settings);
93
94         Parametrizer *param = sim->getParametrizer();
95         param->setSize( settings->resolutionxyz );
96         param->setDomainSize( settings->realsize );
97         param->setAniStart( settings->animStart );
98         param->setNormalizedGStar( settings->gstar );
99
100         // init domain channels
101         vector<ParamFloat> valf; 
102         vector<ParamVec> valv; 
103         vector<double> time;
104
105 #define INIT_CHANNEL_FLOAT(channel,size) \
106         valf.clear(); time.clear(); elbeemSimplifyChannelFloat(channel,&size); \
107         for(int i=0; i<size; i++) { valf.push_back( channel[2*i+0] ); time.push_back( channel[2*i+1] ); } 
108 #define INIT_CHANNEL_VEC(channel,size) \
109         valv.clear(); time.clear(); elbeemSimplifyChannelVec3(channel,&size); \
110         for(int i=0; i<size; i++) { valv.push_back( ParamVec(channel[4*i+0],channel[4*i+1],channel[4*i+2]) ); time.push_back( channel[4*i+3] ); } 
111
112         param->setViscosity( settings->viscosity );
113         if((settings->channelViscosity)&&(settings->channelSizeViscosity>0)) {
114                 INIT_CHANNEL_FLOAT(settings->channelViscosity, settings->channelSizeViscosity);
115                 param->initViscosityChannel(valf,time); }
116
117         param->setGravity( ParamVec(settings->gravity[0], settings->gravity[1], settings->gravity[2]) );
118         if((settings->channelGravity)&&(settings->channelSizeGravity>0)) {
119                 INIT_CHANNEL_VEC(settings->channelGravity, settings->channelSizeGravity);
120                 param->initGravityChannel(valv,time); }
121
122         param->setAniFrameTimeChannel( settings->aniFrameTime );
123         if((settings->channelFrameTime)&&(settings->channelSizeFrameTime>0)) {
124                 INIT_CHANNEL_FLOAT(settings->channelFrameTime, settings->channelSizeFrameTime);
125                 param->initAniFrameTimeChannel(valf,time); }
126
127 #undef INIT_CHANNEL_FLOAT
128 #undef INIT_CHANNEL_VEC
129         
130         // might be set by previous domain
131         if(mpGlob->getAniFrames() < settings->noOfFrames)       mpGlob->setAniFrames( settings->noOfFrames );
132         // set additionally to SimulationObject->mOutFilename
133         mpGlob->setOutFilename( settings->outputPath );
134
135         return 0;
136 }
137
138 void ntlWorld::initDefaults()
139 {
140         mStopRenderVisualization = false;
141         mThreadRunning =  false;
142         mSimulationTime = 0.0; 
143         mFirstSim = 1;
144         mSingleStepDebug =  false;
145         mFrameCnt = 0;
146         mpOpenGLRenderer = NULL;
147
148   /* create scene storage */
149   mpGlob = new ntlRenderGlobals();
150   mpLightList = new vector<ntlLightObject*>;
151   mpPropList = new vector<ntlMaterial*>;
152   mpSims = new vector<SimulationObject*>;
153
154   mpGlob->setLightList(mpLightList);
155   mpGlob->setMaterials(mpPropList);
156   mpGlob->setSims(mpSims);
157
158         /* init default material */
159   ntlMaterial *def = GET_GLOBAL_DEFAULT_MATERIAL;
160         mpPropList->push_back( def );
161
162         /* init the scene object */
163         ntlScene *renderscene = new ntlScene( mpGlob, true );
164         mpGlob->setRenderScene( renderscene );
165         // sim scene shouldnt delete objs, may only contain subset
166         ntlScene *simscene = new ntlScene( mpGlob, false );
167         mpGlob->setSimScene( simscene );
168 }
169
170 void ntlWorld::finishWorldInit()
171 {
172         if(! isSimworldOk() ) return;
173
174         // init the scene for the first time
175   long sstartTime = getTime();
176
177         // first init sim scene for geo setup
178         mpGlob->getSimScene()->buildScene(0.0, true);
179         if(! isSimworldOk() ) return;
180         mpGlob->getRenderScene()->buildScene(0.0, true);
181         if(! isSimworldOk() ) return;
182         long sstopTime = getTime();
183         debMsgStd("ntlWorld::ntlWorld",DM_MSG,"Scene build time: "<< getTimeString(sstopTime-sstartTime) <<" ", 10);
184
185         // TODO check simulations, run first steps
186         mFirstSim = -1;
187         if(mpSims->size() > 0) {
188
189                 // use values from first simulation as master time scale
190                 long startTime = getTime();
191                 
192                 // remember first active sim
193                 for(size_t i=0;i<mpSims->size();i++) {
194                         if(!(*mpSims)[i]->getVisible()) continue;
195                         if((*mpSims)[i]->getPanic())    continue;
196
197                         // check largest timestep
198                         if(mFirstSim>=0) {
199                                 if( (*mpSims)[i]->getTimestep() > (*mpSims)[mFirstSim]->getTimestep() ) {
200                                         mFirstSim = i;
201                                         debMsgStd("ntlWorld::ntlWorld",DM_MSG,"First Sim changed: "<<i ,10);
202                                 }
203                         }
204                         // check any valid sim
205                         if(mFirstSim<0) {
206                                 mFirstSim = i;
207                                 debMsgStd("ntlWorld::ntlWorld",DM_MSG,"First Sim: "<<i ,10);
208                         }
209                 }
210
211                 if(mFirstSim>=0) {
212                         debMsgStd("ntlWorld::ntlWorld",DM_MSG,"Anistart Time: "<<(*mpSims)[mFirstSim]->getStartTime() ,10);
213                         while(mSimulationTime < (*mpSims)[mFirstSim]->getStartTime() ) {
214                         debMsgStd("ntlWorld::ntlWorld",DM_MSG,"Anistart Time: "<<(*mpSims)[mFirstSim]->getStartTime()<<" simtime:"<<mSimulationTime ,10);
215                                 advanceSims(-1);
216                         }
217                         long stopTime = getTime();
218
219                         debMsgStd("ntlWorld::ntlWorld",DM_MSG,"Time for start-sims:"<< getTimeString(stopTime-startTime) , 1);
220 #ifndef NOGUI
221                         guiResetSimulationTimeRange( mSimulationTime );
222 #endif
223                 } else {
224                         if(!mpGlob->getSingleFrameMode()) debMsgStd("ntlWorld::ntlWorld",DM_WARNING,"No active simulations!", 1);
225                 }
226         }
227
228         if(! isSimworldOk() ) return;
229         setElbeemState( SIMWORLD_INITED );
230 }
231
232
233
234 /******************************************************************************
235  * Destructor
236  *****************************************************************************/
237 ntlWorld::~ntlWorld()
238 {
239         delete mpGlob->getRenderScene();
240         delete mpGlob->getSimScene();
241   
242         delete mpGlob;
243         
244         
245         // these get assigned to mpGlob but not freed there
246         delete mpLightList;
247         delete mpPropList; // materials
248         delete mpSims;
249   
250 #ifndef NOGUI
251         if(mpOpenGLRenderer) delete mpOpenGLRenderer;
252 #endif // NOGUI
253         debMsgStd("ntlWorld",DM_NOTIFY, "ntlWorld done", 10);
254 }
255
256 /******************************************************************************/
257 /*! set single frame rendering to filename */
258 void ntlWorld::setSingleFrameOut(string singleframeFilename) {
259         mpGlob->setSingleFrameMode(true);
260         mpGlob->setSingleFrameFilename(singleframeFilename);
261 }
262
263 /******************************************************************************
264  * render a whole animation (command line mode) 
265  *****************************************************************************/
266
267 int ntlWorld::renderAnimation( void )
268 {
269         // only single pic currently
270         //debMsgStd("ntlWorld::renderAnimation : Warning only simulating...",1);
271         if(mpGlob->getAniFrames() < 0) {
272                 debMsgStd("ntlWorld::renderAnimation",DM_NOTIFY,"No frames to render... ",1);
273                 return 1;
274         }
275
276         if(mFirstSim<0) {
277                 debMsgStd("ntlWorld::renderAnimation",DM_NOTIFY,"No reference animation found...",1);
278                 return 1;
279         } 
280
281         mThreadRunning = true; // not threaded, but still use the same flags
282         if(getElbeemState() == SIMWORLD_INITED) {
283                 renderScene();
284         } else if(getElbeemState() == SIMWORLD_STOP) {
285                 // dont render now, just continue
286                 setElbeemState( SIMWORLD_INITED );
287                 mFrameCnt--; // counted one too many from last abort...
288         } else {
289                 debMsgStd("ntlWorld::renderAnimation",DM_NOTIFY,"Not properly inited, stopping...",1);
290                 return 1;
291         }
292         
293         if(mpSims->size() <= 0) {
294                 debMsgStd("ntlWorld::renderAnimation",DM_NOTIFY,"No simulations found, stopping...",1);
295                 return 1;
296         }
297
298         bool simok = true;
299         for( ; ((mFrameCnt<mpGlob->getAniFrames()) && (!getStopRenderVisualization() ) && (simok)); mFrameCnt++) {
300                 if(!advanceSims(mFrameCnt)) {
301                         renderScene();
302                 } // else means sim panicked, so dont render...
303                 else { simok=false; }
304         }
305         mThreadRunning = false;
306         return 0;
307 }
308
309 /******************************************************************************
310  * render a whole animation (visualization mode) 
311  * this function is run in another thread, and communicates 
312  * with the parent thread via a mutex 
313  *****************************************************************************/
314 int ntlWorld::renderVisualization( bool multiThreaded ) 
315 {
316 #ifndef NOGUI
317         if(getElbeemState() != SIMWORLD_INITED) { return 0; }
318
319         if(multiThreaded) mThreadRunning = true;
320         // TODO, check global state?
321         while(!getStopRenderVisualization()) {
322
323                 if(mpSims->size() <= 0) {
324                         debMsgStd("ntlWorld::renderVisualization",DM_NOTIFY,"No simulations found, stopping...",1);
325                         stopSimulationThread();
326                         break;
327                 }
328
329                 // determine stepsize
330                 if(!mSingleStepDebug) {
331                         long startTime = getTime();
332                         advanceSims(mFrameCnt);
333                         mFrameCnt++;
334                         long stopTime = getTime();
335                         debMsgStd("ntlWorld::renderVisualization",DM_MSG,"Time for t="<<mSimulationTime<<": "<< getTimeString(stopTime-startTime) <<" ", 10);
336                 } else {
337                         double targetTime = mSimulationTime + (*mpSims)[mFirstSim]->getTimestep();
338                         singleStepSims(targetTime);
339
340                         // check paniced sims (normally done by advanceSims
341                         bool allPanic = true;
342                         for(size_t i=0;i<mpSims->size();i++) {
343                                 if(!(*mpSims)[i]->getPanic()) allPanic = false;
344                         }
345                         if(allPanic) {
346                                 warnMsg("ntlWorld::advanceSims","All sims panicked... stopping thread" );
347                                 setStopRenderVisualization( true );
348                         }
349                         if(! isSimworldOk() ) {
350                                 warnMsg("ntlWorld::advanceSims","World state error... stopping" );
351                                 setStopRenderVisualization( true );
352                         }
353                 }
354
355                 // save frame
356                 if(mpOpenGLRenderer) mpOpenGLRenderer->saveAnimationFrame( mSimulationTime );
357                 
358                 // for non-threaded check events
359                 if(!multiThreaded) {
360                         Fl::check();
361       gpElbeemFrame->SceneDisplay->doOnlyForcedRedraw();
362                 }
363
364         }
365         mThreadRunning = false;
366         stopSimulationRestoreGui();
367 #else 
368         multiThreaded = false; // remove warning
369 #endif
370         return 0;
371 }
372 /*! render a single step for viz mode */
373 int ntlWorld::singleStepVisualization( void ) 
374 {
375         mThreadRunning = true;
376         double targetTime = mSimulationTime + (*mpSims)[mFirstSim]->getTimestep();
377         singleStepSims(targetTime);
378         mSimulationTime = (*mpSims)[0]->getCurrentTime();
379
380 #ifndef NOGUI
381         if(mpOpenGLRenderer) mpOpenGLRenderer->saveAnimationFrame( mSimulationTime );
382         Fl::check();
383   gpElbeemFrame->SceneDisplay->doOnlyForcedRedraw();
384         mThreadRunning = false;
385         stopSimulationRestoreGui();
386 #else
387         mThreadRunning = false;
388 #endif // NOGUI
389         return 0;
390 }
391
392 // dont use LBM_EPSILON here, time is always double-precision!
393 #define LBM_TIME_EPSILON 1e-10
394
395 /******************************************************************************
396  * advance simulations by time t 
397  *****************************************************************************/
398 int ntlWorld::advanceSims(int framenum)
399 {
400         bool done = false;
401         bool allPanic = true;
402
403         // stop/quit, dont display/render
404         if(getElbeemState()==SIMWORLD_STOP) { 
405                 return 1;
406         }
407
408         for(size_t i=0;i<mpSims->size();i++) { (*mpSims)[i]->setFrameNum(framenum); }
409         double targetTime = mSimulationTime + (*mpSims)[mFirstSim]->getFrameTime(framenum);
410
411         // time stopped? nothing else to do...
412         if( (*mpSims)[mFirstSim]->getFrameTime(framenum) <= 0.0 ){ 
413                 done=true; allPanic=false; 
414         }
415
416         int gstate = 0;
417         myTime_t advsstart = getTime();
418
419         // step all the sims, and check for panic
420         debMsgStd("ntlWorld::advanceSims",DM_MSG, " sims "<<mpSims->size()<<" t"<<targetTime<<" done:"<<done<<" panic:"<<allPanic<<" gstate:"<<gstate, 10); // debug // timedebug
421         while(!done) {
422                 double nextTargetTime = (*mpSims)[mFirstSim]->getCurrentTime() + (*mpSims)[mFirstSim]->getTimestep();
423                 singleStepSims(nextTargetTime);
424
425                 // check target times
426                 done = true;
427                 allPanic = false;
428                 
429                 if((*mpSims)[mFirstSim]->getTimestep() <1e-9 ) { 
430                         // safety check, avoid timesteps that are too small
431                         errMsg("ntlWorld::advanceSims","Invalid time step, causing panic! curr:"<<(*mpSims)[mFirstSim]->getCurrentTime()<<" next:"<<nextTargetTime<<", stept:"<< (*mpSims)[mFirstSim]->getTimestep() );
432                         allPanic = true; 
433                 } else {
434                         for(size_t i=0;i<mpSims->size();i++) {
435                                 if(!(*mpSims)[i]->getVisible()) continue;
436                                 if((*mpSims)[i]->getPanic()) allPanic = true; // do any panic now!?
437                                 debMsgStd("ntlWorld::advanceSims",DM_MSG, "Sim "<<i<<", currt:"<<(*mpSims)[i]->getCurrentTime()<<", nt:"<<nextTargetTime<<", panic:"<<(*mpSims)[i]->getPanic()<<", targett:"<<targetTime, 10); // debug // timedebug
438                         } 
439                 }
440                 if( (targetTime - (*mpSims)[mFirstSim]->getCurrentTime()) > LBM_TIME_EPSILON) done=false;
441                 if(allPanic) done = true;
442         }
443
444         if(allPanic) {
445                 warnMsg("ntlWorld::advanceSims","All sims panicked... stopping thread" );
446                 setStopRenderVisualization( true );
447                 return 1;
448         }
449
450         myTime_t advsend = getTime();
451         debMsgStd("ntlWorld::advanceSims",DM_MSG,"Overall steps so far took:"<< getTimeString(advsend-advsstart)<<" for sim time "<<targetTime, 4);
452
453         // finish step
454         for(size_t i=0;i<mpSims->size();i++) {
455                 SimulationObject *sim = (*mpSims)[i];
456                 if(!sim->getVisible()) continue;
457                 if(sim->getPanic()) continue;
458                 sim->prepareVisualization();
459         }
460
461         return 0;
462 }
463
464 /* advance simulations by a single step */
465 /* dont check target time, if *targetTime==NULL */
466 void ntlWorld::singleStepSims(double targetTime) {
467         const bool debugTime = false;
468         //double targetTime = mSimulationTime + (*mpSims)[mFirstSim]->getTimestep();
469         if(debugTime) errMsg("ntlWorld::singleStepSims","Target time: "<<targetTime);
470
471         for(size_t i=0;i<mpSims->size();i++) {
472                 SimulationObject *sim = (*mpSims)[i];
473                 if(!sim->getVisible()) continue;
474                 if(sim->getPanic()) continue;
475                 bool done = false;
476                 while(!done) {
477                         // try to prevent round off errs
478                         if(debugTime) errMsg("ntlWorld::singleStepSims","Test sim "<<i<<" curt:"<< sim->getCurrentTime()<<" target:"<<targetTime<<" delta:"<<(targetTime - sim->getCurrentTime())<<" stept:"<<sim->getTimestep()<<" leps:"<<LBM_TIME_EPSILON ); // timedebug
479                         if( (targetTime - sim->getCurrentTime()) > LBM_TIME_EPSILON) {
480                                 if(debugTime) errMsg("ntlWorld::singleStepSims","Stepping sim "<<i<<" t:"<< sim->getCurrentTime()); // timedebug
481                                 sim->step();
482                         } else {
483                                 done = true;
484                         }
485                 }
486         }
487
488         mSimulationTime = (*mpSims)[mFirstSim]->getCurrentTime();
489 #ifndef NOGUI
490         if(mpOpenGLRenderer) mpOpenGLRenderer->notifyOfNextStep(mSimulationTime);
491 #endif // NOGUI
492 }
493
494
495
496 extern bool glob_mpactive;
497 extern int glob_mpindex;
498
499 /******************************************************************************
500  * Render the current scene
501  * uses the global variables from the parser
502  *****************************************************************************/
503 int ntlWorld::renderScene( void )
504 {
505 #ifndef ELBEEM_PLUGIN
506         char nrStr[5];                                                                                                          // nr conversion 
507         std::ostringstream outfn_conv("");                      // converted ppm with other suffix 
508   ntlRenderGlobals *glob;                       // storage for global rendering parameters 
509   myTime_t timeStart,totalStart,timeEnd;                // measure user running time 
510   myTime_t rendStart,rendEnd;                           // measure user rendering time 
511   glob = mpGlob;
512
513         // deactivate for all with index!=0 
514         if((glob_mpactive)&&(glob_mpindex>0)) return(0);
515
516         /* check if picture already exists... */
517         if(!glob->getSingleFrameMode() ) {
518                 snprintf(nrStr, 5, "%04d", glob->getAniCount() );
519
520                 if(glob_mpactive) {
521                         outfn_conv  << glob->getOutFilename() <<"_"<<glob_mpindex<<"_" << nrStr << ".png"; /// DEBUG!
522                 } else {
523                         // ORG
524                         outfn_conv  << glob->getOutFilename() <<"_" << nrStr << ".png";
525                 }
526                 
527                 //if((mpGlob->getDisplayMode() == DM_RAY)&&(mpGlob->getFrameSkip())) {
528                 if(mpGlob->getFrameSkip()) {
529                         struct stat statBuf;
530                         if(stat(outfn_conv.str().c_str(),&statBuf) == 0) {
531                                 errorOut("ntlWorld::renderscene Warning: file "<<outfn_conv.str()<<" already exists - skipping frame..."); 
532                                 glob->setAniCount( glob->getAniCount() +1 );
533                                 return(2);
534                         }
535                 } // RAY mode
536         } else {
537                 // single frame rendering, overwrite if necessary...
538                 outfn_conv << glob->getSingleFrameFilename();
539         }
540
541   /* start program */
542         timeStart = getTime();
543
544         /* build scene geometry, calls buildScene(t,false) */
545         glob->getRenderScene()->prepareScene(mSimulationTime);
546
547   /* start program */
548         totalStart = getTime();
549
550
551         /* view parameters are currently not animated */
552         /* calculate rays through projection plane */
553         ntlVec3Gfx direction = glob->getLookat() - glob->getEye();
554         /* calculate width of screen using perpendicular triangle diven by
555          * viewing direction and screen plane */
556         gfxReal screenWidth = norm(direction)*tan( (glob->getFovy()*0.5/180.0)*M_PI );
557
558         /* calculate vector orthogonal to up and viewing direction */
559         ntlVec3Gfx upVec = glob->getUpVec();
560         ntlVec3Gfx rightVec( cross(upVec,direction) );
561         normalize(rightVec);
562
563         /* calculate screen plane up vector, perpendicular to viewdir and right vec */
564         upVec = ntlVec3Gfx( cross(rightVec,direction) );
565         normalize(upVec);
566
567         /* check if vectors are valid */
568         if( (equal(upVec,ntlVec3Gfx(0.0))) || (equal(rightVec,ntlVec3Gfx(0.0))) ) {
569                 errMsg("ntlWorld::renderScene","Invalid viewpoint vectors! up="<<upVec<<" right="<<rightVec);
570                 return(1);
571         }
572
573         /* length from center to border of screen plane */
574         rightVec *= (screenWidth*glob->getAspect() * -1.0);
575         upVec *= (screenWidth * -1.0);
576
577         /* screen traversal variables */
578         ntlVec3Gfx screenPos;                          /* current position on virtual screen */
579         int Xres = glob->getResX();                  /* X resolution */
580         int Yres = glob->getResY();                  /* Y resolution */
581         ntlVec3Gfx rightStep = (rightVec/(Xres/2.0));  /* one step right for a pixel */
582         ntlVec3Gfx upStep    = (upVec/(Yres/2.0));     /* one step up for a pixel */
583     
584
585         /* anti alias init */
586         char  showAAPic = 0;
587         int   aaDepth = glob->getAADepth();
588         int   aaLength;
589         if(aaDepth>=0) aaLength = (2<<aaDepth);
590         else           aaLength = 0;
591         float aaSensRed   = 0.1;
592         float aaSensGreen = 0.1;
593         float aaSensBlue  = 0.1;
594         int   aaArrayX = aaLength*Xres+1;
595         int   aaArrayY = ( aaLength+1 );
596         ntlColor *aaCol = new ntlColor[ aaArrayX*aaArrayY ];
597         char  *aaUse = new char[ aaArrayX*aaArrayY ];
598
599         /* picture storage */
600         int picX = Xres;
601         int picY = Yres;
602         if(showAAPic) {
603                 picX = Xres *aaLength+1;
604                 picY = Yres *aaLength+1;
605         }
606         ntlColor *finalPic = new ntlColor[picX * picY];
607
608
609         /* reset picture vars */
610         for(int j=0;j<aaArrayY;j++) {
611                 for(int i=0;i<aaArrayX;i++) {
612                         aaCol[j*aaArrayX+i] = ntlColor(0.0, 0.0, 0.0);
613                         aaUse[j*aaArrayX+i] = 0;
614                 }
615         }
616         for(int j=0;j<picY;j++) {
617                 for(int i=0;i<picX;i++) {
618                         finalPic[j*picX+i] = ntlColor(0.0, 0.0, 0.0);
619                 }
620         }
621
622         /* loop over all y lines in screen, from bottom to top because
623          * ppm format wants 0,0 top left */
624         rendStart = getTime();
625         glob->setCounterShades(0);
626         glob->setCounterSceneInter(0);
627         for (int scanline=Yres ; scanline > 0 ; --scanline) {
628     
629                 debugOutInter( "ntlWorld::renderScene: Line "<<scanline<<
630                                                                  " ("<< ((Yres-scanline)*100/Yres) <<"%) ", 2, 2000 );
631                 screenPos = glob->getLookat() + upVec*((2.0*scanline-Yres)/Yres)
632                         - rightVec;
633
634                 /* loop over all pixels in line */
635                 for (int sx=0 ; sx < Xres ; ++sx) {
636
637                         if((sx==glob->getDebugPixelX())&&(scanline==(Yres-glob->getDebugPixelY()) )) {
638                                 // DEBUG!!!
639                                 glob->setDebugOut(10);
640                         } else glob->setDebugOut(0);
641                         
642                         /* compute ray from eye through current pixel into scene... */
643                         ntlColor col;
644                         if(aaDepth<0) {
645                                 ntlVec3Gfx dir(screenPos - glob->getEye());
646                                 ntlRay the_ray(glob->getEye(), getNormalized(dir), 0, 1.0, glob );
647
648                                 /* ...and trace it */
649                                 col = the_ray.shade();
650                         } else {
651                                 /* anti alias */
652                                 int ai,aj;                   /* position in grid */
653                                 int aOrg = sx*aaLength;      /* grid offset x */
654                                 int currStep = aaLength;     /* step size */
655                                 char colDiff = 1;            /* do colors still differ too much? */
656                                 ntlColor minCol,maxCol;         /* minimum and maximum Color Values */
657                                 minCol = ntlColor(1.0,1.0,1.0);
658                                 maxCol = ntlColor(0.0,0.0,0.0);
659
660                                 while((colDiff) && (currStep>0)) {
661                                         colDiff = 0;
662             
663                                         for(aj = 0;aj<=aaLength;aj+= currStep) {
664                                                 for(ai = 0;ai<=aaLength;ai+= currStep) {
665
666                                                         /* shade pixel if not done */
667                                                         if(aaUse[aj*aaArrayX +ai +aOrg] == 0) {
668                                                                 aaUse[aj*aaArrayX +ai +aOrg] = 1;
669                                                                 ntlVec3Gfx aaPos( screenPos +
670                                                                                                                                 (rightStep * (ai- aaLength/2)/(gfxReal)aaLength ) +
671                                                                                                                                 (upStep    * (aj- aaLength/2)/(gfxReal)aaLength ) );
672
673                                                                 ntlVec3Gfx dir(aaPos - glob->getEye());
674                                                                 ntlRay the_ray(glob->getEye(), getNormalized(dir), 0, 1.0, glob );
675
676                                                                 /* ...and trace it */
677                                                                 ntlColor newCol= the_ray.shade();
678                                                                 aaCol[aj*aaArrayX +ai +aOrg]= newCol;
679                                                         } /* not used? */
680
681                                                 }
682                                         }
683
684                                         /* check color differences */
685                                         for(aj = 0;aj<aaLength;aj+= currStep) {
686                                                 for(ai = 0;ai<aaLength;ai+= currStep) {
687
688                                                         char thisColDiff = 0;
689                                                         if( 
690                                                                  (fabs(aaCol[aj*aaArrayX +ai +aOrg][0] - 
691                                                                                          aaCol[(aj+0)*aaArrayX +(ai+currStep) +aOrg][0])> aaSensRed ) ||
692                                                                  (fabs(aaCol[aj*aaArrayX +ai +aOrg][1] - 
693                                                                                          aaCol[(aj+0)*aaArrayX +(ai+currStep) +aOrg][1])> aaSensGreen ) ||
694                                                                  (fabs(aaCol[aj*aaArrayX +ai +aOrg][2] - 
695                                                                                          aaCol[(aj+0)*aaArrayX +(ai+currStep) +aOrg][2])> aaSensBlue ) ) {
696                                                                 thisColDiff = 1;
697                                                         } else
698                                                                 if( 
699                                                                          (fabs(aaCol[aj*aaArrayX +ai +aOrg][0] - 
700                                                                                                  aaCol[(aj+currStep)*aaArrayX +(ai+0) +aOrg][0])> aaSensRed ) ||
701                                                                          (fabs(aaCol[aj*aaArrayX +ai +aOrg][1] - 
702                                                                                                  aaCol[(aj+currStep)*aaArrayX +(ai+0) +aOrg][1])> aaSensGreen ) ||
703                                                                          (fabs(aaCol[aj*aaArrayX +ai +aOrg][2] - 
704                                                                                                  aaCol[(aj+currStep)*aaArrayX +(ai+0) +aOrg][2])> aaSensBlue ) ) {
705                                                                         thisColDiff = 1;
706                                                                 } else
707                                                                         if( 
708                                                                                  (fabs(aaCol[aj*aaArrayX +ai +aOrg][0] - 
709                                                                                                          aaCol[(aj+currStep)*aaArrayX +(ai+currStep) +aOrg][0])> aaSensRed ) ||
710                                                                                  (fabs(aaCol[aj*aaArrayX +ai +aOrg][1] - 
711                                                                                                          aaCol[(aj+currStep)*aaArrayX +(ai+currStep) +aOrg][1])> aaSensGreen ) ||
712                                                                                  (fabs(aaCol[aj*aaArrayX +ai +aOrg][2] - 
713                                                                                                          aaCol[(aj+currStep)*aaArrayX +(ai+currStep) +aOrg][2])> aaSensBlue ) ) {
714                                                                                 thisColDiff = 1;
715                                                                         } 
716
717                                                         //colDiff =1;
718                                                         if(thisColDiff) {
719                                                                 /* set diff flag */
720                                                                 colDiff = thisColDiff;
721                                                                 for(int bj=aj;bj<=aj+currStep;bj++) {
722                                                                         for(int bi=ai;bi<=ai+currStep;bi++) {
723                                                                                 if(aaUse[bj*aaArrayX +bi +aOrg]==2) {
724                                                                                         //if(showAAPic) 
725                                                                                         aaUse[bj*aaArrayX +bi +aOrg] = 0;
726                                                                                 }
727                                                                         }
728                                                                 }
729                                                         } else {
730                                                                 /* set all values */
731                                                                 ntlColor avgCol = (
732                                                                                                                                          aaCol[(aj+0       )*aaArrayX +(ai+0       ) +aOrg] +
733                                                                                                                                          aaCol[(aj+0       )*aaArrayX +(ai+currStep) +aOrg] +
734                                                                                                                                          aaCol[(aj+currStep)*aaArrayX +(ai+0       ) +aOrg] +
735                                                                                                                                          aaCol[(aj+currStep)*aaArrayX +(ai+currStep) +aOrg] ) *0.25;
736                                                                 for(int bj=aj;bj<=aj+currStep;bj++) {
737                                                                         for(int bi=ai;bi<=ai+currStep;bi++) {
738                                                                                 if(aaUse[bj*aaArrayX +bi +aOrg]==0) {
739                                                                                         aaCol[bj*aaArrayX +bi +aOrg] = avgCol; 
740                                                                                         aaUse[bj*aaArrayX +bi +aOrg] = 2;
741                                                                                 }
742                                                                         }
743                                                                 }
744                                                         } /* smaller values set */
745
746                                                 }
747                                         }
748
749                                         /* half step size */
750                                         currStep /= 2;
751
752                                 } /* repeat until diff not too big */
753
754                                 /* get average color */
755                                 gfxReal colNum = 0.0;
756                                 col = ntlColor(0.0, 0.0, 0.0);
757                                 for(aj = 0;aj<=aaLength;aj++) {
758                                         for(ai = 0;ai<=aaLength;ai++) {
759                                                 col += aaCol[aj*aaArrayX +ai +aOrg];
760                                                 colNum += 1.0;
761                                         }
762                                 }
763                                 col /= colNum;
764
765                         }
766
767                   /* mark pixels with debugging */
768                         if( glob->getDebugOut() > 0) col = ntlColor(0,1,0);
769
770                         /* store pixel */
771                         if(!showAAPic) {
772                                 finalPic[(scanline-1)*picX+sx] = col; 
773                         }
774                         screenPos +=  rightStep;
775
776                 } /* foreach x */
777
778                 /* init aa array */
779                 if(showAAPic) {
780                         for(int j=0;j<=aaArrayY-1;j++) {
781                                 for(int i=0;i<=aaArrayX-1;i++) {
782                                         if(aaUse[j*aaArrayX +i]==1) finalPic[((scanline-1)*aaLength +j)*picX+i][0] = 1.0;
783                                 }
784                         }
785                 }
786
787                 for(int i=0;i<aaArrayX;i++) {
788                         aaCol[(aaArrayY-1)*aaArrayX+i] = aaCol[0*aaArrayX+i];
789                         aaUse[(aaArrayY-1)*aaArrayX+i] = aaUse[0*aaArrayX+i];
790                 }
791                 for(int j=0;j<aaArrayY-1;j++) {
792                         for(int i=0;i<aaArrayX;i++) {
793                                 aaCol[j*aaArrayX+i] = ntlColor(0.0, 0.0, 0.0);
794                                 aaUse[j*aaArrayX+i] = 0;
795                         }
796                 }
797
798         } /* foreach y */
799         rendEnd = getTime();
800
801
802         /* write png file */
803         {
804                 int w = picX;
805                 int h = picY;
806
807                 unsigned rowbytes = w*4;
808                 unsigned char *screenbuf, **rows;
809                 screenbuf = (unsigned char*)malloc( h*rowbytes );
810                 rows = (unsigned char**)malloc( h*sizeof(unsigned char*) );
811                 unsigned char *filler = screenbuf;
812
813                 // cutoff color values 0..1
814                 for(int j=0;j<h;j++) {
815                         for(int i=0;i<w;i++) {
816                                 ntlColor col = finalPic[j*w+i];
817                                 for (unsigned int cc=0; cc<3; cc++) {
818                                         if(col[cc] <= 0.0) col[cc] = 0.0;
819                                         if(col[cc] >= 1.0) col[cc] = 1.0;
820                                 }
821                                 *filler = (unsigned char)( col[0]*255.0 ); 
822                                 filler++;
823                                 *filler = (unsigned char)( col[1]*255.0 ); 
824                                 filler++;
825                                 *filler = (unsigned char)( col[2]*255.0 ); 
826                                 filler++;
827                                 *filler = (unsigned char)( 255.0 ); 
828                                 filler++; // alpha channel
829                         }
830                 }
831
832                 for(int i = 0; i < h; i++) rows[i] = &screenbuf[ (h - i - 1)*rowbytes ];
833                 writePng(outfn_conv.str().c_str(), rows, w, h);
834         }
835
836
837         // next frame 
838         glob->setAniCount( glob->getAniCount() +1 );
839
840         // done 
841         timeEnd = getTime();
842
843         char resout[1024];
844         snprintf(resout,1024, "NTL Done %s, frame %d/%d (took %s scene, %s raytracing, %s total, %d shades, %d i.s.'s)!\n", 
845                                  outfn_conv.str().c_str(), (glob->getAniCount()), (glob->getAniFrames()+1),
846                                  getTimeString(totalStart-timeStart).c_str(), getTimeString(rendEnd-rendStart).c_str(), getTimeString(timeEnd-timeStart).c_str(),
847                                  glob->getCounterShades(),
848                                  glob->getCounterSceneInter() );
849         debMsgStd("ntlWorld::renderScene",DM_MSG, resout, 1 );
850
851         /* clean stuff up */
852         delete [] aaCol;
853         delete [] aaUse;
854         delete [] finalPic;
855         glob->getRenderScene()->cleanupScene();
856
857         if(mpGlob->getSingleFrameMode() ) {
858                 debMsgStd("ntlWorld::renderScene",DM_NOTIFY, "Single frame mode done...", 1 );
859                 return 1;
860         }
861 #endif // ELBEEM_PLUGIN
862         return 0;
863 }
864
865
866 /******************************************************************************
867  * renderglobals
868  *****************************************************************************/
869
870
871 /*****************************************************************************/
872 /* Constructor with standard value init */
873 ntlRenderGlobals::ntlRenderGlobals() :
874         mpRenderScene(NULL), mpSimScene(NULL),
875   mpLightList( NULL ), mpMaterials( NULL ), mpSims( NULL ),
876   mResX(320), mResY(200), mAADepth(-1), mMaxColVal(255), 
877   mRayMaxDepth( 5 ),
878   mvEye(0.0,0.0,5.0), mvLookat(0.0,0.0,0.0), mvUpvec(0.0,1.0,0.0), 
879   mAspect(320.0/200.0), 
880   mFovy(45), mcBackgr(0.0,0.0,0.0), mcAmbientLight(0.0,0.0,0.0), 
881   mDebugOut( 0 ),
882   mAniStart(0), mAniFrames( -1 ), mAniCount( 0 ),
883         mFrameSkip( 0 ),
884   mCounterRays( 0 ), mCounterShades( 0 ), mCounterSceneInter( 0 ),
885         mOutFilename( "pic" ),
886         mTreeMaxDepth( 30 ), mTreeMaxTriangles( 30 ),
887         mpOpenGlAttr(NULL),
888         mpBlenderAttr(NULL),
889         mTestSphereEnabled( false ),
890         mDebugPixelX( -1 ), mDebugPixelY( -1 ), mTestMode(false),
891         mSingleFrameMode(false), mSingleFrameFilename("")
892         //,mpRndDirections( NULL ), mpRndRoulette( NULL )
893
894         // create internal attribute list for opengl renderer
895         mpOpenGlAttr = new AttributeList("__ntlOpenGLRenderer");
896         mpBlenderAttr = new AttributeList("__ntlBlenderAttr");
897 };
898
899
900 /*****************************************************************************/
901 /* Destructor */
902 ntlRenderGlobals::~ntlRenderGlobals() {
903         if(mpOpenGlAttr) delete mpOpenGlAttr;
904         if(mpBlenderAttr) delete mpBlenderAttr;
905         
906         
907 }
908
909
910 /*****************************************************************************/
911 //! get the next random photon direction
912 //ntlVec3Gfx ntlRenderGlobals::getRandomDirection( void ) { 
913         //return ntlVec3Gfx( 
914                         //(mpRndDirections->getGfxReal()-0.5), 
915                         //(mpRndDirections->getGfxReal()-0.5),  
916                         //(mpRndDirections->getGfxReal()-0.5) ); 
917 //} 
918
919