Ejemplo n.º 1
0
//[NOTE] In addition to some Ogre setup, this function configures PagedGeometry in the scene.
void World::load()
{
	//-------------------------------------- LOAD TERRAIN --------------------------------------
	//Setup the fog up to 500 units away
	sceneMgr->setFog(FOG_LINEAR, viewport->getBackgroundColour(), 0, 100, 700);

	//Load the terrain
	sceneMgr->setWorldGeometry("terrain.cfg");

	//Start off with the camera at the center of the terrain
	camera->setPosition(700, 100, 700);
	
	//-------------------------------------- LOAD TREES --------------------------------------
	//Create and configure a new PagedGeometry instance for trees
	trees = new PagedGeometry(camera, 80);
	trees->addDetailLevel<BatchPage>(150, 50);
	trees->addDetailLevel<ImpostorPage>(500, 50);

	//Create a new TreeLoader2D object
	TreeLoader2D *treeLoader = new TreeLoader2D(trees, TBounds(0, 0, 1500, 1500));
	trees->setPageLoader(treeLoader);

	//Supply the height function to TreeLoader2D so it can calculate tree Y values
	HeightFunction::initialize(sceneMgr);
	treeLoader->setHeightFunction(&HeightFunction::getTerrainHeight);

	//Load a tree entity
	Entity *myTree = sceneMgr->createEntity("Tree", "tree2.mesh");

	//Randomly place 10,000 copies of the tree on the terrain
	Vector3 position = Vector3::ZERO;
	Radian yaw;
	Real scale;
	for (int i = 0; i < 10000; i++){
		yaw = Degree(Math::RangeRandom(0, 360));
		position.x = Math::RangeRandom(0, 1500);
		position.z = Math::RangeRandom(0, 1500);
		scale = Math::RangeRandom(0.5f, 0.6f);

		treeLoader->addTree(myTree, position, yaw, scale);
	}

	//-------------------------------------- LOAD BUSHES --------------------------------------
	//Create and configure a new PagedGeometry instance for bushes
	bushes = new PagedGeometry(camera, 50);
	bushes->addDetailLevel<BatchPage>(80, 50);

	//Create a new TreeLoader2D object for the bushes
	TreeLoader2D *bushLoader = new TreeLoader2D(bushes, TBounds(0, 0, 1500, 1500));
	bushes->setPageLoader(bushLoader);

	//Supply the height function to TreeLoader2D so it can calculate tree Y values
	HeightFunction::initialize(sceneMgr);
	bushLoader->setHeightFunction(&HeightFunction::getTerrainHeight);

	//Load a bush entity
	Entity *myBush = sceneMgr->createEntity("Bush", "Bush.mesh");

	//Randomly place 30,000 copies of the bush on the terrain
	for (int i = 0; i < 30000; i++){
		yaw = Degree(Math::RangeRandom(0, 360));
		position.x = Math::RangeRandom(0, 1500);
		position.z = Math::RangeRandom(0, 1500);
		scale = Math::RangeRandom(0.7f, 0.8f);

		bushLoader->addTree(myBush, position, yaw, scale);
	}
}
Ejemplo n.º 2
0
        void GraphicsManager::ApplySettingGroupImpl(ObjectSettingGroup* Group)
        {
            for( ObjectSettingSetContainer::SubSetIterator SubSetIt = Group->SubSetBegin() ; SubSetIt != Group->SubSetEnd() ; ++SubSetIt )
            {
                String CurrSettingValue;
                if( "RenderSystem" == (*SubSetIt)->GetName() ) {
                    Graphics::RenderSystem RenderSys = Graphics::RS_OpenGL2;
                    CurrSettingValue = (*SubSetIt)->GetSettingValue("Name");
                    if( GetShortenedRenderSystemName(Graphics::RS_DirectX9) == CurrSettingValue )
                        RenderSys = Graphics::RS_DirectX9;
                    else if( GetShortenedRenderSystemName(Graphics::RS_DirectX11) == CurrSettingValue )
                        RenderSys = Graphics::RS_DirectX11;
                    else if( GetShortenedRenderSystemName(Graphics::RS_OpenGL2) == CurrSettingValue )
                        RenderSys = Graphics::RS_OpenGL2;
                    else if( GetShortenedRenderSystemName(Graphics::RS_OpenGLES1) == CurrSettingValue )
                        RenderSys = Graphics::RS_OpenGLES1;
                    else if( GetShortenedRenderSystemName(Graphics::RS_OpenGLES2) == CurrSettingValue )
                        RenderSys = Graphics::RS_OpenGLES2;

                    this->CurrRenderSys = RenderSys;

                    if( !this->OgreBeenInitialized ) {
                        this->SetRenderSystem(this->CurrRenderSys,true);
                    }else{
                        /// @todo May want to make some other data member so that people can accurately get what is set now, instead of what will be set.
                        Entresol::GetSingletonPtr()->_Log("WARNING: Attempting to apply new RenderSystem settings after the GraphicsManager has been initialized.  "
                                                      "These Settings will be applied the next time settings are loaded during manager construction if current settings are saved.");
                    }
                }
                else if( "GameWindow" == (*SubSetIt)->GetName() )
                {
                    GameWindow* CurrWindow = NULL;
                    String WinCaption("Mezzanine Window");
                    Whole WinWidth = 800;
                    Whole WinHeight = 600;
                    Whole WinFlags = 0;

                    ObjectSettingSet* PropertiesSet = (*SubSetIt)->GetChildObjectSettingSet("GameWindowProperties");
                    if( PropertiesSet != NULL ) {
                        // Get the caption.
                        CurrSettingValue = PropertiesSet->GetSettingValue("Caption");
                        if(!CurrSettingValue.empty())
                            WinCaption = CurrSettingValue;
                        // Get the width.
                        CurrSettingValue = PropertiesSet->GetSettingValue("Width");
                        if(!CurrSettingValue.empty())
                            WinWidth = StringTools::ConvertToUInt32(CurrSettingValue);
                        // Get the height.
                        CurrSettingValue = PropertiesSet->GetSettingValue("Height");
                        if(!CurrSettingValue.empty())
                            WinHeight = StringTools::ConvertToUInt32(CurrSettingValue);
                        // Get fullscreen.
                        CurrSettingValue = PropertiesSet->GetSettingValue("Fullscreen");
                        if(!CurrSettingValue.empty()) {
                            if(StringTools::ConvertToBool(CurrSettingValue))
                                WinFlags = (WinFlags | GameWindow::WF_Fullscreen);
                        }
                        // Get hidden.
                        CurrSettingValue = PropertiesSet->GetSettingValue("Hidden");
                        if(!CurrSettingValue.empty()) {
                            if(StringTools::ConvertToBool(CurrSettingValue))
                                WinFlags = (WinFlags | GameWindow::WF_Hidden);
                        }
                        // Get vsync.
                        CurrSettingValue = PropertiesSet->GetSettingValue("Vsync");
                        if(!CurrSettingValue.empty()) {
                            if(StringTools::ConvertToBool(CurrSettingValue))
                                WinFlags = (WinFlags | GameWindow::WF_VsyncEnabled);
                        }
                        // Get resizable.
                        CurrSettingValue = PropertiesSet->GetSettingValue("Resizeable");
                        if(!CurrSettingValue.empty()) {
                            if(StringTools::ConvertToBool(CurrSettingValue))
                                WinFlags = (WinFlags | GameWindow::WF_Resizeable);
                        }
                        // Get maximized.
                        CurrSettingValue = PropertiesSet->GetSettingValue("Maximized");
                        if(!CurrSettingValue.empty()) {
                            if(StringTools::ConvertToBool(CurrSettingValue))
                                WinFlags = (WinFlags | GameWindow::WF_Maximized);
                        }
                        // Get borderless.
                        CurrSettingValue = PropertiesSet->GetSettingValue("Borderless");
                        if(!CurrSettingValue.empty()) {
                            if(StringTools::ConvertToBool(CurrSettingValue))
                                WinFlags = (WinFlags | GameWindow::WF_Borderless);
                        }
                        // Get the FSAA level
                        CurrSettingValue = PropertiesSet->GetSettingValue("FSAA");
                        if(!CurrSettingValue.empty()) {
                            switch( StringTools::ConvertToUInt32(CurrSettingValue) )
                            {
                                case 2:
                                    WinFlags = (WinFlags | GameWindow::WF_FSAA_2);
                                    break;
                                case 4:
                                    WinFlags = (WinFlags | GameWindow::WF_FSAA_4);
                                    break;
                                case 8:
                                    WinFlags = (WinFlags | GameWindow::WF_FSAA_8);
                                    break;
                                case 16:
                                    WinFlags = (WinFlags | GameWindow::WF_FSAA_16);
                                    break;
                            }
                        }
                        // Finally, construct the window.
                        CurrWindow = this->CreateGameWindow(WinCaption,WinWidth,WinHeight,WinFlags);
                    }
                    // Set up the viewports
                    ObjectSettingSet* ViewportsSet = (*SubSetIt)->GetChildObjectSettingSet("Viewports");
                    if( ViewportsSet != NULL && CurrWindow != NULL ) {
                        for( ObjectSettingSetContainer::SubSetIterator VPIt = ViewportsSet->SubSetBegin() ; VPIt != ViewportsSet->SubSetEnd() ; ++VPIt )
                        {
                            if( "Viewport" == (*VPIt)->GetName() ) {
                                Integer ZO = 0;
                                Vector2 Position(0,0);
                                Vector2 Size(1,1);

                                CurrSettingValue = (*VPIt)->GetSettingValue("ZOrder");
                                if( !CurrSettingValue.empty() ) {
                                    ZO = StringTools::ConvertToInteger( CurrSettingValue );
                                }

                                ObjectSettingSet* PositionSet = (*VPIt)->GetChildObjectSettingSet("Position");
                                if( PositionSet != NULL ) {
                                    ObjectSettingSet* PositionVector = PositionSet->GetChildObjectSettingSet("Vector2");

                                    CurrSettingValue = PositionVector->GetSettingValue("X");
                                    if( !CurrSettingValue.empty() ) {
                                        Position.X = StringTools::ConvertToReal( CurrSettingValue );
                                    }
                                    CurrSettingValue = PositionVector->GetSettingValue("Y");
                                    if( !CurrSettingValue.empty() ) {
                                        Position.Y = StringTools::ConvertToReal( CurrSettingValue );
                                    }
                                }

                                ObjectSettingSet* SizeSet = (*VPIt)->GetChildObjectSettingSet("Size");
                                if( SizeSet != NULL ) {
                                    ObjectSettingSet* SizeVector = SizeSet->GetChildObjectSettingSet("Vector2");

                                    CurrSettingValue = SizeVector->GetSettingValue("X");
                                    if( !CurrSettingValue.empty() ) {
                                        Size.X = StringTools::ConvertToReal( CurrSettingValue );
                                    }
                                    CurrSettingValue = SizeVector->GetSettingValue("Y");
                                    if( !CurrSettingValue.empty() ) {
                                        Size.Y = StringTools::ConvertToReal( CurrSettingValue );
                                    }
                                }

                                Viewport* CurrViewport = CurrWindow->CreateViewport(NULL,ZO);
                                CurrViewport->SetDimensions(Position,Size);
                            }// if - Viewport
                        }// for - Viewports
                    }// if - ViewportsSet
                }// if - RS || GameWindow
            }// for - SubSets
        }
