Index: trunk/VUT/work/ogre_changes/OgreMain/include/OgreHardwareOcclusionQuery.h
===================================================================
--- trunk/VUT/work/ogre_changes/OgreMain/include/OgreHardwareOcclusionQuery.h	(revision 92)
+++ trunk/VUT/work/ogre_changes/OgreMain/include/OgreHardwareOcclusionQuery.h	(revision 115)
@@ -96,32 +96,10 @@
       * Pulls the hardware occlusion query too see if there is a result.
       * @retval NumOfFragments will get the resulting number of fragments.
-	  * @param waitForResult if true, the query will wait until a result is available
-      * @return True if success or false if not.
-	  * @Remarks Hardware occlusion is an assyncronius process the result may take a frame or so.
-	  *			one idea is to test pass1 and if not visible skip pass2. Also note that objects
-	  *			not visible must be tested evrey frame. Visable objects don't need testing every frame.
-	  *			Testing non visable objects can be don unlit, no texture with low LOD object.
-	  *        0 will generate all the levels till 1x1. [default: 0]
-      */
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
-	  virtual bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult ) = 0;
-#else
-	 virtual bool pullOcclusionQuery( unsigned int* NumOfFragments ) = 0;
-#endif
-	/**
-      * Pulls the hardware occlusion query too see if there is a result.
-      * @retval NumOfFragments will get the resulting number of fragments.
-	  * @param waitForResult if true, the query will wait until a result is available
       * @return True if success or false if not.
 	  * @Remarks In DX9 mode specifying OCCLUSIONQUERY_FLUSH as the flag, will case the driver to flush whatever API calls are batched.
 	  * In OpenGL mode it makes no difference if you specify OCCLUSIONQUERY_FLUSH or OCCLUSIONQUERY_NOFLUSH.
       */
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
-	virtual bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult,
-									 const HW_OCCLUSIONQUERY flag  ) = 0; 
-#else
-	  virtual bool pullOcclusionQuery( unsigned int* NumOfFragments, 
-									   const HW_OCCLUSIONQUERY flag  ) = 0; 
-#endif
+	virtual bool pullOcclusionQuery(unsigned int* NumOfFragments, const HW_OCCLUSIONQUERY flag = HWOCCLUSIONQUERY_FLUSH) = 0;
+
 	/**
 	  * Let's you get the last pixel count with out doing the hardware occlusion test
@@ -143,4 +121,19 @@
 	virtual void	setSkipRate( int skip ) = 0;
 	virtual int		getSkipRate() = 0;
+
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	/**
+		Pulls occlusion query.
+		@param NumOfFragments number of visible fragments if query result was available.
+		Last query result if query result was not yet available.
+
+		@param waitForResult if true, the function waits until the result is available.
+		Otherwise the function returns immediately, not waiting for the result.
+		@returns true if query result was available, false if result was not yet available
+	*/
+	virtual bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, 
+		const HW_OCCLUSIONQUERY flag = HWOCCLUSIONQUERY_FLUSH ) = 0; 
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
+
 //----------------------------------------------------------------------
 // Private members
