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

Revision 1597, 39.0 KB checked in by mattausch, 18 years ago (diff)

added demo hack

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