Ejemplo n.º 3
0
void ChildWnd1::onCreate()
{
	// create the tabs
	m_tabs.create(8, 8, 400, 360);
	m_tabs.addTab("tab 1");
	m_tabs.addTab("tab 2");
	m_tabs.addTab("Buttons");
	m_tabs.addTab("Radio Buttons");
	m_tabs.addTab("Comboboxes");
	addComponent(&m_tabs);

	// create a simple push button
	m_button1.create(260, 40, "Button", 1);
	//m_button1.create(260, 40, 80, 60, "Button", 1);
	m_button1.setIcon(ResourceManager::inst()->loadImage("gears.png"), Button::NEAR_LEFT, 32,32);
	//m_button1.setFace(Button::UP, ResourceManager::inst()->loadImage("gears.png"));
	m_tabs.addComponent(&m_button1, 0);

	m_button2.create(40, 70, "Button2", 201);
	m_button2.disable();
	m_button3.create(40, 100, "Button3", 202);
	m_button3.repeatClickOnHold(true);
	m_button3.handleButtonDown(makeFunctor(*Application::inst(), &Application::onButtonDown));
	m_button4.create(40, 130, "Button4", 203, makeFunctor(*Application::inst(), &Application::onClick));
	m_button4.setFace(Button::UP, ResourceManager::inst()->loadImage("gears.png"));
	m_button4.setTextColor(Color(0.2f, 0.2f, 0.2f));
	m_button5.create(240, 130, "Button5", 203);
	m_button5.setFace(Button::UP, ResourceManager::inst()->loadImage("gears.png"));
	m_button5.setSize(100, 20);
	m_button5.setTextColor(Color(0.2f, 0.2f, 0.2f));
	//m_tabs.addComponent(&m_button1, 2);
	m_tabs.addComponent(&m_button2, 2);
	m_tabs.addComponent(&m_button3, 2);
	m_tabs.addComponent(&m_button4, 2);
	m_tabs.addComponent(&m_button5, 2);

	m_checkbox1.create(260, 70, "check here", 102);
	m_tabs.addComponent(&m_checkbox1, 0);

	m_label1.create(260, 90, "eò á !@#$%^&*()");
//	m_tabs.addComponent(&m_label1, 0);

	// create a group of radio buttons
	m_radio1.create(20, 20, "Radio Button 1", 2);
	m_radio2.create(20, 40, "Radio Button 2", 3);
	m_group.create(20, 20, 200, 80, "Radio group");
	m_group.addComponent(&m_radio1);
	m_group.addComponent(&m_radio2);
	m_tabs.addComponent(&m_group, 0);

	// create a slider (also an example of using a live
	// variable)
	m_slider.create(20, 120, 300, 4);
	m_slider.bindValue(&m_sliderPos);
	m_slider.setBounds(0, 10, 2, 20);
	m_tabs.addComponent(&m_slider, 0);

	// create a textbox
	m_textbox.create(230, 160, 130, 180, true, true);
	m_textbox.setText("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.");
	m_tabs.addComponent(&m_textbox, 0);
	
	m_listbox1.create(20, 140, 200, 200, ListBox::MULTI_SELECT_SINGLECLICK);
	m_listbox1.addItem("item 1");
	m_listbox1.addItem("disabled item 2");
	m_listbox1.addItem("item 3");
	m_listbox1.addItem("item 4");
	m_listbox1.addItem("item 5");
	for (size_t i=0; i<20; ++i)
		m_listbox1.addItem("item");
	m_listbox1.addItem("last item");
	m_listbox1.disableItem(1);
	int t1 = m_listbox1.getCurrentItem();
	m_listbox1.setCurrentItem(3);
	m_listbox1.selectItem(2, true);
	int t2 = m_listbox1.getCurrentItem();
	Console::print("%d %d\n", t1,t2);
	m_tabs.addComponent(&m_listbox1, 0);

	m_combobox1.create(230, 140, 80, 200);
	m_combobox1.addItem("item 1");
	m_combobox1.addItem("item 2");
	m_combobox1.addItem("item 3");
	m_combobox1.addItem("item 4");
	m_combobox1.disableItem(2);
	m_combobox1.setCurrentItem(1);
	/*m_combobox2.create(230, 120, 80, 200);
	m_combobox2.addItem("item 1");
	m_tabs.addComponent(&m_combobox2, 0);*/
	m_tabs.addComponent(&m_combobox1, 0);

	// create a test viewport
	Viewport vp;
	vp.setPerspectiveProj(0.1f, 100.0f, 45.0f);
	m_vp.create(40, 40, 300, 300, vp, makeFunctor(*Application::inst(), &Application::onRenderVp));
	m_tabs.addComponent(&m_vp, 1);

	// change the size of the window, so that the client area is large
	// enough to hold the contents
	setClientAreaSize(416, 410);
}
Ejemplo n.º 4
0
/** Update the state of the path build process. */
void PathBuildManager::UpdateState()
{
	Viewport *vp = GetViewport();

	if (this->state == PBS_IDLE || this->state == PBS_SINGLE) {
		DisableWorldAdditions();
		this->selected_arrow = INVALID_EDGE;
		this->selected_slope = this->state == PBS_IDLE ? TSL_INVALID : TSL_FLAT;
	}

	/* The tile cursor is controlled by the viewport if waiting for a voxel or earlier. */
	if (vp != nullptr && this->state > PBS_WAIT_VOXEL && this->state <= PBS_WAIT_BUY) {
		vp->tile_cursor.SetCursor(this->pos, CUR_TYPE_TILE);
	}

	/* See whether the PBS_WAIT_ARROW state can be left automatically. */
	if (this->state == PBS_WAIT_ARROW) {
		this->allowed_arrows = GetPathAttachPoints(this->pos);

		/* If a valid selection has been made, or if only one choice exists, take it. */
		if (this->selected_arrow != INVALID_EDGE && ((0x11 << this->selected_arrow) & this->allowed_arrows) != 0) {
			this->state = PBS_WAIT_SLOPE;
		} else if (this->allowed_arrows == (1 << EDGE_NE) || this->allowed_arrows == (0x10 << EDGE_NE)) {
			this->selected_arrow = EDGE_NE;
			this->state = PBS_WAIT_SLOPE;
		} else if (this->allowed_arrows == (1 << EDGE_NW) || this->allowed_arrows == (0x10 << EDGE_NW)) {
			this->selected_arrow = EDGE_NW;
			this->state = PBS_WAIT_SLOPE;
		} else if (this->allowed_arrows == (1 << EDGE_SE) || this->allowed_arrows == (0x10 << EDGE_SE)) {
			this->selected_arrow = EDGE_SE;
			this->state = PBS_WAIT_SLOPE;
		} else if (this->allowed_arrows == (1 << EDGE_SW) || this->allowed_arrows == (0x10 << EDGE_SW)) {
			this->selected_arrow = EDGE_SW;
			this->state = PBS_WAIT_SLOPE;
		}
	}

	/* Set the arrow cursor. Note that display is controlled later. */
	if (vp != nullptr) {
		if (this->state > PBS_WAIT_ARROW && this->state <= PBS_WAIT_BUY) {
			XYZPoint16 arrow_pos = this->ComputeArrowCursorPosition();
			vp->arrow_cursor.SetCursor(arrow_pos, (CursorType)(CUR_TYPE_ARROW_NE + this->selected_arrow));
		} else {
			vp->arrow_cursor.SetInvalid();
		}
	}

	/* See whether the PBS_WAIT_SLOPE state can be left automatically. */
	if (this->state == PBS_WAIT_SLOPE) {
		/* Compute allowed slopes. */
		XYZPoint16 arrow_pos = this->ComputeArrowCursorPosition();
		this->allowed_slopes = CanBuildPathFromEdge(arrow_pos, (TileEdge)((this->selected_arrow + 2) % 4));

		/* If a valid selection has been made, or if only one choice exists, take it. */
		if (this->selected_slope != TSL_INVALID && ((1 << this->selected_slope) & this->allowed_slopes) != 0) {
			this->state = PBS_WAIT_BUY;
		} else if (this->allowed_slopes == (1 << TSL_DOWN)) {
			this->selected_slope = TSL_DOWN;
			this->state = PBS_WAIT_BUY;
		} else if (this->allowed_slopes == (1 << TSL_FLAT)) {
			this->selected_slope = TSL_FLAT;
			this->state = PBS_WAIT_BUY;
		} else if (this->allowed_slopes == (1 << TSL_UP)) {
			this->selected_slope = TSL_UP;
			this->state = PBS_WAIT_BUY;
		}
	}

	/* Handle _additions display. */
	if (vp != nullptr) {
		if (this->state == PBS_SINGLE || this->state == PBS_WAIT_SLOPE) {
			_additions.Clear();
			vp->EnableWorldAdditions();
		} else if (this->state == PBS_WAIT_BUY) {
			_additions.Clear();

			this->ComputeWorldAdditions();
			vp->EnableWorldAdditions();
			vp->EnsureAdditionsAreVisible();
		} else {
			if (this->state != PBS_LONG_BUILD && this->state != PBS_LONG_BUY) vp->DisableWorldAdditions();
		}
	}

	NotifyChange(WC_PATH_BUILDER, ALL_WINDOWS_OF_TYPE, CHG_UPDATE_BUTTONS, 0);
}
void GroceryDashKeyEventHandler::handleKeyEvents(Game *game){


	// WE CAN QUERY INPUT TO SEE WHAT WAS PRESSED
	GameInput *input = game->getInput();

	// LET'S GET THE PLAYER'S PHYSICAL PROPERTIES, IN CASE WE WANT TO CHANGE THEM
	GameStateManager *gsm = game->getGSM();
	TopDownSprite *player = gsm->getSpriteManager()->getPlayer();
	b2Body *playerBody = game->getGSM()->getSpriteManager()->playerBody;
	PhysicalProperties *pp = player->getPhysicalProperties();
	Viewport *viewport = game->getGUI()->getViewport();
	GroceryDashDataLoader* dataLoader = dynamic_cast<GroceryDashDataLoader*>(game->getDataLoader());

	if (!gsm->isGameInProgress()){

		if (input->isKeyDownForFirstTime(ESC_KEY)){
			if (gsm->isAtInGameHelp() == true){
				gsm->goToPauseMenu();
			}
			else{
				if (gsm->isAtSettingsScreen() == true || gsm->isAtAboutScreen() == true || gsm->isAtAchievementsScreen() == true
					|| gsm->isAtHelpScreen() == true || gsm->isAtLevelSelect() == true || gsm->isAtStatsScreen() == true){
					gsm->goToMainMenu();
				}
			}
		}

	}//BRACKET -- !isGameInProgress

	if (gsm->isAtPauseMenu()){

		if (input->isKeyDownForFirstTime(R_KEY))
		{
			gsm->goToGame();
		}
	}



	if (gsm->isGameInProgress())
	{

		if (input->isKeyDownForFirstTime(P_KEY))
		{
			gsm->goToPauseMenu();
		}

		if (input->isKeyDownForFirstTime(L_KEY))
		{
			if ( gsm->isAtItemList() == false){
				gsm->goToItemList();
			}
			else{
				gsm->goToGame();
			}
		}

		if (input->isKeyDownForFirstTime(C_KEY))
		{
			if (gsm->isAtCartScreen() == false){
				gsm->goToCartScreen();
			}
			else{
				gsm->goToGame();
			}
		}

		if (input->isKeyDownForFirstTime(M_KEY)){
			runScript(game);
		}



		// ARROW KEYS PRESSES WILL CONTROL THE PLAYER

		// THE USER MOVES VIA MOUSE BUTTON PRESSES
		if (input->isKeyDown(MOVE_LEFT_CONTROL) && gsm->isPlayerControlDisabled() == false && dataLoader->getIsPayingCashier() == false)
		{
			player->clearPath();
			b2Vec2 moveLeft(-PLAYER_SPEED, 0.0f);
			playerBody->ApplyForceToCenter(moveLeft, true);
			playerBody->SetTransform(playerBody->GetPosition(), (1.0f * PI));
		}
		else if (input->isKeyDown(MOVE_RIGHT_CONTROL) && gsm->isPlayerControlDisabled() == false && dataLoader->getIsPayingCashier() == false)
		{
			player->clearPath();
			b2Vec2 moveRight(PLAYER_SPEED, 0.0f);
			playerBody->ApplyForceToCenter(moveRight, true);
			playerBody->SetTransform(playerBody->GetPosition(), (0.0f * PI));
		}
		else if (input->isKeyDown(MOVE_UP_CONTROL) && gsm->isPlayerControlDisabled() == false && dataLoader->getIsPayingCashier() == false)
		{
			player->clearPath();
			b2Vec2 moveUp(0.0f, -PLAYER_SPEED);
			playerBody->ApplyForceToCenter(moveUp, true);
			playerBody->SetTransform(playerBody->GetPosition(), (1.5f * PI));
			
		}
		else if (input->isKeyDown(MOVE_DOWN_CONTROL) && gsm->isPlayerControlDisabled() == false && dataLoader->getIsPayingCashier() == false)
		{
			player->clearPath();
			b2Vec2 moveDown(0.0f, PLAYER_SPEED);
			playerBody->ApplyForceToCenter(moveDown, true);
			playerBody->SetTransform(playerBody->GetPosition(), (0.5f * PI));
		}
		else if (input->isKeyDownForFirstTime(G_KEY))
		{
			viewport->toggleDebugView();
			game->getGraphics()->toggleDebugTextShouldBeRendered();
		}
		else if (input->isKeyDownForFirstTime(H_KEY))
		{
			game->getGraphics()->toggleB2DrawDebugShouldBeRendered();
		}
		else
		{
			b2Vec2 stay(0.0f, 0.0f);
			playerBody->ApplyForceToCenter(stay, false);
		}



		if (input->isKeyDownForFirstTime(ESC_KEY) && (gsm->isPlayerAtShelf() == true || gsm->isAtItemList() == true)){
			gsm->goToGame();
		}

		if (gsm->isPlayerAtShelf() == true){

			// LEAVE THE SHELF SCREEN without TAKING ANY ITEMS
			if (input->isKeyDownForFirstTime(ESC_KEY)){
				gsm->goToGame();
			}

			int isItemTaken = false;

			if (input->isKeyDownForFirstTime(NUM_1) ^ input->isKeyDownForFirstTime(NUMPAD_1)){
				isItemTaken = dataLoader->takeItemFromShelf(game, gsm->getGameStateShelfAsNumber(), 1);
				runScript_LookUpShelfItemInfo(game, gsm->getGameStateShelfAsNumber(), 1, isItemTaken);
				gsm->goToGame();
			}
			else{
				if (input->isKeyDownForFirstTime(NUM_2) ^ input->isKeyDownForFirstTime(NUMPAD_2)){
					isItemTaken = dataLoader->takeItemFromShelf(game, gsm->getGameStateShelfAsNumber(), 2);
					runScript_LookUpShelfItemInfo(game, gsm->getGameStateShelfAsNumber(), 2, isItemTaken);
					gsm->goToGame();
				}
				else{
					if (input->isKeyDownForFirstTime(NUM_3) ^ input->isKeyDownForFirstTime(NUMPAD_3)){
						isItemTaken = dataLoader->takeItemFromShelf(game, gsm->getGameStateShelfAsNumber(), 3);
						runScript_LookUpShelfItemInfo(game, gsm->getGameStateShelfAsNumber(), 3, isItemTaken);
						gsm->goToGame();
					}
					else{
						if (input->isKeyDownForFirstTime(NUM_4) ^ input->isKeyDownForFirstTime(NUMPAD_4)){
							isItemTaken = dataLoader->takeItemFromShelf(game, gsm->getGameStateShelfAsNumber(), 4);
							runScript_LookUpShelfItemInfo(game, gsm->getGameStateShelfAsNumber(), 4, isItemTaken);
							gsm->goToGame();
						}
						else{
							if (input->isKeyDownForFirstTime(NUM_5) ^ input->isKeyDownForFirstTime(NUMPAD_5)){
								isItemTaken = dataLoader->takeItemFromShelf(game, gsm->getGameStateShelfAsNumber(), 5);
								runScript_LookUpShelfItemInfo(game, gsm->getGameStateShelfAsNumber(), 5, isItemTaken);
								gsm->goToGame();
							}
							else{
								if (input->isKeyDownForFirstTime(NUM_6) ^ input->isKeyDownForFirstTime(NUMPAD_6)){
									isItemTaken = dataLoader->takeItemFromShelf(game, gsm->getGameStateShelfAsNumber(), 6);
									runScript_LookUpShelfItemInfo(game, gsm->getGameStateShelfAsNumber(), 6, isItemTaken);
									gsm->goToGame();
								}
								else{
									if (input->isKeyDownForFirstTime(NUM_7) ^ input->isKeyDownForFirstTime(NUMPAD_7)){
										isItemTaken = dataLoader->takeItemFromShelf(game, gsm->getGameStateShelfAsNumber(), 7);
										runScript_LookUpShelfItemInfo(game, gsm->getGameStateShelfAsNumber(), 7, isItemTaken);
										gsm->goToGame();
									}
									else{
										if (input->isKeyDownForFirstTime(NUM_8) ^ input->isKeyDownForFirstTime(NUMPAD_8)){
											isItemTaken = dataLoader->takeItemFromShelf(game, gsm->getGameStateShelfAsNumber(), 8);
											runScript_LookUpShelfItemInfo(game, gsm->getGameStateShelfAsNumber(), 8, isItemTaken);
											gsm->goToGame();
										}
										else{
											//DO NOTHING
			}	}	}	}	}	}	}	}
		}


		bool viewportMoved = false;
		float viewportVx = 0.0f;
		float viewportVy = 0.0f;
		if (input->isKeyDown(VIEWPORT_UP_CONTROL) && gsm->isPlayerControlDisabled() == false)
		{
			viewportVy -= MAX_VIEWPORT_AXIS_VELOCITY;
			viewportMoved = true;
		}
		if (input->isKeyDown(VIEWPORT_DOWN_CONTROL) && gsm->isPlayerControlDisabled() == false)
		{
			viewportVy += MAX_VIEWPORT_AXIS_VELOCITY;
			viewportMoved = true;
		}
		if (input->isKeyDown(VIEWPORT_LEFT_CONTROL) && gsm->isPlayerControlDisabled() == false)
		{
			viewportVx -= MAX_VIEWPORT_AXIS_VELOCITY;
			viewportMoved = true;
		}
		if (input->isKeyDown(VIEWPORT_RIGHT_CONTROL) && gsm->isPlayerControlDisabled() == false)
		{
			viewportVx += MAX_VIEWPORT_AXIS_VELOCITY;
			viewportMoved = true;
		}
		if (!viewportMoved){
			b2Vec2 playerPos = playerBody->GetPosition();
			float playerX = playerPos.x * SCALING_FACTOR;
			float playerY = playerPos.y * SCALING_FACTOR;
			int SCREEN_WIDTH = 1024;
			int SCREEN_HEIGHT = 768;
			if (viewport->getViewportX() + (viewport->getViewportWidth() * 15 / 32) < playerX){
				viewportVx += MAX_VIEWPORT_AXIS_VELOCITY *
					abs(viewport->getViewportX() + (viewport->getViewportWidth() / 2) - playerX) / (SCREEN_WIDTH / 2);
				viewportMoved = true;
			}
			if (viewport->getViewportX() + (viewport->getViewportWidth() * 17 / 32) > playerX){
				viewportVx -= MAX_VIEWPORT_AXIS_VELOCITY *
					abs(viewport->getViewportX() + (viewport->getViewportWidth() / 2) - playerX) / (SCREEN_WIDTH / 2);
				viewportMoved = true;
			}
			if (viewport->getViewportY() + (viewport->getViewportHeight() * 15 / 32) < playerY){
				viewportVy += MAX_VIEWPORT_AXIS_VELOCITY *
					abs(viewport->getViewportY() + (viewport->getViewportHeight() / 2) - playerY) / (SCREEN_HEIGHT / 2);
				viewportMoved = true;
			}
			if (viewport->getViewportY() + (viewport->getViewportHeight() * 17 / 32) > playerY){
				viewportVy -= MAX_VIEWPORT_AXIS_VELOCITY *
					abs(viewport->getViewportY() + (viewport->getViewportHeight() / 2) - playerY) / (SCREEN_HEIGHT / 2);
				viewportMoved = true;
			}
		}
		//Viewport *viewport = game->getGUI()->getViewport();
		if (viewportMoved){
			viewport->moveViewport((int)floor(viewportVx + 0.5f), (int)floor(viewportVy + 0.5f), game->getGSM()->getWorld()->getWorldWidth(), game->getGSM()->getWorld()->getWorldHeight());
		}
		
		/***********	CHEAT CODES LISTED BELOW *******
		
		
		************************************************/

		// INCREASE TIME REMAINING
		if (input->isKeyDownForFirstTime(I_KEY)){
			runScript_TimeCheat(game, true);
		}//isIncreasingTime


		// DECREASE TIME REMAINING
		if (input->isKeyDownForFirstTime(O_KEY)){
			runScript_TimeCheat(game, false);
		}

		// INCREASE SPENDING LIMIT
		if (input->isKeyDownForFirstTime(Y_KEY)){
			if ((dataLoader->spendingLimit + MONEY_CHEAT_INCREASE) > (dataLoader->levelItemsCost * 2) + MONEY_CHEAT_INCREASE){
				dataLoader->spendingLimit = (dataLoader->levelItemsCost * 2) + MONEY_CHEAT_INCREASE;
			}
			else{
				dataLoader->spendingLimit += MONEY_CHEAT_INCREASE;
			}
			
		}//isIncreasingSpendingLimit


		// DECREASE SPENDING LIMIT
		if (input->isKeyDownForFirstTime(U_KEY)){
			if ((dataLoader->spendingLimit - MONEY_CHEAT_DECREASE) < dataLoader->levelItemsCost){
				dataLoader->spendingLimit = dataLoader->levelItemsCost;
			}
			else{
				dataLoader->spendingLimit -= MONEY_CHEAT_DECREASE;
			}
		}//isDecreasingSpendingLimit

	}// BRACKET -- if (gsm->isGameInProgress())
}
void PaneFrameRenderer::drawQuadRect(Viewport &vp, const mge::Color &color, float x, float y, float w, float h, float thickness) {
	vp.render(Quad(color, x, y, thickness, h));
	vp.render(Quad(color, x, y+h, x+w, -thickness));
	vp.render(Quad(color, x+w, y+h, -thickness, -h));
	vp.render(Quad(color, x+w, y, -w, thickness));
}
Ejemplo n.º 7
0
void LoadEqualizer::_updateNode( Node* node, const Viewport& vp,
                                 const Range& range )
{
    Node* left = node->left;
    Node* right = node->right;

    LBASSERT( left );
    LBASSERT( right );

    Viewport leftVP = vp;
    Viewport rightVP = vp;
    Range leftRange = range;
    Range rightRange = range;

    switch( node->mode )
    {
      default:
        LBUNIMPLEMENTED;

      case MODE_VERTICAL:
        leftVP.w = vp.w * .5f;
        rightVP.x = leftVP.getXEnd();
        rightVP.w = vp.getXEnd() - rightVP.x;
        node->split = leftVP.getXEnd();
        break;

      case MODE_HORIZONTAL:
        leftVP.h = vp.h * .5f;
        rightVP.y = leftVP.getYEnd();
        rightVP.h = vp.getYEnd() - rightVP.y;
        node->split = leftVP.getYEnd();
        break;

      case MODE_DB:
        leftRange.end = range.start + ( range.end - range.start ) * .5f;
        rightRange.start = leftRange.end;
        node->split = leftRange.end;
        break;
    }

    _update( left, leftVP, leftRange );
    _update( right, rightVP, rightRange );

    node->resources = left->resources + right->resources;

    if( left->resources == 0.f )
    {
        node->maxSize    = right->maxSize;
        node->boundary2i = right->boundary2i;
        node->boundaryf  = right->boundaryf;
        node->resistance2i = right->resistance2i;
        node->resistancef = right->resistancef;
    }
    else if( right->resources == 0.f )
    {
        node->maxSize = left->maxSize;
        node->boundary2i = left->boundary2i;
        node->boundaryf = left->boundaryf;
        node->resistance2i = left->resistance2i;
        node->resistancef = left->resistancef;
    }
    else
    {
        switch( node->mode )
        {
        case MODE_VERTICAL:
            node->maxSize.x() = left->maxSize.x() + right->maxSize.x();
            node->maxSize.y() = LB_MIN( left->maxSize.y(), right->maxSize.y());
            node->boundary2i.x() = left->boundary2i.x()+ right->boundary2i.x();
            node->boundary2i.y() = LB_MAX( left->boundary2i.y(),
                                           right->boundary2i.y());
            node->boundaryf = LB_MAX( left->boundaryf, right->boundaryf );
            node->resistance2i.x() = LB_MAX( left->resistance2i.x(),
                                             right->resistance2i.x( ));
            node->resistance2i.y() = LB_MAX( left->resistance2i.y(),
                                             right->resistance2i.y());
            node->resistancef = LB_MAX( left->resistancef, right->resistancef );
            break;
        case MODE_HORIZONTAL:
            node->maxSize.x() = LB_MIN( left->maxSize.x(), right->maxSize.x());
            node->maxSize.y() = left->maxSize.y() + right->maxSize.y();
            node->boundary2i.x() = LB_MAX( left->boundary2i.x(),
                                           right->boundary2i.x() );
            node->boundary2i.y() = left->boundary2i.y()+ right->boundary2i.y();
            node->boundaryf = LB_MAX( left->boundaryf, right->boundaryf );
            node->resistance2i.x() = LB_MAX( left->resistance2i.x(),
                                             right->resistance2i.x() );
            node->resistance2i.y() = LB_MAX( left->resistance2i.y(),
                                             right->resistance2i.y( ));
            node->resistancef = LB_MAX( left->resistancef, right->resistancef );
            break;
        case MODE_DB:
            node->boundary2i.x() = LB_MAX( left->boundary2i.x(),
                                           right->boundary2i.x() );
            node->boundary2i.y() = LB_MAX( left->boundary2i.y(),
                                           right->boundary2i.y() );
            node->boundaryf = left->boundaryf + right->boundaryf;
            node->resistance2i.x() = LB_MAX( left->resistance2i.x(),
                                             right->resistance2i.x() );
            node->resistance2i.y() = LB_MAX( left->resistance2i.y(),
                                             right->resistance2i.y() );
            node->resistancef = LB_MAX( left->resistancef, right->resistancef );
            break;
        default:
            LBUNIMPLEMENTED;
        }
    }
}
Ejemplo n.º 8
0
void ImpostorTexture::renderTextures(bool force)
{
#ifdef IMPOSTOR_FILE_SAVE
	TexturePtr renderTexture;
#else
	TexturePtr renderTexture(texture);
	//if we're not using a file image we need to set up a resource loader, so that the texture is regenerated if it's ever unloaded (such as switching between fullscreen and the desktop in win32)
	loader = std::auto_ptr<ImpostorTextureResourceLoader>(new ImpostorTextureResourceLoader(*this));
#endif
	RenderTexture *renderTarget;
	Camera *renderCamera;
	Viewport *renderViewport;
	SceneNode *camNode;

	//Set up RTT texture
	uint32 textureSize = ImpostorPage::impostorResolution;
	if (renderTexture.isNull()) {
	renderTexture = TextureManager::getSingleton().createManual(getUniqueID("ImpostorTexture"), "Impostors",
				TEX_TYPE_2D, textureSize * IMPOSTOR_YAW_ANGLES, textureSize * IMPOSTOR_PITCH_ANGLES, 0, PF_A8R8G8B8, TU_RENDERTARGET, loader.get());
	}
	renderTexture->setNumMipmaps(MIP_UNLIMITED);
	
	//Set up render target
	renderTarget = renderTexture->getBuffer()->getRenderTarget(); 
	renderTarget->setAutoUpdated(false);
	
	//Set up camera
	camNode = sceneMgr->getSceneNode("ImpostorPage::cameraNode");
	renderCamera = sceneMgr->createCamera(getUniqueID("ImpostorCam"));
	camNode->attachObject(renderCamera);
	renderCamera->setLodBias(1000.0f);
	renderViewport = renderTarget->addViewport(renderCamera);
	renderViewport->setOverlaysEnabled(false);
	renderViewport->setClearEveryFrame(true);
	renderViewport->setShadowsEnabled(false);
	renderViewport->setBackgroundColour(ImpostorPage::impostorBackgroundColor);
	
	//Set up scene node
	SceneNode* node = sceneMgr->getSceneNode("ImpostorPage::renderNode");
	
	Ogre::SceneNode* oldSceneNode = entity->getParentSceneNode();
	if (oldSceneNode) {
		oldSceneNode->detachObject(entity);
	}
	node->attachObject(entity);
	node->setPosition(-entityCenter);
	
	//Set up camera FOV
	const Real objDist = entityRadius * 100;
	const Real nearDist = objDist - (entityRadius + 1); 
	const Real farDist = objDist + (entityRadius + 1);
	
	renderCamera->setAspectRatio(1.0f);
	renderCamera->setFOVy(Math::ATan(entityDiameter / objDist));
	renderCamera->setNearClipDistance(nearDist);
	renderCamera->setFarClipDistance(farDist);
	
	//Disable mipmapping (without this, masked textures look bad)
	MaterialManager *mm = MaterialManager::getSingletonPtr();
	FilterOptions oldMinFilter = mm->getDefaultTextureFiltering(FT_MIN);
	FilterOptions oldMagFilter = mm->getDefaultTextureFiltering(FT_MAG);
	FilterOptions oldMipFilter = mm->getDefaultTextureFiltering(FT_MIP);
	mm->setDefaultTextureFiltering(FO_POINT, FO_LINEAR, FO_NONE);

	//Disable fog
	FogMode oldFogMode = sceneMgr->getFogMode();
	ColourValue oldFogColor = sceneMgr->getFogColour();
	Real oldFogDensity = sceneMgr->getFogDensity();
	Real oldFogStart = sceneMgr->getFogStart();
	Real oldFogEnd = sceneMgr->getFogEnd();
	sceneMgr->setFog(Ogre::FOG_EXP2, Ogre::ColourValue(0,0,0,0), 0.0f, 0.0f, 0.0f); //Ember change
	
	//We need to disable all lightning and render it full bright
	Ogre::ColourValue oldAmbientColour = sceneMgr->getAmbientLight();
	sceneMgr->setAmbientLight(ColourValue::White);

	std::vector<Ogre::MovableObject*> lightStore;
	Ogre::SceneManager::MovableObjectIterator lightIterator = sceneMgr->getMovableObjectIterator(Ogre::LightFactory::FACTORY_TYPE_NAME);
	while (lightIterator.hasMoreElements()) {
		Ogre::MovableObject* light = lightIterator.getNext();
		if (light) {
			if (light->getVisible()) {
				lightStore.push_back(light);
				light->setVisible(false);
			}
		}
	}

	// Get current status of the queue mode
	Ogre::SceneManager::SpecialCaseRenderQueueMode OldSpecialCaseRenderQueueMode = sceneMgr->getSpecialCaseRenderQueueMode();
	//Only render the entity
	sceneMgr->setSpecialCaseRenderQueueMode(Ogre::SceneManager::SCRQM_INCLUDE); 
	sceneMgr->addSpecialCaseRenderQueue(group->geom->getRenderQueue() + 1);

	uint8 oldRenderQueueGroup = entity->getRenderQueueGroup();
	entity->setRenderQueueGroup(group->geom->getRenderQueue() + 1);
	bool oldVisible = entity->getVisible();
	entity->setVisible(true);
	float oldMaxDistance = entity->getRenderingDistance();
	entity->setRenderingDistance(0);

	bool needsRegen = true;
#ifdef IMPOSTOR_FILE_SAVE
	//Calculate the filename hash used to uniquely identity this render
	String strKey = entityKey;
	char key[32] = {0};
	uint32 i = 0;
	for (String::const_iterator it = entityKey.begin(); it != entityKey.end(); ++it)
	{
		key[i] ^= *it;
		i = (i+1) % sizeof(key);
	}
	for (i = 0; i < sizeof(key); ++i)
		key[i] = (key[i] % 26) + 'A';

	String tempdir = this->group->geom->getTempdir();
	ResourceGroupManager::getSingleton().addResourceLocation(tempdir, "FileSystem", "BinFolder");

	String fileNamePNG = "Impostor." + String(key, sizeof(key)) + '.' + StringConverter::toString(textureSize) + ".png";
	String fileNameDDS = "Impostor." + String(key, sizeof(key)) + '.' + StringConverter::toString(textureSize) + ".dds";

	//Attempt to load the pre-render file if allowed
	needsRegen = force;
	if (!needsRegen){
		try{
			texture = TextureManager::getSingleton().load(fileNameDDS, "BinFolder", TEX_TYPE_2D, MIP_UNLIMITED);
		}
		catch (...){
			try{
				texture = TextureManager::getSingleton().load(fileNamePNG, "BinFolder", TEX_TYPE_2D, MIP_UNLIMITED);
			}
			catch (...){
				needsRegen = true;
			}
		}
	}
#endif

	if (needsRegen){
		//If this has not been pre-rendered, do so now
		const float xDivFactor = 1.0f / IMPOSTOR_YAW_ANGLES;
		const float yDivFactor = 1.0f / IMPOSTOR_PITCH_ANGLES;
		for (int o = 0; o < IMPOSTOR_PITCH_ANGLES; ++o){ //4 pitch angle renders
#ifdef IMPOSTOR_RENDER_ABOVE_ONLY
			Radian pitch = Degree((90.0f * o) * yDivFactor); //0, 22.5, 45, 67.5
#else
			Radian pitch = Degree((180.0f * o) * yDivFactor - 90.0f);
#endif

			for (int i = 0; i < IMPOSTOR_YAW_ANGLES; ++i){ //8 yaw angle renders
				Radian yaw = Degree((360.0f * i) * xDivFactor); //0, 45, 90, 135, 180, 225, 270, 315
					
				//Position camera
				camNode->setPosition(0, 0, 0);
                camNode->setOrientation(Quaternion(yaw, Vector3::UNIT_Y) * Quaternion(-pitch, Vector3::UNIT_X));
                camNode->translate(Vector3(0, 0, objDist), Node::TS_LOCAL);
						
				//Render the impostor
				renderViewport->setDimensions((float)(i) * xDivFactor, (float)(o) * yDivFactor, xDivFactor, yDivFactor);
				renderTarget->update();
			}
		}
	
#ifdef IMPOSTOR_FILE_SAVE
		//Save RTT to file with respecting the temp dir
		renderTarget->writeContentsToFile(tempdir + fileNamePNG);

		//Load the render into the appropriate texture view
		texture = TextureManager::getSingleton().load(fileNamePNG, "BinFolder", TEX_TYPE_2D, MIP_UNLIMITED);
#else
		texture = renderTexture;
#endif
	}
	

	entity->setVisible(oldVisible);
	entity->setRenderQueueGroup(oldRenderQueueGroup);
	entity->setRenderingDistance(oldMaxDistance);
	sceneMgr->removeSpecialCaseRenderQueue(group->geom->getRenderQueue() + 1);
	// Restore original state
	sceneMgr->setSpecialCaseRenderQueueMode(OldSpecialCaseRenderQueueMode); 

	//Re-enable mipmapping
	mm->setDefaultTextureFiltering(oldMinFilter, oldMagFilter, oldMipFilter);

	//Re-enable fog
	sceneMgr->setFog(oldFogMode, oldFogColor, oldFogDensity, oldFogStart, oldFogEnd);

	//Re-enable both scene lightning and disabled individual lights
	sceneMgr->setAmbientLight(oldAmbientColour);
	for (std::vector<Ogre::MovableObject*>::const_iterator I = lightStore.begin(); I != lightStore.end(); ++I) {
		(*I)->setVisible(true);
	}

	//Delete camera
	renderTarget->removeViewport(0);
	renderCamera->getSceneManager()->destroyCamera(renderCamera);
	
	//Delete scene node
	node->detachAllObjects();
	if (oldSceneNode) {
		oldSceneNode->attachObject(entity);
	}
#ifdef IMPOSTOR_FILE_SAVE
	//Delete RTT texture
	assert(!renderTexture.isNull());
	String texName2(renderTexture->getName());

	renderTexture.setNull();
	if (TextureManager::getSingletonPtr())
		TextureManager::getSingleton().remove(texName2);
#endif
}
Ejemplo n.º 9
0
//
// setup of the image generation stage
//
static void createAcquisitionStage()
{
    size_t num_ports = win->getMFPort()->size();
    if (num_ports == 0)
        return;

    UInt32 width  = win->getWidth();
    UInt32 height = win->getHeight();

    Real32 a = Real32(width) / Real32(height);
    width = UInt32(a*height);

    Viewport* vp = staticVp;

    Node* internalRoot = rootNode(mgr->getRoot());

    //
    // Setup the FBO
    //
    spSimpleFBO.reset(new SimpleFBO(width, height, true, true, true, false));
    
    //spSimpleFBO->fbo()->setPostProcessOnDeactivate(true);
    //spSimpleFBO->colorBuffer(0)->setReadBack(true);

    //
    // We would like to render the scene but won't detach it from its parent.
    // The VisitSubTree allows just that.
    //
    VisitSubTreeUnrecPtr visitor = VisitSubTree::create();
    visitor->setSubTreeRoot(internalRoot);
    NodeUnrecPtr visit_node = makeNodeFor(visitor);

    //
    // The stage object does provide a render target for the frame buffer attachment.
    // SimpleStage has a camera, a background and the left, right, top, bottom
    // fields to let you restrict rendering to a sub-rectangle of your FBO, i.e.
    // they give you a viewport.
    //
    SimpleStageUnrecPtr stage = SimpleStage::create();
    stage->setRenderTarget(spSimpleFBO->fbo());
    stage->setCamera      (vp->getCamera());
    stage->setBackground  (vp->getBackground());
    //
    // Give the stage core a place to live
    //
    NodeUnrecPtr stage_node = makeNodeFor(stage);
    stage_node->addChild(visit_node);

    //
    //   root
    //    |
    //    +- SimpleStage
    //            |
    //            +- VisitSubTree -> ApplicationScene
    //
    NodeUnrecPtr root = makeCoredNode<Group>();
    root->addChild(stage_node);

    //
    // Give the root node a place to live, i.e. create a passive
    // viewport and add it to the window.
    //
    ViewportUnrecPtr stage_viewport = PassiveViewport::create();
    stage_viewport->setRoot      (stage_node);
    stage_viewport->setBackground(vp->getBackground());
    stage_viewport->setCamera    (vp->getCamera());

    win->addPort(stage_viewport);

    mgr->update();
    win->renderNoFinish(mgr->getRenderAction());
    win->frameExit();
    win->deactivate ();

    //ImageUnrecPtr col_image = Image::create();
    //col_image->set(Image::OSG_RGBA_PF, width, height);
        
    //TextureObjChunk* texObj = spSimpleFBO->colorTexObj(0);
    //texObj->getImage()->subImage(0, 0, 0, width, height, 1, col_image);
    //col_image->write("d:/my_Test_opensg.png");

    win->subPortByObj(stage_viewport);
}
Ejemplo n.º 10
0
void glRect(Viewport v, int inset)
{
  glRecti(v.l+inset,v.b+inset,v.r()-inset,v.t()-inset);
}
Ejemplo n.º 11
0
void Shadows::recreate()
{
    bool enabled = Settings::Manager::getBool("enabled", "Shadows");

    bool split = Settings::Manager::getBool("split", "Shadows");

    sh::Factory::getInstance ().setGlobalSetting ("shadows", enabled && !split ? "true" : "false");
    sh::Factory::getInstance ().setGlobalSetting ("shadows_pssm", enabled && split ? "true" : "false");

    if (!enabled)
    {
        mSceneMgr->setShadowTechnique(SHADOWTYPE_NONE);
        return;
    }

    int texsize = Settings::Manager::getInt("texture size", "Shadows");
    mSceneMgr->setShadowTextureSize(texsize);

    mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED);

    // no point light shadows, i'm afraid. might revisit this with Deferred Shading
    mSceneMgr->setShadowTextureCountPerLightType(Light::LT_POINT, 0);

    mSceneMgr->setShadowTextureCountPerLightType(Light::LT_DIRECTIONAL, split ? 3 : 1);
    mSceneMgr->setShadowTextureCount(split ? 3 : 1);

    mSceneMgr->setShadowTextureSelfShadow(true);
    mSceneMgr->setShadowCasterRenderBackFaces(true);
    mSceneMgr->setShadowTextureCasterMaterial("openmw_shadowcaster_default");
    mSceneMgr->setShadowTexturePixelFormat(PF_FLOAT32_R);
    mSceneMgr->setShadowDirectionalLightExtrusionDistance(1000000);

    mShadowFar = split ? Settings::Manager::getInt("split shadow distance", "Shadows") : Settings::Manager::getInt("shadow distance", "Shadows");
    mSceneMgr->setShadowFarDistance(mShadowFar);

    mFadeStart = Settings::Manager::getFloat("fade start", "Shadows");

    ShadowCameraSetupPtr shadowCameraSetup;
    if (split)
    {
        mPSSMSetup = new PSSMShadowCameraSetup();

        // Make sure to keep this in sync with the camera's near clip distance!
        mPSSMSetup->setSplitPadding(mRendering->getCamera()->getNearClipDistance());

        mPSSMSetup->calculateSplitPoints(3, mRendering->getCamera()->getNearClipDistance(), mShadowFar);

        const Real adjustFactors[3] = {64, 64, 64};
        for (int i=0; i < 3; ++i)
        {
            mPSSMSetup->setOptimalAdjustFactor(i, adjustFactors[i]);
            /*if (i==0)
                mSceneMgr->setShadowTextureConfig(i, texsize, texsize, Ogre::PF_FLOAT32_R);
            else if (i ==1)
                mSceneMgr->setShadowTextureConfig(i, texsize/2, texsize/2, Ogre::PF_FLOAT32_R);
            else if (i ==2)
                mSceneMgr->setShadowTextureConfig(i, texsize/4, texsize/4, Ogre::PF_FLOAT32_R);*/
        }

        // Populate from split point 1, not 0, since split 0 isn't useful (usually 0)
        const PSSMShadowCameraSetup::SplitPointList& splitPointList = getPSSMSetup()->getSplitPoints();
        sh::Vector3* splitPoints = new sh::Vector3(splitPointList[1], splitPointList[2], splitPointList[3]);

        sh::Factory::getInstance ().setSharedParameter ("pssmSplitPoints", sh::makeProperty<sh::Vector3>(splitPoints));

        shadowCameraSetup = ShadowCameraSetupPtr(mPSSMSetup);
    }
    else
    {
        LiSPSMShadowCameraSetup* lispsmSetup = new LiSPSMShadowCameraSetup();
        lispsmSetup->setOptimalAdjustFactor(64);
        //lispsmSetup->setCameraLightDirectionThreshold(Degree(0));
        //lispsmSetup->setUseAggressiveFocusRegion(false);
        shadowCameraSetup = ShadowCameraSetupPtr(lispsmSetup);
    }
    mSceneMgr->setShadowCameraSetup(shadowCameraSetup);

    sh::Vector4* shadowFar_fadeStart = new sh::Vector4(mShadowFar, mFadeStart * mShadowFar, 0, 0);
    sh::Factory::getInstance ().setSharedParameter ("shadowFar_fadeStart", sh::makeProperty<sh::Vector4>(shadowFar_fadeStart));

    // Set visibility mask for the shadow render textures
    int visibilityMask = RV_Actors * Settings::Manager::getBool("actor shadows", "Shadows")
                            + (RV_Statics + RV_StaticsSmall) * Settings::Manager::getBool("statics shadows", "Shadows")
                            + RV_Misc * Settings::Manager::getBool("misc shadows", "Shadows")
            + RV_Terrain * (Settings::Manager::getBool("terrain shadows", "Shadows"));
    for (int i = 0; i < (split ? 3 : 1); ++i)
    {
        TexturePtr shadowTexture = mSceneMgr->getShadowTexture(i);
        Viewport* vp = shadowTexture->getBuffer()->getRenderTarget()->getViewport(0);
        vp->setVisibilityMask(visibilityMask);
    }

    // --------------------------------------------------------------------------------------------------------------------
    // --------------------------- Debug overlays to display the content of shadow maps -----------------------------------
    // --------------------------------------------------------------------------------------------------------------------
    /*
    if (Settings::Manager::getBool("debug", "Shadows"))
    {
        OverlayManager& mgr = OverlayManager::getSingleton();
        Overlay* overlay;

        // destroy if already exists
        if ((overlay = mgr.getByName("DebugOverlay")))
            mgr.destroy(overlay);

        overlay = mgr.create("DebugOverlay");
        for (size_t i = 0; i < (split ? 3 : 1); ++i) {
            TexturePtr tex = mRendering->getScene()->getShadowTexture(i);

            // Set up a debug panel to display the shadow

            if (MaterialManager::getSingleton().resourceExists("Ogre/DebugTexture" + StringConverter::toString(i)))
                MaterialManager::getSingleton().remove("Ogre/DebugTexture" + StringConverter::toString(i));
            MaterialPtr debugMat = MaterialManager::getSingleton().create(
                "Ogre/DebugTexture" + StringConverter::toString(i),
                ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

            debugMat->getTechnique(0)->getPass(0)->setLightingEnabled(false);
            TextureUnitState *t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState(tex->getName());
            t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);

            OverlayContainer* debugPanel;

            // destroy container if exists
            try
            {
                if ((debugPanel =
                    static_cast<OverlayContainer*>(
                        mgr.getOverlayElement("Ogre/DebugTexPanel" + StringConverter::toString(i)
                    ))))
                    mgr.destroyOverlayElement(debugPanel);
            }
            catch (Ogre::Exception&) {}

            debugPanel = (OverlayContainer*)
                (OverlayManager::getSingleton().createOverlayElement("Panel", "Ogre/DebugTexPanel" + StringConverter::toString(i)));
            debugPanel->_setPosition(0.8, i*0.25);
            debugPanel->_setDimensions(0.2, 0.24);
            debugPanel->setMaterialName(debugMat->getName());
            debugPanel->show();
            overlay->add2D(debugPanel);
            overlay->show();
        }
    }
    else
    {
        OverlayManager& mgr = OverlayManager::getSingleton();
        Overlay* overlay;

        if ((overlay = mgr.getByName("DebugOverlay")))
            mgr.destroy(overlay);
    }
    */
}
Ejemplo n.º 12
0
void glRect(Viewport v)
{
  glRecti(v.l,v.b,v.r(),v.t());
}
Ejemplo n.º 13
0
/**
 * Renders the window using OpenGL.
 * @post win is rendered (In stereo if it is a stereo window).
 */