Index: trunk/VUT/work/ogre_changes/OgreMain/include/OgreRenderQueueSortingGrouping.h
===================================================================
--- trunk/VUT/work/ogre_changes/OgreMain/include/OgreRenderQueueSortingGrouping.h	(revision 115)
+++ trunk/VUT/work/ogre_changes/OgreMain/include/OgreRenderQueueSortingGrouping.h	(revision 115)
@@ -0,0 +1,373 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2005 The OGRE Team
+Also see acknowledgements in Readme.html
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+#ifndef __RenderQueueSortingGrouping_H__
+#define __RenderQueueSortingGrouping_H__
+
+// Precompiler options
+#include "OgrePrerequisites.h"
+#include "OgreIteratorWrappers.h"
+#include "OgreMaterial.h"
+#include "OgreTechnique.h"
+#include "OgrePass.h"
+#include "OgreMaterialManager.h"
+
+namespace Ogre {
+
+    /** Renderables in the queue grouped by priority.
+    @remarks
+        This class simply groups renderables for rendering. All the 
+        renderables contained in this class are destined for the same
+        RenderQueueGroup (coarse groupings like those between the main
+        scene and overlays) and have the same priority (fine groupings
+        for detailed overlap control).
+    @par
+        This class optimises the grouped renderables by sorting them by
+        material to reduce render state changes, and outsorts transparent
+        objects.
+    */
+    class RenderPriorityGroup
+    {
+        /** Internal struct reflecting a single Pass for a Renderable. 
+        This is used to sort transparent objects.
+        */
+        struct RenderablePass
+        {
+            /// Pointer to the Renderable details
+            Renderable* renderable;
+            /// Pointer to the Pass
+            Pass* pass;
+
+            RenderablePass(Renderable* rend, Pass* p) :renderable(rend), pass(p) {}
+        };
+
+        /// Comparator to order non-transparent object passes
+        struct SolidQueueItemLess
+        {
+            bool _OgreExport operator()(const Pass* a, const Pass* b) const
+            {
+                // Sort by passHash, which is pass, then texture unit changes
+                unsigned long hasha = a->getHash();
+                unsigned long hashb = b->getHash();
+                if (hasha == hashb)
+                {
+                    // Must differentiate by pointer incase 2 passes end up with the same hash
+                    return a < b;
+                }
+                else
+                {
+                    return hasha < hashb;
+                }
+            }
+        };
+        /// Comparator to order transparent object passes
+        struct TransparentQueueItemLess
+        {
+            const Camera* camera;
+            bool _OgreExport operator()(const RenderablePass& a, const RenderablePass& b) const
+            {
+                if (a.renderable == b.renderable)
+                {
+                    // Same renderable, sort by pass hash
+                    return a.pass->getHash() < b.pass->getHash();
+                }
+                else
+                {
+                    // Different renderables, sort by depth
+                    Real adepth = a.renderable->getSquaredViewDepth(camera);
+                    Real bdepth = b.renderable->getSquaredViewDepth(camera);
+				    if (adepth == bdepth)
+				    {
+                        // Must return deterministic result, doesn't matter what
+                        return a.pass < b.pass;
+				    }
+				    else
+				    {
+				        // Sort DESCENDING by depth (ie far objects first)
+					    return (adepth > bdepth);
+				    }
+                }
+
+            }
+        };
+    public:
+        /** Vector of RenderablePass objects, this is built on the assumption that
+         vectors only ever increase in size, so even if we do clear() the memory stays
+         allocated, ie fast */
+        typedef std::vector<RenderablePass> TransparentRenderablePassList;
+        typedef std::vector<Renderable*> RenderableList;
+        /** Map of pass to renderable lists, used for solid objects since ordering within objects not
+        important. */
+        typedef std::map<Pass*, RenderableList*, SolidQueueItemLess> SolidRenderablePassMap;
+    protected:
+        /// Parent queue group
+        RenderQueueGroup* mParent;
+        bool mSplitPassesByLightingType;
+        bool mSplitNoShadowPasses;
+        /// Solid pass list, used when no shadows, modulative shadows, or ambient passes for additive
+        SolidRenderablePassMap mSolidPasses;
+        /// Solid per-light pass list, used with additive shadows
+        SolidRenderablePassMap mSolidPassesDiffuseSpecular;
+        /// Solid decal (texture) pass list, used with additive shadows
+        SolidRenderablePassMap mSolidPassesDecal;
+        /// Solid pass list, used when shadows are enabled but shadow receive is turned off for these passes
+        SolidRenderablePassMap mSolidPassesNoShadow;
+
+		/// Transparent list
+		TransparentRenderablePassList mTransparentPasses;
+
+        /// Totally empties and destroys a solid pass map
+        void destroySolidPassMap(SolidRenderablePassMap& passmap);
+
+        /// remove a pass entry from all solid pass maps
+        void removeSolidPassEntry(Pass* p);
+
+        /// Clear a solid pass map at the end of a frame
+        void clearSolidPassMap(SolidRenderablePassMap& passmap);
+        /// Internal method for adding a solid renderable
+        void addSolidRenderable(Technique* pTech, Renderable* rend, bool toNoShadowMap);
+        /// Internal method for adding a solid renderable
+        void addSolidRenderableSplitByLightType(Technique* pTech, Renderable* rend);
+        /// Internal method for adding a transparent renderable
+        void addTransparentRenderable(Technique* pTech, Renderable* rend);
+
+    public:
+        RenderPriorityGroup(RenderQueueGroup* parent, 
+            bool splitPassesByLightingType, bool splitNoShadowPasses) 
+            :mParent(parent), mSplitPassesByLightingType(splitPassesByLightingType),
+            mSplitNoShadowPasses(splitNoShadowPasses) { }
+
+        ~RenderPriorityGroup() {
+            // destroy all the pass map entries
+            destroySolidPassMap(mSolidPasses);
+            destroySolidPassMap(mSolidPassesDecal);
+            destroySolidPassMap(mSolidPassesDiffuseSpecular);
+            destroySolidPassMap(mSolidPassesNoShadow);
+            mTransparentPasses.clear();
+
+        }
+
+        /** Get the collection of solid passes currently queued */
+        const SolidRenderablePassMap& _getSolidPasses(void) const
+        { return mSolidPasses; }
+        /** Get the collection of solid passes currently queued (per-light) */
+        const SolidRenderablePassMap& _getSolidPassesDiffuseSpecular(void) const
+        { return mSolidPassesDiffuseSpecular; }
+        /** Get the collection of solid passes currently queued (decal textures)*/
+        const SolidRenderablePassMap& _getSolidPassesDecal(void) const
+        { return mSolidPassesDecal; }
+        /** Get the collection of solid passes for which shadow receipt is disabled*/
+        const SolidRenderablePassMap& _getSolidPassesNoShadow(void) const
+        { return mSolidPassesNoShadow; }
+        /** Get the collection of transparent passes currently queued */
+        const TransparentRenderablePassList& _getTransparentPasses(void) const
+        { return mTransparentPasses; }
+
+
+        /** Add a renderable to this group. */
+        void addRenderable(Renderable* pRend);
+
+		/** Sorts the objects which have been added to the queue; transparent objects by their 
+            depth in relation to the passed in Camera. */
+		void sort(const Camera* cam);
+
+        /** Clears this group of renderables. 
+        */
+        void clear(void);
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+		/** Clears solids in this group of renderables. Leaves transparents in group.
+        */
+        void clearSolids(void);
+#endif // GTP_VISIBILITY_MODIFIED_OGRE		
+        /** Sets whether or not the queue will split passes by their lighting type,
+        ie ambient, per-light and decal. 
+        */
+        void setSplitPassesByLightingType(bool split)
+        {
+            mSplitPassesByLightingType = split;
+        }
+
+        /** Sets whether or not passes which have shadow receive disabled should
+            be separated. 
+        */
+        void setSplitNoShadowPasses(bool split)
+        {
+            mSplitNoShadowPasses = split;
+        }
+
+
+    };
+
+
+    /** A grouping level underneath RenderQueue which groups renderables
+    to be issued at coarsely the same time to the renderer.
+    @remarks
+        Each instance of this class itself hold RenderPriorityGroup instances, 
+        which are the groupings of renderables by priority for fine control
+        of ordering (not required for most instances).
+    @par
+        This is an internal OGRE class, not intended for apps to use.
+    */
+    class RenderQueueGroup
+    {
+    public:
+        typedef std::map<ushort, RenderPriorityGroup*, std::less<ushort> > PriorityMap;
+        typedef MapIterator<PriorityMap> PriorityMapIterator;
+    protected:
+        RenderQueue* mParent;
+        bool mSplitPassesByLightingType;
+        bool mSplitNoShadowPasses;
+        /// Map of RenderPriorityGroup objects
+        PriorityMap mPriorityGroups;
+		/// Whether shadows are enabled for this queue
+		bool mShadowsEnabled;
+
+
+    public:
+		RenderQueueGroup(RenderQueue* parent, bool splitPassesByLightingType, 
+            bool splitNoShadowPasses) 
+            :mParent(parent), mSplitPassesByLightingType(splitPassesByLightingType),
+            mSplitNoShadowPasses(splitNoShadowPasses), mShadowsEnabled(true) {}
+
+        ~RenderQueueGroup() {
+            // destroy contents now
+            PriorityMap::iterator i;
+            for (i = mPriorityGroups.begin(); i != mPriorityGroups.end(); ++i)
+            {
+                delete i->second;
+            }
+        }
+
+        /** Get an iterator for browsing through child contents. */
+        PriorityMapIterator getIterator(void)
+        {
+            return PriorityMapIterator(mPriorityGroups.begin(), mPriorityGroups.end());
+        }
+
+        /** Add a renderable to this group, with the given priority. */
+        void addRenderable(Renderable* pRend, ushort priority)
+        {
+            // Check if priority group is there
+            PriorityMap::iterator i = mPriorityGroups.find(priority);
+            RenderPriorityGroup* pPriorityGrp;
+            if (i == mPriorityGroups.end())
+            {
+                // Missing, create
+                pPriorityGrp = new RenderPriorityGroup(this, 
+                    mSplitPassesByLightingType, mSplitNoShadowPasses);
+                mPriorityGroups.insert(PriorityMap::value_type(priority, pPriorityGrp));
+            }
+            else
+            {
+                pPriorityGrp = i->second;
+            }
+
+            // Add
+            pPriorityGrp->addRenderable(pRend);
+
+        }
+
+        /** Clears this group of renderables. 
+        @remarks
+            Doesn't delete any priority groups, just empties them. Saves on 
+            memory deallocations since the chances are rougly the same kinds of 
+            renderables are going to be sent to the queue again next time.
+        */
+        void clear(void)
+        {
+            PriorityMap::iterator i, iend;
+            iend = mPriorityGroups.end();
+            for (i = mPriorityGroups.begin(); i != iend; ++i)
+            {
+                i->second->clear();
+            }
+
+        }
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE	
+		/** Clears only solid renderables. Leaves transparents in queue. */
+		void clearSolids(void)
+        {
+            PriorityMap::iterator i, iend;
+            iend = mPriorityGroups.end();
+            for (i = mPriorityGroups.begin(); i != iend; ++i)
+            {
+                i->second->clearSolids();
+            }
+        }
+#endif // GTP_VISIBILITY_MODIFIED_OGRE		
+
+		/** Indicate whether a given queue group will be doing any
+		shadow setup.
+		@remarks
+		This method allows you to inform the queue about a queue group, and to 
+		indicate whether this group will require shadow processing of any sort.
+		In order to preserve rendering order, OGRE has to treat queue groups
+		as very separate elements of the scene, and this can result in it
+		having to duplicate shadow setup for each group. Therefore, if you
+		know that a group which you are using will never need shadows, you
+		should preregister the group using this method in order to improve
+		the performance.
+		*/
+		void setShadowsEnabled(bool enabled) { mShadowsEnabled = enabled; }
+
+		/** Are shadows enabled for this queue? */
+		bool getShadowsEnabled(void) const { return mShadowsEnabled; }
+
+        /** Sets whether or not the queue will split passes by their lighting type,
+        ie ambient, per-light and decal. 
+        */
+        void setSplitPassesByLightingType(bool split)
+        {
+            mSplitPassesByLightingType = split;
+            PriorityMap::iterator i, iend;
+            iend = mPriorityGroups.end();
+            for (i = mPriorityGroups.begin(); i != iend; ++i)
+            {
+                i->second->setSplitPassesByLightingType(split);
+            }
+        }
+        /** Sets whether or not the queue will split passes which have shadow receive
+        turned off (in their parent material), which is needed when certain shadow
+        techniques are used.
+        */
+        void setSplitNoShadowPasses(bool split)
+        {
+            mSplitNoShadowPasses = split;
+            PriorityMap::iterator i, iend;
+            iend = mPriorityGroups.end();
+            for (i = mPriorityGroups.begin(); i != iend; ++i)
+            {
+                i->second->setSplitNoShadowPasses(split);
+            }
+        }
+
+    };
+
+
+
+}
+
+#endif
+
+
Index: trunk/VUT/work/ogre_changes/OgreMain/include/OgreSceneManager.h
===================================================================
--- trunk/VUT/work/ogre_changes/OgreMain/include/OgreSceneManager.h	(revision 74)
+++ trunk/VUT/work/ogre_changes/OgreMain/include/OgreSceneManager.h	(revision 115)
@@ -128,10 +128,11 @@
 			@param node scene node to be rendered
 			@param cam current camera
+			@param leaveTransparentsInQueue if only solid objects should be rendered
 		*/
-		void _renderSceneNode( Camera *cam, SceneNode *node );
-		/** deletes all queues which we were currently processing
-			@remark clears renderqueue after rendering scene node
+		void _renderSceneNode(Camera *cam, SceneNode *node, bool leaveTransparentsInQueue = false);
+		/** deletes all processed queues
+			@remark clears render queues after rendering scene node
 		*/
