示例#1
0
int main( int argc, char **argv )
{

    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // construct the viewer.
    osgViewer::Viewer viewer;

    bool needToSetHomePosition = false;

    // read the scene from the list of file specified commandline args.
    osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);

    // if one hasn't been loaded create an earth and sun test model.
    if (!scene) 
    {
        scene = createScene(); 
        needToSetHomePosition = true;
    }
    
    // Create a DepthPartitionNode to manage partitioning of the scene
    osg::ref_ptr<DepthPartitionNode> dpn = new DepthPartitionNode;
    dpn->addChild(scene.get());
    dpn->setActive(true); // Control whether the node analyzes the scene
        
    // pass the loaded scene graph to the viewer.
    viewer.setSceneData(dpn.get());

    viewer.setCameraManipulator(new osgGA::TrackballManipulator);

    if (needToSetHomePosition)
    {
      viewer.getCameraManipulator()->setHomePosition(osg::Vec3d(0.0,-5.0*r_earth,0.0),osg::Vec3d(0.0,0.0,0.0),osg::Vec3d(0.0,0.0,1.0));
    }
    
    // depth partion node is only supports single window/single threaded at present.
    viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);

    return viewer.run();
}
	 int startup(){
		 _root = new Ogre::Root("plugins_d.cfg");
		 /*
		 if(!_root->showConfigDialog()){
			 return -1;
		 }
		 */

		 Ogre::RenderSystem* _rs = _root->getRenderSystemByName("Direct3D9 Rendering Subsystem");
		// or use "OpenGL Rendering Subsystem"
		_root->setRenderSystem(_rs);
		_rs->setConfigOption("Full Screen", "No");
		_rs->setConfigOption("Video Mode", "800 x 600 @ 32-bit colour");
		_rs->setConfigOption("FSAA", "0");
		_rs->setConfigOption("Floating-point mode", "Fastest");
		_rs->setConfigOption("Use Multihead", "Auto");
		_rs->setConfigOption("VSync", "No");
		_rs->setConfigOption("VSync Interval", "1");

		 Ogre::RenderWindow* window = _root->initialise(true, "Ventana Ogre");

		 _sceneManager =  _root->createSceneManager(Ogre::ST_GENERIC);

		 Ogre::Camera* camera = _sceneManager->createCamera("Camera");
		 camera->setPosition(Ogre::Vector3(0.0f,300.0f,-1000.0f));
		 camera->lookAt(Ogre::Vector3(0,0,0));
		 camera->setNearClipDistance(5);

		 Ogre::Viewport* viewport = window->addViewport(camera);
		 viewport->setBackgroundColour(Ogre::ColourValue(0.0,0.0,0.0));
		 camera->setAspectRatio(Ogre::Real(viewport->getActualWidth()/viewport->getActualHeight()));

		 _listener = new FrameListenerProyectos(window,camera);
		 _root->addFrameListener(_listener);

		 loadResources();
		 createScene();
		 _root->startRendering();

		 return 0;
	 }
