source: GTP/trunk/App/Demos/Geom/Demo_LodTrees/main.cpp @ 1529

Revision 1529, 10.9 KB checked in by gumbau, 18 years ago (diff)

Demos upgraded to the new programming interface

Line 
1/*      ==========================================================================
2 *      (C) 2006 Universitat Jaume I
3 *      ==========================================================================
4 *      PROYECT:        GAME TOOLS
5 *      ==========================================================================*/
6/**     CONTENT:       
7        *
8        *
9        *       @file   main.cpp
10/** COMMENTS:
11        * Model must be in "media/models" folder.
12        * Lod file must be in "media/GT" folder.
13/*===========================================================================*/
14#include "ExampleApplication.h"
15#include "GeoLodTreeLibrary.h"
16#include "GeoMeshLoader.h"
17
18
19// Distance values
20#define dist_min 300
21#define dist_max 700
22
23// Model name
24#define model_name "arbol"
25
26
27//Global variables
28Entity* entity;
29Geometry::LodTreeLibrary* myTrees;
30Ogre::Mesh *ogreMesh=NULL;
31Geometry::GeoMeshLoader *meshloader=NULL;
32bool force_maxLODfactor = false;
33
34Ogre::Vector3 forest_center;
35
36ColourValue color=ColourValue::Red;
37
38Camera* theCam;
39Entity* pPlaneEnt;
40
41OverlayElement* mInfo;
42OverlayElement* mInfo2;
43
44
45/*void DumpDataToOgreBuffers(Ogre::Mesh *original_mesh, Geometry::LodTreeLibrary *lodTreesLib)
46{
47        // Copy to Ogre buffers including the degenerated triangles
48        Ogre::HardwareIndexBufferSharedPtr      ibuf;
49        Ogre::IndexData *indexes;
50        Ogre::RenderOperation mRenderOp;
51
52        for (int submesh=0; submesh < original_mesh->getNumSubMeshes(); submesh++)
53        {
54                bool istrunk = lodTreesLib->GetLeavesSubMesh()!=submesh;
55                original_mesh->getSubMesh(submesh)->_getRenderOperation(mRenderOp,0);
56
57                // we will suppose this submesh is the foliage
58                int indices_to_render = lodTreesLib->CurrentLOD_Foliage_IndexCount();           
59                int offset = 0;
60
61                if (istrunk)
62                {
63                        // this submesh is the trunk
64                        offset = lodTreesLib->GetValidTrunkOffset(submesh);
65                        indices_to_render = lodTreesLib->GetValidTrunkIndexCount(submesh);
66                }
67
68                ibuf = mRenderOp.indexData->indexBuffer;
69                mRenderOp.indexData->indexStart = 0;
70                mRenderOp.indexData->indexCount = indices_to_render;           
71
72                unsigned long* pIdx = static_cast<unsigned long*>(ibuf->lock(Ogre::HardwareBuffer::HBL_NORMAL));
73
74                for (int k=0; k<indices_to_render; k++)
75                        if (istrunk)
76                                pIdx[k] = lodTreesLib->CurrentLOD_Trunk_Indices()->GetIndex(k+offset);
77                        else
78                                pIdx[k] = lodTreesLib->CurrentLOD_Foliage_Indices()->GetIndex(k);
79
80                       
81                ibuf->unlock();
82        }
83}*/
84
85class FresnelFrameListener : public ExampleFrameListener
86{
87        int manage;
88
89public:
90
91    FresnelFrameListener(RenderWindow* win, Camera* cam)
92        : ExampleFrameListener(win, cam, false, false)
93    {
94                manage=1;
95        }
96
97        bool frameStarted(const FrameEvent& evt)
98    {
99                Vector3 dist;
100                int distance=0,inc2=0,d;
101                unsigned int nlod,diflods;
102
103                // Move upto 80 units/second
104                Real MoveFactor = 180.0 * evt.timeSinceLastFrame;
105
106                // Copy the current state of the input devices
107                mInputDevice->capture();
108
109                // If this is the first frame, pick a speed
110                if (evt.timeSinceLastFrame == 0)
111                {
112                        mMoveScale = 1;
113                        mRotScale = 0.1;
114                }
115                // Otherwise scale movement units by time passed since last frame
116                else
117                {
118                        // Move about 100 units per second,
119                        mMoveScale = mMoveSpeed * evt.timeSinceLastFrame;
120                        // Take about 10 seconds for full rotation
121                        mRotScale = mRotateSpeed * evt.timeSinceLastFrame;
122                }
123
124                mRotX = 0;
125        mRotY = 0;
126            mTranslateVector = Vector3::ZERO;
127
128                //LOD selection
129                int difdist = dist_max - dist_min;
130       
131                int i=0;
132
133                dist = forest_center - mCamera->getPosition();
134                distance =dist.length();
135
136                float lodfactor = (float)(distance - dist_min) / (float)(dist_max - dist_min);
137                lodfactor = 1.0f - lodfactor;
138
139                if (lodfactor<0.0f)
140                        lodfactor=0.0f;
141                if (lodfactor>1.0f)
142                        lodfactor=1.0f;
143
144                if (force_maxLODfactor)
145                        lodfactor=1.0f;
146
147                static float lodfactorBefore = -1.0f;
148                if (fabsf(lodfactorBefore-lodfactor)>0.05f)
149                {
150                        myTrees->GoToLod(lodfactor);
151//                      DumpDataToOgreBuffers(ogreMesh,myTrees);
152                        lodfactorBefore=lodfactor;
153                }
154
155                // Move the node
156                if(mInputDevice->isKeyDown(Ogre::KC_UP))
157                  mTranslateVector.z = -mMoveScale;
158
159
160                if(mInputDevice->isKeyDown(Ogre::KC_DOWN))
161                  mTranslateVector.z = mMoveScale;
162
163                // Instead of moving the ship left and right, rotate it using yaw()
164                if(mInputDevice->isKeyDown(Ogre::KC_LEFT))
165                  mCamera->yaw(mRotScale);
166
167                force_maxLODfactor=mInputDevice->isKeyDown(Ogre::KC_F2);                 
168
169                if(mInputDevice->isKeyDown(Ogre::KC_RIGHT))
170                  mCamera->yaw(-mRotScale);
171
172                if(mInputDevice->isKeyDown(Ogre::KC_ESCAPE))
173                {
174                        //delete myTrees;
175                    return false;
176                }
177
178        if( mInputDevice->getMouseButton( 1 ) )
179        {
180            mTranslateVector.x += mInputDevice->getMouseRelativeX() * 0.13;
181            mTranslateVector.y -= mInputDevice->getMouseRelativeY() * 0.13;
182        }
183        else
184        {
185            mRotX = Degree(-mInputDevice->getMouseRelativeX() * 0.13);
186            mRotY = Degree(-mInputDevice->getMouseRelativeY() * 0.13);
187        }
188
189
190                char cadena[256];
191
192                               
193                sprintf(cadena,"Distance: %d",distance);
194               
195                mInfo->setCaption(cadena);
196
197                sprintf(cadena,"LOD factor: %f",lodfactor);
198
199                mInfo2->setCaption(cadena);
200
201                mCamera->yaw(mRotX);
202        mCamera->pitch(mRotY);
203        mCamera->moveRelative(mTranslateVector);
204
205                return true;
206    }
207};
208
209class CustomIndexData : public Geometry::IndexData
210{
211private:
212        Ogre::Mesh *targetMesh;
213        Ogre::HardwareIndexBufferSharedPtr ibuf;
214        Ogre::RenderOperation mRenderOp;
215        unsigned long* pIdx;
216public:
217        CustomIndexData(Ogre::Mesh *ogremesh):Geometry::IndexData(){
218                targetMesh=ogremesh;
219                pIdx=NULL;
220        }
221        virtual ~CustomIndexData(void){}
222
223        virtual void Begin(unsigned int submeshid, unsigned int indexcount){
224                targetMesh->getSubMesh(submeshid)->_getRenderOperation(mRenderOp,0);
225                ibuf = mRenderOp.indexData->indexBuffer;
226                mRenderOp.indexData->indexCount = indexcount;
227                pIdx = static_cast<unsigned long*>(ibuf->lock(Ogre::HardwareBuffer::HBL_NORMAL));
228        }
229        virtual void SetIndex(unsigned int i, unsigned int index){
230                pIdx[i] = index; //lodStripsLib->dataRetrievalInterface->GetIndex(k+offset);
231        }
232        virtual void End(){
233                ibuf->unlock();
234        }
235
236        virtual void BorrowIndexData(const Geometry::IndexData *){}
237};
238
239
240class FresnelApplication : public ExampleApplication
241{
242protected:
243public:
244    FresnelApplication()
245        {
246        }
247
248    ~FresnelApplication()
249    {
250    }
251protected:
252   
253
254
255    // Just override the mandatory create scene method
256    void createScene(void)
257    {
258//              mat = new MaterialPtr[1];
259               
260        theCam = mCamera;
261                theCam->setPosition(0,20,dist_min-40);
262        // Set ambient light
263        mSceneMgr->setAmbientLight(ColourValue(0.4, 0.4, 0.4));
264
265        // Create a directional light
266                Light* l = mSceneMgr->createLight("MainLight");
267                l->setType(Light::LT_DIRECTIONAL);
268        l->setDirection(0.0,-1.0,0.0);
269       
270        // Define a floor plane mesh
271                Plane plane( Vector3::UNIT_Y, 0 );
272
273                MeshManager::getSingleton().createPlane("ground",
274                        ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane,
275                        1500,1500,20,20,true,1,5,5,Vector3::UNIT_Z);
276
277                Entity* suelo = mSceneMgr->createEntity( "GroundEntity", "ground" );
278                mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(suelo);
279               
280
281                suelo->setMaterialName("Examples/GrassFloor");
282                suelo->setCastShadows(false);       
283
284       
285        mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox");
286
287        // My node to which all objects will be attached
288        SceneNode* myRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
289
290                std::string model_file=model_name;
291                model_file.append(".mesh");
292
293                //Models
294        entity = mSceneMgr->createEntity(model_name, "../../../OgreStuff/media/GT/ML12m.mesh");
295
296                ogreMesh = entity->getMesh().getPointer();
297
298                // load LOD info from the object
299                meshloader=new Geometry::GeoMeshLoader;
300                Geometry::Mesh *themesh = meshloader->load("../../../OgreStuff/media/GT/ML12m.mesh");
301
302                if (!meshloader->GetLodStripsData())
303            OGRE_EXCEPT(1, "The loaded mesh does not contain LOD info for the trunk","LOD Demo");
304                if (!meshloader->GetTreeSimpSeq())
305            OGRE_EXCEPT(1, "The loaded mesh does not contain LOD info for the foliage","LOD Demo");
306
307                myTrees = new Geometry::LodTreeLibrary( meshloader->GetLodStripsData(),
308                                                                                                meshloader->GetTreeSimpSeq(),
309                                                                                                themesh,
310                                                                                                new CustomIndexData(ogreMesh));
311
312                entity->setNormaliseNormals(true);
313
314                for (int submesh=0; submesh < ogreMesh->getNumSubMeshes(); submesh++)
315                {
316                        bool istrunk = myTrees->GetLeavesSubMesh()!=submesh;
317                        if (istrunk)
318                                entity->getSubEntity(submesh)->setMaterialName("Examples/Populifolia/trunk");
319                        else
320                                entity->getSubEntity(submesh)->setMaterialName("Examples/Populifolia/leaf");
321                }
322
323                forest_center=Ogre::Vector3(150.0f,0.0f,0.0f);
324                for (int i=1; i<8; i++) // 20
325                        for (int j=1; j<8; j++) // 20
326                        {
327                                char newTreeName[16]="";
328                                sprintf(newTreeName,"arbol_%d_%d",i,j);
329                                Ogre::SceneNode * auxnode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
330                                Ogre::Entity *auxent = entity->clone(newTreeName);
331                                auxnode->attachObject( auxent );
332                                auxnode->scale(4.0f,4.0f,4.0f);
333                                auxnode->rotate(Ogre::Vector3(0,0,1),Ogre::Degree(rand()%360));
334                                auxnode->rotate(Ogre::Vector3(1,0,0),Ogre::Radian(-3.14159f*0.5f),Ogre::Node::TS_WORLD);
335                                float randomsepx = (float)((rand()%18)-9);
336                                float randomsepy = (float)((rand()%12)-6);
337                                auxnode->translate(i*30.0f+randomsepx,0.0f,-j*30.0f-randomsepx);
338                                auxent->setNormaliseNormals(true);
339                        }
340
341                if (!meshloader->GetLodStripsData() || !meshloader->GetTreeSimpSeq())
342            OGRE_EXCEPT(1, "The loaded mesh does not contain any LOD info","LOD Demo");
343
344
345        // show overlay
346        Overlay* pOver = OverlayManager::getSingleton().getByName("Demo_LodStrips/Overlay");   
347        mInfo = OverlayManager::getSingleton().getOverlayElement("Demo_LodStrips/Info_1");
348                mInfo2 = OverlayManager::getSingleton().getOverlayElement("Demo_LodStrips/Info_2");
349            pOver->show();
350
351    }
352
353    void createFrameListener(void)
354    {
355        mFrameListener= new FresnelFrameListener(mWindow, mCamera);
356        mFrameListener->showDebugOverlay(true);
357        mRoot->addFrameListener(mFrameListener);
358    }
359
360};
361
362
363
364#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
365#define WIN32_LEAN_AND_MEAN
366#include "windows.h"
367#endif
368
369#ifdef __cplusplus
370extern "C" {
371#endif
372
373#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
374INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
375#else
376int main(int argc, char **argv)
377#endif
378{
379    // Create application object
380    FresnelApplication app;
381
382    try {
383        app.go();
384    } catch( Exception& e ) {
385#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
386        MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
387#else
388        std::cerr << "An exception has occured: " << e.getFullDescription();
389#endif
390    }
391
392
393    return 0;
394}
395
396#ifdef __cplusplus
397}
398#endif
Note: See TracBrowser for help on using the repository browser.