-		void _deleteRenderedQueueGroups();
+		void _deleteRenderedQueueGroups(bool leaveTransparentsInQueue);
 		/** Internal method used by _renderVisibleObjects to deal with renderables
             which override the camera's own view / projection materices. 
Index: trunk/VUT/work/ogre_changes/OgreMain/src/OgreRenderQueueSortingGrouping.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/OgreMain/src/OgreRenderQueueSortingGrouping.cpp	(revision 115)
+++ trunk/VUT/work/ogre_changes/OgreMain/src/OgreRenderQueueSortingGrouping.cpp	(revision 115)
@@ -0,0 +1,319 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2005 The OGRE Team
+Also see acknowledgements in Readme.html
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place - Suite 330, Boston, MA 02111-1307, USA, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+-----------------------------------------------------------------------------
+*/
+#include "OgreStableHeaders.h"
+#include "OgreRenderQueueSortingGrouping.h"
+
+namespace Ogre {
+
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::destroySolidPassMap(SolidRenderablePassMap& passmap)
+    {
+        // destroy all the pass map entries
+        SolidRenderablePassMap::iterator i, iend;
+        iend = passmap.end();
+        for (i = passmap.begin(); i != iend; ++i)
+        {
+            // Free the list associated with this pass
+            delete i->second;
+        }
+        passmap.clear();
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::removeSolidPassEntry(Pass* p)
+    {
+        SolidRenderablePassMap::iterator i;
+
+        i = mSolidPasses.find(p);
+        if (i != mSolidPasses.end())
+        {
+            // free memory
+            delete i->second;
+            // erase from map
+            mSolidPasses.erase(i);
+        }
+
+        i = mSolidPassesDiffuseSpecular.find(p);
+        if (i != mSolidPassesDiffuseSpecular.end())
+        {
+            // free memory
+            delete i->second;
+            // erase from map
+            mSolidPassesDiffuseSpecular.erase(i);
+        }
+        i = mSolidPassesDecal.find(p);
+        if (i != mSolidPassesDecal.end())
+        {
+            // free memory
+            delete i->second;
+            // erase from map
+            mSolidPassesDecal.erase(i);
+        }
+        i = mSolidPassesNoShadow.find(p);
+        if (i != mSolidPassesNoShadow.end())
+        {
+            // free memory
+            delete i->second;
+            // erase from map
+            mSolidPassesNoShadow.erase(i);
+        }
+
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::clearSolidPassMap(SolidRenderablePassMap& passmap)
+    {
+        SolidRenderablePassMap::iterator i, iend;
+        iend = passmap.end();
+        for (i = passmap.begin(); i != iend; ++i)
+        {
+            // Clear the list associated with this pass, but leave the pass entry
+            i->second->clear();
+        }
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::addRenderable(Renderable* rend)
+    {
+        // Check material & technique supplied (the former since the default implementation
+        // of getTechnique is based on it for backwards compatibility
+        Technique* pTech;
+        if(rend->getMaterial().isNull() || !rend->getTechnique())
+        {
+            // Use default base white
+			MaterialPtr baseWhite = MaterialManager::getSingleton().getByName("BaseWhite");
+            pTech = baseWhite->getTechnique(0);
+        }
+        else
+        {
+            // Get technique
+            pTech = rend->getTechnique();
+        }
+
+        // Transparent and depth settings mean depth sorting is required?
+        if (pTech->isTransparent() && 
+            !(pTech->isDepthWriteEnabled() && pTech->isDepthCheckEnabled()) )
+        {
+            addTransparentRenderable(pTech, rend);
+        }
+        else
+        {
+            if (mSplitNoShadowPasses && !pTech->getParent()->getReceiveShadows())
+            {
+                // Add solid renderable and add passes to no-shadow group
+                addSolidRenderable(pTech, rend, true);
+            }
+            else
+            {
+                if (mSplitPassesByLightingType)
+                {
+                    addSolidRenderableSplitByLightType(pTech, rend);
+                }
+                else
+                {
+                    addSolidRenderable(pTech, rend, false);
+                }
+            }
+        }
+
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::addSolidRenderable(Technique* pTech, 
+        Renderable* rend, bool addToNoShadow)
+    {
+        Technique::PassIterator pi = pTech->getPassIterator();
+
+        SolidRenderablePassMap* passMap;
+        if (addToNoShadow)
+        {
+            passMap = &mSolidPassesNoShadow;
+        }
+        else
+        {
+            passMap = &mSolidPasses;
+        }
+
+
+        while (pi.hasMoreElements())
+        {
+            // Insert into solid list
+            Pass* p = pi.getNext();
+            SolidRenderablePassMap::iterator i = passMap->find(p);
+            if (i == passMap->end())
+            {
+                std::pair<SolidRenderablePassMap::iterator, bool> retPair;
+                // Create new pass entry, build a new list
+                // Note that this pass and list are never destroyed until the engine
+                // shuts down, although the lists will be cleared
+                retPair = passMap->insert(
+                    SolidRenderablePassMap::value_type(p, new RenderableList() ) );
+                assert(retPair.second && "Error inserting new pass entry into SolidRenderablePassMap");
+                i = retPair.first;
+            }
+            // Insert renderable
+            i->second->push_back(rend);
+
+        }
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::addSolidRenderableSplitByLightType(Technique* pTech, Renderable* rend)
+    {
+        // Divide the passes into the 3 categories
+        Technique::IlluminationPassIterator pi = 
+            pTech->getIlluminationPassIterator();
+
+        while (pi.hasMoreElements())
+        {
+            // Insert into solid list
+            IlluminationPass* p = pi.getNext();
+            SolidRenderablePassMap* passMap;
+            switch(p->stage)
+            {
+            case IS_AMBIENT:
+                passMap = &mSolidPasses;
+                break;
+            case IS_PER_LIGHT:
+                passMap = &mSolidPassesDiffuseSpecular;
+                break;
+            case IS_DECAL:
+                passMap = &mSolidPassesDecal;
+                break;
+            };
+
+            SolidRenderablePassMap::iterator i = passMap->find(p->pass);
+            if (i == passMap->end())
+            {
+                std::pair<SolidRenderablePassMap::iterator, bool> retPair;
+                // Create new pass entry, build a new list
+                // Note that this pass and list are never destroyed until the engine
+                // shuts down, although the lists will be cleared
+                retPair = passMap->insert(
+                    SolidRenderablePassMap::value_type(p->pass, new RenderableList() ) );
+                assert(retPair.second && "Error inserting new pass entry into SolidRenderablePassMap");
+                i = retPair.first;
+            }
+            // Insert renderable
+            i->second->push_back(rend);
+        }
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::addTransparentRenderable(Technique* pTech, Renderable* rend)
+    {
+        Technique::PassIterator pi = pTech->getPassIterator();
+
+        while (pi.hasMoreElements())
+        {
+            // Insert into transparent list
+            mTransparentPasses.push_back(RenderablePass(rend, pi.getNext()));
+        }
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::sort(const Camera* cam)
+    {
+        TransparentQueueItemLess transFunctor;
+        transFunctor.camera = cam;
+
+        std::stable_sort(mTransparentPasses.begin(), mTransparentPasses.end(), 
+            transFunctor);
+    }
+    //-----------------------------------------------------------------------
+    void RenderPriorityGroup::clear(void)
+    {
+        SolidRenderablePassMap::iterator i, iend;
+        // Delete queue groups which are using passes which are to be
+        // deleted, we won't need these any more and they clutter up 
+        // the list and can cause problems with future clones
+        const Pass::PassSet& graveyardList = Pass::getPassGraveyard();
+        Pass::PassSet::const_iterator gi, giend;
+        giend = graveyardList.end();
+        for (gi = graveyardList.begin(); gi != giend; ++gi)
+        {
+            removeSolidPassEntry(*gi);
+        }
+
+        // Now remove any dirty passes, these will have their hashes recalculated
+        // by the parent queue after all groups have been processed
+        // If we don't do this, the std::map will become inconsistent for new insterts
+        const Pass::PassSet& dirtyList = Pass::getDirtyHashList();
+        Pass::PassSet::const_iterator di, diend;
+        diend = dirtyList.end();
+        for (di = dirtyList.begin(); di != diend; ++di)
+        {
+            removeSolidPassEntry(*di);
+        }
+        // NB we do NOT clear the graveyard or the dirty list here, because 
+        // it needs to be acted on for all groups, the parent queue takes 
+        // care of this afterwards
+
+        // We do not clear the unchanged solid pass maps, only the contents of each list
+        // This is because we assume passes are reused a lot and it saves resorting
+        clearSolidPassMap(mSolidPasses);
+        clearSolidPassMap(mSolidPassesDecal);
+        clearSolidPassMap(mSolidPassesDiffuseSpecular);
+        clearSolidPassMap(mSolidPassesNoShadow);
+
+        // Always empty the transparents list
+        mTransparentPasses.clear();
+
+    }
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE	
+	//-----------------------------------------------------------------------
+    void RenderPriorityGroup::clearSolids(void)
+    {
+      /*  SolidRenderablePassMap::iterator i, iend;
+        // Delete queue groups which are using passes which are to be
+        // deleted, we won't need these any more and they clutter up 
+        // the list and can cause problems with future clones
+        const Pass::PassSet& graveyardList = Pass::getPassGraveyard();
+        Pass::PassSet::const_iterator gi, giend;
+        giend = graveyardList.end();
+        for (gi = graveyardList.begin(); gi != giend; ++gi)
+        {
+            removeSolidPassEntry(*gi);
+        }
+
+        // Now remove any dirty passes, these will have their hashes recalculated
+        // by the parent queue after all groups have been processed
+        // If we don't do this, the std::map will become inconsistent for new insterts
+        const Pass::PassSet& dirtyList = Pass::getDirtyHashList();
+        Pass::PassSet::const_iterator di, diend;
+        diend = dirtyList.end();
+        for (di = dirtyList.begin(); di != diend; ++di)
+        {
+            removeSolidPassEntry(*di);
+        }*/
+        // NB we do NOT clear the graveyard or the dirty list here, because 
+        // it needs to be acted on for all groups, the parent queue takes 
+        // care of this afterwards
+
+        // We do not clear the unchanged solid pass maps, only the contents of each list
+        // This is because we assume passes are reused a lot and it saves resorting
+        clearSolidPassMap(mSolidPasses);
+        clearSolidPassMap(mSolidPassesDecal);
+        clearSolidPassMap(mSolidPassesDiffuseSpecular);
+        clearSolidPassMap(mSolidPassesNoShadow);
+    }
+#endif // GTP_VISIBILITY_MODIFIED_OGRE		
+//-----------------------------------------------------------------------
+
+}
+
Index: trunk/VUT/work/ogre_changes/OgreMain/src/OgreSceneManager.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/OgreMain/src/OgreSceneManager.cpp	(revision 99)
+++ trunk/VUT/work/ogre_changes/OgreMain/src/OgreSceneManager.cpp	(revision 115)
@@ -59,5 +59,5 @@
 #include "OgreDataStream.h"
 #include "OgreStaticGeometry.h"
-#include <windows.h> //matt: remove later
+
 // This class implements the most basic scene manager
 
@@ -665,7 +665,4 @@
         if (lastUsedVertexProgram)
         {
-			//matt: remove later
-			//OutputDebugString("unbinding vertex program\n");
-
             mDestRenderSystem->unbindGpuProgram(GPT_VERTEX_PROGRAM);
             lastUsedVertexProgram = false;
@@ -990,5 +987,4 @@
                                const String& groupName)
 {
-    mSkyPlaneEnabled = enable;
     if (enable)
     {
@@ -1061,4 +1057,5 @@
 
     }
+	mSkyPlaneEnabled = enable;
 }
 //-----------------------------------------------------------------------
@@ -1071,5 +1068,4 @@
                              const String& groupName)
 {
-    mSkyBoxEnabled = enable;
     if (enable)
     {
@@ -1143,5 +1139,5 @@
 
     }
-
+	mSkyBoxEnabled = enable;
 }
 //-----------------------------------------------------------------------
@@ -1157,5 +1153,4 @@
                               const String& groupName)
 {
-    mSkyDomeEnabled = enable;
     if (enable)
     {
@@ -1164,5 +1159,5 @@
         {
             OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, 
-                "Sky dome material '" + materialName + " not found.",
+                "Sky dome material '" + materialName + "' not found.",
                 "SceneManager::setSkyDome");
         }
@@ -1208,4 +1203,5 @@
 
     }
+	mSkyDomeEnabled = enable;
 }
 //-----------------------------------------------------------------------
@@ -2658,4 +2654,6 @@
     {
         Light* l = i->second;
+		if (l->isVisible())
+		{
         if (l->getType() == Light::LT_DIRECTIONAL)
         {
@@ -2675,4 +2673,5 @@
 
         }
+    }
     }
 
@@ -4180,5 +4179,5 @@
 #ifdef GTP_VISIBILITY_MODIFIED_OGRE
 //-----------------------------------------------------------------------
-void SceneManager::_renderSceneNode( Camera *cam, SceneNode *node )
+void SceneManager::_renderSceneNode(Camera *cam, SceneNode *node, bool leaveTransparentsInQueue)
 {
 	node->_findVisibleObjects(cam, getRenderQueue(), false, mDisplayNodes, false);
@@ -4186,8 +4185,8 @@
 	
 	// delete all rendered objects from renderqueue
-	_deleteRenderedQueueGroups();
-}
-//-----------------------------------------------------------------------
-void SceneManager::_deleteRenderedQueueGroups()
+	_deleteRenderedQueueGroups(leaveTransparentsInQueue);
+}
+//-----------------------------------------------------------------------
+void SceneManager::_deleteRenderedQueueGroups(bool leaveTransparentsInQueue)
 {
 	RenderQueue::QueueGroupIterator queueIt = getRenderQueue()->_getQueueGroupIterator();
@@ -4200,5 +4199,14 @@
 
 		if (isRenderQueueToBeProcessed(qId))
+		{
+			if (leaveTransparentsInQueue)
+			{
+				pGroup->clearSolids();
+			}
+			else
+			{
 			pGroup->clear();
+	}
+		}
 	}
 	
Index: trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctreeSceneManager.h
===================================================================
--- trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctreeSceneManager.h	(revision 112)
+++ trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctreeSceneManager.h	(revision 115)
@@ -105,10 +105,14 @@
 	/** Renders one octant of an octree, i.e., renders current octant
 		node and does not traverse deeper into the tree.
+
 		@remark Note that OctreeNode instances are NOT part of the octree 
 		hierarchy, instead one octant of an Octree contains many OctreeNode instances.
-		@param octree the octree to be rendered
+		
 		@param cam current camera
+		@param octree the octant to be rendered (without children)
+		@param onlyShadowCasters if only shadow casters are rendered
+		@param leaveTransparentsInQueue if transparemt should be left in queue for later processing
 	*/
-	void _renderOctant(Camera* cam, Octree *octree, bool onlyShadowCasters);
+	void _renderOctant(Camera* cam, Octree *octree, bool onlyShadowCasters, bool leaveTransparentsInQueue = false);
 
 	/** Returns stored list of boxes */
@@ -214,4 +218,5 @@
     IntersectionSceneQuery* createIntersectionQuery(unsigned long mask);
 
+
 protected:
 
Index: trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctree.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctree.cpp	(revision 61)
+++ trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctree.cpp	(revision 115)
@@ -109,9 +109,4 @@
 		mDepth = 0;
 
-	//matt: remove later
-	//char msg[100];
-	//sprintf(msg, "creating new octant in depth %d", mDepth);
-	//OutputDebugString(msg);
-
 #endif //GTP_VISIBILITY_MODIFIED_OGRE
     mNumNodes = 0;
@@ -171,9 +166,4 @@
 
 	mWireBoundingBox->setupBoundingBox(mBox);
-
-	// matt: change this back
-	//AxisAlignedBox box; _getCullBounds(&box); 
-	//mWireBoundingBox->setupBoundingBox(box);
-
     return mWireBoundingBox;
 }
Index: trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctreeSceneManager.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctreeSceneManager.cpp	(revision 112)
+++ trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctreeSceneManager.cpp	(revision 115)
@@ -39,5 +39,5 @@
 #include <OgreOctreeCamera.h>
 #include <OgreRenderSystem.h>
-#include <windows.h>
+
 
 extern "C"
@@ -508,8 +508,4 @@
         }
 
-		//matt: remove later
-		//OutputDebugString("adding octree node\n");
-		
-
         _addOctreeNode( n, octant -> mChildren[ x ][ y ][ z ], ++depth );
 
@@ -1173,5 +1169,6 @@
 }
 //-----------------------------------------------------------------------
