source: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOcclusionCullingSceneManager.cpp @ 1595

Revision 1595, 39.3 KB checked in by mattausch, 18 years ago (diff)
Line 
1#include "OgreOcclusionCullingSceneManager.h"
2#include "OgreVisibilityOptionsManager.h"
3#include <OgreMath.h>
4#include <OgreIteratorWrappers.h>
5#include <OgreRenderSystem.h>
6#include <OgreCamera.h>
7#include <OgreLogManager.h>
8#include <OgreStringConverter.h>
9#include <OgreEntity.h>
10#include <OgreSubEntity.h>
11#include <OgreMaterialManager.h>
12#include <OgreIteratorWrappers.h>
13#include <OgreHeightmapTerrainPageSource.h>
14#include "VspBspTree.h"
15#include "Containers.h"
16#include "ViewCellsManager.h"
17#include <OgreConfigFile.h>
18#include "OgreTypeConverter.h"
19#include "OgreMeshInstance.h"
20#include "common.h"
21#include "OgreBoundingBoxConverter.h"
22#include <OgreManualObject.h>
23
24
25namespace Ogre {
26
27//-----------------------------------------------------------------------
28OcclusionCullingSceneManager::OcclusionCullingSceneManager(const String& name,
29                                                        GtpVisibility::VisibilityManager *visManager):
30TerrainSceneManager(name),
31mVisibilityManager(visManager),
32mShowVisualization(false),
33mRenderNodesForViz(false),
34mRenderNodesContentForViz(false),
35mVisualizeCulledNodes(false),
36mLeavePassesInQueue(0),
37mDelayRenderTransparents(true),
38mUseDepthPass(false),
39mIsDepthPassPhase(false),
40mUseItemBuffer(false),
41mIsItemBufferPhase(false),
42mCurrentEntityId(1),
43mEnableDepthWrite(true),
44mSkipTransparents(false),
45mRenderTransparentsForItemBuffer(true),
46mExecuteVertexProgramForAllPasses(false),
47mIsHierarchicalCulling(false),
48mViewCellsLoaded(false),
49mUseViewCells(false),
50mUseVisibilityFilter(false),
51mCurrentViewCell(NULL),
52mElementaryViewCell(NULL),
53mDeleteQueueAfterRendering(true),
54mNormalExecution(false)
55{
56        Ogre::LogManager::getSingleton().logMessage("creating occlusion culling scene manager");
57
58        mHierarchyInterface = new OctreeHierarchyInterface(this, mDestRenderSystem);
59       
60        if (0)
61        {
62                mDisplayNodes = true;
63                mShowBoundingBoxes = true;
64                mShowBoxes = true;
65        }
66
67        // TODO: set maxdepth to reasonable value
68        mMaxDepth = 50;
69}
70//-----------------------------------------------------------------------
71void OcclusionCullingSceneManager::InitDepthPass()
72{
73        MaterialPtr depthMat = MaterialManager::getSingleton().getByName("Visibility/DepthPass");
74
75        if (depthMat.isNull())
76    {
77                depthMat = MaterialManager::getSingleton().create(
78                "Visibility/DepthPass",
79                ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
80
81        mDepthPass = depthMat->getTechnique(0)->getPass(0);
82                mDepthPass->setColourWriteEnabled(false);
83                mDepthPass->setDepthWriteEnabled(true);
84                mDepthPass->setLightingEnabled(false);
85        }
86        else
87        {
88                mDepthPass = depthMat->getTechnique(0)->getPass(0);
89        }
90}
91//-----------------------------------------------------------------------
92OcclusionCullingSceneManager::~OcclusionCullingSceneManager()
93{
94        OGRE_DELETE(mHierarchyInterface);
95        CLEAR_CONTAINER(mObjects);
96        OGRE_DELETE(mCurrentViewCell);
97}
98//-----------------------------------------------------------------------
99void OcclusionCullingSceneManager::InitItemBufferPass()
100{
101        MaterialPtr itemBufferMat = MaterialManager::getSingleton().
102                getByName("Visibility/ItemBufferPass");
103
104        if (itemBufferMat.isNull())
105    {
106                // Init
107                itemBufferMat = MaterialManager::getSingleton().create("Visibility/ItemBufferPass",
108                ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
109
110                mItemBufferPass = itemBufferMat->getTechnique(0)->getPass(0);
111                mItemBufferPass->setColourWriteEnabled(true);
112                mItemBufferPass->setDepthWriteEnabled(true);
113                mItemBufferPass->setLightingEnabled(true);
114                //mItemBufferPass->setLightingEnabled(false);
115        }
116        else
117        {
118                mItemBufferPass = itemBufferMat->getTechnique(0)->getPass(0);
119        }
120        //mItemBufferPass->setAmbient(1, 1, 0);
121}
122//-------------------------------------------------------------------------
123#if 1
124void OcclusionCullingSceneManager::setWorldGeometry( DataStreamPtr& stream, const String& typeName )
125{
126    // Clear out any existing world resources (if not default)
127    if (ResourceGroupManager::getSingleton().getWorldResourceGroupName() !=
128        ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME)
129    {
130        ResourceGroupManager::getSingleton().clearResourceGroup(
131            ResourceGroupManager::getSingleton().getWorldResourceGroupName());
132    }
133        destroyLevelIndexes();
134    mTerrainPages.clear();
135    // Load the configuration
136    loadConfig(stream);
137        initLevelIndexes();
138
139    // Resize the octree, allow for 1 page for now
140    float max_x = mOptions.scale.x * mOptions.pageSize;
141    float max_y = mOptions.scale.y;
142    float max_z = mOptions.scale.z * mOptions.pageSize;
143
144        float maxAxis = std::max(max_x, max_y);
145        maxAxis = std::max(maxAxis, max_z);
146        resize( AxisAlignedBox( 0, 0, 0, maxAxis, maxAxis, maxAxis ) );
147   
148    setupTerrainMaterial();
149
150    setupTerrainPages();
151
152 }
153#endif
154//-----------------------------------------------------------------------
155void OcclusionCullingSceneManager::PrepareVisualization(Camera *cam)
156{
157        // add player camera for visualization purpose
158        try
159        {
160                Camera *c;
161                if ((c = getCamera("PlayerCam")) != NULL)
162                {
163                        getRenderQueue()->addRenderable(c);
164                }   
165    }
166    catch (...)
167    {
168        // ignore
169    }
170        // add bounding boxes of rendered objects
171        if (0)
172        for (BoxList::iterator it = mBoxes.begin(); it != mBoxes.end(); ++it)
173        {
174                getRenderQueue()->addRenderable(*it);
175        }
176
177        MovableObjectsMap::const_iterator mit, mit_end = mViewCellsGeometry.end();
178/*
179        for (mit = mViewCellsGeometry.begin(); mit != mit_end; ++ mit)
180        {
181                (*mit).second->_updateRenderQueue(getRenderQueue());
182        }
183*/     
184
185        if (mRenderNodesForViz || mRenderNodesContentForViz)
186        {
187                // HACK: change node material so it is better suited for visualization
188                MaterialPtr nodeMat = MaterialManager::getSingleton().getByName("Core/NodeMaterial");
189                nodeMat->setAmbient(1, 1, 0);
190                nodeMat->setLightingEnabled(true);
191                nodeMat->getTechnique(0)->getPass(0)->removeAllTextureUnitStates();
192
193                for (NodeList::iterator it = mVisible.begin(); it != mVisible.end(); ++it)
194                {
195                        if (mRenderNodesForViz)
196                        {
197                                // render the leaf nodes
198                                if ((*it)->numAttachedObjects() &&
199                                        !(*it)->numChildren() &&
200                                        ((*it)->getAttachedObject(0)->getMovableType() == "Entity") &&
201                                        (*it)->getAttachedObject(0)->isVisible())
202                                {
203                                        getRenderQueue()->addRenderable((*it));
204                                }
205
206                                // addbounding boxes instead of node itself
207                                //(*it)->_addBoundingBoxToQueue(getRenderQueue());
208                        }
209
210                        // add renderables itself
211                        if (mRenderNodesContentForViz)
212                        {
213                                (*it)->_addToRenderQueue(cam, getRenderQueue(), false);
214                        }
215                }
216        }       
217}
218//-----------------------------------------------------------------------
219const Pass *OcclusionCullingSceneManager::_setPass(const Pass* pass, bool evenIfSuppressed)
220{
221        if (mNormalExecution)
222        {
223                return SceneManager::_setPass(pass);
224        }
225
226        // TODO: setting vertex program is not efficient
227        //Pass *usedPass = ((mIsDepthPassPhase && !pass->hasVertexProgram()) ? mDepthPass : pass);
228       
229        // set depth fill pass if we currently do not make an aabb occlusion query
230        const bool useDepthPass =
231                (mIsDepthPassPhase && !mHierarchyInterface->IsBoundingBoxQuery());
232
233        const IlluminationRenderStage savedStage = mIlluminationStage;
234       
235        // set illumination stage to NONE so no shadow material is used
236        // for depth pass or for occlusion query
237        if (mIsDepthPassPhase || mHierarchyInterface->IsBoundingBoxQuery())
238        {
239                mIlluminationStage = IRS_NONE;
240        }
241       
242        // --- set vertex program of current pass in order to set correct depth
243        if (mExecuteVertexProgramForAllPasses &&
244                mIsDepthPassPhase &&
245                pass->hasVertexProgram())
246        {
247                // add vertex program of current pass to depth pass
248                mDepthPass->setVertexProgram(pass->getVertexProgramName());
249
250                if (mDepthPass->hasVertexProgram())
251                {
252                        const GpuProgramPtr& prg = mDepthPass->getVertexProgram();
253                        // Load this program if not done already
254                        if (!prg->isLoaded())
255                                prg->load();
256                        // Copy params
257                        mDepthPass->setVertexProgramParameters(pass->getVertexProgramParameters());
258                }
259        }
260        else if (mDepthPass->hasVertexProgram()) // reset vertex program
261        {
262                mDepthPass->setVertexProgram("");
263        }
264       
265        const Pass *usedPass = useDepthPass ? mDepthPass : pass;
266
267        // save old depth write: needed for item buffer
268        const bool IsDepthWrite = usedPass->getDepthWriteEnabled();
269
270        // global option which enables / disables depth writes
271        if (!mEnableDepthWrite)
272        {
273                //usedPass->setDepthWriteEnabled(false);
274        }
275        //else if (mIsItemBufferPass) {usedPass = mItemBufferPass;}
276       
277
278        //-- set actual pass here
279
280        const Pass *result = SceneManager::_setPass(usedPass);
281
282
283        // reset depth write
284        if (!mEnableDepthWrite)
285        {
286                //usedPass->setDepthWriteEnabled(IsDepthWrite);
287        }
288
289        // reset illumination stage
290        mIlluminationStage = savedStage;
291
292        return result;
293}
294//-----------------------------------------------------------------------
295void OcclusionCullingSceneManager::_findVisibleObjects(Camera* cam,
296                                                                                                                bool onlyShadowCasters)
297{
298        if (mNormalExecution)
299        {
300                OctreeSceneManager::_findVisibleObjects(cam, onlyShadowCasters);
301                return;
302        }
303
304        if (mShowVisualization)
305    {
306                //////////////
307                //-- show visible scene nodes and octree bounding boxes from last frame
308
309                PrepareVisualization(cam);
310        }
311        else
312        {       
313                // for hierarchical culling, we interleave identification
314                // and rendering of objects in _renderVisibibleObjects
315
316                // for the shadow pass we use only standard rendering
317                // because of low occlusion
318                if (mShadowTechnique == SHADOWTYPE_TEXTURE_MODULATIVE &&
319                        mIlluminationStage == IRS_RENDER_TO_TEXTURE)
320                {
321                        OctreeSceneManager::_findVisibleObjects(cam, onlyShadowCasters);
322                }
323
324                // only shadow casters will be rendered in shadow texture pass
325                if (0) mHierarchyInterface->SetOnlyShadowCasters(onlyShadowCasters);
326
327                ///////////
328                //-- apply view cell pvs
329                UpdatePvs(cam);
330        }
331               
332        // lists only used for visualization
333        mVisible.clear();
334        mBoxes.clear();
335}
336//-----------------------------------------------------------------------
337void OcclusionCullingSceneManager::_renderVisibleObjects()
338{
339        if (mNormalExecution)
340        {
341                // the standard octree rendering mode
342                OctreeSceneManager::_renderVisibleObjects();
343                return;
344        }
345
346        InitDepthPass();          // create material for depth pass
347        InitItemBufferPass(); // create material for item buffer pass
348
349        // save ambient light to reset later
350        ColourValue savedAmbient = mAmbientLight;
351
352        ////////////////////
353        //-- apply standard rendering for some modes
354        //-- (e.g., the visualization mode, the shadow pass)
355
356        if (mShowVisualization ||
357           (mShadowTechnique == SHADOWTYPE_TEXTURE_MODULATIVE &&
358            mIlluminationStage == IRS_RENDER_TO_TEXTURE))
359        {       
360                IlluminationRenderStage savedStage = mIlluminationStage;
361       
362                if (mShowVisualization)
363                {
364                        // disable illumination stage to prevent rendering shadows
365                        mIlluminationStage = IRS_NONE;
366                }
367
368                // standard rendering for shadow maps because of performance
369                TerrainSceneManager::_renderVisibleObjects();
370
371                mIlluminationStage = savedStage;
372        }
373        else //-- the hierarchical culling algorithm
374        {
375                // note matt: this is also called in TerrainSceneManager: really necessary?
376                mDestRenderSystem -> setLightingEnabled(false);
377
378                if (mUseItemBuffer)
379                {
380                        // don't render backgrounds for item buffer
381                        clearSpecialCaseRenderQueues();
382                        getRenderQueue()->clear();
383                }
384
385                ////////////////////
386                //-- hierarchical culling
387
388                // the objects of different layers (e.g., background, scene,
389                // overlay) must be identified and rendered one after another
390
391                // first render all early skies
392                clearSpecialCaseRenderQueues();
393                addSpecialCaseRenderQueue(RENDER_QUEUE_BACKGROUND);
394                addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_EARLY);
395                setSpecialCaseRenderQueueMode(SceneManager::SCRQM_INCLUDE);
396
397                TerrainSceneManager::_renderVisibleObjects();
398
399#ifdef GTP_VISIBILITY_MODIFIED_OGRE
400                // delete previously rendered content
401                _deleteRenderedQueueGroups();
402#endif
403
404                ///////////////////
405                //-- prepare queue for visible objects (i.e., all but overlay and skies late)
406
407                clearSpecialCaseRenderQueues();
408                addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_LATE);
409                addSpecialCaseRenderQueue(RENDER_QUEUE_OVERLAY);
410       
411                // exclude this queues from hierarchical rendering
412                setSpecialCaseRenderQueueMode(SceneManager::SCRQM_EXCLUDE);
413
414                // set all necessary parameters for
415                // hierarchical visibility culling and rendering
416                InitVisibilityCulling(mCameraInProgress);
417
418
419                /**
420                * the hierarchical culling algorithm
421                * for depth pass: we just find objects and update depth buffer
422                * for "delayed" rendering: we render some passes afterwards
423                * e.g., transparents, because they need front-to-back sorting
424                **/
425               
426                mVisibilityManager->ApplyVisibilityCulling();
427
428                // delete remaining renderables from queue:
429                // all which are not in mLeavePassesInQueue)
430#ifdef GTP_VISIBILITY_MODIFIED_OGRE
431                _deleteRenderedQueueGroups(mLeavePassesInQueue);
432#endif
433
434                /////////////
435                //-- reset parameters needed for special rendering
436               
437                mIsDepthPassPhase = false;
438                mIsItemBufferPhase = false;
439                mSkipTransparents = false;
440                mIsHierarchicalCulling = false;
441               
442                mLeavePassesInQueue = 0;
443               
444                if (mUseDepthPass) // the shaded geometry is rendered in a second pass
445                {
446                        // add visible nodes found by the visibility culling algorithm
447                        NodeList::const_iterator it, it_end = mVisible.end();
448
449                        //getRenderQueue()->clear();
450                        for (it = mVisible.begin(); it != it_end; ++ it)
451                        {
452                                (*it)->_addToRenderQueue(mCameraInProgress, getRenderQueue(), false);
453                        }
454                }
455
456                /////////////
457                //-- now we can render all remaining queue objects
458                //-- used for depth pass, transparents, overlay
459                clearSpecialCaseRenderQueues();
460
461                TerrainSceneManager::_renderVisibleObjects();
462        } // end hierarchical culling
463               
464        // HACK: set the new render level index, important to avoid cracks
465        // in terrain caused by LOD
466        TerrainRenderable::NextRenderLevelIndex();
467       
468        // reset ambient light
469        setAmbientLight(savedAmbient);
470
471        // almost same effect as below
472        getRenderQueue()->clear(mDeleteQueueAfterRendering);
473
474        if (0)
475        {
476                if (!mDeleteQueueAfterRendering)
477                        getRenderQueue()->clear(true); // finally clear render queue
478                else
479                        OGRE_DELETE(mRenderQueue); // HACK: should rather only be cleared ...
480        }
481
482        if (0) WriteLog(); // write out stats
483}
484
485//-----------------------------------------------------------------------
486void OcclusionCullingSceneManager::_updateSceneGraph(Camera* cam)
487{
488        if (mNormalExecution)
489        {
490                OctreeSceneManager::_updateSceneGraph(cam);
491                return;
492        }
493
494        mVisibilityManager->GetCullingManager()->SetHierarchyInterface(mHierarchyInterface);
495        mHierarchyInterface->SetRenderSystem(mDestRenderSystem);
496
497        TerrainSceneManager::_updateSceneGraph(cam);
498}
499//-----------------------------------------------------------------------
500bool OcclusionCullingSceneManager::setOption(const String & key, const void * val)
501{
502        if (key == "UseDepthPass")
503        {
504                mUseDepthPass = (*static_cast<const bool *>(val));
505                return true;
506        }
507        if (key == "PrepareVisualization")
508        {
509                mShowVisualization = (*static_cast<const bool *>(val));
510                return true;
511        }
512        if (key == "RenderNodesForViz")
513        {
514                mRenderNodesForViz = (*static_cast<const bool *>(val));
515                return true;
516        }
517        if (key == "RenderNodesContentForViz")
518        {
519                mRenderNodesContentForViz = (*static_cast<const bool *>(val));
520                return true;
521        }
522        if (key == "SkyBoxEnabled")
523        {
524                mSkyBoxEnabled = (*static_cast<const bool *>(val));
525                return true;
526        }
527        if (key == "SkyPlaneEnabled")
528        {
529                mSkyPlaneEnabled = (*static_cast<const bool *>(val));
530                return true;
531        }
532        if (key == "SkyDomeEnabled")
533        {
534                mSkyDomeEnabled = (*static_cast<const bool *>(val));
535                return true;
536        }
537        if (key == "VisualizeCulledNodes")
538        {
539                mVisualizeCulledNodes = (*static_cast<const bool *>(val));
540                return true;
541        }
542        if (key == "DelayRenderTransparents")
543        {
544                mDelayRenderTransparents = (*static_cast<const bool *>(val));
545                return true;
546        }
547        if (key == "DepthWrite")
548        {
549                mEnableDepthWrite = (*static_cast<const bool *>(val));
550                return true;
551        }
552        if (key == "UseItemBuffer")
553        {
554                mUseItemBuffer = (*static_cast<const bool *>(val));
555                return true;
556        }
557        if (key == "ExecuteVertexProgramForAllPasses")
558        {
559                mExecuteVertexProgramForAllPasses  = (*static_cast<const bool *>(val));
560                return true;
561        }
562        if (key == "RenderTransparentsForItemBuffer")
563        {
564                mRenderTransparentsForItemBuffer  = (*static_cast<const bool *>(val));
565                return true;
566        }
567        else if (key == "DeleteRenderQueue")
568        {
569                mDeleteQueueAfterRendering = (*static_cast<const bool *>(val));
570                return true;
571        }
572        if (key == "NodeVizScale")
573        {
574                OctreeNode::setVizScale(*static_cast<const float *>(val));
575                return true;
576        }
577        if (key == "LoadViewCells")
578        {
579                if (!mViewCellsLoaded)
580                {
581                        String filename(static_cast<const char *>(val));
582                        mViewCellsLoaded = LoadViewCells(filename);     
583                }
584
585                return mViewCellsLoaded;
586        }
587        if (key == "UseViewCells")
588        {
589                if (mViewCellsLoaded)
590                {
591                        mUseViewCells = *static_cast<const bool *>(val);
592
593                        // reset view cell
594                        OGRE_DELETE(mCurrentViewCell);
595                       
596                        if (mUseViewCells)
597                        {
598                                mCurrentViewCell = mViewCellsManager->GenerateViewCell();
599                        }
600
601                        mElementaryViewCell = NULL;
602
603                        // if we use view cells, all objects are set to false initially
604                        SetObjectsVisible(!mUseViewCells);
605                }
606
607                return true;
608        }
609        if (key == "NormalExecution")
610        {
611                mNormalExecution = *static_cast<const bool *>(val);
612                return true;
613        }
614        if (key == "UseVisibilityFilter")
615        {
616                mUseVisibilityFilter = *static_cast<const bool *>(val);
617                // set null =>recomputation of the pvs
618        mElementaryViewCell = NULL;
619                return true;
620        }
621
622        return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
623                setOption(key, val) || TerrainSceneManager::setOption(key, val);
624}
625//-----------------------------------------------------------------------
626bool OcclusionCullingSceneManager::getOption(const String & key, void *val)
627{
628        if (key == "NumHierarchyNodes")
629        {
630                * static_cast<unsigned int *>(val) = (unsigned int)mNumOctants;
631                return true;
632        }
633        if (key == "VisibilityManager")
634        {
635                * static_cast<GtpVisibility::VisibilityManager **>(val) =
636                        (GtpVisibility::VisibilityManager *)mVisibilityManager;
637                return true;
638        }
639        if (key == "HierarchInterface")
640        {
641                * static_cast<GtpVisibility::HierarchyInterface **>(val) =
642                        (GtpVisibility::HierarchyInterface *)mHierarchyInterface;
643                return true;
644        }
645
646        return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
647                getOption(key, val) && TerrainSceneManager::getOption(key, val);
648}
649//-----------------------------------------------------------------------
650bool OcclusionCullingSceneManager::getOptionValues(const String & key,
651                                                                                                        StringVector &refValueList)
652{
653        return TerrainSceneManager::getOptionValues( key, refValueList);
654}
655//-----------------------------------------------------------------------
656bool OcclusionCullingSceneManager::getOptionKeys(StringVector & refKeys)
657{
658        return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
659                getOptionKeys(refKeys) || TerrainSceneManager::getOptionKeys(refKeys);
660}
661//-----------------------------------------------------------------------
662void OcclusionCullingSceneManager::setVisibilityManager(GtpVisibility::
663                                                                                                                 VisibilityManager *visManager)
664{
665        mVisibilityManager = visManager;
666}
667//-----------------------------------------------------------------------
668GtpVisibility::VisibilityManager *OcclusionCullingSceneManager::getVisibilityManager( void )
669{
670        return mVisibilityManager;
671}
672//-----------------------------------------------------------------------
673void OcclusionCullingSceneManager::WriteLog()
674{
675        std::stringstream d;
676
677        d << "Depth pass: " << StringConverter::toString(mUseDepthPass) << ", "
678          << "Delay transparents: " << StringConverter::toString(mDelayRenderTransparents) << ", "
679          << "Use optimization: " << StringConverter::toString(mHierarchyInterface->GetTestGeometryForVisibleLeaves()) << ", "
680          << "Algorithm type: " << mVisibilityManager->GetCullingManagerType() << ", "
681          << "Hierarchy nodes: " << mNumOctants << ", "
682          << "Traversed nodes: " << mHierarchyInterface->GetNumTraversedNodes() << ", "
683          << "Rendered nodes: " << mHierarchyInterface->GetNumRenderedNodes() << ", "
684          << "Query culled nodes: " << mVisibilityManager->GetCullingManager()->GetNumQueryCulledNodes() << ", "
685          << "Frustum culled nodes: " << mVisibilityManager->GetCullingManager()->GetNumFrustumCulledNodes() << ", "
686      << "Queries issued: " << mVisibilityManager->GetCullingManager()->GetNumQueriesIssued() << ", "
687          << "Found objects: " << (int)mVisible.size() << "\n";
688
689        LogManager::getSingleton().logMessage(d.str());
690}
691//-----------------------------------------------------------------------
692void OcclusionCullingSceneManager::renderBasicQueueGroupObjects(RenderQueueGroup* pGroup,
693                                                                                                                                QueuedRenderableCollection::OrganisationMode om)
694{
695    // Basic render loop
696    // Iterate through priorities
697    RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
698
699    while (groupIt.hasMoreElements())
700    {
701        RenderPriorityGroup* pPriorityGrp = groupIt.getNext();
702
703        // Sort the queue first
704        pPriorityGrp->sort(mCameraInProgress);
705
706        // Do solids
707        renderObjects(pPriorityGrp->getSolidsBasic(), om, true);
708
709                // for correct rendering, transparents must be rendered
710                // after hierarchical culling => don't render them now
711
712        if (mNormalExecution || !mSkipTransparents)
713                {
714                        // Do transparents (always descending)
715                        renderObjects(pPriorityGrp->getTransparents(),
716                        QueuedRenderableCollection::OM_SORT_DESCENDING, true);
717                }
718
719
720    } // for each priority
721}
722
723//-----------------------------------------------------------------------
724bool OcclusionCullingSceneManager::validatePassForRendering(Pass* pass)
725{
726        if (mNormalExecution)
727        {
728                return SceneManager::validatePassForRendering(pass);
729        }
730
731        // skip all but first pass if we are doing the depth pass
732        if ((mIsDepthPassPhase || mIsItemBufferPhase) && (pass->getIndex() > 0))
733        {
734                return false;
735        }
736        // all but first pass
737        /*else if ((!mIsDepthPassPhase || mIsItemBufferPhase) && (pass->getIndex() != 0))
738        {
739                return false;
740        }*/
741
742        return SceneManager::validatePassForRendering(pass);
743}
744//-----------------------------------------------------------------------
745void OcclusionCullingSceneManager::_renderQueueGroupObjects(RenderQueueGroup* pGroup,
746                                                                                                                        QueuedRenderableCollection::OrganisationMode om)
747{
748        if (mNormalExecution || !mIsItemBufferPhase)
749        {
750                TerrainSceneManager::_renderQueueGroupObjects(pGroup, om);
751                return;
752        }
753#ifdef  ITEM_BUFFER
754        //-- item buffer
755        //-- item buffer: render objects using false colors
756
757    // Iterate through priorities
758    RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
759
760        while (groupIt.hasMoreElements())
761    {
762                RenderItemBuffer(groupIt.getNext());
763        }
764#endif // ITEM_BUFFER
765}
766#ifdef ITEM_BUFFER
767//-----------------------------------------------------------------------
768void OcclusionCullingSceneManager::RenderItemBuffer(RenderPriorityGroup* pGroup)
769{
770        // Do solids
771        QueuedRenderableCollection solidObjs = pGroup->getSolidsBasic();//msz
772
773        // ----- SOLIDS LOOP -----
774        RenderPriorityGroup::SolidRenderablePassMap::const_iterator ipass, ipassend;
775        ipassend = solidObjs.end();
776
777        for (ipass = solidObjs.begin(); ipass != ipassend; ++ipass)
778        {
779                // Fast bypass if this group is now empty
780                if (ipass->second->empty())
781                        continue;
782
783                // Render only first pass of renderable as false color
784                if (ipass->first->getIndex() > 0)
785                        continue;
786
787                RenderPriorityGroup::RenderableList* rendList = ipass->second;
788               
789                RenderPriorityGroup::RenderableList::const_iterator irend, irendend;
790                irendend = rendList->end();
791                       
792                for (irend = rendList->begin(); irend != irendend; ++irend)
793                {
794                        if (0)
795                        {
796                                std::stringstream d; d << "itembuffer, pass name: " <<
797                                        ipass->first->getParent()->getParent()->getName();
798
799                                LogManager::getSingleton().logMessage(d.str());
800                        }
801                       
802                        RenderSingleObjectForItemBuffer(*irend, ipass->first);
803                }
804        }
805
806        //-- TRANSPARENT LOOP: must be handled differently from solids
807
808        // transparents are treated either as solids or completely discarded
809        if (mRenderTransparentsForItemBuffer)
810        {
811                QueuedRenderableCollection transpObjs = pGroup->getTransparents(); //msz
812                RenderPriorityGroup::TransparentRenderablePassList::const_iterator
813                        itrans, itransend;
814
815                itransend = transpObjs.end();
816                for (itrans = transpObjs.begin(); itrans != itransend; ++itrans)
817                {
818                        // like for solids, render only first pass
819                        if (itrans->pass->getIndex() == 0)
820                        {       
821                                RenderSingleObjectForItemBuffer(itrans->renderable, itrans->pass);
822                        }
823                }
824        }
825}
826//-----------------------------------------------------------------------
827void OcclusionCullingSceneManager::RenderSingleObjectForItemBuffer(Renderable *rend, Pass *pass)
828{
829        static LightList nullLightList;
830       
831        int col[4];
832       
833        // -- create color code out of object id
834        col[0] = (rend->getId() >> 16) & 255;
835        col[1] = (rend->getId() >> 8) & 255;
836        col[2] = rend->getId() & 255;
837//      col[3] = 255;
838
839        //mDestRenderSystem->setColour(col[0], col[1], col[2], col[3]);
840   
841        mItemBufferPass->setAmbient(ColourValue(col[0] / 255.0f,
842                                                                                    col[1] / 255.0f,
843                                                                                        col[2] / 255.0f, 1));
844
845        // set vertex program of current pass
846        if (mExecuteVertexProgramForAllPasses && pass->hasVertexProgram())
847        {
848                mItemBufferPass->setVertexProgram(pass->getVertexProgramName());
849
850                if (mItemBufferPass->hasVertexProgram())
851                {
852                        const GpuProgramPtr& prg = mItemBufferPass->getVertexProgram();
853                        // Load this program if not done already
854                        if (!prg->isLoaded())
855                                prg->load();
856                        // Copy params
857                        mItemBufferPass->setVertexProgramParameters(pass->getVertexProgramParameters());
858                }
859        }
860        else if (mItemBufferPass->hasVertexProgram())
861        {
862                mItemBufferPass->setVertexProgram("");
863        }
864
865        const Pass *usedPass = _setPass(mItemBufferPass);
866
867
868        // render a single object, this will set up auto params if required
869        renderSingleObject(rend, usedPass, false, &nullLightList);
870}
871#endif // ITEM_BUFFER
872//-----------------------------------------------------------------------
873GtpVisibility::VisibilityManager *OcclusionCullingSceneManager::GetVisibilityManager()
874{
875        return mVisibilityManager;
876}
877//-----------------------------------------------------------------------
878void OcclusionCullingSceneManager::InitVisibilityCulling(Camera *cam)
879{
880        // reset culling manager stats
881        mVisibilityManager->GetCullingManager()->InitFrame(mVisualizeCulledNodes);
882
883        // set depth pass flag before rendering
884        mIsDepthPassPhase = mUseDepthPass;
885
886        mIsHierarchicalCulling = true; // during hierarchical culling
887
888        // item buffer needs full ambient lighting to use item colors as unique id
889        if (mUseItemBuffer)
890        {
891                mIsItemBufferPhase = true;
892                setAmbientLight(ColourValue(1,1,1,1));
893        }
894
895
896        // set passes which are stored in render queue
897        // for rendering AFTER hierarchical culling, i.e., passes which need
898        // a special rendering order
899       
900        mLeavePassesInQueue = 0;
901
902        // if we have the depth pass or use an item buffer, no passes are left in the queue
903        if (1 && !mUseDepthPass && !mUseItemBuffer)
904        {
905                if (mShadowTechnique == SHADOWTYPE_STENCIL_ADDITIVE)
906                {
907                        // TODO: remove this pass because it should be processed during hierarchical culling
908                        //mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_NOSHADOW;
909
910                        mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_DECAL;
911                        mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_DIFFUSE_SPECULAR;
912                        mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
913
914                        // just render ambient passes
915                        /*** msz: no more IRS_AMBIENT, see OgreSceneManager.h ***/
916                        // mIlluminationStage = IRS_AMBIENT;
917                        //getRenderQueue()->setSplitPassesByLightingType(true);
918                }
919       
920                if (mShadowTechnique == SHADOWTYPE_STENCIL_MODULATIVE)
921                {
922                        mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_NOSHADOW;
923                        mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
924                }
925       
926                // transparents should be rendered after hierarchical culling to
927                // provide front-to-back ordering
928                if (mDelayRenderTransparents)
929                {
930                        mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
931                }
932        }
933
934        // skip rendering transparents during the hierarchical culling
935        // (because they will be rendered afterwards)
936        mSkipTransparents =
937                (mIsDepthPassPhase || (mLeavePassesInQueue & RenderPriorityGroup::TRANSPARENT_PASSES));
938
939        // -- initialise interface for rendering traversal of the hierarchy
940        mHierarchyInterface->SetHierarchyRoot(mOctree);
941       
942        // possible two cameras (one for culling, one for rendering)
943        mHierarchyInterface->InitTraversal(mCameraInProgress,
944                                                                           mCullCamera ? getCamera("CullCamera") : NULL,
945                                                                           mLeavePassesInQueue);
946               
947}
948//-----------------------------------------------------------------------
949OctreeHierarchyInterface *OcclusionCullingSceneManager::GetHierarchyInterface()
950{
951        return mHierarchyInterface;
952}
953//-----------------------------------------------------------------------
954void OcclusionCullingSceneManager::endFrame()
955{
956        TerrainRenderable::ResetRenderLevelIndex();
957}
958//-----------------------------------------------------------------------
959Entity* OcclusionCullingSceneManager::createEntity(const String& entityName,
960                                                                                                        const String& meshName)
961{
962        Entity *ent = SceneManager::createEntity(entityName, meshName);
963
964        for (int i = 0; i < (int)ent->getNumSubEntities(); ++i)
965        {
966                ent->getSubEntity(i)->setId(mCurrentEntityId);
967        }
968
969        // increase counter of entity id values
970        ++ mCurrentEntityId;
971
972        return ent;
973}
974//-----------------------------------------------------------------------
975void OcclusionCullingSceneManager::renderAdditiveStencilShadowedQueueGroupObjects(
976        RenderQueueGroup* pGroup, QueuedRenderableCollection::OrganisationMode om)
977{
978        // only render solid passes during hierarchical culling
979        if (mIsHierarchicalCulling)
980        {
981                RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
982            LightList lightList;
983
984                while (groupIt.hasMoreElements())
985                {
986                        RenderPriorityGroup* pPriorityGrp = groupIt.getNext();
987
988                        // Sort the queue first
989                        pPriorityGrp->sort(mCameraInProgress);
990
991                        // Clear light list
992                        lightList.clear();
993
994                        // Render all the ambient passes first, no light iteration, no lights
995                        /*** msz: no more IRS_AMBIENT, see OgreSceneManager.h ***/
996                        // mIlluminationStage = IRS_AMBIENT;
997
998                        OctreeSceneManager::renderObjects(pPriorityGrp->getSolidsBasic(), om, false, &lightList);
999                        // Also render any objects which have receive shadows disabled
1000                        OctreeSceneManager::renderObjects(pPriorityGrp->getSolidsNoShadowReceive(), om, true);
1001#if 0           
1002                        std::stringstream d;
1003                        d << " solid size: " << (int)pPriorityGrp->_getSolidPasses().size()
1004                                << " solid no shadow size: " << (int)pPriorityGrp->_getSolidPassesNoShadow().size()
1005                                << "difspec size: " << (int)pPriorityGrp->_getSolidPassesDiffuseSpecular().size()
1006                                << " decal size: " << (int)pPriorityGrp->_getSolidPassesDecal().size();
1007                        LogManager::getSingleton().logMessage(d.str());
1008#endif
1009                }
1010        }
1011        else // render the rest of the passes
1012        {
1013                OctreeSceneManager::renderAdditiveStencilShadowedQueueGroupObjects(pGroup, om);
1014        }
1015}
1016//-----------------------------------------------------------------------
1017void OcclusionCullingSceneManager::renderModulativeStencilShadowedQueueGroupObjects(
1018        RenderQueueGroup* pGroup, QueuedRenderableCollection::OrganisationMode om)
1019{
1020   if (mIsHierarchicalCulling)
1021   {
1022           // Iterate through priorities
1023           RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
1024
1025           while (groupIt.hasMoreElements())
1026           {
1027                   RenderPriorityGroup* pPriorityGrp = groupIt.getNext();
1028
1029                   // Sort the queue first
1030                   pPriorityGrp->sort(mCameraInProgress);
1031
1032                   // Do (shadowable) solids
1033                   OctreeSceneManager::renderObjects(pPriorityGrp->getSolidsBasic(), om, true);
1034           }
1035   }
1036   else
1037   {
1038           OctreeSceneManager::renderModulativeStencilShadowedQueueGroupObjects(pGroup, om);
1039   }
1040}
1041//-------------------------------------------------------------------------
1042void OcclusionCullingSceneManager::SetObjectsVisible(const bool visible)
1043{
1044        GtpVisibilityPreprocessor::ObjectContainer::iterator it, it_end = mObjects.end();
1045
1046        for (it = mObjects.begin(); it != it_end; ++ it)
1047        {
1048                OgreMeshInstance *omi = static_cast<OgreMeshInstance *>(*it);
1049                Entity *ent = omi->GetEntity();
1050               
1051                ent->setVisible(visible);
1052        }
1053}
1054//-----------------------------------------------------------------------
1055bool OcclusionCullingSceneManager::LoadViewCells(const String &filename)
1056{
1057        // objects are set to invisible initially
1058        SetObjectsVisible(false);
1059       
1060        // converter between view cell ids and Ogre entites
1061        GtpVisibilityPreprocessor::IndexedBoundingBoxContainer iboxes;
1062        OctreeBoundingBoxConverter bconverter(this);
1063
1064        // load the view cells assigning the found objects to the pvss
1065        const bool finalizeViewCells = true;
1066        mViewCellsManager =
1067                GtpVisibilityPreprocessor::ViewCellsManager::LoadViewCells(filename, &mObjects, true, &bconverter);
1068
1069        if (finalizeViewCells)
1070        {
1071                CreateViewCellsGeometry();
1072        }
1073
1074        return (mViewCellsManager != NULL);
1075}
1076//-------------------------------------------------------------------------
1077void OcclusionCullingSceneManager::ApplyViewCellPvs(GtpVisibilityPreprocessor::ViewCell *vc,
1078                                                                                                        const bool load)
1079{       // NOTE: should not encounter NULL view cell,
1080        // rather apply view cell representing unbounded space then
1081        if (!vc)
1082        {       
1083                // if no there is no view cell, set everything visible
1084                SetObjectsVisible(true);
1085                return;
1086        }
1087               
1088        GtpVisibilityPreprocessor::ObjectPvsMap::const_iterator oit,
1089                        oit_end = vc->GetPvs().mEntries.end();
1090
1091        ////////////
1092        //-- set PVS of view cell to visible
1093
1094        for (oit = vc->GetPvs().mEntries.begin(); oit != oit_end; ++ oit)
1095        {
1096                if (!(*oit).first) continue;
1097
1098                OgreMeshInstance *omi = dynamic_cast<OgreMeshInstance *>((*oit).first);
1099                omi->GetEntity()->setVisible(load);
1100                //GtpVisibilityPreprocessor::Debug << "assigned id " << omi->GetId() << endl;
1101        }
1102}
1103//-------------------------------------------------------------------------
1104void OcclusionCullingSceneManager::UpdatePvs(Camera *cam)
1105{
1106        if (!(mViewCellsLoaded && mUseViewCells))
1107                return;
1108
1109        const GtpVisibilityPreprocessor::Vector3 viewPoint =
1110                OgreTypeConverter::ConvertFromOgre(cam->getDerivedPosition());
1111
1112        GtpVisibilityPreprocessor::ViewCell *newElementary =
1113                mViewCellsManager->GetViewCell(viewPoint);
1114
1115        // elementary view cell did not change => apply same pvs
1116        if (mElementaryViewCell == newElementary)
1117                return;
1118
1119        mElementaryViewCell = newElementary;
1120        LogManager::getSingleton().logMessage("unloading");
1121       
1122                std::stringstream d;
1123                d << "here2 " << mViewCellsGeometry.size();
1124                LogManager::getSingleton().logMessage(d.str());
1125
1126        //////////////
1127        //-- unload old pvs
1128
1129        ApplyViewCellPvs(mCurrentViewCell, false);
1130
1131        // set old view cell geometry to invisible
1132    if (mCurrentViewCell && mCurrentViewCell->GetMesh())
1133        {
1134                const int id = mCurrentViewCell->GetId();
1135               
1136                std::stringstream str;
1137                str << "id : " << id << " of " << mViewCellsGeometry.size();
1138                LogManager::getSingleton().logMessage(str.str());
1139
1140                mViewCellsGeometry[id]->setVisible(false);
1141        }
1142
1143        // the new view cell
1144        GtpVisibilityPreprocessor::ViewCell *viewCell;
1145               
1146        if (mUseVisibilityFilter)
1147        {       
1148                ////////////
1149                //-- compute new filtered cell
1150
1151                GtpVisibilityPreprocessor::PrVs prvs;
1152                mViewCellsManager->GetPrVS(viewPoint, prvs, 5);
1153                viewCell = prvs.mViewCell;
1154        }
1155        else
1156        {
1157                viewCell = newElementary;LogManager::getSingleton().logMessage("here55");
1158        }
1159
1160        ///////////////
1161        //-- load new pvs
1162
1163        // set new view cell geometry to invisible
1164        if (viewCell && viewCell->GetMesh())
1165        {
1166                const int id = viewCell->GetId();
1167               
1168                std::stringstream str;
1169                str << "id : " << id << " of " << mViewCellsGeometry.size();
1170                LogManager::getSingleton().logMessage(str.str());
1171
1172                mViewCellsGeometry[id]->setVisible(false);
1173        }
1174
1175        ApplyViewCellPvs(viewCell, true);
1176
1177        // store pvs
1178        if (viewCell)
1179        {
1180                mCurrentViewCell->SetPvs(viewCell->GetPvs());
1181                mCurrentViewCell->SetMesh(viewCell->GetMesh());
1182                mCurrentViewCell->SetId(viewCell->GetId());
1183
1184                // delete merge tree of filtered view cell
1185                if (mUseVisibilityFilter)
1186                        mViewCellsManager->DeleteLocalMergeTree(viewCell);
1187        }
1188}
1189//-------------------------------------------------------------------------
1190void OcclusionCullingSceneManager::CreateViewCellsGeometry()
1191{
1192        LogManager::getSingleton().logMessage("creating view cells geometry");
1193
1194        GtpVisibilityPreprocessor::ViewCellContainer viewCells = mViewCellsManager->GetViewCells();
1195
1196        GtpVisibilityPreprocessor::ViewCellContainer::const_iterator it, it_end = viewCells.end();
1197        for (it = viewCells.begin(); it != it_end; ++ it)
1198        {
1199                GtpVisibilityPreprocessor::ViewCell *viewCell = *it;
1200
1201                std::stringstream str;
1202                str << "id : " << viewCell->GetId();
1203
1204                ManualObject *manual = OgreTypeConverter::ConvertToOgre(viewCell->GetMesh(), this);
1205                mViewCellsGeometry[viewCell->GetId()] = manual;
1206
1207                // attach to scene node
1208                getRootSceneNode()->createChildSceneNode()->attachObject(manual);
1209               
1210                // initialy set to invisible
1211                manual->setVisible(false);
1212        }
1213}
1214
1215#if 0
1216//-------------------------------------------------------------------------
1217void OcclusionCullingSceneManager::TestVisible(SceneNode *node)
1218{
1219        // first test for scene node, then for octant (part of the hierarchy)
1220        if (!node->mVisibleChildren)
1221                node->setVisible(false);
1222
1223        node->getOctant()->mVisibleChildren --;
1224}
1225//-------------------------------------------------------------------------
1226void OcclusionCullingSceneManager::TestVisible(Octree *octant)
1227{
1228        // first test for scene node, then for octant (part of the hierarchy)
1229        if (!octant->mVisibleChildren)
1230        {
1231                octant->setVisible(false);
1232        }
1233}
1234
1235//-------------------------------------------------------------------------
1236void OcclusionCullingSceneManager::UpdateVisibility(Entity *ent)
1237{
1238        if (!ent->isVisible())
1239        {
1240                bool visible = TestVisible(ent->getParentNode());
1241               
1242                if (!visible)
1243                        visible = TestVisible(octant->getParentNode());
1244
1245                if (!visible)
1246                        mHierarchyInterface->pullupVisibility();
1247        }
1248}
1249#endif
1250//-----------------------------------------------------------------------
1251const String OcclusionCullingSceneManagerFactory::FACTORY_TYPE_NAME = "OcclusionCullingSceneManager";
1252//-----------------------------------------------------------------------
1253void OcclusionCullingSceneManagerFactory::initMetaData(void) const
1254{
1255        mMetaData.typeName = FACTORY_TYPE_NAME;
1256        mMetaData.description = "Scene manager organising the scene on the basis of an octree with advanced occlusion culling (TM).";
1257        mMetaData.sceneTypeMask = 0xFFFF; // support all types
1258        mMetaData.worldGeometrySupported = false;
1259}
1260//-----------------------------------------------------------------------
1261SceneManager *OcclusionCullingSceneManagerFactory::createInstance(
1262                const String& instanceName)
1263{
1264        OcclusionCullingSceneManager* tsm = new OcclusionCullingSceneManager(instanceName, visManager);
1265       
1266        // Create & register default sources (one per manager)
1267        HeightmapTerrainPageSource* ps = new HeightmapTerrainPageSource();
1268        mTerrainPageSources.push_back(ps);
1269        tsm->registerPageSource("Heightmap", ps);
1270
1271        return tsm;
1272}
1273//-----------------------------------------------------------------------
1274void OcclusionCullingSceneManagerFactory::destroyInstance(SceneManager* instance)
1275{
1276        delete instance;
1277}
1278
1279} // namespace Ogre
Note: See TracBrowser for help on using the repository browser.