//-------------------------------------------------------------------------------------
bool BaseApplication::setup(void)
{
    mRoot = new Ogre::Root(mPluginsCfg);

    setupResources();

    bool carryOn = configure();
    if (!carryOn) return false;

    chooseSceneManager();
    createCamera();
    createViewports();

    // Set default mipmap level (NB some APIs ignore this)
    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);

	//Need this for the loading bar?
	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Essential");

    // Create any resource listeners (for loading screens)  This could be helpful?
    createResourceListener();

    // Load resources
	//mTrayMgr should be initialized in the Frame Listener
	createFrameListener();
	std::string path = __FILE__; //gets the current cpp file's path with the cpp file
	path = path.substr(0,1+path.find_last_of('\\')); //removes filename to leave path
	path+= "\\Sounds\\YBPR_part1.wav"; //if txt file is in the same directory as cpp file
	PlaySound(path.c_str(), NULL, SND_FILENAME|SND_ASYNC);    //Intro song plays immediately
	
	//loader bar for loading
	mTrayMgr->showLoadingBar(1, 0); 
	loadResources();
	mTrayMgr->hideLoadingBar();

	createGUI();  //my guis  - make these before creating scene?
	// Create the scene
	createScene();

    return true;
};
示例#4
0
Application::Application(void)
{
	Globals::app = this;

	// We want to have our own custom log manager, so we create this (it will be made the singleton because it is the 
	// first log manager created) before we setup all of Ogre's facilities.
	Ogre::LogManager *default_log_manager = new Ogre::LogManager;
	default_log_manager->createLog(DEFAULT_LOG_FILE, true, true, false);

	// Setup all of Ogre's facilities.
	if (!setup())
	{
		return;
	}

	// Create the scene.
	createScene();

	Kyanite::AudioManager *newAudioManager = new Kyanite::AudioManager;
	newAudioManager->createBufferGroup("TestBufferGroup");
}
//-----------------------------------------------------------------------
OgreControlComponent::OgreControlComponent(wxWindow* parent, 
	wxWindowID id,
	const wxPoint& pos,
	const wxSize& size,
	long style,
	const wxValidator& val,
	const wxString& name) : 
	wxOgreControl(parent, id, pos, size, style, val, name),
	mSceneManager(0),
	mMainSceneNode(0),
	mCurrentParticleSystem(0)
{
	// Although some signal-slot construction should be used here, this also works. It is less elegant.
//	Connect(wxEVT_MOTION, wxMouseEventHandler(OgreControlComponent::OnMouseMove));
//	Connect(wxEVT_ENTER_WINDOW, wxMouseEventHandler(OgreControlComponent::OnWindowEnter));
//	Connect(wxEVT_LEAVE_WINDOW, wxMouseEventHandler(OgreControlComponent::OnWindowLeave));
//	Connect(wxEVT_LEFT_DOWN, wxMouseEventHandler(OgreControlComponent::OnMouseLButtonPressed));
//	Connect(wxEVT_RIGHT_DOWN, wxMouseEventHandler(OgreControlComponent::OnMouseRButtonPressed));
	Connect(wxEVT_DESTROY, wxCommandEventHandler(OgreControlComponent::OnClose));
	createScene();
}
示例#6
0
int main(int argc, char **argv)
{
     
    //Timer begin
    std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
    std::cout << "Rendering.";
    createScene();
    std::cout << ".";
    std::cout << ".";
    calcRays();
    std::cout << "Done" << std::endl << std::endl;
    camera->renderImage();

    //Timer end
    std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::seconds>( t2 - t1 ).count();

    std::cout << "Duration in seconds:" << duration << std::endl << std::endl << std::endl;
    
    return 0;
}
示例#7
0
SampleWindow::SampleWindow(Parameters& parameters)
#if USE_SDL
: SDLWindow(parameters) {
#else
: GLFWWindow(parameters) {
#endif
	m_camera->setPosition(Vec3(0.0f, 0.0f, -10.0f));
    createEffects();
    createScene();
}

SampleWindow::~SampleWindow() {
    destroyScene();
    destroyEffects();
}

void SampleWindow::createEffects() {
    m_visualEffects[0] = m_renderer->createVisualEffect("smooth.vert", "smooth.frag");
    m_visualEffects[1] = m_renderer->createVisualEffect("gouraud.vert", "gouraud.frag");
    m_visualEffects[2] = m_renderer->createVisualEffect("phong.vert", "phong.frag");
}
void OgreWidget::initOgreSystem()
{
    ogreRoot = new Ogre::Root();

    Ogre::RenderSystem *renderSystem = ogreRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
    ogreRoot->setRenderSystem(renderSystem);
    ogreRoot->initialise(false);

    ogreSceneManager = ogreRoot->createSceneManager(Ogre::ST_GENERIC);

    Ogre::NameValuePairList viewConfig;
    Ogre::String widgetHandle;
#ifdef Q_WS_WIN
    widgetHandle = Ogre::StringConverter::toString((size_t)((HWND)winId()));
#else
    QWidget *q_parent = dynamic_cast <QWidget *> (parent());
    QX11Info xInfo = x11Info();

    widgetHandle = Ogre::StringConverter::toString ((unsigned long)xInfo.display()) +
        ":" + Ogre::StringConverter::toString ((unsigned int)xInfo.screen()) +
        ":" + Ogre::StringConverter::toString ((unsigned long)q_parent->winId());

#endif
    viewConfig["externalWindowHandle"] = widgetHandle;
    ogreRenderWindow = ogreRoot->createRenderWindow("Ogre rendering window",
                width(), height(), false, &viewConfig);

    ogreCamera = ogreSceneManager->createCamera("myCamera");
    Ogre::Vector3 camPos(0, 50,150);
        ogreCamera->setPosition(camPos);
        ogreCamera->lookAt(0,50,0);
    emit cameraPositionChanged(camPos);

    ogreViewport = ogreRenderWindow->addViewport(ogreCamera);
    ogreViewport->setBackgroundColour(Ogre::ColourValue(0,0,255));
    ogreCamera->setAspectRatio(Ogre::Real(width()) / Ogre::Real(height()));

        setupNLoadResources();
        createScene();
}
示例#9
0
	void BaseManager::registerWindow(HWND _hWnd, HGE* _mpHGE, bool _isWindowed) {
		hWnd = _hWnd;
		mpHGE = _mpHGE;

#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32

		char buf[MAX_PATH];
		::GetModuleFileNameA(0, (LPCH)&buf, MAX_PATH);

		HINSTANCE instance = ::GetModuleHandleA(buf);

		HICON hIcon = ::LoadIcon(instance, MAKEINTRESOURCE(1001));
		if (hIcon)
		{
			::SendMessageA((HWND)hWnd, WM_SETICON, 1, (LPARAM)hIcon);
			::SendMessageA((HWND)hWnd, WM_SETICON, 0, (LPARAM)hIcon);
		}
#endif

		hInstance = instance;

		RECT rect = { 0, 0, 0, 0 };
		GetClientRect(hWnd, &rect);
		int width = rect.right - rect.left;
		int height = rect.bottom - rect.top;

		windowAdjustSettings(hWnd, width, height, !_isWindowed);

		//createRender(width, height, _isWindowed);

		createGui();

		createInput((size_t)hWnd);

		createPointerManager((size_t)hWnd);

		createScene();

		_windowResized();
	}
void OgreApp::constructObject()
{
    if(! initializeRoot())
    {
        // user cancelled config, so leave
        return;
    }
    Ogre::LogManager::getSingletonPtr()->logMessage("+++ root configured");

    // initialize Root -- have it create a render window for us
    root->initialise(true);
    Ogre::LogManager::getSingletonPtr()->logMessage("+++ root initialized");
    // get a pointer to the auto-created window
    window = root->getAutoCreatedWindow();
    Ogre::LogManager::getSingletonPtr()->logMessage("+++ render window created");

    if(oisEnabled)
    {
        initializeOIS(window);
        Ogre::LogManager::getSingletonPtr()->logMessage("+++ OIS initialized");
        mouse->setEventCallback(this);
        keyboard->setEventCallback(this);
        mouse->setBuffered(true);
        keyboard->setBuffered(true);
    }


    createSceneManager();
    //Ogre::LogManager::getSingletonPtr()->logMessage("+++ scene manager created");
    setupResources();
    //Ogre::LogManager::getSingletonPtr()->logMessage("+++ resources setup");
    createScene();
    //Ogre::LogManager::getSingletonPtr()->logMessage("+++ scene created");
    createFrameListener();
    //Ogre::LogManager::getSingletonPtr()->logMessage("+++ frameListener created");
    // register our frame listener
    if(frameListener) root->addFrameListener(frameListener);
    //Ogre::LogManager::getSingletonPtr()->logMessage("+++ frameListener registered");

}
    virtual void initEvent()
    {
        vl::Log::notify(appletInfo());

        mSceneKdTree = new vl::SceneManagerActorKdTree;
        rendering()->as<vl::Rendering>()->sceneManagers()->push_back(mSceneKdTree.get());

        mText = new vl::Text;
        mText->setFont( vl::defFontManager()->acquireFont("/font/bitstream-vera/VeraMono.ttf", 10, false) );
        mText->setAlignment(vl::AlignHCenter | vl::AlignTop);
        mText->setViewportAlignment(vl::AlignHCenter | vl::AlignTop);
        mText->setColor(vl::white);
        mText->translate(0,-10,0);
        mTextActor = sceneManager()->tree()->addActor(mText.get(), new vl::Effect);
        mTextActor->effect()->shader()->enable(vl::EN_BLEND);

        mTestNumber = 0;
        mViewDepth  = -1;

        createScene();
        mText->setText( mText->text() + "\nPress left/right to change the test number\nPress up/down to change the visible tree level");
    }
示例#12
0
//---------------------------------------------------------------------------
bool BaseApplication::setup(void)
{
    mRoot = new Ogre::Root(mPluginsCfg);

    setupResources();

    bool carryOn = configure();
    if (!carryOn) return false;

    chooseSceneManager();
    createCamera();
    createViewports();

    // Set default mipmap level (NB some APIs ignore this)
    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);

    // Create any resource listeners (for loading screens)
    createResourceListener();
    // Load resources
    loadResources();

    // Create the scene
    createScene();

    createFrameListener();

    SDL_Init(SDL_INIT_EVERYTHING);
    Mix_OpenAudio(22050,MIX_DEFAULT_FORMAT,2,4096);
    music = Mix_LoadMUS("Music/0/bgm2.mp3");
    Mix_PlayMusic(music,-1);
    Mix_VolumeMusic(50);
    Mix_Volume(-1, 110);
          
    setupMainMenu();
    mStats = new Stats();
    mStopwatch = new Stopwatch();

    return true;
};
示例#13
0
void LightingApp::mainLoop() {
    inpController.reset(new InputController());
    inpController->setMouseSensetive(0.2f);
    inpController->setMoveSpeed(10.f);
    scenePtr.reset(createScene());
    inpController->setSceneToControll(scenePtr.get());

    currDrawTimeP = getAppRunDuration();
    prevDrawTimeP = currDrawTimeP;

    while (isAppRunning())
    {
        prevDrawTimeP = currDrawTimeP;
        currDrawTimeP = getAppRunDuration();
        inpController->process(currDrawTimeP - prevDrawTimeP);

        scenePtr->update();
        scenePtr->render();

        surfaceSwapBuffers();
    }
}
示例#14
0
int main( int argc,
         char * argv[] )
{
    btCollisionWorld* collisionWorld = initCollision();

    osg::ArgumentParser arguments( &argc, argv );
    MoveManipulator* mm = new MoveManipulator;
    osg::ref_ptr< osg::Group > root =(osg::Group*) createScene( collisionWorld, mm, arguments );

    osgViewer::Viewer viewer;
    viewer.setUpViewInWindow( 10, 30, 800, 600 );
    viewer.setCameraManipulator( new osgGA::TrackballManipulator() );
    viewer.addEventHandler( mm );

           osgbCollision::GLDebugDrawer* dbgDraw = new osgbCollision::GLDebugDrawer();
        dbgDraw->setDebugMode( ~btIDebugDraw::DBG_DrawText );
        collisionWorld->setDebugDrawer( dbgDraw );
        root->addChild( dbgDraw->getSceneGraph() );

    viewer.setSceneData( root.get() );



    bool lastColState = false;
    while( !viewer.done() )
    {
        collisionWorld->performDiscreteCollisionDetection();

        detectCollision( lastColState, collisionWorld );
          dbgDraw->BeginDraw();

        collisionWorld->debugDrawWorld();
            dbgDraw->EndDraw();
        viewer.frame();
    }

    return( 0 );
}
int main(int argc, char** argv)
{
	// create the model
	osg::Group* root = new osg::Group;
	root->addChild(createScene());
	root->addChild(createBackground());

	root->getOrCreateStateSet();

	osg::ArgumentParser arguments(&argc, argv);
	osgViewer::Viewer viewer(arguments);

	osgUtil::ShaderGenVisitor shaderGenVisitor;
	shaderGenVisitor.setRootStateSet(viewer.getCamera()->getStateSet());
	root->accept(shaderGenVisitor);

	//osgDB::writeNodeFile(*root,"geoemtry.osgt");

	// add model to viewer.
	viewer.setSceneData(root);

	return viewer.run();
}
示例#16
0
bool Game::frameRenderingQueued(const Ogre::FrameEvent &evt){

	if(mShutDownFlag)
		return false;

	if(mOnlineMode && mGCListener->isClosed())
		return false;

	mInput->capture();

	if(mGameRunning){

		if(!mSceneCreated){

			// Creates the scene.
			createScene();

			// Enables the player's inputs.
			mInput->addMouseMoveListener(mLocalPlayer);
			mInput->addKeyboardPressListener(mLocalPlayer);
			mInput->addKeyboardReleaseListener(mLocalPlayer);
			mInput->addSensorFusionListener(mLocalPlayer);

		}

		for(unsigned int i = 0; i < mPlayerList->size(); i++)
			(*mPlayerList)[i]->frameRenderingQueued(evt);

		mLocalMap->frameRenderingQueued(evt);
		mBombManager->frameRenderingQueued(evt);
		mWorld->stepSimulation(evt.timeSinceLastFrame);

	}

	return true;

}
示例#17
0
void Application::initialise()
{

	//m_root = new Ogre::Root( "ogre_plugins.txt", "ogre_configuration.txt", "ogre_log.txt" );
	m_root = new Ogre::Root();

	// Initialise display options.
	// It shows the ugly dialog at start-up, so if you don't want to see it, it's up to you 
	// to remove this line and initialise display options manually ( e.g. reading them from 
	// a text file ).
	bool configDialogUserContinue = m_root->showConfigDialog();
	if ( ! configDialogUserContinue )
	{
		throw std::exception( "User closed/canceled config dialog" );
	}

	// Create window with chosen display options.
	m_window = m_root->initialise( true, "Ogre Window" );

	m_sceneManager = m_root->createSceneManager( Ogre::ST_GENERIC );

	m_camera = m_sceneManager->createCamera( "DefaultCamera" );

	m_viewport = m_window->addViewport( m_camera );

	m_viewport->setBackgroundColour( Ogre::ColourValue( 0.5, 0.5, 1 ) );

	SimpleInputManager::initialise( m_window );

	loadResources();

	createScene();

	setupCEGUI();

	setupOverlay();
}
示例#18
0
void Module2900::updateScene() {
	if (!updateChild()) {
		switch (_sceneNum) {
		case 0:
			if (_moduleResult == (uint32)-1) {
				leaveModule((uint32)-1);
			} else {
				_teleporterModuleResult = _moduleResult;
				switch (getGlobalVar(V_TELEPORTER_WHICH)) {
				case 0:
					createScene(3, 4);
					break;
				case 1:
					createScene(2, 2);
					break;
				case 2:
					createScene(5, 2);
					break;
				case 3:
					createScene(4, 2);
					break;
				case 4:
					createScene(6, 2);
					break;
				case 5:
					createScene(1, 2);
					break;
				default:
					leaveModule(_moduleResult);
					break;
				}
			}
			break;
		case 1:
		case 2:
		case 3:
		case 4:
		case 5:
		case 6:
			leaveModule(_teleporterModuleResult);
			break;
		}
	}
}
示例#19
0
//---------------------------------------------------------------------------
bool BaseApplication::setup(void)
{
    mRoot = new Ogre::Root(mPluginsCfg);

    setupResources();

    bool carryOn = configure();
    if (!carryOn) return false;

	if(ARTOOLKITON){
		setupARToolkit();
	}

	setupPhysx();

	mBolasController = BolasController::getInstance();

    chooseSceneManager();
    createCamera();
    createViewports();

    // Set default mipmap level (NB some APIs ignore this)
    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);

    // Create any resource listeners (for loading screens)
    createResourceListener();
    // Load resources
    loadResources();

    // Create the scene
    createScene();

    createFrameListener();

    return true;
};
示例#20
0
	RenderBoxWrap::RenderBoxWrap(MyGUI::RenderBoxPtr _box) :
		mEntity(nullptr),
		mRttCam(nullptr),
		mCamNode(nullptr),
		mRotationSpeed(RENDER_BOX_AUTO_ROTATION_SPEED),
		mMouseRotation(false),
		mLeftPressed(false),
		mAutoRotation(false),
		mEntityState(nullptr),
		mScale(1.0f),
		mCurrentScale(1.0f),
		mUseScale(false),
		mNodeForSync(nullptr),
		mSceneManagerForSync(nullptr),
		mRenderBox(_box),
		mFrameAdvise(false)
	{
		createScene();
		mRenderBox->eventMouseDrag = newDelegate(this, &RenderBoxWrap::notifyMouseDrag);
		mRenderBox->eventMouseWheel = newDelegate(this, &RenderBoxWrap::notifyMouseWheel);
		mRenderBox->eventMouseButtonPressed = newDelegate(this, &RenderBoxWrap::notifyMouseButtonPressed);
		mRenderBox->eventMouseButtonReleased = newDelegate(this, &RenderBoxWrap::notifyMouseButtonReleased);
		mRenderBox->eventUpdateViewport = newDelegate(this, &RenderBoxWrap::notifyUpdateViewport);
	}