-void OctreeSceneManager::_renderOctant(Camera *cam, Octree *octant, bool onlyShadowCasters)
+void OctreeSceneManager::_renderOctant(Camera *cam, Octree *octant, bool onlyShadowCasters, 
+									   bool leaveTransparentsInQueue)//, bool useZPassQueue)
 {
 	//Add stuff to be rendered;
@@ -1188,5 +1185,4 @@
 		{
 			sn->_addToRenderQueue(cam, getRenderQueue(), onlyShadowCasters);
-			//node->_findVisibleObjects(cam, getRenderQueue(), false, mDisplayNodes, false);
 			mVisible.push_back(sn);
 
@@ -1207,12 +1203,14 @@
 	if (mShowBoxes)
 	{
+		octant->getWireBoundingBox()->setMaterial("BaseWhiteNoLighting");
+
 		getRenderQueue()->addRenderable(octant->getWireBoundingBox());
 		mBoxes.push_back(octant->getWireBoundingBox());
 	}
 
+	//-- the actual rendering
 	SceneManager::_renderVisibleObjects();
-
 	// delete all rendered objects from the render queue
-	_deleteRenderedQueueGroups();
+	_deleteRenderedQueueGroups(leaveTransparentsInQueue);
 }
 #endif // GTP_VISIBILITY_MODIFIED_OGRE
Index: trunk/VUT/work/ogre_changes/Samples/Common/include/ExampleFrameListener.h
===================================================================
--- trunk/VUT/work/ogre_changes/Samples/Common/include/ExampleFrameListener.h	(revision 100)
+++ trunk/VUT/work/ogre_changes/Samples/Common/include/ExampleFrameListener.h	(revision 115)
@@ -300,9 +300,6 @@
 		return true;
 	}
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
-	virtual void moveCamera() // made virtual by matt (16.05.05)
-#else
+
 	void moveCamera()
-#endif // GTP_VISIBILTIY_MODIFIED_OGRE
 	{
 
Index: trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreGLHardwareOcclusionQuery.h
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreGLHardwareOcclusionQuery.h	(revision 92)
+++ trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreGLHardwareOcclusionQuery.h	(revision 115)
@@ -88,15 +88,6 @@
 	void beginOcclusionQuery();
 	void endOcclusionQuery();
-
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
-	bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult,
-							 const HW_OCCLUSIONQUERY flag  ); 
-	bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult );
-#else
-	bool pullOcclusionQuery( unsigned int* NumOfFragments );
 	bool pullOcclusionQuery( unsigned int* NumOfFragments, const HW_OCCLUSIONQUERY flag  ); 
-#endif // GTP_VISIBILITY_MODIFIED_OGRE
-
-	unsigned int getLastQuerysPixelcount() { return m_uintPixelCount; }
+	unsigned int getLastQuerysPixelcount() { return mPixelCount; }
 
 	// This functions are optional, it's a simple filter that simply skipps some hardware occlusion tests on visable objects only
@@ -115,8 +106,10 @@
 	  */
 
-	void setSkipRate( int skip ) { m_Skip = skip; }		// Using 2 only 50 % of the tests are actully made and 3 results in only 33% of the tests. So on.
-	int	 getSkipRate() { return m_Skip; } 
+	void setSkipRate( int skip ) { mSkipInterval = skip; }		// Using 2 only 50 % of the tests are actully made and 3 results in only 33% of the tests. So on.
+	int	 getSkipRate() { return mSkipInterval; } 
 
-
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, const HW_OCCLUSIONQUERY flag = HWOCCLUSIONQUERY_FLUSH ); 
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
 //----------------------------------------------------------------------
 // Protected members
@@ -124,12 +117,11 @@
 protected:
 
-	unsigned int	m_uintPixelCount;
-	unsigned int	m_uintQuery[1];
+	unsigned int	mPixelCount;
+	GLuint			mQueryID;
 	bool			m_bOcclusionQuery;
-	int				m_SkipCounter;		// m_SkipConter =  m_SkipConter % m_Skip; if ( m_SkipConter == 0 && m_uintPixelCount !=0 ) TestHWOcclusion else just return 
-	static int		m_Skip;				// This is shared by all instancies
-	bool			m_bHWOcclusionSupport;
+	int				mSkipCounter;
+	int				mSkipInterval;
+	bool			mHasOcclusionSupport;
 };
-
 
 }
Index: trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreGLPrerequisites.h
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreGLPrerequisites.h	(revision 97)
+++ trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreGLPrerequisites.h	(revision 115)
@@ -70,4 +70,8 @@
 extern GL_SecondaryColorPointerEXT_Func glSecondaryColorPointerEXT_ptr;
 