void D3dDrawManager::renderWindow(D3dWindow* win)
{
   float vp_ox, vp_oy, vp_sx, vp_sy;    // Viewport origin and size
   Viewport::View view;                 // The view for the active viewport

   DisplayPtr the_display = win->getDisplay();   // Get the display for easy access

   // Update the projections for the display using the current app's scale factor
   // NOTE: This relies upon no other thread trying to update this display at the same time
   float scale_factor = mApp->getDrawScaleFactor();
   the_display->updateProjections(scale_factor);

   //mGlDrawManager->setCurrentContext(win->getId());     // Set TSS data of context id
   //mGlDrawManager->currentUserData()->setGlWindow(win);

   // --- SET CONTEXT --- //
   win->makeCurrent();
 

   // VIEWPORT cleaning
   if (win->hasDirtyViewport())
   {
      win->updateViewport();
   }

   // CONTEXT INIT(): Check if we need to call contextInit()
   // - Must call when context is new OR application is new
   if (win->hasDirtyContext())
   {
      // Have dirty context
      //mGlDrawManager->currentUserData()->setUser(NULL);         // Set user data
      //mGlDrawManager->currentUserData()->setProjection(NULL);
      //mGlDrawManager->currentUserData()->setViewport(NULL);     // Set vp data
      //mGlDrawManager->currentUserData()->setGlWindow(win);      // Set the gl window

      mApp->contextInit(win->mRenderDevice);   // Call context init function
      win->setDirtyContext(false);        // All clean now
   }

   // BUFFER PRE DRAW: Check if we need to clear stereo buffers
   if (win->isStereo())
   {
      win->setViewBuffer(Viewport::RIGHT_EYE);
      mApp->bufferPreDraw();
      win->setViewBuffer(Viewport::LEFT_EYE);
      mApp->bufferPreDraw();
   }
   else
   {
      mApp->bufferPreDraw();
   }

   mApp->contextPreDraw();                 // Do any context pre-drawing

   // --- FOR EACH VIEWPORT -- //
   Viewport* viewport = NULL;
   size_t num_vps = the_display->getNumViewports();
   for ( size_t vp_num = 0; vp_num < num_vps; ++vp_num )
   {
      viewport = the_display->getViewport(vp_num);

      // Should viewport be rendered???
      if (viewport->isActive())
      {
         view = viewport->getView();

         // Set the glViewport to draw within
         viewport->getOriginAndSize(vp_ox, vp_oy, vp_sx, vp_sy);
         win->setViewport(vp_ox, vp_oy, vp_sx, vp_sy);

         // Set user information
         //mGlDrawManager->currentUserData()->setUser(viewport->getUser());       // Set user data
         //mGlDrawManager->currentUserData()->setViewport(viewport);              // Set the viewport

         // ---- SURFACE & Simulator --- //
         // if (viewport->isSurface())
         {
            SimViewport*       sim_vp(NULL);
            D3dSimInterfacePtr draw_sim_i;

            if (viewport->isSimulator())
            {
               sim_vp = dynamic_cast<SimViewport*>(viewport);
               vprASSERT(NULL != sim_vp);
               if (NULL != sim_vp)
               {
                  draw_sim_i =
                     boost::dynamic_pointer_cast<D3dSimInterface>(
                        sim_vp->getDrawSimInterface()
                     );
               }
            }

            if ((Viewport::STEREO == view) || (Viewport::LEFT_EYE == view))      // LEFT EYE
            {
               win->setViewBuffer(Viewport::LEFT_EYE);
               win->setProjection(viewport->getLeftProj());
               //mGlDrawManager->currentUserData()->setProjection(viewport->getLeftProj());

               mApp->draw(win->mRenderDevice);

               if ( NULL != draw_sim_i.get() )
               {
                  draw_sim_i->draw(scale_factor);
               }
            }
            if ((Viewport::STEREO == view) || (Viewport::RIGHT_EYE == view))    // RIGHT EYE
            {
               win->setViewBuffer(Viewport::RIGHT_EYE);
               win->setProjection(viewport->getRightProj());
               //mGlDrawManager->currentUserData()->setProjection(viewport->getRightProj());

               mApp->draw(win->mRenderDevice);

               if ( NULL != draw_sim_i.get() )
               {
                  draw_sim_i->draw(scale_factor);
               }
            }
         }
      }  // should viewport be rendered
   }     // for each viewport

   // -- Post context stuff --- //
   mApp->contextPostDraw();
}
Ejemplo n.º 14
0
void TreeEqualizer::_assign( Node* node, const Viewport& vp,
                             const Range& range )
{
    LBLOG( LOG_LB2 ) << "assign " << vp << ", " << range << " time "
                     << node->time << " split " << node->split << std::endl;
    LBASSERTINFO( vp.isValid(), vp );
    LBASSERTINFO( range.isValid(), range );
    LBASSERTINFO( node->resources > 0.f || !vp.hasArea() || !range.hasData(),
                  "Assigning work to unused compound: " << vp << ", " << range);

    Compound* compound = node->compound;
    if( compound )
    {
        LBASSERTINFO( vp == Viewport::FULL || range == Range::ALL,
                      "Mixed 2D/DB load-balancing not implemented" );

        compound->setViewport( vp );
        compound->setRange( range );
        LBLOG( LOG_LB2 ) << compound->getChannel()->getName() << " set " << vp
                         << ", " << range << std::endl;
        return;
    }

    switch( node->mode )
    {
    case MODE_VERTICAL:
    {
        // Ensure minimum size
        const Compound* root = getCompound();
        const float pvpW = float( root->getInheritPixelViewport().w );
        const float end = vp.getXEnd();
        const float boundary = float( node->boundary2i.x( )) / pvpW;
        float absoluteSplit = vp.x + vp.w * node->split;

        if( node->left->resources == 0.f )
            absoluteSplit = vp.x;
        else if( node->right->resources == 0.f )
            absoluteSplit = end;
        else if( boundary > 0 )
        {
            const float right = vp.getXEnd() - absoluteSplit;
            const float left = absoluteSplit - vp.x;
            const float maxRight = float( node->right->maxSize.x( )) / pvpW;
            const float maxLeft = float( node->left->maxSize.x( )) / pvpW;

            if( right > maxRight )
                absoluteSplit = end - maxRight;
            else if( left > maxLeft )
                absoluteSplit = vp.x + maxLeft;
            
            if( (absoluteSplit - vp.x) < boundary )
                absoluteSplit = vp.x + boundary;
            if( (end - absoluteSplit) < boundary )
                absoluteSplit = end - boundary;
                
            const uint32_t ratio = uint32_t( absoluteSplit / boundary + .5f );
            absoluteSplit = ratio * boundary;
        }

        absoluteSplit = LB_MAX( absoluteSplit, vp.x );
        absoluteSplit = LB_MIN( absoluteSplit, end);

        node->split = (absoluteSplit - vp.x ) / vp.w;
        LBLOG( LOG_LB2 ) << "Constrained split " << vp << " at X "
                         << node->split << std::endl;

        // traverse children
        Viewport childVP = vp;
        childVP.w = (absoluteSplit - vp.x);
        _assign( node->left, childVP, range );

        childVP.x = childVP.getXEnd();
        childVP.w = end - childVP.x;

        // Fix 2994111: Rounding errors with 2D LB and 16 sources
        //   Floating point rounding may create a width for the 'right'
        //   child which is slightly below the parent width. Correct it.
        while( childVP.getXEnd() < end )
            childVP.w += std::numeric_limits< float >::epsilon();

        _assign( node->right, childVP, range );
        break;
    }

    case MODE_HORIZONTAL:
    {
        // Ensure minimum size
        const Compound* root = getCompound();
        const float pvpH = float( root->getInheritPixelViewport().h );
        const float end = vp.getYEnd();
        const float boundary = float( node->boundary2i.y( )) / pvpH;
        float absoluteSplit = vp.y + vp.h * node->split;

        if( node->left->resources == 0.f )
            absoluteSplit = vp.y;
        else if( node->right->resources == 0.f )
            absoluteSplit = end;
        else if( boundary > 0 )
        {
            const float right = vp.getYEnd() - absoluteSplit;
            const float left = absoluteSplit - vp.y;
            const float maxRight = float( node->right->maxSize.y( )) / pvpH;
            const float maxLeft = float( node->left->maxSize.y( )) / pvpH;

            if( right > maxRight )
                absoluteSplit = end - maxRight;
            else if( left > maxLeft )
                absoluteSplit = vp.y + maxLeft;
            
            if( (absoluteSplit - vp.y) < boundary )
                absoluteSplit = vp.y + boundary;
            if( (end - absoluteSplit) < boundary )
                absoluteSplit = end - boundary;
                
            const uint32_t ratio = uint32_t( absoluteSplit / boundary + .5f );
            absoluteSplit = ratio * boundary;
        }

        absoluteSplit = LB_MAX( absoluteSplit, vp.y );
        absoluteSplit = LB_MIN( absoluteSplit, end);

        node->split = (absoluteSplit - vp.y ) / vp.h;
        LBLOG( LOG_LB2 ) << "Constrained split " << vp << " at X "
                         << node->split << std::endl;

        // traverse children
        Viewport childVP = vp;
        childVP.h = (absoluteSplit - vp.y);
        _assign( node->left, childVP, range );

        childVP.y = childVP.getYEnd();
        childVP.h = end - childVP.y;

        // Fix 2994111: Rounding errors with 2D LB and 16 sources
        //   Floating point rounding may create a width for the 'right'
        //   child which is slightly below the parent width. Correct it.
        while( childVP.getYEnd() < end )
            childVP.h += std::numeric_limits< float >::epsilon();

        _assign( node->right, childVP, range );
        break;
    }

    case MODE_DB:
    {
        LBASSERT( vp == Viewport::FULL );
        const float end = range.end;
        float absoluteSplit = range.start + (range.end-range.start)*node->split;

        const float boundary( node->boundaryf );
        if( node->left->resources == 0.f )
            absoluteSplit = range.start;
        else if( node->right->resources == 0.f )
            absoluteSplit = end;

        const uint32_t ratio = uint32_t( absoluteSplit / boundary + .5f );
        absoluteSplit = ratio * boundary;
        if( (absoluteSplit - range.start) < boundary )
            absoluteSplit = range.start;
        if( (end - absoluteSplit) < boundary )
            absoluteSplit = end;

        node->split = (absoluteSplit-range.start) / (range.end-range.start);
        LBLOG( LOG_LB2 ) << "Constrained split " << range << " at pos "
                         << node->split << std::endl;

        Range childRange = range;
        childRange.end = absoluteSplit;
        _assign( node->left, vp, childRange );

        childRange.start = childRange.end;
        childRange.end   = range.end;
        _assign( node->right, vp, childRange);
        break;
    }

    default:
        LBUNIMPLEMENTED;
    }
}
Ejemplo n.º 15
0
//-----------------------------------------------------------------------
void CompositorInstance::createResources()
{
static size_t dummyCounter = 0;
    freeResources();
    /// Create temporary textures
    /// In principle, temporary textures could be shared between multiple viewports
    /// (CompositorChains). This will save a lot of memory in case more viewports
    /// are composited.
    CompositionTechnique::TextureDefinitionIterator it = mTechnique->getTextureDefinitionIterator();
    while(it.hasMoreElements())
    {
        CompositionTechnique::TextureDefinition *def = it.getNext();

        /// Determine width and height
        int width = def->width.adjust +
            static_cast<int>(mChain->getViewport()->getActualWidth() * def->width.viewport) +
            static_cast<int>(mChain->getViewport()->getActualWidth() * def->width.previous);    // FIXME
        int height = def->height.adjust +
            static_cast<int>(mChain->getViewport()->getActualHeight() * def->height.viewport) +
            static_cast<int>(mChain->getViewport()->getActualHeight() * def->height.previous);  // FIXME
        if (width <= 0)
        {
            // Throw exception? Not that case, because user can't guarantee
            // provides correct parameters always, since it might related to
            // viewport dimensions which can't control by user all the way.
            width = 1;
        }
        if (height <= 0)
        {
            // Throw exception? Not that case, because user can't guarantee
            // provides correct parameters always, since it might related to
            // viewport dimensions which can't control by user all the way.
            height = 1;
        }

        /// Make the tetxure
        TexturePtr tex = TextureManager::getSingleton().createManual(
            "CompositorInstanceTexture"+StringConverter::toString(dummyCounter), 
            ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D, 
            (uint)width, (uint)height, 0, def->format, TU_RENDERTARGET );    
        ++dummyCounter;
        mLocalTextures[def->name] = tex;
        
        /// Set up viewport over entire texture
        RenderTexture *rtt = tex->getBuffer()->getRenderTarget();
        rtt->setAutoUpdated( false );

        Camera* camera = mChain->getViewport()->getCamera();

        // Save last viewport and current aspect ratio
        Viewport* oldViewport = camera->getViewport();
        Real aspectRatio = camera->getAspectRatio();

        Viewport* v = rtt->addViewport( camera );
        v->setClearEveryFrame( false );
        v->setOverlaysEnabled( false );
        v->setBackgroundColour( ColourValue( 0, 0, 0, 0 ) );

        // Should restore aspect ratio, in case of auto aspect ratio
        // enabled, it'll changed when add new viewport.
        camera->setAspectRatio(aspectRatio);
        // Should restore last viewport, i.e. never disturb user code
        // which might based on that.
        camera->_notifyViewport(oldViewport);
    }
    
}
void c2d::ParticleRendererGeometry::viewportChanged(RenderContext& context, const Viewport & viewport)
{
   mConstants.projection.setOrtho(viewport.getWidth(), viewport.getHeight(), -1, 1);

   mpUniformBuffer->set(context, &mConstants, sizeof(mConstants));
}
Ejemplo n.º 17
0
void GraphicsContext::resizedImplementation(int x, int y, int width, int height)
{
    std::set<osg::Viewport*> processedViewports;

    if (!_traits) return;

    double widthChangeRatio = double(width) / double(_traits->width);
    double heigtChangeRatio = double(height) / double(_traits->height);
    double aspectRatioChange = widthChangeRatio / heigtChangeRatio;


    for(Cameras::iterator itr = _cameras.begin();
        itr != _cameras.end();
        ++itr)
    {
        Camera* camera = (*itr);

        // resize doesn't affect Cameras set up with FBO's.
        if (camera->getRenderTargetImplementation()==osg::Camera::FRAME_BUFFER_OBJECT) continue;

        Viewport* viewport = camera->getViewport();
        if (viewport)
        {
            // avoid processing a shared viewport twice
            if (processedViewports.count(viewport)==0)
            {
                processedViewports.insert(viewport);

                if (viewport->x()==0 && viewport->y()==0 &&
                    viewport->width()>=_traits->width && viewport->height()>=_traits->height)
                {
                    viewport->setViewport(0,0,width,height);
                }
                else
                {
                    viewport->x() = static_cast<osg::Viewport::value_type>(double(viewport->x())*widthChangeRatio);
                    viewport->y() = static_cast<osg::Viewport::value_type>(double(viewport->y())*heigtChangeRatio);
                    viewport->width() = static_cast<osg::Viewport::value_type>(double(viewport->width())*widthChangeRatio);
                    viewport->height() = static_cast<osg::Viewport::value_type>(double(viewport->height())*heigtChangeRatio);
                }
            }
        }

        // if aspect ratio adjusted change the project matrix to suit.
        if (aspectRatioChange != 1.0)
        {
            osg::View* view = camera->getView();
            osg::View::Slave* slave = view ? view->findSlaveForCamera(camera) : 0;


            if (slave)
            {
                if (camera->getReferenceFrame()==osg::Transform::RELATIVE_RF)
                {
                    switch(view->getCamera()->getProjectionResizePolicy())
                    {
                        case(osg::Camera::HORIZONTAL): slave->_projectionOffset *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0); break;
                        case(osg::Camera::VERTICAL): slave->_projectionOffset *= osg::Matrix::scale(1.0, aspectRatioChange,1.0); break;
                        default: break;
                    }
                }
                else
                {
                    switch(camera->getProjectionResizePolicy())
                    {
                        case(osg::Camera::HORIZONTAL): camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0); break;
                        case(osg::Camera::VERTICAL): camera->getProjectionMatrix() *= osg::Matrix::scale(1.0, aspectRatioChange,1.0); break;
                        default: break;
                    }
                }
            }
            else
            {
                Camera::ProjectionResizePolicy policy = view ? view->getCamera()->getProjectionResizePolicy() : camera->getProjectionResizePolicy();
                switch(policy)
                {
                    case(osg::Camera::HORIZONTAL): camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0); break;
                    case(osg::Camera::VERTICAL): camera->getProjectionMatrix() *= osg::Matrix::scale(1.0, aspectRatioChange,1.0); break;
                    default: break;
                }

                osg::Camera* master = view ? view->getCamera() : 0;
                if (view && camera==master)
                {
                    for(unsigned int i=0; i<view->getNumSlaves(); ++i)
                    {
                        osg::View::Slave& child = view->getSlave(i);
                        if (child._camera.valid() && child._camera->getReferenceFrame()==osg::Transform::RELATIVE_RF)
                        {
                            // scale the slaves by the inverse of the change that has been applied to master, to avoid them be
                            // scaled twice (such as when both master and slave are on the same GraphicsContexts) or by the wrong scale
                            // when master and slave are on different GraphicsContexts.
                            switch(policy)
                            {
                                case(osg::Camera::HORIZONTAL): child._projectionOffset *= osg::Matrix::scale(aspectRatioChange,1.0,1.0); break;
                                case(osg::Camera::VERTICAL): child._projectionOffset *= osg::Matrix::scale(1.0, 1.0/aspectRatioChange,1.0); break;
                                default: break;
                            }
                        }
                    }
                }


            }

        }

    }

    _traits->x = x;
    _traits->y = y;
    _traits->width = width;
    _traits->height = height;
}
Ejemplo n.º 18
0
util::PointViewportPx projection::toPointViewportPx(const Viewport& viewport, const util::PointWorldCoord& world_coord)
{
    // Returns the world cooridate converted into a viewport pixel.
    return viewport.toPointViewportPx(fetch(viewport).toPointWorldPx(viewport, world_coord));
}
Ejemplo n.º 19
0
//[NOTE] In addition to some Ogre setup, this function configures PagedGeometry in the scene.
void World::load()
{
	//-------------------------------------- LOAD TERRAIN --------------------------------------
	//Setup the fog up to 1500 units away
	sceneMgr->setFog(FOG_LINEAR, viewport->getBackgroundColour(), 0, 100, 900);

	//Load the terrain
	sceneMgr->setWorldGeometry("terrain2.cfg");

	//Start off with the camera at the center of the terrain
	camera->setPosition(700, 100, 700);

	//Setup a skybox
	sceneMgr->setSkyBox(true, "3D-Diggers/SkyBox", 2000);

	//-------------------------------------- LOAD GRASS --------------------------------------
	//Create and configure a new PagedGeometry instance for grass
	grass = new PagedGeometry(camera, 30);
	grass->addDetailLevel<GrassPage>(60);

	//Create a GrassLoader object
	grassLoader = new GrassLoader(grass);
	grass->setPageLoader(grassLoader);	//Assign the "treeLoader" to be used to load geometry for the PagedGeometry instance

	//Supply a height function to GrassLoader so it can calculate grass Y values
	HeightFunction::initialize(sceneMgr);
	grassLoader->setHeightFunction(&HeightFunction::getTerrainHeight);

	//Add some grass to the scene with GrassLoader::addLayer()
	GrassLayer *l = grassLoader->addLayer("3D-Diggers/plant1sprite");

	//Configure the grass layer properties (size, density, animation properties, fade settings, etc.)
	l->setMinimumSize(0.7f, 0.7f);
	l->setMaximumSize(0.9f, 0.9f);
	l->setAnimationEnabled(true);		//Enable animations
	l->setSwayDistribution(7.0f);		//Sway fairly unsynchronized
	l->setSwayLength(0.1f);				//Sway back and forth 0.5 units in length
	l->setSwaySpeed(0.4f);				//Sway 1/2 a cycle every second
	l->setDensity(3.0f);				//Relatively dense grass
	l->setRenderTechnique(GRASSTECH_SPRITE);
	l->setFadeTechnique(FADETECH_GROW);	//Distant grass should slowly raise out of the ground when coming in range

	//[NOTE] This sets the color map, or lightmap to be used for grass. All grass will be colored according
	//to this texture. In this case, the colors of the terrain is used so grass will be shadowed/colored
	//just as the terrain is (this usually makes the grass fit in very well).
	l->setColorMap("terrain_texture2.jpg");

	//This sets the density map that will be used to determine the density levels of grass all over the
	//terrain. This can be used to make grass grow anywhere you want to; in this case it's used to make
	//grass grow only on fairly level ground (see densitymap.png to see how this works).
	l->setDensityMap("densitymap.png");

	//setMapBounds() must be called for the density and color maps to work (otherwise GrassLoader wouldn't
	//have any knowledge of where you want the maps to be applied). In this case, the maps are applied
	//to the same boundaries as the terrain.
	l->setMapBounds(TBounds(0, 0, 1500, 1500));	//(0,0)-(1500,1500) is the full boundaries of the terrain

	//-------------------------------------- LOAD TREES --------------------------------------
	//Create and configure a new PagedGeometry instance
	trees = new PagedGeometry();
	trees->setCamera(camera);	//Set the camera so PagedGeometry knows how to calculate LODs
	trees->setPageSize(50);	//Set the size of each page of geometry
	trees->setInfinite();		//Use infinite paging mode

#ifdef WIND
	//WindBatchPage is a variation of BatchPage which includes a wind animation shader
	trees->addDetailLevel<WindBatchPage>(90, 30);		//Use batches up to 150 units away, and fade for 30 more units
#else
	trees->addDetailLevel<BatchPage>(90, 30);		//Use batches up to 150 units away, and fade for 30 more units
#endif
	trees->addDetailLevel<ImpostorPage>(700, 50);	//Use impostors up to 400 units, and for for 50 more units

	//Create a new TreeLoader2D object
	TreeLoader2D *treeLoader = new TreeLoader2D(trees, TBounds(0, 0, 1500, 1500));
	trees->setPageLoader(treeLoader);	//Assign the "treeLoader" to be used to load geometry for the PagedGeometry instance

	//Supply a height function to TreeLoader2D so it can calculate tree Y values
	HeightFunction::initialize(sceneMgr);
	treeLoader->setHeightFunction(&HeightFunction::getTerrainHeight);

	//[NOTE] This sets the color map, or lightmap to be used for trees. All trees will be colored according
	//to this texture. In this case, the shading of the terrain is used so trees will be shadowed
	//just as the terrain is (this should appear like the terrain is casting shadows on the trees).
	//You may notice that TreeLoader2D / TreeLoader3D doesn't have a setMapBounds() function as GrassLoader
	//does. This is because the bounds you specify in the TreeLoader2D constructor are used to apply
	//the color map.
	treeLoader->setColorMap("terrain_lightmap.jpg");

	//Load a tree entity
	Entity *tree1 = sceneMgr->createEntity("Tree1", "fir05_30.mesh");

	Entity *tree2 = sceneMgr->createEntity("Tree2", "fir14_25.mesh");

#ifdef WIND
	trees->setCustomParam(tree1->getName(), "windFactorX", 15);
	trees->setCustomParam(tree1->getName(), "windFactorY", 0.01);
	trees->setCustomParam(tree2->getName(), "windFactorX", 22);
	trees->setCustomParam(tree2->getName(), "windFactorY", 0.013);
#endif

	//Randomly place 10000 copies of the tree on the terrain
	Ogre::Vector3 position = Ogre::Vector3::ZERO;
	Radian yaw;
	Real scale;
	for (int i = 0; i < 10000; i++){
		yaw = Degree(Math::RangeRandom(0, 360));

		position.x = Math::RangeRandom(0, 1500);
		position.z = Math::RangeRandom(0, 1500);

		scale = Math::RangeRandom(0.07f, 0.12f);

		float rnd = Math::UnitRandom();
		if (rnd < 0.5f)
		{
		//[NOTE] Unlike TreeLoader3D, TreeLoader2D's addTree() function accepts a Vector2D position (x/z)
		//The Y value is calculated during runtime (to save memory) from the height function supplied (above)
		if (Math::UnitRandom() < 0.5f)
			treeLoader->addTree(tree1, position, yaw, scale);
		//else
		//	treeLoader->addTree(tree2, position, yaw, scale);
		}
		else
			treeLoader->addTree(tree2, position, yaw, scale);
	}

	//-------------------------------------- LOAD BUSHES --------------------------------------
	//Create and configure a new PagedGeometry instance for bushes
	bushes = new PagedGeometry(camera, 50);

#ifdef WIND
	bushes->addDetailLevel<WindBatchPage>(80, 50);
#else
	bushes->addDetailLevel<BatchPage>(80, 50);
#endif

	//Create a new TreeLoader2D object for the bushes
	TreeLoader2D *bushLoader = new TreeLoader2D(bushes, TBounds(0, 0, 1500, 1500));
	bushes->setPageLoader(bushLoader);

	//Supply the height function to TreeLoader2D so it can calculate tree Y values
	HeightFunction::initialize(sceneMgr);
	bushLoader->setHeightFunction(&HeightFunction::getTerrainHeight);

	bushLoader->setColorMap("terrain_lightmap.jpg");

	//Load a bush entity
	Entity *fern = sceneMgr->createEntity("Fern", "farn1.mesh");

	Entity *plant = sceneMgr->createEntity("Plant", "plant2.mesh");

	Entity *mushroom = sceneMgr->createEntity("Mushroom", "shroom1_1.mesh");

#ifdef WIND
	bushes->setCustomParam(fern->getName(), "factorX", 1);
	bushes->setCustomParam(fern->getName(), "factorY", 0.01);

	bushes->setCustomParam(plant->getName(), "factorX", 0.6);
	bushes->setCustomParam(plant->getName(), "factorY", 0.02);
#endif

	//Randomly place 20,000 bushes on the terrain
	for (int i = 0; i < 20000; i++){
		yaw = Degree(Math::RangeRandom(0, 360));
		position.x = Math::RangeRandom(0, 1500);
		position.z = Math::RangeRandom(0, 1500);

		float rnd = Math::UnitRandom();
		if (rnd < 0.8f) {
			scale = Math::RangeRandom(0.3f, 0.4f);
			bushLoader->addTree(fern, position, yaw, scale);
		} else if (rnd < 0.9) {
			scale = Math::RangeRandom(0.2f, 0.6f);
			bushLoader->addTree(mushroom, position, yaw, scale);
		} else {
			scale = Math::RangeRandom(0.3f, 0.5f);
			bushLoader->addTree(plant, position, yaw, scale);
		}
	}

}
Ejemplo n.º 20
0
util::PointWorldCoord projection::toPointWorldCoord(const Viewport& viewport, const util::PointViewportPx& viewport_px)
{
    // Return the viewport pixel converted into a world coordinate (uses the current world focus px).
    return toPointWorldCoord(viewport, viewport.toPointWorldPx(viewport_px, viewport.focusPointWorldPx()));
}
Ejemplo n.º 21
0
void LoadEqualizer::_computeSplit( Node* node, const float time,
                                   LBDatas* datas, const Viewport& vp,
                                   const Range& range )
{
    LBLOG( LOG_LB2 ) << "_computeSplit " << vp << ", " << range << " time "
                    << time << std::endl;
    LBASSERTINFO( vp.isValid(), vp );
    LBASSERTINFO( range.isValid(), range );
    LBASSERTINFO( node->resources > 0.f || !vp.hasArea() || !range.hasData(),
                  "Assigning " << node->resources <<
                  " work to viewport " << vp << ", " << range );

    Compound* compound = node->compound;
    if( compound )
    {
        _assign( compound, vp, range );
        return;
    }

    LBASSERT( node->left && node->right );

    LBDatas workingSet = datas[ node->mode ];
    const float leftTime = node->resources > 0 ?
                           time * node->left->resources / node->resources : 0.f;
    float timeLeft = LB_MIN( leftTime, time ); // correct for fp rounding error

    switch( node->mode )
    {
        case MODE_VERTICAL:
        {
            LBASSERT( range == Range::ALL );

            float splitPos = vp.x;
            const float end = vp.getXEnd();

            while( timeLeft > std::numeric_limits< float >::epsilon() &&
                   splitPos < end )
            {
                LBLOG( LOG_LB2 ) << timeLeft << "ms left using "
                                << workingSet.size() << " tiles" << std::endl;

                // remove all irrelevant items from working set
                for( LBDatas::iterator i = workingSet.begin();
                     i != workingSet.end(); )
                {
                    const Data& data = *i;
                    if( data.vp.getXEnd() > splitPos )
                        ++i;
                    else
                        i = workingSet.erase( i );
                }
                if( workingSet.empty( ))
                    break;

                // find next 'discontinouity' in loads
                float currentPos = 1.0f;
                for( LBDatas::const_iterator i = workingSet.begin();
                     i != workingSet.end(); ++i )
                {
                    const Data& data = *i;
                    if( data.vp.x > splitPos && data.vp.x < currentPos )
                        currentPos = data.vp.x;
                    const float xEnd = data.vp.getXEnd();
                    if( xEnd > splitPos && xEnd < currentPos )
                        currentPos = xEnd;
                }

                const float width = currentPos - splitPos;
                LBASSERTINFO( width > 0.f, currentPos << "<=" << splitPos );
                LBASSERT( currentPos <= 1.0f );

                // accumulate normalized load in splitPos...currentPos
                LBLOG( LOG_LB2 ) << "Computing load in X " << splitPos << "..."
                                 << currentPos << std::endl;
                float currentTime = 0.f;
                for( LBDatas::const_iterator i = workingSet.begin();
                     i != workingSet.end(); ++i )
                {
                    const Data& data = *i;

                    if( data.vp.x >= currentPos ) // not yet needed data sets
                        break;

                    float yContrib = data.vp.h;
                    if( data.vp.y < vp.y )
                        yContrib -= (vp.y - data.vp.y);

                    const float dataEnd = data.vp.getYEnd();
                    const float vpEnd   = vp.getYEnd();
                    if( dataEnd > vpEnd )
                        yContrib -= (dataEnd - vpEnd);

                    if( yContrib > 0.f )
                    {
                        const float percentage = ( width / data.vp.w ) *
                                                 ( yContrib / data.vp.h );
                        currentTime += ( data.time * percentage );

                        LBLOG( LOG_LB2 ) << data.vp << " contributes "
                                         << yContrib << " in " << vp.h << " ("
                                         << percentage << ") with " << data.time
                                         << ": " << ( data.time * percentage )
                                         << " vp.y " << vp.y << " dataEnd "
                                         << dataEnd << " vpEnd " << vpEnd
                                         << std::endl;
                        LBASSERT( percentage < 1.01f )
                    }
                }

                LBLOG( LOG_LB2 ) << splitPos << "..." << currentPos << ": t="
                                 << currentTime << " of " << timeLeft
                                 << std::endl;

                if( currentTime >= timeLeft ) // found last region
                {
                    splitPos += ( width * timeLeft / currentTime );
                    timeLeft = 0.0f;
                }
                else
                {
                    timeLeft -= currentTime;
                    splitPos  = currentPos;
                }
            }

            LBLOG( LOG_LB2 ) << "Should split at X " << splitPos << std::endl;
            if( getDamping() < 1.f )
                splitPos = (1.f - getDamping()) * splitPos +
                            getDamping() * node->split;
            LBLOG( LOG_LB2 ) << "Dampened split at X " << splitPos << std::endl;

            // There might be more time left due to MIN_PIXEL rounding by parent
            // LBASSERTINFO( timeLeft <= .001f, timeLeft );

            // Ensure minimum size
            const Compound* root = getCompound();
            const float pvpW = static_cast< float >(
                root->getInheritPixelViewport().w );
            const float boundary = static_cast< float >( node->boundary2i.x()) /
                                       pvpW;
            if( node->left->resources == 0.f )
                splitPos = vp.x;
            else if( node->right->resources == 0.f )
                splitPos = end;
            else if( boundary > 0 )
            {
                const float lengthRight = vp.getXEnd() - splitPos;
                const float lengthLeft = splitPos - vp.x;
                const float maxRight =
                    static_cast< float >( node->right->maxSize.x( )) / pvpW;
                const float maxLeft =
                    static_cast< float >( node->left->maxSize.x( )) / pvpW;
                if( lengthRight > maxRight )
                    splitPos = end - maxRight;
                else if( lengthLeft > maxLeft )
                    splitPos = vp.x + maxLeft;

                if( (splitPos - vp.x) < boundary )
                    splitPos = vp.x + boundary;
                if( (end - splitPos) < boundary )
                    splitPos = end - boundary;

                const uint32_t ratio =
                           static_cast< uint32_t >( splitPos / boundary + .5f );
                splitPos = ratio * boundary;
            }

            splitPos = LB_MAX( splitPos, vp.x );
            splitPos = LB_MIN( splitPos, end);

            const float newPixelW = pvpW * splitPos;
            const float oldPixelW = pvpW * node->split;
            if( int( fabs(newPixelW - oldPixelW) ) < node->resistance2i.x( ))
                splitPos = node->split;
            else
                node->split = splitPos;

            LBLOG( LOG_LB2 ) << "Constrained split " << vp << " at X "
                             << splitPos << std::endl;

            // balance children
            Viewport childVP = vp;
            childVP.w = (splitPos - vp.x);
            _computeSplit( node->left, leftTime, datas, childVP, range );

            childVP.x = childVP.getXEnd();
            childVP.w = end - childVP.x;
            // Fix 2994111: Rounding errors with 2D LB and 16 sources
            //   Floating point rounding may create a width for the 'right'
            //   child which is slightly below the parent width. Correct it.
            while( childVP.getXEnd() < end )
                childVP.w += std::numeric_limits< float >::epsilon();
            _computeSplit( node->right, time-leftTime, datas, childVP, range );
            break;
        }

        case MODE_HORIZONTAL:
        {
            LBASSERT( range == Range::ALL );
            float splitPos = vp.y;
            const float end = vp.getYEnd();

            while( timeLeft > std::numeric_limits< float >::epsilon() &&
                   splitPos < end )
            {
                LBLOG( LOG_LB2 ) << timeLeft << "ms left using "
                                 << workingSet.size() << " tiles" << std::endl;

                // remove all unrelevant items from working set
                for( LBDatas::iterator i = workingSet.begin();
                     i != workingSet.end(); )
                {
                    const Data& data = *i;
                    if( data.vp.getYEnd() > splitPos )
                        ++i;
                    else
                        i = workingSet.erase( i );
                }
                if( workingSet.empty( ))
                    break;

                // find next 'discontinuouity' in loads
                float currentPos = 1.0f;
                for( LBDatas::const_iterator i = workingSet.begin();
                     i != workingSet.end(); ++i )
                {
                    const Data& data = *i;
                    if( data.vp.y > splitPos && data.vp.y < currentPos )
                        currentPos = data.vp.y;
                    const float yEnd = data.vp.getYEnd();
                    if( yEnd > splitPos && yEnd < currentPos )
                        currentPos = yEnd;
                }

                const float height = currentPos - splitPos;
                LBASSERTINFO( height > 0.f, currentPos << "<=" << splitPos );
                LBASSERT( currentPos <= 1.0f );

                // accumulate normalized load in splitPos...currentPos
                LBLOG( LOG_LB2 ) << "Computing load in Y " << splitPos << "..."
                                << currentPos << std::endl;
                float currentTime = 0.f;
                for( LBDatas::const_iterator i = workingSet.begin();
                     i != workingSet.end(); ++i )
                {
                    const Data& data = *i;

                    if( data.vp.y >= currentPos ) // not yet needed data sets
                        break;

                    float xContrib = data.vp.w;

                    if( data.vp.x < vp.x )
                        xContrib -= (vp.x - data.vp.x);

                    const float dataEnd = data.vp.getXEnd();
                    const float vpEnd   = vp.getXEnd();
                    if( dataEnd > vpEnd )
                        xContrib -= (dataEnd - vpEnd);

                    if( xContrib > 0.f )
                    {
                        const float percentage = ( height / data.vp.h ) *
                                                 ( xContrib / data.vp.w );
                        currentTime += ( data.time * percentage );

                        LBLOG( LOG_LB2 ) << data.vp << " contributes "
                                         << xContrib << " in " << vp.w << " ("
                                         << percentage << ") with " << data.time
                                         << ": " << ( data.time * percentage )
                                         << " total " << currentTime << " vp.x "
                                         << vp.x << " dataEnd " << dataEnd
                                         << " vpEnd " << vpEnd << std::endl;
                        LBASSERT( percentage < 1.01f )
                    }
                }

                LBLOG( LOG_LB2 ) << splitPos << "..." << currentPos << ": t="
                                 << currentTime << " of " << timeLeft
                                 << std::endl;

                if( currentTime >= timeLeft ) // found last region
                {
                    splitPos += (height * timeLeft / currentTime );
                    timeLeft = 0.0f;
                }
                else
                {
                    timeLeft -= currentTime;
                    splitPos  = currentPos;
                }
            }

            LBLOG( LOG_LB2 ) << "Should split at Y " << splitPos << std::endl;
            if( getDamping() < 1.f )
                splitPos = (1.f - getDamping( )) * splitPos +
                            getDamping() * node->split;
            LBLOG( LOG_LB2 ) << "Dampened split at Y " << splitPos << std::endl;

            const Compound* root = getCompound();

            const float pvpH = static_cast< float >(
                root->getInheritPixelViewport().h );
            const float boundary = static_cast< float >(node->boundary2i.y( )) /
                                       pvpH;

            if( node->left->resources == 0.f )
                splitPos = vp.y;
            else if( node->right->resources == 0.f )
                splitPos = end;
            else if ( boundary > 0 )
            {
                const float lengthRight = vp.getYEnd() - splitPos;
                const float lengthLeft = splitPos - vp.y;
                const float maxRight =
                    static_cast< float >( node->right->maxSize.y( )) / pvpH;
                const float maxLeft =
                    static_cast< float >( node->left->maxSize.y( )) / pvpH;
                if( lengthRight > maxRight )
                    splitPos = end - maxRight;
                else if( lengthLeft > maxLeft )
                    splitPos = vp.y + maxLeft;

                if( (splitPos - vp.y) < boundary )
                    splitPos = vp.y + boundary;
                if( (end - splitPos) < boundary )
                    splitPos = end - boundary;

                const uint32_t ratio =
                           static_cast< uint32_t >( splitPos / boundary + .5f );
                splitPos = ratio * boundary;
            }

            splitPos = LB_MAX( splitPos, vp.y );
            splitPos = LB_MIN( splitPos, end );

            const float newPixelH = pvpH * splitPos;
            const float oldPixelH = pvpH * node->split;
            if( int( fabs(newPixelH - oldPixelH) ) < node->resistance2i.y( ))
                splitPos = node->split;
            else
                node->split = splitPos;

            LBLOG( LOG_LB2 ) << "Constrained split " << vp << " at Y "
                             << splitPos << std::endl;

            Viewport childVP = vp;
            childVP.h = (splitPos - vp.y);
            _computeSplit( node->left, leftTime, datas, childVP, range );

            childVP.y = childVP.getYEnd();
            childVP.h = end - childVP.y;
            while( childVP.getYEnd() < end )
                childVP.h += std::numeric_limits< float >::epsilon();
            _computeSplit( node->right, time - leftTime, datas, childVP, range);
            break;
        }

        case MODE_DB:
        {
            LBASSERT( vp == Viewport::FULL );
            float splitPos = range.start;
            const float end = range.end;

            while( timeLeft > std::numeric_limits< float >::epsilon() &&
                   splitPos < end )
            {
                LBLOG( LOG_LB2 ) << timeLeft << "ms left using "
                                 << workingSet.size() << " tiles" << std::endl;

                // remove all irrelevant items from working set
                for( LBDatas::iterator i = workingSet.begin();
                     i != workingSet.end(); )
                {
                    const Data& data = *i;
                    if( data.range.end > splitPos )
                        ++i;
                    else
                        i = workingSet.erase( i );
                }
                if( workingSet.empty( ))
                    break;

                // find next 'discontinouity' in loads
                float currentPos = 1.0f;
                for( LBDatas::const_iterator i = workingSet.begin();
                     i != workingSet.end(); ++i )
                {
                    const Data& data = *i;
                    currentPos = LB_MIN( currentPos, data.range.end );
                }

                const float size = currentPos - splitPos;
                LBASSERTINFO( size > 0.f, currentPos << "<=" << splitPos );
                LBASSERT( currentPos <= 1.0f );

                // accumulate normalized load in splitPos...currentPos
                LBLOG( LOG_LB2 ) << "Computing load in range " << splitPos
                                << "..." << currentPos << std::endl;
                float currentTime = 0.f;
                for( LBDatas::const_iterator i = workingSet.begin();
                     i != workingSet.end(); ++i )
                {
                    const Data& data = *i;

                    if( data.range.start >= currentPos ) // not yet needed data
                        break;
#if 0
                    // make sure we cover full area
                    LBASSERTINFO(  data.range.start <= splitPos,
                                   data.range.start << " > " << splitPos );
                    LBASSERTINFO( data.range.end >= currentPos,
                                  data.range.end << " < " << currentPos);
#endif
                    currentTime += data.time * size / data.range.getSize();
                }

                LBLOG( LOG_LB2 ) << splitPos << "..." << currentPos << ": t="
                                 << currentTime << " of " << timeLeft
                                 << std::endl;

                if( currentTime >= timeLeft ) // found last region
                {
                    const float width = currentPos - splitPos;
                    splitPos += (width * timeLeft / currentTime );
                    timeLeft = 0.0f;
                }
                else
                {
                    timeLeft -= currentTime;
                    splitPos  = currentPos;
                }
            }
            LBLOG( LOG_LB2 ) << "Should split at " << splitPos << std::endl;
            if( getDamping() < 1.f )
                splitPos = (1.f - getDamping( )) * splitPos +
                            getDamping() * node->split;
            LBLOG( LOG_LB2 ) << "Dampened split at " << splitPos << std::endl;

            const float boundary( node->boundaryf );
            if( node->left->resources == 0.f )
                splitPos = range.start;
            else if( node->right->resources == 0.f )
                splitPos = end;

            const uint32_t ratio = static_cast< uint32_t >
                      ( splitPos / boundary + .5f );
            splitPos = ratio * boundary;
            if( (splitPos - range.start) < boundary )
                splitPos = range.start;
            if( (end - splitPos) < boundary )
                splitPos = end;

            if( fabs( splitPos - node->split ) < node->resistancef )
                splitPos = node->split;
            else
                node->split = splitPos;

            LBLOG( LOG_LB2 ) << "Constrained split " << range << " at pos "
                             << splitPos << std::endl;

            Range childRange = range;
            childRange.end = splitPos;
            _computeSplit( node->left, leftTime, datas, vp, childRange );

            childRange.start = childRange.end;
            childRange.end   = range.end;
            _computeSplit( node->right, time - leftTime, datas, vp, childRange);
            break;
        }

        default:
            LBUNIMPLEMENTED;
    }
}
Ejemplo n.º 22
0
    MainWindow() : audio_window(settings, mute_item), video_window(settings, *this), input_window(settings, input, [&]{ run(); }),
                   circuit(nullptr), prev_ui_state{false, false, false, false}
    {
        // Load config file
        nall::string config_path = configpath();
        config_path.append("dice/");
        directory::create(config_path);

        settings.filename = {config_path, "settings.cfg"};
        settings.load();
        
        onClose = &Application::quit;

        // Game menu
        game_menu.setText("Game");

        new_game_item.setText("New Game...");
        new_game_item.onActivate = [&] { game_window.create(geometry().position()); };
        game_window.cancel_button.onActivate = [&] { game_window.setModal(false); game_window.setVisible(false); };
        
        game_window.start_button.onActivate = [&]
        {
            GameDesc& g = game_list[game_window.game_view.selection()];
            if(circuit) delete circuit; 
            circuit = new Circuit(settings, *input, *video, g.desc, g.command_line);
            game_window.setModal(false);
            game_window.setVisible(false);
            onSize();
        };

        game_menu.append(new_game_item);

        end_game_item.setText("End Game");
        end_game_item.onActivate = [&] 
        { 
            if(circuit) 
            {
                delete circuit; 
                circuit = nullptr;
            }
            onSize();
        };
        game_menu.append(end_game_item);

        game_menu.append(game_sep[0]);
        pause_item.setText("Pause");
        pause_item.onToggle = [&] { settings.pause = pause_item.checked(); };
        throttle_item.setText("Throttle");
        throttle_item.setChecked(true);
        throttle_item.onToggle = [&]
        { 
            settings.throttle = throttle_item.checked();
            if(settings.throttle && circuit) // Adjust rtc
            {
                uint64_t emu_time = circuit->global_time * 1000000.0 * Circuit::timescale;
                circuit->rtc += int64_t(circuit->rtc.get_usecs()) - emu_time;
            }
        };
        game_menu.append(pause_item, throttle_item);

        game_menu.append(game_sep[1]);
        exit_item.setText("Exit");
        exit_item.onActivate = onClose;
        game_menu.append(exit_item);

        append(game_menu);

        // Settings menu
        settings_menu.setText("Settings");

        audio_item.setText("Audio Settings...");
        settings_menu.append(audio_item);
        audio_item.onActivate = [&] { audio_window.create(geometry().position()); };
        audio_window.onClose = audio_window.exit_button.onActivate = [&] 
        {
            mute_item.setChecked(settings.audio.mute);
            audio_window.setModal(false);
            audio_window.setVisible(false);
            if(circuit) circuit->audio.toggle_mute();
        };
        mute_item.setText("Mute Audio");
        mute_item.setChecked(settings.audio.mute);
        mute_item.onToggle = [&] 
        { 
            settings.audio.mute = mute_item.checked(); 
            if(circuit) circuit->audio.toggle_mute(); 
        };

        settings_menu.append(mute_item);
        settings_menu.append(settings_sep[0]);

        video_item.setText("Video Settings...");
        video_item.onActivate = [&] { video_window.create(geometry().position()); };
        status_visible_item.setText("Status Bar Visible");
        status_visible_item.setChecked(settings.video.status_visible);
        status_visible_item.onToggle = [&] 
        { 
            settings.video.status_visible = status_visible_item.checked();
            setStatusVisible(settings.video.status_visible);
        };
        fullscreen_item.setText("Fullscreen");
        fullscreen_item.onToggle = [&] { toggleFullscreen(fullscreen_item.checked()); };
        settings_menu.append(video_item, status_visible_item, fullscreen_item);

        settings_menu.append(settings_sep[1]);
        input_item.setText("Configure Inputs...");
        input_item.onActivate = [&] { input_window.create(geometry().position()); };
        input_window.onClose = [&] 
        {
            if(input_window.active_selector) input_window.active_selector->assign(KeyAssignment::None);
            input_window.setModal(false);
            input_window.setVisible(false);
        };
        input_window.exit_button.onActivate = [&]
        {
            if(input_window.active_selector) 
                input_window.active_selector->assign(KeyAssignment::None);
            else
            {
                input_window.setModal(false);
                input_window.setVisible(false);
            }
        };

        settings_menu.append(input_item);

        dipswitch_item.setText("Configure DIP Switches...");
        dipswitch_item.onActivate = [&] 
        { 
            int selection = 0;
            if(circuit) for(int i = 0; i < dipswitch_window.game_configs.size(); i++)
            {            
                if(circuit->game_config == dipswitch_window.game_configs[i])
                {
                    selection = i;
                    break;
                }
            }
            dipswitch_window.create(geometry().position(), selection); 
        };
        dipswitch_window.onClose = dipswitch_window.exit_button.onActivate = [&] 
        {
            dipswitch_window.game_configs[dipswitch_window.current_config].save();
            dipswitch_window.setModal(false);
            dipswitch_window.setVisible(false);
        };
        settings_menu.append(settings_sep[2]);
        settings_menu.append(dipswitch_item);

        append(settings_menu);

        setStatusVisible(settings.video.status_visible);

        setBackgroundColor({0, 0, 0});
        layout.setMargin(0);
        viewport = new Viewport();
        layout.append(*viewport, {~0, ~0});
        append(layout);

        // Initialize SDL, input, etc.
        settings.num_mice = ManyMouse_Init();

        if(SDL_Init(SDL_INIT_AUDIO|SDL_INIT_JOYSTICK) < 0)
	    {
	        printf("Unable to init SDL:\n%s\n", SDL_GetError());
		    exit(1);
	    }

        input = new Input();
        video = Video::createDefault(layout, viewport);

        onSize = [&] {

            if((signed)geometry().height < 0 || (signed)geometry().width < 0)
                return;
            
            video->video_init(geometry().width, geometry().height, settings.video);

            if(circuit == nullptr)
            {
                drawLogo();
            }

            viewport->setFocused();
        };

        setTitle(VERSION_STRING);
        setFrameGeometry({(Desktop::workspace().width - 640) / 2, (Desktop::workspace().height - 480) / 2, 640, 480});
        setMenuVisible();
        setVisible();

        onSize();
    }
