source: OGRE/trunk/ogrenew/PlugIns/OctreeSceneManager/include/OgreTerrainSceneManager.h @ 692

Revision 692, 18.2 KB checked in by mattausch, 19 years ago (diff)

adding ogre 1.2 and dependencies

Line 
1/*
2-----------------------------------------------------------------------------
3This source file is part of OGRE
4(Object-oriented Graphics Rendering Engine)
5For the latest info, see http://www.ogre3d.org/
6
7Copyright (c) 2000-2005 The OGRE Team
8Also see acknowledgements in Readme.html
9
10This program is free software; you can redistribute it and/or modify it under
11the terms of the GNU Lesser General Public License as published by the Free Software
12Foundation; either version 2 of the License, or (at your option) any later
13version.
14
15This program is distributed in the hope that it will be useful, but WITHOUT
16ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
18
19You should have received a copy of the GNU Lesser General Public License along with
20this program; if not, write to the Free Software Foundation, Inc., 59 Temple
21Place - Suite 330, Boston, MA 02111-1307, USA, or go to
22http://www.gnu.org/copyleft/lesser.txt.
23-----------------------------------------------------------------------------
24*/
25/***************************************************************************
26terrainscenemanager.h  -  description
27---------------------
28  begin                : Mon Sep 23 2002
29  copyright            : (C) 2002 by Jon Anderson
30  email                : janders@users.sf.net
31
32  Enhancements 2003 - 2004 (C) The OGRE Team
33
34***************************************************************************/
35
36#ifndef TERRAINSCENEMANAGER_H
37#define TERRAINSCENEMANAGER_H
38
39#include "OgreTerrainPrerequisites.h"
40#include "OgreOctreeSceneManager.h"
41#include "OgreOctreeSceneQuery.h"
42#include "OgreTerrainRenderable.h"
43#include "OgreTerrainPageSource.h"
44#include "OgreIteratorWrappers.h"
45
46
47namespace Ogre
48{
49
50class Image;
51
52typedef std::vector < TerrainPage * > TerrainPageRow;
53typedef std::vector < TerrainPageRow > TerrainPage2D;
54
55/** Default implementation of RaySceneQuery. */
56class _OgreTerrainExport TerrainRaySceneQuery : public OctreeRaySceneQuery
57{
58protected:
59        WorldFragment mWorldFrag;
60public:
61    TerrainRaySceneQuery(SceneManager* creator);
62    ~TerrainRaySceneQuery();
63
64    /** See RayScenQuery. */
65    void execute(RaySceneQueryListener* listener);
66};
67
68
69
70/** This is a basic SceneManager for organizing TerrainRenderables into a total landscape.
71  * It loads a terrain from a .cfg file that specifices what textures/scale/mipmaps/etc to use.
72  *@author Jon Anderson
73  */
74
75class _OgreTerrainExport TerrainSceneManager : public OctreeSceneManager
76{
77public:
78    TerrainSceneManager(const String& name);
79    virtual ~TerrainSceneManager( );
80
81        /// @copydoc SceneManager::getTypeName
82        const String& getTypeName(void) const;
83
84    /** Loads the terrain using parameters int he given config file. */
85    void setWorldGeometry( const String& filename );
86    /** Loads the terrain using parameters in the given config file (contained
87                in a stream). */
88        virtual void setWorldGeometry(DataStreamPtr& stream,
89                const String& typeName = StringUtil::BLANK);
90
91    /** Aligns TerrainRenderable neighbors, and renders them. */
92    virtual void _renderVisibleObjects( void );
93
94    /** Returns the height at the given terrain coordinates. */
95    float getHeightAt( float x, float y );
96
97
98    bool intersectSegment( const Vector3 & start, const Vector3 & end, Vector3 * result );
99
100    /** Sets the texture to use for the main world texture. */
101    void setWorldTexture(const String& textureName);
102    /** Sets the texture to use for the detail texture. */
103    void setDetailTexture(const String& textureName);
104    /** Sets the number of times per tile the detail texture should be repeated. */
105    void setDetailTextureRepeat(int repeat);
106    /** Sets the dimensions of each tile (must be power of 2 + 1) */
107    void setTileSize(int size);
108    /** Sets the dimensions of each page (must be power of 2 + 1) */
109    void setPageSize(int size);
110    /** Sets the maximum screen space pixel error.  */
111    void setMaxPixelError(int pixelError);
112    /** Sets how to scale the terrain data. */
113    void setScale(const Vector3& scale);
114    /** Sets the maximum geomipmap level to allow. */
115    void setMaxGeoMipMapLevel(int maxMip);
116   
117    /** Gets the texture to use for the main world texture. */
118    const String& getWorldTexture(void) { return mWorldTextureName; }
119    /** Gets the texture to use for the detail texture. */
120    const String& getDetailTexture(void) { return mDetailTextureName; }
121    /** Gets the number of times per tile the detail texture should be repeated. */
122    int getDetailTextureRepeat(void);
123    /** Gets the dimensions of each tile (must be power of 2 + 1) */
124    int getTileSize(void);
125    /** Gets the dimensions of each page (must be power of 2 + 1) */
126    int getPageSize(void);
127    /** Gets the maximum screen space pixel error.  */
128    int getMaxPixelError(void);
129    /** Gets how to scale the terrain data. */
130    const Vector3& getScale(void);
131    /** Gets the maximum geomipmap level to allow. */
132    int getMaxGeoMipMapLevel(void);
133
134
135
136    /** Sets whether the terrain should use triangle strips or not.
137    @remarks
138        The default is not, in which case it uses triangle lists.
139    */
140    void setUseTriStrips(bool useStrips);
141    /** Sets whether or not terrain tiles should be morphed between LODs
142    (NB requires vertex program support). */
143    void setUseLODMorph(bool useMorph);
144    /** Sets whether vertex normals will be generated for the terrain. */
145    void setUseVertexNormals(bool useNormals);
146    /** Sets whether vertex colours will be used. */
147    void setUseVertexColours(bool useColours);
148
149    /** Sets the name of a custom material to use to shade the landcape.
150    @remarks
151        This method allows you to provide a custom material which will be
152        used to render the landscape instead of the standard internal
153        material. This gives you a great deal of flexibility and allows you
154        to perform special effects if you wish. Note that because you determine
155        every aspect of the material, this setting makes the use of setWorldTexture
156        and setDetailTexture redundant.
157    @par
158        In your custom material, you can use all the usual features of Ogre's
159        materials, including multiple passes if you wish. You can also use
160        the programmable pipeline to hook vertex and fragment programs into the
161        terrain rendering. The plugin provides the following vertex components:
162        <ul>
163            <li>positions</li>
164            <li>2 sets of texture coordinates (index 0 is world texture,
165            index 1 is detail texture)</li>
166            <li>Normals, if enabled</li>
167            <li>Per-vertex delta values, for morphing a higher LOD tile into
168                a lower LOD tile. This is one float per vertex bound as 'blend
169                weight'. If you want to use this you also have to provide the
170                name or index of the parameter you wish to receive the morph factor
171                (@see setCustomMaterialMorphFactorParam)</li>
172        </ul>
173    */
174    void setCustomMaterial(const String& materialName);
175    /** Sets the name of the vertex program parameter to which to pass the
176        LOD morph factor.
177    @remarks
178        When LOD morphing is enabled, and you are using a custom material to
179        shade the terrain, you need to inform this class of the parameter you
180        wish the current LOD morph factor to be passed to. This is a simple
181        float parameter value that the plugin will set from 0 to 1, depending on
182        the morph stage of a tile. 0 represents no morphing, ie the vertices are
183        all in the original position. 1 represents a complete morph such that
184        the height of the vertices is the same as they are at the next lower LOD
185        level. The vertex program must use this factor, in conjunction with the
186        per-vertex height delta values (bound as 'blend weight'), to displace
187        vertices.
188    @note This version of the method lets you specify a parameter name, compatible
189        with high-level vertex programs. There is an alternative signature method
190        which allows you to set the parameter index for low-level assembler programs.
191    @param paramName The name of the parameter which will receive the morph factor
192    */
193    void setCustomMaterialMorphFactorParam(const String& paramName);
194    /** Sets the index of the vertex program parameter to which to pass the
195        LOD morph factor.
196    @remarks
197        When LOD morphing is enabled, and you are using a custom material to
198        shade the terrain, you need to inform this class of the parameter you
199        wish the current LOD morph factor to be passed to. This is a simple
200        float parameter value that the plugin will set from 0 to 1, depending on
201        the morph stage of a tile. 0 represents no morphing, ie the vertices are
202        all in the original position. 1 represents a complete morph such that
203        the height of the vertices is the same as they are at the next lower LOD
204        level. The vertex program must use this factor, in conjunction with the
205        per-vertex height delta values (bound as 'blend weight'), to displace
206        vertices.
207    @note This version of the method lets you specify a parameter index, compatible
208        with low-level assembler vertex programs. There is an alternative signature method
209        which allows you to set the parameter name for high-level programs.
210    @param paramName The name of the parameter which will receive the morph factor
211    */
212    void setCustomMaterialMorphFactorParam(size_t paramIndex);
213    /** Sets the distance at which the LOD will start to morph downwards, as
214    a proportion of the distance between the LODs. */
215    void setLODMorphStart(Real morphStart);
216
217    /** Returns the TerrainRenderable that contains the given pt.
218        If no tile exists at the point, it returns 0;
219    */
220    virtual TerrainRenderable * getTerrainTile( const Vector3 & pt );
221
222    /** Returns the TerrainPage that contains the given pt.
223    If no page exists at the point, it returns 0;
224    */
225    virtual TerrainPage* getTerrainPage( const Vector3 & pt );
226
227    /** Creates a RaySceneQuery for this scene manager.
228    @remarks
229        This method creates a new instance of a query object for this scene manager,
230        looking for objects which fall along a ray. See SceneQuery and RaySceneQuery
231        for full details.
232    @par
233        The instance returned from this method must be destroyed by calling
234        SceneManager::destroyQuery when it is no longer required.
235    @param ray Details of the ray which describes the region for this query.
236    @param mask The query mask to apply to this query; can be used to filter out
237        certain objects; see SceneQuery for details.
238    */
239    RaySceneQuery*
240        createRayQuery(const Ray& ray, unsigned long mask = 0xFFFFFFFF);
241
242    /** Overridden in order to store the first camera created as the primary
243        one, for determining error metrics and the 'home' terrain page.
244    */
245    Camera* createCamera( const String &name );
246    /// Gets the terrain options
247    const TerrainOptions& getOptions(void) { return mOptions; }
248
249    /** Sets the given option for the SceneManager.
250    @remarks
251        Options are (in addition to those supported by superclasses):
252        "PageSize", int*;
253        "TileSize", int*;
254        "PrimaryCamera, Camera*;
255        "MaxMipMapLevel", int*;
256        "Scale", Vector3 *;
257        "MaxPixelError", int*;
258        "UseTriStrips", bool*;
259        "VertexProgramMorph", bool*;
260        "DetailTile", int*;
261        "LodMorphStart", Real*;
262        "VertexNormals", bool*;
263        "VertexColours", bool*;
264        "MorphLODFactorParamName", String*;
265        "MorphLODFactorParamIndex", size_t*;
266        "CustomMaterialName", String*;
267        "WorldTexture", String*;
268        "DetailTexture", String*;
269    */
270    virtual bool setOption( const String &, const void * );
271
272    /** Sets the 'primary' camera, i.e. the one which will be used to determine
273        the 'home' terrain page, and to calculate the error metrics.
274    */
275    virtual void setPrimaryCamera(const Camera* cam);
276    /// Internal map of page source name to page source
277    typedef std::map<String, TerrainPageSource*> PageSourceMap;
278
279    /// Iterator over all page sources
280    typedef ConstMapIterator<PageSourceMap> PageSourceIterator;
281    /// Get an iterator over all page sources
282    PageSourceIterator getPageSourceIterator(void);
283    /** Registers a TerrainPageSource class and associates it with a named type
284        of source.
285    @remarks
286        This function allows external classes to register themselves as providers
287        of terrain pages of a particular type. Only one page source can be
288        active at once, and the active one is selected by calling
289        selectPageSource(typeName), which is part of plugin configuration.
290    @note The terrain engine comes with a default page source which loads
291        greyscale heightmap images, registered under the type name "Heightmap".
292    @param typeName A unique String to associate with this type of source
293    @param source Pointer to the class which will implement this source.
294    */
295    virtual void registerPageSource(const String& typeName, TerrainPageSource* source);
296    /** Selects a given page source based on its type name.
297    @remarks
298        This method activates a single page source based on its typename,
299        e.g. "Heightmap". It also passes to it a number of custom options
300        which the source is able to interpret however it likes.
301    @param typeName The type name of the page source to activate
302    @param optionList A list of string parameters, which are expected to begin
303        with 'typeName.' (e.g. "Heightmap.image"), with their appropriate
304        values.
305    */
306    virtual void selectPageSource(const String& typeName,
307        TerrainPageSourceOptionList& optionList);
308
309    /** Attaches a previously built page to the list of available pages.
310    @remarks
311        TerrainPageSource subclasses will call this method once they have
312        pages available to be added to the working set. Note that whilst you
313        can build TerrainPage instances in another thread if you like, this
314        method must be called in the same thread as the main rendering loop
315        in order to avoid concurrency issues.
316    @param pageX, pageZ The page index at which to attach the page
317    @param page The page to attach
318    */
319    virtual void attachPage(ushort pageX, ushort pageZ, TerrainPage* page);
320    /// Get a pointer to the material being used for the terrain
321    MaterialPtr& getTerrainMaterial(void);
322    // Overridden from basic scene manager
323    void _renderScene(Camera *cam, Viewport *vp, bool includeOverlays);
324
325    /// Get the SceneNode under which all terrain nodes are attached.
326    SceneNode* getTerrainRootNode(void) const { return mTerrainRoot; }
327    /** Overridden from SceneManager */
328    void clearScene(void);
329        /** Overridden from SceneManager */
330        void setWorldGeometryRenderQueue(uint8 qid);
331
332        /// Get the shared list of indexes cached (internal use only)
333        TerrainBufferCache& _getIndexCache(void) {return mIndexCache;}
334
335        /// Get the shared level index list (internal use only)
336        LevelArray& _getLevelIndex(void) { return mLevelIndex; }
337
338        /// Get the current page count (internal use only)
339        size_t _getPageCount(void) { return mTerrainPages.size(); }
340
341        /// Shutdown cleanly before we get destroyed
342        void shutdown(void);
343
344
345protected:
346
347    /// Validates that the size picked for the terrain is acceptable
348    bool _checkSize( int s )
349    {
350        for ( int i = 0; i < 16; i++ )
351        {
352            printf( "Checking...%d\n", ( 1 << i ) + 1 );
353
354            if ( s == ( 1 << i ) + 1 )
355                return true;
356        }
357
358        return false;
359
360    }
361
362    /// The node to which all terrain tiles are attached
363    SceneNode * mTerrainRoot;
364    /// Terrain size, detail etc
365    TerrainOptions mOptions;
366    /// Should we use an externally-defined custom material?
367    bool mUseCustomMaterial;
368    /// The name of the custom material to use
369    String mCustomMaterialName;
370    /// The name of the world texture
371    String mWorldTextureName;
372    /// The name of the detail texture
373    String mDetailTextureName;
374    /// Are we using a named parameter to hook up LOD morph?
375    bool mUseNamedParameterLodMorph;
376    /// The name of the parameter to send the LOD morph to
377    String mLodMorphParamName;
378    /// The index of the parameter to send the LOD morph to
379    size_t mLodMorphParamIndex;
380    /// Whether paging is enabled, or whether a single page will be used
381    bool mPagingEnabled;
382    /// The number of pages to render outside the 'home' page
383    unsigned short mLivePageMargin;
384    /// The number of pages to keep loaded outside the 'home' page
385    unsigned short mBufferedPageMargin;
386    /// Grid of buffered pages
387    TerrainPage2D mTerrainPages;
388        //-- attributes to share across tiles
389        /// Shared list of index buffers
390        TerrainBufferCache mIndexCache;
391        /// Shared array of IndexData (reuse indexes across tiles)
392        LevelArray mLevelIndex;
393   
394    /// Internal method for loading configurations settings
395    void loadConfig(DataStreamPtr& stream);
396
397    /// Sets up the terrain material
398    void setupTerrainMaterial(void);
399    /// Sets up the terrain page slots
400    void setupTerrainPages(void);
401        /// Initialise level indexes
402        void initLevelIndexes(void);
403        /// Destroy level indexes
404        void destroyLevelIndexes(void);
405
406
407    /// Map of source type -> TerrainPageSource
408    PageSourceMap mPageSources;
409    /// The currently active page source
410    TerrainPageSource* mActivePageSource;
411
412};
413/// Factory for TerrainSceneManager
414class TerrainSceneManagerFactory : public SceneManagerFactory
415{
416protected:
417        typedef std::vector<TerrainPageSource*> TerrainPageSources;
418        TerrainPageSources mTerrainPageSources;
419        void initMetaData(void) const;
420public:
421        TerrainSceneManagerFactory();
422        ~TerrainSceneManagerFactory();
423        /// Factory type name
424        static const String FACTORY_TYPE_NAME;
425        SceneManager* createInstance(const String& instanceName);
426        void destroyInstance(SceneManager* instance);
427};
428
429}
430
431#endif
Note: See TracBrowser for help on using the repository browser.