+// Pointer to glSecondaryColor3fEXT function
+typedef void (APIENTRY *GL_SecondaryColor3fEXT_Func)(GLfloat, GLfloat, GLfloat);
+extern GL_SecondaryColor3fEXT_Func glSecondaryColor3fEXT_ptr;
+
 // Pointer to glGenBuffersARB function
 typedef void (APIENTRY *GL_GenBuffersARB_Func)(GLsizei, GLuint*);
@@ -208,39 +212,4 @@
 extern GL_GetOcclusionQueryuivNV_Func glGetOcclusionQueryuivNV_ptr;
 
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
-// Pointer to glGenQueriesARB function
-typedef void (APIENTRY *GL_GenQueriesARB_Func) (GLsizei n, GLuint *ids);
-extern GL_GenQueriesARB_Func glGenQueriesARB_ptr;
-
-// Pointer to glDeleteQueriesARB function
-typedef void (APIENTRY *GL_DeleteQueriesARB_Func) (GLsizei n, const GLuint *ids);
-extern GL_DeleteQueriesARB_Func glDeleteQueriesARB_ptr;
-
-// Pointer to glIsQueryARB function
-typedef GLboolean (APIENTRY *GL_IsQueryARB_Func) (GLuint id);
-extern GL_IsQueryARB_Func glIsQueryARB_ptr;
-
-// Pointer to glBeginQueryARB function
-typedef void (APIENTRY *GL_BeginQueryARB_Func) (GLenum target, GLuint id);
-extern GL_BeginQueryARB_Func glBeginQueryARB_ptr;
-
-// Pointer to glEndQueryARB function
-typedef void (APIENTRY *GL_EndQueryARB_Func) (GLenum target);
-extern GL_EndQueryARB_Func glEndQueryARB_ptr;
-
-// Pointer to glGetQueryivARB function
-typedef void (APIENTRY *GL_GetQueryivARB_Func) (GLuint id, GLenum pname, GLint *params);
-extern GL_GetQueryivARB_Func glGetQueryivARB_ptr;
-
-// Pointer to glGetQueryObjectivARB function
-typedef void (APIENTRY *GL_GetQueryObjectivARB_Func) (GLuint id, GLenum pname, GLint *params);
-extern GL_GetQueryObjectivARB_Func glGetQueryObjectivARB_ptr;
-
-// Pointer to glGetQueryObjectuivARB function
-typedef void (APIENTRY *GL_GetQueryObjectuivARB_Func) (GLuint id, GLenum pname, GLuint *params);
-extern GL_GetQueryObjectuivARB_Func glGetQueryObjectuivARB_ptr;
-
-#endif // GTP_VISIBILITY_MODIFIED_OGRE
-
 extern PFNGLCOMPRESSEDTEXIMAGE1DARBPROC glCompressedTexImage1DARB_ptr;
 extern PFNGLCOMPRESSEDTEXIMAGE2DARBPROC glCompressedTexImage2DARB_ptr;
@@ -253,4 +222,31 @@
 };
 
+// Pointer to glGenQueriesARB function
+typedef void (APIENTRY *GL_GenQueriesARB_Func) (GLuint n, GLuint *ids);
+extern GL_GenQueriesARB_Func glGenQueriesARB_ptr;
+
+// Pointer to glDeleteQueriesARB function
+typedef void (APIENTRY *GL_DeleteQueriesARB_Func) (GLuint n, const GLuint *ids);
+extern GL_DeleteQueriesARB_Func glDeleteQueriesARB_ptr;
+
+// Pointer to glBeginQueryARB function
+typedef void (APIENTRY *GL_BeginQueryARB_Func) (GLenum target, GLuint id);
+extern GL_BeginQueryARB_Func glBeginQueryARB_ptr;
+
+// Pointer to glEndQueryARB function
+typedef void (APIENTRY *GL_EndQueryARB_Func) (GLenum target);
+extern GL_EndQueryARB_Func glEndQueryARB_ptr;
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+// Pointer to glGetQueryivARB function
+typedef void (APIENTRY *GL_GetQueryivARB_Func) (GLuint id, GLenum pname, GLint *params);
+extern GL_GetQueryivARB_Func glGetQueryivARB_ptr;
+
+// Pointer to glGetQueryObjectivARB function
+typedef void (APIENTRY *GL_GetQueryObjectivARB_Func) (GLuint id, GLenum pname, GLint *params);
+extern GL_GetQueryObjectivARB_Func glGetQueryObjectivARB_ptr;
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
+// Pointer to glGetQueryObjectuivARB function
+typedef void (APIENTRY *GL_GetQueryObjectuivARB_Func) (GLuint id, GLenum pname, GLuint *params);
+extern GL_GetQueryObjectuivARB_Func glGetQueryObjectuivARB_ptr;
 
 
Index: trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLHardwareOcclusionQuery.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLHardwareOcclusionQuery.cpp	(revision 99)
+++ trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLHardwareOcclusionQuery.cpp	(revision 115)
@@ -27,7 +27,6 @@
 #include "OgreException.h"
 