示例#21
0
int MyApp::start() {
  _root = new Ogre::Root();
  
  if(!_root->restoreConfig()) {
    _root->showConfigDialog();
    _root->saveConfig();
  }
  
  Ogre::RenderWindow* window = _root->initialise(true,"MyApp Example");
  _sceneManager = _root->createSceneManager(Ogre::ST_GENERIC);
  _sceneManager->setAmbientLight(Ogre::ColourValue(1, 1, 1));
  _sceneManager->addRenderQueueListener(new Ogre::OverlaySystem());
  
  Ogre::Camera* cam = _sceneManager->createCamera("MainCamera");
  cam->setPosition(Ogre::Vector3(5,20,20));
  cam->lookAt(Ogre::Vector3(0,0,0));
  cam->setNearClipDistance(5);
  cam->setFarClipDistance(10000);
  
  Ogre::Viewport* viewport = window->addViewport(cam);
  viewport->setBackgroundColour(Ogre::ColourValue(0.0,0.0,0.0));
  double width = viewport->getActualWidth();
  double height = viewport->getActualHeight();
  cam->setAspectRatio(width / height);
  
  loadResources();
  createScene();
  createOverlay();

  _framelistener = new MyFrameListener(window, cam, _overlayManager, 
				       _sceneManager);
  _root->addFrameListener(_framelistener);
  
  _root->startRendering();
  return 0;
}
示例#22
0
Module1600::Module1600(NeverhoodEngine *vm, Module *parentModule, int which)
	: Module(vm, parentModule) {

	if (which < 0)
		createScene(_vm->gameState().sceneNum, -1);
	else if (which == 1)
		createScene(4, 1);
	else if (which == 2)
		createScene(5, 0);
	else if (which == 3)
		createScene(6, 1);
	else if (which == 4)
		createScene(1, 0);
	else
		createScene(0, 0);

	_vm->_soundMan->addSoundList(0x1A008D8, kModule1600SoundList);
	_vm->_soundMan->setSoundListParams(kModule1600SoundList, true, 50, 600, 5, 150);
	_vm->_soundMan->playTwoSounds(0x1A008D8, 0x41861371, 0x43A2507F, 0);

}
示例#23
0
    //-------------------------------------------------------------------------
    //                                   i n i t
    //-------------------------------------------------------------------------
    int CApplication::init()
    {
        SIrrlichtCreationParameters cp;
        static SKeyMap keyMap[5];
        keyMap[0].Action = EKA_MOVE_FORWARD;
        keyMap[0].KeyCode = KEY_KEY_W;
        keyMap[1].Action = EKA_STRAFE_LEFT;
        keyMap[1].KeyCode = KEY_KEY_A;
        keyMap[2].Action = EKA_MOVE_BACKWARD;
        keyMap[2].KeyCode = KEY_KEY_S;
        keyMap[3].Action = EKA_STRAFE_RIGHT;
        keyMap[3].KeyCode = KEY_KEY_D;
        keyMap[4].Action = EKA_JUMP_UP;
        keyMap[4].KeyCode = KEY_SPACE;

        int result=0;
        stringc msg;


        // use null device for early file system access
        IrrlichtDevice* m_nullDevice = createDevice(EDT_NULL);
        IFileSystem* fileSystem = m_nullDevice->getFileSystem();

        m_currentDirectory = fileSystem->getWorkingDirectory();
        m_currentDirectory = fileSystem->flattenFilename(m_currentDirectory);
        if(m_argv)
        {
            m_appExecutable = m_argv[0];
        }
        else
        {
            m_appExecutable = "irrlicht.exe";
        }


        stringc appBaseName;
        appBaseName = fileSystem->getAbsolutePath(m_appExecutable);
        appBaseName = fileSystem->getFileBasename(appBaseName, false);

        //
        // create log writer
        //
        m_logName = appBaseName;
        m_logName += ".log";

        m_logFile = fileSystem->createAndWriteFile(m_logName);

        msg = "Created log file: ";
        msg += m_logName;
        logMessage(msg);

        //
        // configuration system
        //
        // locate the data directory - underneath our executable or outside of it.
        stringc temp("data/");
        if(!fileSystem->existFile(temp))
        {
            temp = "../data/";
            // todo - look for "data.zip"...
        }
        m_dataRoot = fileSystem->getAbsolutePath(temp);
        m_configName = m_dataRoot;
        m_configName += "/cfg/";
        m_configName += appBaseName;
        m_configName += ".xml";


        if(!fileSystem->existFile(m_configName))
        {
            // not in data/cfg or ../data/cfg so look in the working directory.
            m_configName = appBaseName;
            m_configName += ".xml";
            if(!fileSystem->existFile(m_configName))
            {
                return -1;
            }
        }

        // load the config file
        m_config = new CXMLConfig();
        if(!m_config->load(m_configName))
        {
            return -1;
        }

        // setup the device based on config settings
        stringc sdriver = m_config->getString("driver","video","EDT_OPENGL");
        cp.DriverType = EDT_OPENGL;
        if(sdriver == "EDT_DIRECT3D9")
            cp.DriverType = EDT_DIRECT3D9;        
        cp.WindowSize = m_config->getDimension("resolution","video",dimension2di(800, 600));
        cp.Bits = m_config->getInt("colordepth","video",32);
        cp.Fullscreen = m_config->getBool("fullscreen","video",false);
        cp.Vsync = m_config->getBool("vsync","video",true);
        cp.Stencilbuffer = m_config->getBool("stencilbuffer","video",false);
        cp.AntiAlias = m_config->getInt("antialias","video",0);
        cp.EventReceiver = this;
        cp.WindowId = 0;

        m_device =  createDeviceEx(cp);
        if(!m_device)
            return -1;

        m_fileSystem = m_device->getFileSystem();
        m_videoDriver = m_device->getVideoDriver();
        m_sceneManager = m_device->getSceneManager();
        m_gui = m_device->getGUIEnvironment();

        m_device->getCursorControl()->setVisible(m_config->getBool("HWCursorVisible","video",true));
        m_device->setWindowCaption(stringw(m_title).c_str());


        //
        // add configured file systems
        //
        if(_initFileSystems())
            return -1;

        //
        // set up the default font
        //        
        stringc fontFolder = "fnt/";
        stringc defFonts = fontFolder + "defaults.zip";
        if(m_fileSystem->existFile(defFonts.c_str()))
        {
            m_fileSystem->addZipFileArchive(defFonts.c_str());
            m_defaultFont = m_gui->getFont("tdeffont.xml");
            if(m_defaultFont)
            {
                m_defaultFont->grab();
                m_gui->getSkin()->setFont(m_defaultFont);
            }
            m_monoFont = m_gui->getFont("monospace.xml");
            if(m_monoFont)
            {
                m_monoFont->grab();
            }
        }

        m_world = m_sceneManager->createMetaTriangleSelector();

        // camera setup
        f32 rotateSpeed = m_config->getFloat("rotateSpeed","options",100.f);
        m_orgMoveSpeed = m_config->getFloat("moveSpeed","options",0.001f);
        f32 jumpSpeed = m_config->getFloat("jumpSpeed","options",0.05f);
        m_camera = m_sceneManager->addCameraSceneNodeFPS(0, rotateSpeed, m_orgMoveSpeed, -1,keyMap,5,true, jumpSpeed);

        vector3df v = m_config->getVector3("campos","options");
        m_camera->setPosition(v);

        v = m_config->getVector3("camtarget","options");
        m_camera->setTarget(v);

        bool collisionEnabled = m_config->getBool("collision","options");
        if(collisionEnabled)
        {
            vector3df gravity,ellipsoid;
            gravity = m_config->getVector3("gravity","options",vector3df(0,-0.1f,0));
            ellipsoid = m_config->getVector3("ellipsoid","options",vector3df(2,5,2));
            m_collisionResponse = m_sceneManager->createCollisionResponseAnimator(m_world,m_camera,
                ellipsoid, gravity);
            m_camera->addAnimator(m_collisionResponse);
        }
        
        // debug & help panels setup
        m_debugPanel = new gui::CGUITextPanel(m_gui, "debugPanel", rectf(0.25f,0.005f,0.75f,0.05f));
        m_debugPanel->addItem("Node: Pos(x,y,z) Hpr(x,y,z) Dir(x,y,z)", EGUIA_CENTER);
        m_debugPanel->addItem("Frame: Avg(0.0) Min(0.0) Max(0.0)", EGUIA_CENTER);
        m_debugPanel->setVisible(true);

        m_helpPanel = new gui::CGUITextPanel(m_gui, "helpPanel", rectf(0.005f,0.005f,0.245f,0.05f));
        m_helpPanel->addItem(" wasd - Movement");
        m_helpPanel->addItem("   F1 - Toggle Help");
        m_helpPanel->addItem("   F2 - Toggle Debug");

        createScene();

        return result;
    }