Ejemplo n.º 23
0
/**
 * Build a path from #_path_builder xpos/ypos to the mouse cursor position.
 * @param mousexy Mouse position.
 */
void PathBuildManager::ComputeNewLongPath(const Point32 &mousexy)
{
	static const TrackSlope slope_prios_down[] = {TSL_DOWN, TSL_FLAT, TSL_UP,   TSL_INVALID}; // Order of preference when going down.
	static const TrackSlope slope_prios_flat[] = {TSL_FLAT, TSL_UP,   TSL_DOWN, TSL_INVALID}; // Order of preference when at the right height.
	static const TrackSlope slope_prios_up[]   = {TSL_UP,   TSL_FLAT, TSL_DOWN, TSL_INVALID}; // Order of preference when going up.

	Viewport *vp = GetViewport();
	if (vp == nullptr) return;

	int c1, c2, c3;
	switch (vp->orientation) {
		case VOR_NORTH: c1 =  1; c2 =  2; c3 =  2; break;
		case VOR_EAST:  c1 = -1; c2 = -2; c3 =  2; break;
		case VOR_SOUTH: c1 =  1; c2 = -2; c3 = -2; break;
		case VOR_WEST:  c1 = -1; c2 =  2; c3 = -2; break;
		default: NOT_REACHED();
	}

	XYZPoint16 path_pos(0, 0, 0);
	path_pos.y = this->pos.y * 256 + 128;
	int32 lambda_y = path_pos.y - mousexy.y; // Distance to constant Y plane at current tile cursor.
	path_pos.x = this->pos.x * 256 + 128;
	int32 lambda_x = path_pos.x - mousexy.x; // Distance to constant X plane at current tile cursor.

	if (abs(lambda_x) < abs(lambda_y)) {
		/* X constant. */
		path_pos.x /= 256;
		path_pos.y = Clamp<int32>(mousexy.y + c1 * lambda_x, 0, _world.GetYSize() * 256 - 1) / 256;
		path_pos.z = Clamp<int32>(vp->view_pos.z + c3 * lambda_x, 0, WORLD_Z_SIZE * 256 - 1) / 256;
	} else {
		/* Y constant. */
		path_pos.x = Clamp<int32>(mousexy.x + c1 * lambda_y, 0, _world.GetXSize() * 256 - 1) / 256;
		path_pos.y /= 256;
		path_pos.z = Clamp<int32>(vp->view_pos.z + c2 * lambda_y, 0, WORLD_Z_SIZE * 256 - 1) / 256;
	}

	if (this->long_pos != path_pos) {
		this->long_pos = path_pos;

		_additions.Clear();
		path_pos = this->pos;
		/* Find the right direction from the selected tile to the current cursor location. */
		TileEdge direction;
		Point16 dxy;
		for (direction = EDGE_BEGIN; direction < EDGE_COUNT; direction++) {
			dxy = _tile_dxy[direction];
			if (!GoodDirection(dxy.x, path_pos.x, this->long_pos.x) || !GoodDirection(dxy.y, path_pos.y, this->long_pos.y)) continue;
			break;
		}
		if (direction == EDGE_COUNT) return;

		/* 'Walk' to the cursor as long as possible. */
		while (path_pos.x != this->long_pos.x || path_pos.y != this->long_pos.y) {
			uint8 slopes = CanBuildPathFromEdge(path_pos, direction);
			const TrackSlope *slope_prio;
			/* Get order of slope preference. */
			if (path_pos.z > this->long_pos.z) {
				slope_prio = slope_prios_down;
			} else if (path_pos.z == this->long_pos.z) {
				slope_prio = slope_prios_flat;
			} else {
				slope_prio = slope_prios_up;
			}
			/* Find best slope, and take it. */
			while (*slope_prio != TSL_INVALID && (slopes & (1 << *slope_prio)) == 0) slope_prio++;
			if (*slope_prio == TSL_INVALID) break;

			path_pos.x += dxy.x;
			path_pos.y += dxy.y;

			const Voxel *v = _world.GetVoxel(path_pos);
			if (v != nullptr && HasValidPath(v)) {
				if (!ChangePath(path_pos, this->path_type, false)) break;

				if (*slope_prio == TSL_UP) path_pos.z++;
			} else {
				if (*slope_prio == TSL_UP) {
					if (!BuildUpwardPath(path_pos, static_cast<TileEdge>((direction + 2) & 3), this->path_type, false)) break;
					path_pos.z++;
				} else if (*slope_prio == TSL_DOWN) {
					v = _world.GetVoxel(path_pos + XYZPoint16(0, 0, -1));

					if (v != nullptr && HasValidPath(v)) {
						if (!ChangePath(path_pos + XYZPoint16(0, 0, -1), this->path_type, false)) break;
					} else {
						if (!BuildDownwardPath(path_pos, static_cast<TileEdge>((direction + 2) & 3), this->path_type, false)) break;
					}
					path_pos.z--;
				} else {
					if (!BuildFlatPath(path_pos, this->path_type, false)) break;
				}
			}
		}
		vp->EnableWorldAdditions();
		vp->EnsureAdditionsAreVisible();
	}
}
Ejemplo n.º 24
0
void FourViewLayout::panActiveViewport(const vec2& delta)
{
	Viewport* vp = this->getActiveViewport();
	if (vp)
		vp->camera->pan(delta.x * vp->getAspect(), delta.y);
}
Ejemplo n.º 25
0
void Config::activateCanvas( Canvas* canvas )
{
    LBASSERT( canvas->isStopped( ));
    LBASSERT( lunchbox::find( getCanvases(), canvas ) != getCanvases().end( ));

    const Layouts& layouts = canvas->getLayouts();
    const Segments& segments = canvas->getSegments();

    for( Layouts::const_iterator i = layouts.begin();
         i != layouts.end(); ++i )
    {
        const Layout* layout = *i;
        if( !layout )
            continue;

        const Views& views = layout->getViews();
        for( Views::const_iterator j = views.begin();
             j != views.end(); ++j )
        {
            View* view = *j;

            for( Segments::const_iterator k = segments.begin();
                 k != segments.end(); ++k )
            {
                Segment* segment = *k;
                Viewport viewport = segment->getViewport();
                viewport.intersect( view->getViewport( ));

                if( !viewport.hasArea( ))
                {
                    LBLOG( LOG_VIEW )
                        << "View " << view->getName() << view->getViewport()
                        << " doesn't intersect " << segment->getName()
                        << segment->getViewport() << std::endl;

                    continue;
                }

                Channel* segmentChannel = segment->getChannel();
                if( !segmentChannel )
                {
                    LBWARN << "Segment " << segment->getName()
                           << " has no output channel" << std::endl;
                    continue;
                }

                if ( findChannel( segment, view ))
                    continue;

                // create and add new channel
                Channel* channel = new Channel( *segmentChannel );
                channel->init(); // not in ctor, virtual method
                channel->setOutput( view, segment );

                //----- compute channel viewport:
                // segment/view intersection in canvas space...
                Viewport contribution = viewport;
                // ... in segment space...
                contribution.transform( segment->getViewport( ));

                // segment output area
                if( segmentChannel->hasFixedViewport( ))
                {
                    Viewport subViewport = segmentChannel->getViewport();
                    LBASSERT( subViewport.isValid( ));
                    if( !subViewport.isValid( ))
                        subViewport = eq::fabric::Viewport::FULL;

                    // ...our part of it
                    subViewport.apply( contribution );
                    channel->setViewport( subViewport );
                    LBLOG( LOG_VIEW )
                        << "View @" << (void*)view << ' ' << view->getViewport()
                        << " intersects " << segment->getName()
                        << segment->getViewport() << " at " << subViewport
                        << " using channel @" << (void*)channel << std::endl;
                }
                else
                {
                    PixelViewport pvp = segmentChannel->getPixelViewport();
                    LBASSERT( pvp.isValid( ));
                    pvp.apply( contribution );
                    channel->setPixelViewport( pvp );
                    LBLOG( LOG_VIEW )
                        << "View @" << (void*)view << ' ' << view->getViewport()
                        << " intersects " << segment->getName()
                        << segment->getViewport() << " at " << pvp
                        << " using channel @" << (void*)channel << std::endl;
                }

                if( channel->getWindow()->isAttached( ))
                    // parent is already registered - register channel as well
                    getServer()->registerObject( channel );
            }
        }
    }
}
Ejemplo n.º 26
0
void ContrastEditLayout::panActiveViewport(const vec2& delta)
{
	Viewport* vp = this->getActiveViewport();
	if (vp)// && vp->name != Viewport::CONTRAST_EDITOR)
		vp->camera->pan(delta.x * vp->getAspect(), delta.y);
}
Ejemplo n.º 27
0
//****************************************************
// sets the window up
//****************************************************
void initScene() {
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Clear to black, fully transparent

    myReshape(viewport.getWidth(),viewport.getHeight());
}
Ejemplo n.º 28
0
void GameStateManager::updateViewport(Game *game, float time)
{
	AnimatedSprite *p = spriteManager->getPlayer();
	PhysicalProperties *pp = p->getPhysicalProperties();
	float pVelX = pp->getVelocityX()*time;
	float pVelY = pp->getVelocityY()*time;

	//VIEWPORT SCOPING
	Viewport *vp = game->getGUI()->getViewport();
	
	if(pVelX < 0 
		&& (pp->round(pp->getX() - vp->getViewportX())) < vp->getViewportWidth()/3)
	{
		vp->setScrollSpeedX(pVelX);
		/*if(vp->getViewportX() == 0)
			vp->setScrollSpeedX(0);*/
	}
	else if(pVelX > 0 
		&& (pp->round(pp->getX() - vp->getViewportX())) > (vp->getViewportWidth()/3*2))
	{
		vp->setScrollSpeedX(pVelX);
		/*if(vp->getViewportX()+vp->getViewportWidth() == world.getWorldWidth())
			vp->setScrollSpeedX(0);*/
		
	}
	else
	{
		vp->setScrollSpeedX(0);
	}

	if(pVelY < 0 
		&& (pp->round(pp->getY() - vp->getViewportY())) < vp->getViewportHeight()/3)
	{
		vp->setScrollSpeedY(pVelY);
		/*if(vp->getViewportY() == 0)
			vp->setScrollSpeedY(0);*/
	}
	else if(pVelY > 0 
		&& (pp->round(pp->getY() - vp->getViewportY())) > (vp->getViewportHeight()/3*2))
	{
		vp->setScrollSpeedY(pVelY);
		/*if(vp->getViewportY()+vp->getViewportHeight() == world.getWorldHeight())
			vp->setScrollSpeedY(0);*/
	}
	else
	{
		vp->setScrollSpeedY(0);
	}

	vp->moveViewport(	vp->getScrollSpeedX(),
						vp->getScrollSpeedY(),
						world.getWorldWidth(),
						world.getWorldHeight());
}
Ejemplo n.º 29
0
void display(void)
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glUseProgram(shader);

	// Enable light sources.
	glEnable(GL_LIGHTING);
	if (lights_enabled[0])
	{
		// Abuse GL_SPOT_CUTOFF as a switch to toggle the light.
		glEnable(GL_LIGHT0);
		glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 1.0f);
		glLightfv(GL_LIGHT0, GL_POSITION, lights[0]);
		glLightfv(GL_LIGHT0, GL_DIFFUSE,  lights_diffuse[0]);
		glLightfv(GL_LIGHT0, GL_SPECULAR, lights_specular[0]);
	}
	else
		glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 0.0f);

	if (lights_enabled[1])
	{
		glEnable(GL_LIGHT1);
		glLightf(GL_LIGHT1, GL_SPOT_CUTOFF, 1.0f);
		glLightfv(GL_LIGHT1, GL_POSITION, lights[1]);
		glLightfv(GL_LIGHT1, GL_DIFFUSE,  lights_diffuse[1]);
		glLightfv(GL_LIGHT1, GL_SPECULAR, lights_specular[1]);
	}
	else
		glLightf(GL_LIGHT1, GL_SPOT_CUTOFF, 0.0f);

	// Copy the orientation matrix to a float array. That's needed so we
	// can pass it to the shaders.
	float oriMatrix[16];
	Mat4 T = win.orientationMatrix();
	for (int i = 0; i < 16; i++)
		oriMatrix[i] = T[i];

	// Same for position of the camera.
	float fpos[3];
	fpos[0] = win.pos().x();
	fpos[1] = win.pos().y();
	fpos[2] = win.pos().z();

	glUniformMatrix4fv(handle_rot, 1, true, oriMatrix);
	glUniform3fv(handle_pos, 1, fpos);
	glUniform1f(handle_eyedist, win.eyedist());
	glUniform1f(handle_stepsize, raymarching_stepsize);
	glUniform1f(handle_accuracy, raymarching_accuracy);
	glUniform4fv(handle_user_params0, 1, user_params[0]);
	glUniform4fv(handle_user_params1, 1, user_params[1]);

	// Draw one quad so that we get one fragment covering the whole
	// screen.
	double r = win.ratio();
	glBegin(GL_QUADS);
	glVertex3f(-r, -1,  0);
	glVertex3f( r, -1,  0);
	glVertex3f( r,  1,  0);
	glVertex3f(-r,  1,  0);
	glEnd();

	// Draw coordinate system?
	if (drawCS)
	{
		glUseProgram(0);
		glDisable(GL_LIGHTING);
		glEnable(GL_DEPTH_TEST);
		glPushMatrix();

		glLineWidth(3.0);

		// In y direction, move to -0.75.
		// In x direction, move to  0.75. From that point on, add the
		// difference of width and height in world coordinates. This
		// will keep the (drawn) coordinate system at a position with a
		// fixed margin to the window borders.
		glTranslated(0.75 + (win.w() - win.h()) / (double)win.h(),
				-0.75, 0);
		glScaled(0.2, 0.2, 0.2);
		glMultMatrixf(oriMatrix);

		glBegin(GL_LINES);

		glColor3f(1.0, 0.0, 0.0);
		glVertex3f(0, 0, 0);
		glVertex3f(1, 0, 0);

		glColor3f(0.0, 1.0, 0.0);
		glVertex3f(0, 0, 0);
		glVertex3f(0, 1, 0);

		glColor3f(0.0, 0.0, 1.0);
		glVertex3f(0, 0, 0);
		glVertex3f(0, 0, 1);

		glEnd();

		glPopMatrix();
		glDisable(GL_DEPTH_TEST);
	}

	glutSwapBuffers();
}
Ejemplo n.º 30
0
/** The method sends a ray into the scene and the point of the closest intersection
    is used to set a new center for the manipulator. For Orbit-style manipulators,
    the orbiting center is set. For FirstPerson-style manipulators, view is pointed
    towards the center.*/