+
 namespace Ogre {
-
-int GLHardwareOcclusionQuery::m_Skip = 0;
 
 /**
@@ -36,19 +35,9 @@
   *
   * @author Lee Sandberg email: lee@abcmedia.se
+  *
+  * Updated on 12/7/2004 by Chris McGuirk
+  * - Implemented ARB_occlusion_query
   */
 
-/* Functions used;
-
-glGenOcclusionQueriesNV_ptr( 1, m_uintQuery );
-glDeleteOcclusionQueriesNV_ptr( 1, &m_uintQuery[0] );
-glBeginOcclusionQueryNV_ptr( m_uintQuery[0] );
-glEndOcclusionQueryNV_ptr();
-glGetOcclusionQueryuivNV_ptr( m_uintQuery[0], GL_PIXEL_COUNT_NV, NumOfFragments );
-
-  TO DO: change this to the new ARB functions...
-
-*/
-
-#ifndef GTP_VISIBILITY_MODIFIED_OGRE
 /**
   * Default object constructor
@@ -57,23 +46,26 @@
 GLHardwareOcclusionQuery::GLHardwareOcclusionQuery() 
 { 
-	m_uintPixelCount = 0; 
-	m_SkipCounter = 0;
+	mPixelCount = 0; 
+	mSkipCounter = 0;
+	mSkipInterval = 0;
 
 	// Check for hardware occlusion support
-    if( glDeleteOcclusionQueriesNV_ptr != 0 )	// This is a hack to see if hw occlusion is supported. pointer is 0 if it's not supported.
+	// This is a hack to see if hw occlusion is supported. pointer is 0 if it's not supported.
+	//if (glGenQueriesARB_ptr != 0)
+	if (glGenOcclusionQueriesNV_ptr != 0)
     {
-		m_bHWOcclusionSupport = true;
+		mHasOcclusionSupport = true;
 	}
 	else
 	{
-		m_bHWOcclusionSupport = false;
+		mHasOcclusionSupport = false;
 	}
 
-	if( m_bHWOcclusionSupport )
+	if(mHasOcclusionSupport)
 	{
-		glGenOcclusionQueriesNV_ptr( 1, m_uintQuery );	
+		//glGenQueriesARB_ptr(1, &mQueryID );	
+		glGenOcclusionQueriesNV_ptr(1, &mQueryID);
 	}
 }
-
 
 /**
@@ -82,7 +74,8 @@
 GLHardwareOcclusionQuery::~GLHardwareOcclusionQuery() 
 { 
-	if( m_bHWOcclusionSupport )
+	if( mHasOcclusionSupport )
 	{
-		glDeleteOcclusionQueriesNV_ptr( 1, &m_uintQuery[0] );  
+		//glDeleteQueriesARB_ptr(1, &mQueryID);  
+		glDeleteOcclusionQueriesNV_ptr(1, &mQueryID);  
 	}	
 }
@@ -93,10 +86,21 @@
 void GLHardwareOcclusionQuery::beginOcclusionQuery() 
 { 
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
+	// Make it fail silently if hardware occlusion isn't supported
+	if(mHasOcclusionSupport)
 	{
-		if  ( m_SkipCounter ==  m_Skip ) { m_SkipCounter = 0; };		// Counter starts at 0 again at m_Skip 
-		if ( m_SkipCounter == 0 && m_uintPixelCount != 0 ) // New or none visable objects must allways be tested but visable objects can be skiped
+		// Counter starts at 0 again at mSkipInterval 
+#ifndef GTP_VISIBILITY_MODIFIED_OGRE
+		if(mSkipCounter == mSkipInterval) 
+#else
+		if (mSkipCounter >= mSkipInterval)  // otherwise no query ever issued if mSkipInterval = 0 !
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
+	{
+			mSkipCounter = 0; 
+		}
+
+		if (mSkipCounter == 0)
 		{
-			glBeginOcclusionQueryNV_ptr( m_uintQuery[0] );
+			//glBeginQueryARB_ptr(GL_SAMPLES_PASSED_ARB, mQueryID);
+			glBeginOcclusionQueryNV_ptr(mQueryID);
 		}
 	}
@@ -105,40 +109,26 @@
 void GLHardwareOcclusionQuery::endOcclusionQuery() 
 { 
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
+	// Make it fail silently if hardware occlusion isn't supported
+	if(mHasOcclusionSupport)
 	{
-		if( m_SkipCounter == 0 && m_uintPixelCount != 0 ) // New or none visable objects must allways be tested but visable objects can be skiped
+		if( mSkipCounter == 0)
 		{
+			//glEndQueryARB_ptr(GL_SAMPLES_PASSED_ARB);
 			glEndOcclusionQueryNV_ptr();
 		}
-		m_SkipCounter++;
-	}
-}
 
-bool GLHardwareOcclusionQuery::pullOcclusionQuery( unsigned int * NumOfFragments) 
-{
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
-	{
-		glGetOcclusionQueryuivNV_ptr( m_uintQuery[0], GL_PIXEL_COUNT_NV, NumOfFragments );
+		mSkipCounter++;
 	} 
-	else
-	{
-		*NumOfFragments = 100000;		// Fails quitlly -> every object tested is visable.
-	}
-
-	m_uintPixelCount = *NumOfFragments; 
-
-	return true;
 }
 
 //------------------------------------------------------------------
-// OpenGL dosn't use the flag, but to fulfil the abstract interface we need to include this function.
-// Using this function in OpenGL mode simple works the same way as calling the other function without the flag parameter,
-// but in DX9 it works differentlly, see notes in the DX9 implementation.
-//--
+// OpenGL dosn't use the flag paramter.
+//------------------------------------------------------------------
 bool GLHardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments, const HW_OCCLUSIONQUERY flag  ) 
 {
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
+	if( mHasOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
 	{
-		glGetOcclusionQueryuivNV_ptr( m_uintQuery[0], GL_PIXEL_COUNT_NV, NumOfFragments );
+		//glGetQueryObjectuivARB_ptr(mQueryID, GL_QUERY_RESULT_ARB, NumOfFragments);
+glGetOcclusionQueryuivNV_ptr(mQueryID, GL_PIXEL_COUNT_NV, NumOfFragments);
 	}
 	else
@@ -147,83 +137,28 @@
 	}
 
-	m_uintPixelCount = *NumOfFragments; 
+	mPixelCount = *NumOfFragments; 
 	
 	return true;
 }
 
-#else // GTP_VISIBILITY_MODIFIED_OGRE
-
-//------------------------------------------------------------------
-GLHardwareOcclusionQuery::GLHardwareOcclusionQuery() 
-{ 
-	m_uintPixelCount = 0; 
-	m_SkipCounter = 0;
-
-	// Check for hardware occlusion support
-    if ( glDeleteOcclusionQueriesNV_ptr != 0 )	// This is a hack to see if hw occlusion is supported. pointer is 0 if it's not supported.
-	//if ( glDeleteQueriesARB_ptr != 0 )
-	{
-		m_bHWOcclusionSupport = true;
-	}
-	else
-	{
-		m_bHWOcclusionSupport = false;
-	}
-
-	if ( m_bHWOcclusionSupport )
-	{
-		glGenOcclusionQueriesNV_ptr( 1, m_uintQuery );	
-		//glGenQueriesARB_ptr(1, m_uintQuery);
-	}
-}
-
-
-//------------------------------------------------------------------
-GLHardwareOcclusionQuery::~GLHardwareOcclusionQuery() 
-{ 
-	if ( m_bHWOcclusionSupport )
-	{
-		glDeleteOcclusionQueriesNV_ptr( 1, &m_uintQuery[0] );  
-		//glDeleteQueriesARB_ptr(1, &m_uintQuery[0]);
-	}	
-}
-
-//------------------------------------------------------------------
-void GLHardwareOcclusionQuery::beginOcclusionQuery() 
-{ 
-	if ( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
-	{
-		// do the actual occlusion query for this node
-		glBeginOcclusionQueryNV_ptr( m_uintQuery[0] );
-		//glBeginQueryARB_ptr(GL_SAMPLES_PASSED_ARB, m_uintQuery[0]);
-	}
-}
-	
-void GLHardwareOcclusionQuery::endOcclusionQuery() 
-{ 
-	if ( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
-	{
-		glEndOcclusionQueryNV_ptr();
-		//glEndQueryARB_ptr(GL_SAMPLES_PASSED_ARB);
-	}
-}
-//------------------------------------------------------------------
-bool GLHardwareOcclusionQuery::pullOcclusionQuery( unsigned int * NumOfFragments, const bool waitForResult) 
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	//------------------------------------------------------------------
+	bool GLHardwareOcclusionQuery::pullOcclusionQuery( unsigned int * NumOfFragments, const bool waitForResult, const HW_OCCLUSIONQUERY flag) 
 {
 	unsigned int isAvailable = GL_TRUE;
-	//int isAvailable = GL_TRUE;
 
-	if( m_bHWOcclusionSupport )	
+		if (mHasOcclusionSupport)	
 	{
 		if (!waitForResult)
 		{
-			glGetOcclusionQueryuivNV_ptr( m_uintQuery[0], GL_PIXEL_COUNT_AVAILABLE_NV, &isAvailable );
-			//glGetQueryivARB_ptr(m_uintQuery[0], GL_QUERY_RESULT_AVAILABLE_ARB, &isAvailable);
+			// use nv queries rather that arb because they are faster (no flush)
+				//glGetQueryivARB_ptr(mQueryID, GL_QUERY_RESULT_AVAILABLE_ARB, &isAvailable);
+				glGetOcclusionQueryuivNV_ptr(mQueryID, GL_PIXEL_COUNT_AVAILABLE_NV, &isAvailable);
 		}
 
 		if (isAvailable == GL_TRUE)
 		{
-			glGetOcclusionQueryuivNV_ptr( m_uintQuery[0], GL_PIXEL_COUNT_NV, NumOfFragments );
-			//glGetQueryObjectuivARB_ptr( m_uintQuery[0], GL_QUERY_RESULT_ARB, NumOfFragments);
+				//glGetQueryObjectuivARB_ptr(mQueryID, GL_QUERY_RESULT_ARB, NumOfFragments);
+				glGetOcclusionQueryuivNV_ptr(mQueryID, GL_PIXEL_COUNT_NV, NumOfFragments);
 		}
 	} 
@@ -234,19 +169,9 @@
 	}
 
-	m_uintPixelCount = *NumOfFragments; 
+		mPixelCount = *NumOfFragments; 
 
 	return isAvailable == GL_TRUE;	
 }
 
-//------------------------------------------------------------------
-bool GLHardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, const HW_OCCLUSIONQUERY flag  ) 
-{
-	return pullOcclusionQuery(NumOfFragments, waitForResult);
+#endif // GTP_VIBILITY_MODIFIED_OGRE
 }
-
-#endif // GTP_VISIBILITY_MODIFIED_OGRE
-
-
-}
-
-
Index: trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLRenderSystem.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLRenderSystem.cpp	(revision 97)
+++ trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLRenderSystem.cpp	(revision 115)
@@ -58,4 +58,5 @@
 GL_ClientActiveTextureARB_Func glClientActiveTextureARB_ptr;
 GL_SecondaryColorPointerEXT_Func glSecondaryColorPointerEXT_ptr;
+GL_SecondaryColor3fEXT_Func glSecondaryColor3fEXT_ptr;
 GL_GenBuffersARB_Func glGenBuffersARB_ptr;
 GL_BindBufferARB_Func glBindBufferARB_ptr;
@@ -97,15 +98,13 @@
 GL_EndOcclusionQueryNV_Func glEndOcclusionQueryNV_ptr;
 GL_GetOcclusionQueryuivNV_Func glGetOcclusionQueryuivNV_ptr;
- 
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 GL_GenQueriesARB_Func glGenQueriesARB_ptr;
 GL_DeleteQueriesARB_Func glDeleteQueriesARB_ptr;
-GL_IsQueryARB_Func glIsQueryARB_ptr;
 GL_BeginQueryARB_Func glBeginQueryARB_ptr;
 GL_EndQueryARB_Func glEndQueryARB_ptr;
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 GL_GetQueryivARB_Func glGetQueryivARB_ptr;
 GL_GetQueryObjectivARB_Func glGetQueryObjectivARB_ptr;
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
 GL_GetQueryObjectuivARB_Func glGetQueryObjectuivARB_ptr;
-#endif // GTP_VISIBILITY_MODIFIED_OGRE
 
 namespace Ogre {
@@ -191,4 +190,5 @@
         glClientActiveTextureARB_ptr = 0;
         glSecondaryColorPointerEXT_ptr = 0;
+        glSecondaryColor3fEXT_ptr = 0;
         glGenBuffersARB_ptr = 0;
         glBindBufferARB_ptr = 0;
@@ -220,15 +220,13 @@
         glEndOcclusionQueryNV_ptr = 0;
         glGetOcclusionQueryuivNV_ptr = 0;
-
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 		glGenQueriesARB_ptr = 0;
 		glDeleteQueriesARB_ptr = 0;
-		glIsQueryARB_ptr = 0;
 		glBeginQueryARB_ptr = 0;
 		glEndQueryARB_ptr = 0;
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 		glGetQueryivARB_ptr = 0;
 		glGetQueryObjectivARB_ptr = 0;
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
 		glGetQueryObjectuivARB_ptr = 0;
-#endif // GTP_VISIBILITY_MODIFIED_OGRE
 
         mCurrentLights = 0;
@@ -543,4 +541,6 @@
         glSecondaryColorPointerEXT_ptr = 
             (GL_SecondaryColorPointerEXT_Func)mGLSupport->getProcAddress("glSecondaryColorPointerEXT");
+        glSecondaryColor3fEXT_ptr = 
+            (GL_SecondaryColor3fEXT_Func)mGLSupport->getProcAddress("glSecondaryColor3fEXT");
         glGenBuffersARB_ptr = 
             (GL_GenBuffersARB_Func)mGLSupport->getProcAddress("glGenBuffersARB");
@@ -622,26 +622,21 @@
         glGetOcclusionQueryuivNV_ptr =
             (GL_GetOcclusionQueryuivNV_Func)mGLSupport->getProcAddress("glGetOcclusionQueryuivNV");
-		glGetQueryObjectivARB_ptr = 
-			 (GL_GetQueryObjectivARB_Func)mGLSupport->getProcAddress("glGetQueryObjectivARB");
-		glGetQueryObjectuivARB_ptr = 
-			 (GL_GetQueryObjectuivARB_Func)mGLSupport->getProcAddress("glGetQueryObjectuivARB");
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+
 		glGenQueriesARB_ptr = 
 			 (GL_GenQueriesARB_Func)mGLSupport->getProcAddress("glGenQueriesARB");
 		glDeleteQueriesARB_ptr =
 			(GL_DeleteQueriesARB_Func)mGLSupport->getProcAddress("glDeleteQueriesARB");
-		glIsQueryARB_ptr =
-			(GL_IsQueryARB_Func)mGLSupport->getProcAddress("glIsQueryARB");
 		glBeginQueryARB_ptr =
 			 (GL_BeginQueryARB_Func)mGLSupport->getProcAddress("glBeginQueryARB");
 		glEndQueryARB_ptr =
 			 (GL_EndQueryARB_Func)mGLSupport->getProcAddress("glEndQueryARB");
+	#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 		glGetQueryivARB_ptr = 
 			(GL_GetQueryivARB_Func)mGLSupport->getProcAddress("glGetQueryivARB");
 		glGetQueryObjectivARB_ptr = 
 			 (GL_GetQueryObjectivARB_Func)mGLSupport->getProcAddress("glGetQueryObjectivARB");
+	#endif // GTP_VISIBILITY_MODIFIED_OGRE
 		glGetQueryObjectuivARB_ptr = 
 			 (GL_GetQueryObjectuivARB_Func)mGLSupport->getProcAddress("glGetQueryObjectuivARB");
-#endif // GTP_VISIBILITY_MODIFIED_OGRE
 
         mCapabilities->log(LogManager::getSingleton().getDefaultLog());
@@ -1857,4 +1852,6 @@
 		    cv1[2] = bm.colourArg1.b;
 		    cv1[3] = bm.colourArg1.a;
+			mManualBlendColours[stage][0] = bm.colourArg1;
+
 
 		    cv2[0] = bm.colourArg2.r;
@@ -1862,16 +1859,17 @@
 		    cv2[2] = bm.colourArg2.b;
 		    cv2[3] = bm.colourArg2.a;
+			mManualBlendColours[stage][1] = bm.colourArg2;
         }
 
 		if (bm.blendType == LBT_ALPHA)
         {
-		    cv1[0] = 0;
-		    cv1[1] = 0;
-		    cv1[2] = 0;
+		    cv1[0] = mManualBlendColours[stage][0].r;
+		    cv1[1] = mManualBlendColours[stage][0].g;
+		    cv1[2] = mManualBlendColours[stage][0].b;
 		    cv1[3] = bm.alphaArg1;
 
-		    cv2[0] = 0;
-		    cv2[1] = 0;
-		    cv2[2] = 0;
+		    cv2[0] = mManualBlendColours[stage][1].r;
+		    cv2[1] = mManualBlendColours[stage][1].g;
+		    cv2[2] = mManualBlendColours[stage][1].b;
 		    cv2[3] = bm.alphaArg2;
         }
@@ -2249,4 +2247,5 @@
         }
         glColor4f(1,1,1,1);
+        glSecondaryColor3fEXT_ptr(0.0f, 0.0f, 0.0f);
 
         // UnGuard
@@ -2537,4 +2536,6 @@
         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
         glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);        
+        glEnable(GL_COLOR_SUM);
+
         // Check for FSAA
         // Enable the extension if it was enabled by the GLSupport
Index: trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/include/OgreD3D9HardwareOcclusionQuery.h
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/include/OgreD3D9HardwareOcclusionQuery.h	(revision 92)
+++ trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/include/OgreD3D9HardwareOcclusionQuery.h	(revision 115)
@@ -33,8 +33,6 @@
 namespace Ogre {
 
-
-
 // If you use multiple rendering passes you can test only the first pass and all other passes don't have to be rendered 
-// if the first pass resultet has too few pixels visable.
+	// if the first pass resultet has too few pixels visible.
 
 // Be sure to render all occlluder first and whats out so the RenderQue don't switch places on 
@@ -46,4 +44,6 @@
   *
   * @author Lee Sandberg, email lee@abcmedia.se
+	*
+	* Updated on 12/7/2004 by Chris McGuirk
   */
 class D3D9HardwareOcclusionQuery : public HardwareOcclusionQuery
@@ -71,35 +71,27 @@
 	void beginOcclusionQuery();	
 	void endOcclusionQuery();
+		bool pullOcclusionQuery( unsigned int* NumOfFragments, const HW_OCCLUSIONQUERY flag = HWOCCLUSIONQUERY_FLUSH);
+		unsigned int getLastQuerysPixelcount() { return mPixelCount; }
 
-#ifdef GTP_VISIBILITY_MODIFIED_OGRE
-	bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult,
-							 const HW_OCCLUSIONQUERY flag  ); 
-	bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult );
-#else
-	bool pullOcclusionQuery( unsigned int* NumOfFragments );
-	bool pullOcclusionQuery( unsigned int* NumOfFragments, const HW_OCCLUSIONQUERY flag  ); 
-#endif // GTP_VISIBILITY_MODIFIED_OGRE
-
-	unsigned int getLastQuerysPixelcount() { return m_uintPixelCount; }
-	
-	// This functions are optional, it's a simple filter that simply skips some hardware occlusion tests on visable objects only
-	// It's easy to use if you don't have to keep track on which objects are visable (can be skipped) and what objects arn't visable..
-	// (None visable objects and object you introduce for the first time have allways to be tested allthough the cheepest possible 
-	// LOD (Level Of Detail) mesh and material wize). 
+		// These functions are optional, it's a simple filter that simply skips some hardware occlusion tests on visible objects only
+		// It's easy to use if you don't have to keep track of which objects are visible (can be skipped) and what objects arn't visible..
+		// (None visible objects and object you introduce for the first time have always to be tested although the cheapest possible 
+		// LOD (Level Of Detail) mesh and material-wise). 
 
 	/**
 	  *   
-	  * Remarks This function allows you to set how often the hardware occlusion really are sent to the driver
+		* Remarks This function allows you to set how often the hardware occlusion query is sent to the driver
 	  * if you set it to 0 every hw occlusion test is acctually made. If you set it to 1 only the half of your queries are sent 
-	  * for all visable objects. 2 will result in 25% of all queries to acctualy be sent. 
-	  * New and none visable objects will be tested all the time.
-	  * This functionality is here because this class can keep track on visable and none visable objects for you.
+		* 2 will result in 25% of all queries to acctualy be sent. 
+		* This functionality is here because this class can keep track on visible and none visible objects for you.
 	  * Once you you set the SkipRate for any hardware occlusion instance it effects all others.
 	  */
 