示例#24
0
void PauseState::enter ()
{
  _root = Ogre::Root::getSingletonPtr();
  createScene();
  _exitGame = false;
}
示例#25
0
文件: main.cpp 项目: KevinGuo0211/OSG
int main( int argc, char **argv )
{
	// use an ArgumentParser object to manage the program arguments.
 	osg::ArgumentParser arguments(&argc,argv);
// 
// 	// set up the usage document, in case we need to print out how to use this program.
// 	arguments.getApplicationUsage()->setDescription(arguments.getApplicationName() + " demonstrates the use of multiple render targets (MRT) with frame buffer objects (FBOs). A render to texture (RTT) camera is used to render to four textures using a single shader. The four textures are then combined to texture the viewed geometry.");
// 	arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] ...");
// 	arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information.");
// 	arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture.");
// 	arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture.");
// 	arguments.getApplicationUsage()->addCommandLineOption("--image","Render one of the targets to an image, then apply a post draw callback to modify it and use this image to update the final texture. Print some texture values when using HDR.");
// 	arguments.getApplicationUsage()->addCommandLineOption("--hdr","Use high dynamic range (HDR). Create floating point textures to render to.");

	// construct the viewer.
	osgViewer::Viewer viewer(arguments);
	osg::GraphicsContext::Traits *pTraits = new osg::GraphicsContext::Traits;
	pTraits->x = 100;
	pTraits->y = 100;
	pTraits->width = 1024;
	pTraits->height = 768;
	pTraits->windowName = "Hive Application";
	pTraits->windowDecoration = true;
	pTraits->doubleBuffer = true;
	osg::GraphicsContext* pGraphicsContext = osg::GraphicsContext::createGraphicsContext(pTraits);

	osg::Camera *pCamera = new osg::Camera;
	pCamera->setGraphicsContext(pGraphicsContext);
	pCamera->setViewport(new osg::Viewport(0, 0, pTraits->width, pTraits->height));
	pCamera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
	pCamera->setClearColor(osg::Vec4f(0.2f, 0.2f, 0.4f, 1.0f));
	pCamera->setProjectionMatrixAsPerspective(45, (float)pTraits->width/pTraits->height, 0.1, 100);
	viewer.setCamera(pCamera); 

	// if user request help write it out to cout.
	if (arguments.read("-h") || arguments.read("--help"))
	{
		arguments.getApplicationUsage()->write(std::cout);
		return 1;
	}

	unsigned tex_width = 512;
	unsigned tex_height = 512;
// 	while (arguments.read("--width", tex_width)) {}
// 	while (arguments.read("--height", tex_height)) {}

	bool useHDR = false;
//	while (arguments.read("--hdr")) { useHDR = true; }

	bool useImage = false;
//	while (arguments.read("--image")) { useImage = true; }

	bool useMultiSample = false;
//	while (arguments.read("--ms")) { useMultiSample = true; }

	osg::Group* subGraph = createRTTQuad(tex_width, tex_height, useHDR);

	osg::Group* rootNode = new osg::Group();
	rootNode->addChild(createScene(subGraph, tex_width, tex_height, useHDR, useImage, useMultiSample));

	// add model to the viewer.
	viewer.setSceneData( rootNode );

	return viewer.run();
}
示例#26
0
bool BasicWindow::go(void) {

	// 1. define the root object:
	
	mRoot = new Ogre::Root(mPluginsFileName);

	// 2. define the resources that ogre will use:

	Ogre::ConfigFile configFile;
	configFile.load(mResourcesFileName);
	Ogre::ConfigFile::SectionIterator sectionsIter = configFile.getSectionIterator();
	Ogre::ConfigFile::SettingsMultiMap::iterator settingsIter;
	Ogre::ConfigFile::SettingsMultiMap* settings;
	Ogre::String secName, typeName, archName;

	while(sectionsIter.hasMoreElements()) {
		secName  = sectionsIter.peekNextKey();
		settings = sectionsIter.getNext();
		for (settingsIter=settings->begin(); settingsIter!=settings->end(); ++settingsIter) {
			typeName = settingsIter->first;
			archName = settingsIter->second;
			Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
		}
	}

	// 3. choose and setup the render system:

	if (!(mRoot->restoreConfig() || mRoot->showConfigDialog())) {
		return false;
	}

	// 4. create the render window:

	mWindow = mRoot->initialise(true, "Testing");

	// 5. initialise the required resources:

	Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	// 6. setup scene:

	mSceneMgr = mRoot->createSceneManager("DefaultSceneManager");
	
	mCamera   = mSceneMgr->createCamera("mCamera");
	mCamera->setNearClipDistance(1);
	//mCamera->setFarClipDistance(10000);

	mCameraMan = new OgreBites::SdkCameraMan(mCamera);

	Ogre::Viewport* vp = mWindow->addViewport(mCamera);
	//vp->setBackgroundColour(Ogre::ColourValue(1, 1, 1));
	mCamera->setAspectRatio(Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));

	mCameraNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("cameraNode");
	mCameraNode->attachObject(mCamera);

	createGUI();
	createScene();

	// 7. setup 3rd party libraries and plugins:

	Utils::log("*** Initialising OIS ***");
	OIS::ParamList paramList;
	size_t windowHandle = 0;
	std::ostringstream windowHandleString;
	mWindow->getCustomAttribute("WINDOW", &windowHandle);
	windowHandleString << windowHandle;
	paramList.insert(std::make_pair(std::string("WINDOW"), windowHandleString.str()));

	mInputManager = OIS::InputManager::createInputSystem(paramList);
	mKeyboard     = static_cast<OIS::Keyboard*>(mInputManager->createInputObject(OIS::OISKeyboard, true));
	mMouse        = static_cast<OIS::Mouse*>(mInputManager->createInputObject(OIS::OISMouse, true));

	windowResized(mWindow);  //<- sets mouse clipping size

	// 8. add listeners and callbacks:

	Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);
	mRoot->addFrameListener(this);
	mMouse->setEventCallback(this);
	mKeyboard->setEventCallback(this);

	// 9. start the render loop

	mRoot->startRendering();

	return true;
}
示例#27
0
MStatus AbcImport::doIt(const MArgList & args)
{
    MStatus status;

    MArgParser argData(syntax(), args, &status);

    MString filename("");
    MString connectRootNodes("");
    MString filterString("");
    MString excludeFilterString("");

    MObject reparentObj = MObject::kNullObj;

    bool    swap = false;
    bool    createIfNotFound = false;
    bool    removeIfNoUpdate = false;

    bool    debugOn = false;

    if (argData.isFlagSet("help"))
    {
        MGlobal::displayInfo(usage);
        return status;
    }

    if (argData.isFlagSet("debug"))
        debugOn = true;

    if (argData.isFlagSet("reparent"))
    {
        MString parent("");
        MDagPath reparentDagPath;
        status = argData.getFlagArgument("reparent", 0, parent);
        if (status == MS::kSuccess
            && getDagPathByName(parent, reparentDagPath) == MS::kSuccess)
        {
            reparentObj = reparentDagPath.node();
        }
        else
        {
            MString theWarning = parent;
            theWarning += MString(" is not a valid DagPath");
            printWarning(theWarning);
        }
    }

    if (!argData.isFlagSet("connect") && argData.isFlagSet("mode"))
    {
        MString modeStr;
        argData.getFlagArgument("mode", 0, modeStr);
        if (modeStr == "replace")
            deleteCurrentSelection();
        else if (modeStr == "open")
        {
            MFileIO fileIo;
            fileIo.newFile(true);
        }
    }
    else if (argData.isFlagSet("connect"))
    {
        swap = true;
        argData.getFlagArgument("connect", 0, connectRootNodes);

        if (argData.isFlagSet("createIfNotFound"))
        {
            createIfNotFound = true;
        }

        if (argData.isFlagSet("removeIfNoUpdate"))
            removeIfNoUpdate = true;
    }

    if (argData.isFlagSet("filterObjects"))
    {
        argData.getFlagArgument("filterObjects", 0, filterString);
    }

    if (argData.isFlagSet("excludeFilterObjects"))
    {
        argData.getFlagArgument("excludeFilterObjects", 0, excludeFilterString);
    }

    // if the flag isn't specified we'll only do stuff marked with the Maya
    // meta data
    bool recreateColorSets = false;
    if (argData.isFlagSet("recreateAllColorSets"))
    {
        recreateColorSets = true;
    }

    status = argData.getCommandArgument(0, filename);
    MString abcNodeName;
    if (status == MS::kSuccess)
    {
        {
            MString fileRule, expandName;
            MString alembicFileRule = "alembicCache";
            MString alembicFilePath = "cache/alembic";

            MString queryFileRuleCmd;
            queryFileRuleCmd.format("workspace -q -fre \"^1s\"",
                alembicFileRule);
            MString queryFolderCmd;
            queryFolderCmd.format("workspace -en `workspace -q -fre \"^1s\"`",
                alembicFileRule);

            // query the file rule for alembic cache
            MGlobal::executeCommand(queryFileRuleCmd, fileRule);
            if (fileRule.length() > 0)
            {
                // we have alembic file rule, query the folder
                MGlobal::executeCommand(queryFolderCmd, expandName);
            }

            // resolve the expanded file rule
            if (expandName.length() == 0)
            {
                expandName = alembicFilePath;
            }

            // get the path to the alembic file rule
            MFileObject directory;
            directory.setRawFullName(expandName);
            MString directoryName = directory.resolvedFullName();

            // resolve the relative path
            MFileObject absoluteFile;
            absoluteFile.setRawFullName(filename);
			absoluteFile.setResolveMethod(MFileObject::kInputFile);
#if MAYA_API_VERSION < 201300
            if (absoluteFile.resolvedFullName() !=
                absoluteFile.expandedFullName())
            {
#else
            if (!MFileObject::isAbsolutePath(filename)) {
#endif
                // this is a relative path
                MString absoluteFileName = directoryName + "/" + filename;
                absoluteFile.setRawFullName(absoluteFileName);
                filename = absoluteFile.resolvedFullName();
            }
            else
            {
                filename = absoluteFile.resolvedFullName();
            }
        }

        MFileObject fileObj;
        status = fileObj.setRawFullName(filename);
        if (status == MS::kSuccess && fileObj.exists())
        {
            ArgData inputData(filename, debugOn, reparentObj,
                swap, connectRootNodes, createIfNotFound, removeIfNoUpdate,
                recreateColorSets, filterString, excludeFilterString);
            abcNodeName = createScene(inputData);

            if (inputData.mSequenceStartTime != inputData.mSequenceEndTime &&
                inputData.mSequenceStartTime != -DBL_MAX &&
                inputData.mSequenceEndTime != DBL_MAX)
            {
                if (argData.isFlagSet("fitTimeRange"))
                {
                    MTime sec(1.0, MTime::kSeconds);
                    setPlayback(
                        inputData.mSequenceStartTime * sec.as(MTime::uiUnit()),
                        inputData.mSequenceEndTime * sec.as(MTime::uiUnit()) );
                }

                if (argData.isFlagSet("setToStartFrame"))
                {
                    MTime sec(1.0, MTime::kSeconds);
                    MGlobal::viewFrame( inputData.mSequenceStartTime *
                        sec.as(MTime::uiUnit()) );
                }
            }
        }
        else
        {
            MString theError("In AbcImport::doIt(), ");
            theError += filename;
            theError += MString(" doesn't exist");
            printError(theError);
        }
    }

    MPxCommand::setResult(abcNodeName);

    return status;
}
示例#28
0
void Module2300::updateScene() {
	if (!updateChild()) {
		switch (_sceneNum) {
		case 0:
			if (_moduleResult == 1)
				createScene(1, 4);
			else
				leaveModule(0);
			break;
		case 1:
			if (_moduleResult == 1)
				createScene(0, 0);
			else if (_vm->isDemo())
				createScene(9999, 0);
			else if (_moduleResult == 2)
				createScene(2, 1);
			else if (_moduleResult == 3)
				createScene(1, 3);
			else if (_moduleResult == 4)
				createScene(3, 1);
			else if (_moduleResult == 5)
				leaveModule(3);
			else
				leaveModule(4);
			break;
		case 2:
			if (_moduleResult == 1)
				leaveModule(1);
			else
				createScene(1, 5);
			break;
		case 3:
			if (_moduleResult == 1)
				leaveModule(2);
			else
				createScene(1, 1);
			break;
		case 4:
			_vm->_soundMan->setTwoSoundsPlayFlag(false);
			createScene(1, 2);
			break;
		case 9999:
			createScene(1, -1);
			break;
		}
	} else {
		switch (_sceneNum) {
		case 1:
			if (_isWallBroken && navigationScene()->isWalkingForward() && navigationScene()->getNavigationIndex() == 4 &&
				navigationScene()->getFrameNumber() % 2) {
				_soundVolume++;
				_vm->_soundMan->setSoundVolume(0x90F0D1C3, _soundVolume);
			}
			if (navigationScene()->isWalkingForward() && navigationScene()->getNavigationIndex() == 0 &&
				navigationScene()->getFrameNumber() == 50) {
				_vm->_soundMan->playTwoSounds(0x1A214010, 0x48498E46, 0x50399F64, 0);
				_vm->_soundMan->setSoundVolume(0x48498E46, 70);
				_vm->_soundMan->setSoundVolume(0x50399F64, 70);
			}
			break;
		case 3:
			if (_isWallBroken && navigationScene()->isWalkingForward() && navigationScene()->getFrameNumber() % 2) {
				_soundVolume--;
				_vm->_soundMan->setSoundVolume(0x90F0D1C3, _soundVolume);
			}
			break;
		}
	}
}
示例#29
0
	PhysicsManager::PhysicsManager() :	mScene(0) 
	{
		initialize();
		createScene();
	}
示例#30
0
int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use node masks to create stereo images.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
    arguments.getApplicationUsage()->addCommandLineOption("-d <float>","Time delay in seconds between the display of successive image pairs when in auto advance mode.");
    arguments.getApplicationUsage()->addCommandLineOption("-a","Enter auto advance of image pairs on start up.");
    arguments.getApplicationUsage()->addCommandLineOption("-x <float>","Horizontal offset of left and right images.");
    arguments.getApplicationUsage()->addCommandLineOption("-y <float>","Vertical offset of left and right images.");
    arguments.getApplicationUsage()->addCommandLineOption("--disk","Keep images on disk");
    arguments.getApplicationUsage()->addCommandLineOption("-files <filename>","Load filenames from a file");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("--SingleThreaded","Select SingleThreaded threading model for viewer.");
    arguments.getApplicationUsage()->addCommandLineOption("--CullDrawThreadPerContext","Select CullDrawThreadPerContext threading model for viewer.");
    arguments.getApplicationUsage()->addCommandLineOption("--DrawThreadPerContext","Select DrawThreadPerContext threading model for viewer.");
    arguments.getApplicationUsage()->addCommandLineOption("--CullThreadPerCameraDrawThreadPerContext","Select CullThreadPerCameraDrawThreadPerContext threading model for viewer.");


    // construct the viewer.
    osgViewer::Viewer viewer(arguments);

    // register the handler to add keyboard and mouse handling.
    SlideEventHandler* seh = new SlideEventHandler();
    viewer.addEventHandler(seh);

    // read any time delay argument.
    float timeDelayBetweenSlides = 5.0f;
    while (arguments.read("-d",timeDelayBetweenSlides)) {}

    bool autoSteppingActive = false;
    while (arguments.read("-a")) autoSteppingActive = true;

    float offsetX=0.0f;
    while (arguments.read("-x",offsetX)) {}

    float offsetY=0.0f;
    while (arguments.read("-y",offsetY)) {}

    bool onDisk=false;
    while (arguments.read("--disk")) {
        onDisk=true;
    }

    std::string filename="";
    FileList fileList;
    // extract the filenames from the a file, one filename per line.
    while (arguments.read("-files",filename)) {
        osgDB::ifstream is(filename.c_str());
        if (is) {
            std::string line;
            while (std::getline(is,line,'\n')) fileList.push_back(line);
            is.close();
        }

    }

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    osgViewer::Viewer::ThreadingModel threading = osgViewer::Viewer::SingleThreaded;
    while (arguments.read("--SingleThreaded")) threading = osgViewer::Viewer::SingleThreaded;
    while (arguments.read("--CullDrawThreadPerContext")) threading = osgViewer::Viewer::CullDrawThreadPerContext;
    while (arguments.read("--DrawThreadPerContext")) threading = osgViewer::Viewer::DrawThreadPerContext;
    while (arguments.read("--CullThreadPerCameraDrawThreadPerContext")) threading = osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext;

    viewer.setThreadingModel(threading);

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    // extract the filenames from the arguments list.
    for(int pos=1; pos<arguments.argc(); ++pos)
    {
        if (arguments.isString(pos)) fileList.push_back(arguments[pos]);
    }

    if (fileList.empty())
    {
        fileList.push_back("Images/dog_left_eye.jpg");
        fileList.push_back("Images/dog_right_eye.jpg");
    }
    else if (fileList.size()<2)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    // now the windows have been realized we switch off the cursor to prevent it
    // distracting the people seeing the stereo images.
    double fovy, aspectRatio, zNear, zFar;
    viewer.getCamera()->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);

    float radius = 1.0f;
    float height = 2*radius*tan(osg::DegreesToRadians(fovy)*0.5f);
    float length = osg::PI*radius;  // half a cylinder.

    // use a texture matrix to control the placement of the image.
    osg::TexMat* texmatLeft = new osg::TexMat;
    osg::TexMat* texmatRight = new osg::TexMat;

    // creat the scene from the file list.
    osg::ref_ptr<osg::Switch> rootNode;
    if (!onDisk)  rootNode = createScene(fileList,texmatLeft,texmatRight,radius,height,length);
    else rootNode=new osg::Switch();

    //osgDB::writeNodeFile(*rootNode,"test.osg");



    viewer.getCamera()->setCullMask(0xffffffff);
    viewer.getCamera()->setCullMaskLeft(0x00000001);
    viewer.getCamera()->setCullMaskRight(0x00000002);

    // set up the use of stereo by default.
    osg::DisplaySettings::instance()->setStereo(true);

    if (osg::DisplaySettings::instance()->getStereoMode()==osg::DisplaySettings::ANAGLYPHIC)
    {
        rootNode->setStateSet(createColorToGreyscaleStateSet());
    }


    // set the scene to render
    viewer.setSceneData(rootNode.get());


    // create the windows and run the threads.
    viewer.realize();


    // switch off the cursor
    osgViewer::Viewer::Windows windows;
    viewer.getWindows(windows);
    for(osgViewer::Viewer::Windows::iterator itr = windows.begin();
            itr != windows.end();
            ++itr)
    {
        (*itr)->useCursor(false);
    }

    viewer.setFusionDistance(osgUtil::SceneView::USE_FUSION_DISTANCE_VALUE,radius);

    // set up the SlideEventHandler.
    if (onDisk) seh->set(fileList,rootNode.get(),offsetX,offsetY,texmatLeft,texmatRight,radius,height,length,timeDelayBetweenSlides,autoSteppingActive);
    else seh->set(rootNode.get(),offsetX,offsetY,texmatLeft,texmatRight,timeDelayBetweenSlides,autoSteppingActive);

    osg::Matrix homePosition;
    homePosition.makeLookAt(osg::Vec3(0.0f,0.0f,0.0f),osg::Vec3(0.0f,1.0f,0.0f),osg::Vec3(0.0f,0.0f,1.0f));

    while( !viewer.done() )
    {
        viewer.getCamera()->setViewMatrix(homePosition);

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    return 0;
}