bool StandardManipulator::setCenterByMousePointerIntersection( const GUIEventAdapter& ea, GUIActionAdapter& us )
{
    osg::View* view = us.asView();
    if( !view )
        return false;

    Camera *camera = view->getCamera();
    if( !camera )
        return false;

    // prepare variables
    float x = ( ea.getX() - ea.getXmin() ) / ( ea.getXmax() - ea.getXmin() );
    float y = ( ea.getY() - ea.getYmin() ) / ( ea.getYmax() - ea.getYmin() );
    LineSegmentIntersector::CoordinateFrame cf;
    Viewport *vp = camera->getViewport();
    if( vp ) {
        cf = Intersector::WINDOW;
        x *= vp->width();
        y *= vp->height();
    } else
        cf = Intersector::PROJECTION;

    // perform intersection computation
    ref_ptr< LineSegmentIntersector > picker = new LineSegmentIntersector( cf, x, y );
    IntersectionVisitor iv( picker.get() );
    camera->accept( iv );

    // return on no intersections
    if( !picker->containsIntersections() )
        return false;

    // get all intersections
    LineSegmentIntersector::Intersections& intersections = picker->getIntersections();

    // get current transformation
    osg::Vec3d eye, oldCenter, up;
    getTransformation( eye, oldCenter, up );

    // new center
    osg::Vec3d newCenter = (*intersections.begin()).getWorldIntersectPoint();

    // make vertical axis correction
    if( getVerticalAxisFixed() )
    {

        CoordinateFrame coordinateFrame = getCoordinateFrame( newCenter );
        Vec3d localUp = getUpVector( coordinateFrame );

        fixVerticalAxis( newCenter - eye, up, up, localUp, true );

    }

    // set the new center
    setTransformation( eye, newCenter, up );


    // warp pointer
    // note: this works for me on standard camera on GraphicsWindowEmbedded and Qt,
    //       while it was necessary to implement requestWarpPointer like follows:
    //
    // void QOSGWidget::requestWarpPointer( float x, float y )
    // {
    //    osgViewer::Viewer::requestWarpPointer( x, y );
    //    QCursor::setPos( this->mapToGlobal( QPoint( int( x+.5f ), int( y+.5f ) ) ) );
    // }
    //
    // Additions of .5f are just for the purpose of rounding.
    centerMousePointer( ea, us );

    return true;
}