+		void setSkipRate( int skip ) { mSkipInterval = skip; }			// Using 2 only 50 % of the tests are actully made and 3 results in only 33% of the tests. So on.
+		int	 getSkipRate() { return mSkipInterval; } 
 
-	void setSkipRate( int skip ) { m_Skip = skip; }			// Using 2 only 50 % of the tests are actually made and 3 results in only 33% of the tests. So on.
-	int	 getSkipRate() { return m_Skip; } 
-
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, const HW_OCCLUSIONQUERY flag = HWOCCLUSIONQUERY_FLUSH ); 
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
 //----------------------------------------------------------------------
 // Protected members
@@ -107,14 +99,10 @@
 protected:
 
-	bool pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, 
-						     const DWORD queryFlag );
-
-	unsigned int		m_uintPixelCount;		
-	IDirect3DQuery9*	m_pD3DQuery;
-	IDirect3DDevice9*   m_pD3DDevice;       // d3d device
-	bool				m_bOcclusionQuery;
-	int					m_SkipCounter;		// m_SkipConter =  m_SkipConter % m_Skip; if ( m_SkipConter == 0 && m_uintPixelCount !=0 ) TestHWOcclusion else just return 
-	static int			m_Skip;				// This is shared by all instancies
-	bool				m_bHWOcclusionSupport;
+		unsigned int		mPixelCount;		
+		IDirect3DQuery9*	mpQuery;
+		IDirect3DDevice9*   mpDevice;
+		int					mSkipCounter;
+		int					mSkipInterval;
+		bool				mHasOcclusionSupport;
 };
 
Index: trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/src/OgreD3D9HardwareOcclusionQuery.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/src/OgreD3D9HardwareOcclusionQuery.cpp	(revision 97)
+++ trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/src/OgreD3D9HardwareOcclusionQuery.cpp	(revision 115)
@@ -29,6 +29,4 @@
 namespace Ogre {
 
-int D3D9HardwareOcclusionQuery::m_Skip = 0;
-
 /**
   * This is a class that is the DirectX9 implementation of 
@@ -36,30 +34,31 @@
   *
   * @author Lee Sandberg
+	*
+	* Updated on 12/7/2004 by Chris McGuirk
   */
 
 /**
   * Default object constructor
-  * 
   */
 D3D9HardwareOcclusionQuery::D3D9HardwareOcclusionQuery( IDirect3DDevice9* pD3DDevice ) 
 { 
-	m_pD3DDevice = pD3DDevice;
-	m_uintPixelCount = 0; 
-	m_SkipCounter = 0;
-	m_bHWOcclusionSupport = false;
+		mpDevice = pD3DDevice;
+		mPixelCount = 0; 
+		mSkipCounter = 0;
+		mSkipInterval = 0;
+		mHasOcclusionSupport = false;
 
-	HRESULT hr = m_pD3DDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &m_pD3DQuery);
+		// create the occlusion query
+		HRESULT hr = mpDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &mpQuery);
+
 	if ( hr != D3D_OK ) 
 	{
-		//OGRE_EXCEPT(hr, "D3D9HardwareOcclusionQuery couldn't create hardware occlusion query object.", 
-        //        "D3D9HardwareOcclusionQuery::D3D9HardwareOcclusionQuery");
-		m_bHWOcclusionSupport = false;
+			mHasOcclusionSupport = false;
 	}
 	else 
 	{
-		m_bHWOcclusionSupport = true;
+			mHasOcclusionSupport = true;
 	}
 }
-
 
 /**
@@ -68,8 +67,7 @@
 D3D9HardwareOcclusionQuery::~D3D9HardwareOcclusionQuery() 
 { 
-	SAFE_RELEASE( m_pD3DQuery ); 
+		SAFE_RELEASE(mpQuery); 
 }
 
-#ifndef GTP_VISIBILITY_MODIFIED_OGRE
 //------------------------------------------------------------------
 // Occlusion query functions (see base class documentation for this)
@@ -77,61 +75,45 @@
 void D3D9HardwareOcclusionQuery::beginOcclusionQuery() 
 { 
-	if( m_bHWOcclusionSupport )		// Make it fail silently if hardware occlusion isn't supported
+		// Make it fail silently if hardware occlusion isn't supported
+		if(mHasOcclusionSupport)
 	{
-		if  ( m_SkipCounter ==  m_Skip ) { m_SkipCounter = 0; };		// Counter starts at 0 again at m_Skip 
-		
-		if ( m_SkipCounter == 0 && m_uintPixelCount != 0 )	// New or none visable objects must allways be tested but visable objects can be skiped
+#ifndef GTP_VISIBILITY_MODIFIED_OGRE
+			// Counter starts at 0 again at mSkipInterval 
+			if(mSkipCounter == mSkipInterval) 
+#else
+			if (mSkipCounter >= mSkipInterval)  // otherwise no query ever issued if mSkipInterval = 0 !
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
 		{
-			m_pD3DQuery->Issue(D3DISSUE_BEGIN); 
+				mSkipCounter = 0; 
+}
+			//std::stringstream d; d << "count: " << mSkipCounter;
+			//LogManager::getSingleton().logMessage(d.str());
+			if (mSkipCounter == 0)
+		{
+				mpQuery->Issue(D3DISSUE_BEGIN); 
 		}
 	}
+	
 }
-	
-void D3D9HardwareOcclusionQuery::endOcclusionQuery() 
-{ 
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
+
+	void D3D9HardwareOcclusionQuery::endOcclusionQuery() 
 	{
-		if (m_SkipCounter == 0 && m_uintPixelCount != 0 ) // New or none visable objects must allways be tested but visable objects can be skiped
-		{
-			m_pD3DQuery->Issue(D3DISSUE_END); 
-		}
-		m_SkipCounter++;								 // The skip counter is increased 
+		// Make it fail silently if hardware occlusion isn't supported
+		if(mHasOcclusionSupport)
+			{
+			if(mSkipCounter == 0)
+			{ 
+				mpQuery->Issue(D3DISSUE_END); 
+	}
+
+			// The skip counter is increased
+			mSkipCounter++; 
 	}
 }
 
 //------------------------------------------------------------------
-// This version of pullOcclusionQuery cases the DX9 API/Driver to flush all commands to the 3D card
-// to allow a fast result from the query, but at the cost of poorer batching of API calls to the card.
-// Note: OpenGL dosn't use this flag at all so the application running OpenGL won't display any different behaviour.
-//--
-bool D3D9HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments) 
-{
-	HRESULT hr;
-	
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
-	{
-		hr = m_pD3DQuery->GetData( NumOfFragments, sizeof( NumOfFragments ), D3DGETDATA_FLUSH );
-
-		if ( hr != S_OK ) 
-			{
-				return false; 
-			}
-			else 
-			{ 
-				m_uintPixelCount = *NumOfFragments; 
-				return true; 
-			}
-	}
-	else
-	{
-		m_uintPixelCount = 100000; // Fails quitlly if hardware occlusion is not supported - every object is visable
-		return true;
-	}
-}
-
-//------------------------------------------------------------------
-// This version of pullOcclusionQuery cases the DX9 API/Driver to not flush all commands to the 3D card
+	// This version of pullOcclusionQuery causes the DX9 API/Driver to not flush all commands to the 3D card
 // to allow a fast result from the query, but the batching of API calls to the card will be normal. 
-// But the query wont be processed until the card recives the query in the nexr batch.
+	// But the query wont be processed until the card recives the query in the next batch.
 // Note: OpenGL dosn't use this flag at all so the application running OpenGL won't display any different behaviour.
 //--
@@ -140,97 +122,52 @@
 	HRESULT hr;
 
-	// TO DO: USE lockOpts= D3D9Mappings::get(options); instead of RS_OCCLUSIONQUERY enum
+		// Make it fail silently if hardware occlusion isn't supported
+		if(mHasOcclusionSupport)
+	{
+			DWORD d3dFlags = (flag == HWOCCLUSIONQUERY_FLUSH) ? D3DGETDATA_FLUSH : 0;
+	
+			// run until success (http://www.gamedev.net/reference/programming/features/occlusionculling/page2.asp)
+			while(hr = mpQuery->GetData( NumOfFragments, sizeof( NumOfFragments ), d3dFlags) == S_FALSE);
 
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
-	{
-	
-		switch( flag )
-		{
-			case HWOCCLUSIONQUERY_FLUSH : 	
-				hr = m_pD3DQuery->GetData( NumOfFragments, sizeof( NumOfFragments ), D3DGETDATA_FLUSH );
-			break;
-
-			case HWOCCLUSIONQUERY_NOFLUSH :	
-				hr = m_pD3DQuery->GetData( NumOfFragments, sizeof( NumOfFragments ), 0 );
-			break;
-		};
-
-
-
-		if ( hr != S_OK ) 
-			{
-				return false; 
+			mPixelCount = *NumOfFragments;
 			}
 			else 
 			{ 
-				m_uintPixelCount = *NumOfFragments; 
-				return true; 
+			// fail silently if not supported, assume visible i suppose
+			mPixelCount = 100000;
 			}
-	}
-	else 
-	{
-		m_uintPixelCount = 100000; // Fails quitlly if hardware occlusion is not supported - every object is visable
+
 		return true;
 	}
-}
-#else // GTP_VISIBILITY_MODIFIED_OGRE
+
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 //------------------------------------------------------------------
-void D3D9HardwareOcclusionQuery::beginOcclusionQuery() 
-{ 
-	if( m_bHWOcclusionSupport )		// Make it fail silently if hardware occlusion isn't supported
+	bool D3D9HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, 
+													     const HW_OCCLUSIONQUERY flag ) 
 	{
-		m_pD3DQuery->Issue(D3DISSUE_BEGIN); 
+		HRESULT hr = S_OK;
+		DWORD queryFlag = (flag == HWOCCLUSIONQUERY_FLUSH) ? D3DGETDATA_FLUSH : 0;
+
+		if (mHasOcclusionSupport)	// In case hardware occlusion isn't supported
+		{	
+			do
+			{
+				hr = mpQuery->GetData(NumOfFragments, sizeof(NumOfFragments), queryFlag);
+	    	}
+			while(waitForResult && (hr == S_FALSE));
+		
+			mPixelCount = *NumOfFragments;
+		}
+		else
+		{
+			mPixelCount = 100000; // every object is visible
+		}
+	
+		return hr == S_OK;
 	}
-}
-//------------------------------------------------------------------
-void D3D9HardwareOcclusionQuery::endOcclusionQuery() 
-{ 
-	if( m_bHWOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
-	{
-		m_pD3DQuery->Issue(D3DISSUE_END); 
-	}
-}
-//------------------------------------------------------------------
-bool D3D9HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult ) 
-{
-	return pullOcclusionQuery(NumOfFragments, waitForResult, HWOCCLUSIONQUERY_FLUSH);
-}
-
-//------------------------------------------------------------------
-bool D3D9HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, 
-												     const HW_OCCLUSIONQUERY flag  ) 
-{
-	DWORD queryFlag = flag == HWOCCLUSIONQUERY_FLUSH ? D3DGETDATA_FLUSH : 0;
-	// TO DO: USE lockOpts= D3D9Mappings::get(options); instead of RS_OCCLUSIONQUERY enum
-
-	return pullOcclusionQuery(NumOfFragments, waitForResult, queryFlag);
-}
-
-//------------------------------------------------------------------
-bool D3D9HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments, const bool waitForResult, 
-												     const DWORD queryFlag ) 
-{
-	HRESULT hr = S_OK;
-
-	if( m_bHWOcclusionSupport )	// In case hardware occlusion isn't supported
-	{	
-		do
-		{
-			hr = m_pD3DQuery->GetData( NumOfFragments, sizeof( NumOfFragments ), queryFlag );
-	    	}
-		while(waitForResult && (hr == S_FALSE));
-		
-		m_uintPixelCount = *NumOfFragments; 
-	}
-	else
-	{
-		m_uintPixelCount = 100000; // every object is visible
-	}
-	
-	return hr == S_OK;
-}
 
 
 #endif // GTP_VISIBILITY_MODIFIED_OGRE
 
-} // namespace OGre
+
+}
