Exemple #1
0
void Viewer::read()
{
    for( unsigned int i = 0; !m_offset && i < readers.size(); ++i )
    {
        if( readers[i]->empty() ) { continue; }
        Eigen::Vector3d p = readers[i]->somePoint();
        m_offset = std::fabs( p.x() ) > 1000 || std::fabs( p.y() ) > 1000 || std::fabs( p.z() ) > 1000 ? p : Eigen::Vector3d( 0, 0, 0 );
        std::cerr << "view-points: reader no. " << i << " scene offset (" << m_offset->transpose() << "); scene radius: " << scene_radius() << std::endl;
    }
    if( !m_offset ) { return; }
    bool need_update = false;
    for( unsigned int i = 0; i < readers.size(); ++i )
    {
        if( readers[i]->update( *m_offset ) > 0 ) { need_update = true; };
    }
    m_shutdown = true;
    bool ready_to_look = true;
    for( unsigned int i = 0; m_shutdown && i < readers.size(); ++i )
    {
        m_shutdown = m_shutdown && readers[i]->isShutdown();
        ready_to_look = ready_to_look && ( readers[i]->isShutdown() || ( readers.size() > 1 && readers[i]->isStdIn() ) );
    }
    if( !m_cameraReader && m_cameraposition )
    {
        setCameraPosition( *m_cameraposition, *m_cameraorientation );
        m_cameraposition.reset();
        m_cameraorientation.reset();
    }
    else if( m_cameraReader )
    {
        Eigen::Vector3d position = m_cameraReader->position();
        Eigen::Vector3d orientation = m_cameraReader->orientation();
        if( !m_cameraposition || !m_cameraposition->isApprox( position ) || !m_cameraorientation->isApprox( orientation ) )
        {
            m_cameraposition = position;
            m_cameraorientation = orientation;
            setCameraPosition( position, orientation );
        }
    }
    else if( readers[0]->m_extents && readers[0]->m_num_points > 0 && ( m_shutdown || ready_to_look || readers[0]->m_num_points >= readers[0]->size / 10 ) )
    {
        QVector3D min( readers[0]->m_extents->min().x(), readers[0]->m_extents->min().y(), readers[0]->m_extents->min().z() );
        QVector3D max( readers[0]->m_extents->max().x(), readers[0]->m_extents->max().y(), readers[0]->m_extents->max().z() );
        updateView( min, max );
        if( !m_cameraFixed && !m_lookAt )
        {
            m_lookAt = true;
            lookAtCenter();
        }
    }
    if( need_update ) { update(); }
    if( m_shutdown && m_exit_on_end_of_input ) { shutdown(); }
}
	void CutsceneControlState::run(Real elapsedTime)
	{
	    CameraPosition pos = getBestCameraPosition();
	    switch (pos.type)
	    {
	    case CPT_FIXED:
	        setCameraPosition(pos.position);
	        setCameraOrientation(pos.orientation1);
	        break;
	    case CPT_ROTATING:
	        setCameraPosition(pos.position);
	        lookAt(mTarget->getPosition());
	        break;
	    }
	}
void OgreWidget::keyPressEvent(QKeyEvent *e)
{
        static QMap<int, Ogre::Vector3> keyCoordModificationMapping;
        static bool mappingInitialised = false;

        if(!mappingInitialised)
        {
                keyCoordModificationMapping[Qt::Key_W] 		  = Ogre::Vector3( 0, 0,-5);
                keyCoordModificationMapping[Qt::Key_S] 		  = Ogre::Vector3( 0, 0, 5);
                keyCoordModificationMapping[Qt::Key_A] 		  = Ogre::Vector3(-5, 0, 0);
                keyCoordModificationMapping[Qt::Key_D] 		  = Ogre::Vector3( 5, 0, 0);
                keyCoordModificationMapping[Qt::Key_PageUp]   = Ogre::Vector3( 0, 5, 0);
                keyCoordModificationMapping[Qt::Key_PageDown] = Ogre::Vector3( 0,-5, 0);

                mappingInitialised = true;
        }

        QMap<int, Ogre::Vector3>::iterator keyPressed =
                keyCoordModificationMapping.find(e->key());
        if(keyPressed != keyCoordModificationMapping.end() && ogreCamera)
        {
                const Ogre::Vector3 &actualCamPos = ogreCamera->getPosition();
                setCameraPosition(actualCamPos + keyPressed.value());

                e->accept();
        }
    else
    {
        e->ignore();
    }
}
void OgreWidget::mouseMoveEvent(QMouseEvent *e)
{
    if(e->buttons().testFlag(Qt::LeftButton) && oldPos != invalidMousePoint)
    {
        const QPoint &pos = e->pos();
        Ogre::Real deltaX = pos.x() - oldPos.x();
        Ogre::Real deltaY = pos.y() - oldPos.y();

        if(e->modifiers().testFlag(Qt::ControlModifier))
        {
            deltaX *= turboModifier;
            deltaY *= turboModifier;
        }

        Ogre::Vector3 camTranslation(deltaX, deltaY, 0);
        const Ogre::Vector3 &actualCamPos = ogreCamera->getPosition();
        setCameraPosition(actualCamPos + camTranslation);

        oldPos = pos;
        e->accept();
    }
    else
    {
        e->ignore();
    }
}
Exemple #5
0
vpImageSimulator&
vpImageSimulator::operator=(const vpImageSimulator& sim)
{
  for(int i=0;i<4;i++)
  {
    X[i] = sim.X[i];
    pt[i] = sim.pt[i];
  }
  
  Ic = sim.Ic;
  Ig = sim.Ig;
  
  bgColor = sim.bgColor;
  cleanPrevImage = sim.cleanPrevImage;
  
  focal = sim.focal;
  
  normal_obj = sim.normal_obj;
  euclideanNorm_u = sim.euclideanNorm_u;
  euclideanNorm_v = sim.euclideanNorm_v;
  
  colorI = sim.colorI;
  interp = sim.interp;
  
  setCameraPosition(sim.cMt);
  
  return *this;
}
Exemple #6
0
void Projector::loadXML2(ofXml &xml) {
    string str;
    float val;

    // color
    if (xml.exists("[@brightness]")) {
        brightness = ofToFloat( xml.getAttribute("[@brightness]"));
    }
    if (xml.exists("[@contrast]")) {
        contrast = ofToFloat( xml.getAttribute("[@contrast]") );
    }
    if (xml.exists("[@saturation]")) {
        saturation = ofToFloat( xml.getAttribute("[@saturation]") );
    }

    // plane warp
    plane.width = width;
    plane.height = height;
    plane.load(xml, projectorStartingIndex);


    // camera position
    if (xml.exists("[@position]")) {
        str = xml.getAttribute("[@position]");
        float azi  = ofToFloat(ofSplitString(str, ",")[0]);
        float ele  = ofToFloat(ofSplitString(str, ",")[1]);
        float dis  = ofToFloat(ofSplitString(str, ",")[2]);
        setCameraPosition(azi, ele, dis);
    }

    // camera orientation
    if (xml.exists("[@orientation]")) {
        str = xml.getAttribute("[@orientation]");
        float roll = ofToFloat(ofSplitString(str, ",")[0]);
        float tilt = ofToFloat(ofSplitString(str, ",")[1]);
        float pan = ofToFloat(ofSplitString(str, ",")[2]);
        setCameraOrientation(roll, tilt, pan);
    }

    // camera lens fov
    if (xml.exists("[@fov]")) {
        val = ofToFloat( xml.getAttribute("[@fov]") );
        setCameraFov(val);
    }

    //camera lens offset
    if (xml.exists("[@offset]")) {
        str = xml.getAttribute("[@offset]");
        float offX  = ofToFloat(ofSplitString(str, ",")[0]);
        float offY  = ofToFloat(ofSplitString(str, ",")[1]);
        setCameraOffset(offX, offY);
    }

	curves.load(projectorStartingIndex);

    mask.width = width;
    mask.height = height;
    mask.load(projectorStartingIndex);
}
RobotWindow::RobotWindow(double x, double y, double z)
	: WindowControl(),
	  platform(x, y, z),
	  robot(5, platform),
	  textLives(), textGameOver(), textFps(),
	  borderland(8, 200),
	  platformColor()
{
	// registra os parêmtros da criação da classe
	platWidth = x;
	platHeight = y;
	platDeep = z;

	// cria e configura objetos para desenhar os textos
	textGameOver.setFontStyle(GLUT_BITMAP_TIMES_ROMAN_24);
	textGameOver.setText("GAME OVER");
	textGameOver.setPosition(-0.25, 0.1, -1);
	textGameOver.setColor(vermelho);
	textLives.setText("Vidas: %d", robot.getLives());
	textLives.setPosition(-0.95, 0.9, -1);
	textLives.setColor(verde);
	textFps.setText("FPS: %d", getFps());
	textFps.setPosition(-0.95, -0.95, -1);

	// agenda um evento para garantir ao menos um
	// glutPostRedisplay() por segundo
	newEvent(EVENT_POST_REDISPLAY, 1000);
	setFPS(120);

	// executa a configuração do ambiente openGL
    setTitle("SCARA - OpenGL");
	configure();

	// configura a posicição inicial da câmera
	robot.configureLookAt(lookAt);

	// agenda o evento de animação de iniciação do programa
	cameraRadius = 400;
	setCameraPosition(180, 90);
	newEvent(EVENT_RESET, interval);

	// inicia desenhando o limite espacial do jogo
	drawCage = true;

	// define as cores do robô
	platformColor.setColor(cinzaEscuro);
	robot.base.setColor(cinzaMaisEscuro);
	robot.armBase.setColor(amarelo);
	robot.arm.setColor(cinzaMaisEscuro);
    robot.clawBase.setColor(amarelo);
    robot.claw.hand.setColor(vermelho);

	// configurações iniciais de controles do jogo
	mouseX = mouseY = 0;
	mouseButton = 0;
	mouseState = GLUT_UP;
	eventFlying = 0;

}
Exemple #8
0
bool UIMinimap::floorDown()
{
    Position pos = getCameraPosition();
    if(!pos.down())
        return false;
    setCameraPosition(pos);
    return true;
}
void visualization::DetectionVisualizer::configure()
{
  BaseVisualizer::configure();
  setCameraPosition(0.214395, 0.134601, 0.369816, 0.190149, 0.0424081, 1.09322, -0.13325, -0.93753, 0.321374);
  setCameraFieldOfView(0.8575);
  setCameraClipDistances(0.0067374, 6.7374);
  setPosition(637, 145);
  setSize(727, 619);
  ROS_INFO("Initiated detection visualizer!");
}
/**
 * modifica os ângulos de rotação pela entrada de eventos de mouse (movimento)
 */
void RobotWindow::mouseMove(int x, int y) {
	if (mouseButton == GLUT_LEFT_BUTTON && mouseState == GLUT_DOWN) {
		float dx = x - mouseX;
		float dy = y - mouseY;
		cameraLongitude -= (dx * FATOR_ROTACAO_MOUSE);
		cameraLatitude += (dy * FATOR_ROTACAO_MOUSE);
		mouseX = x;
		mouseY = y;
		setCameraPosition(cameraLongitude, cameraLatitude);
		glutPostRedisplay();
	}
}
void GlassViewer::fitCameraToModel(int pad) {
	float sw = MIN(getWidth()*0.5f-pad, getHeight()*0.5f-pad);
	model_t *m = Res_GetModel(model);
	
	float bw = m->bSphere.r;
	float ez = 1/tan(DEG2RAD(fov/2.0));
	
	float Az = m->bSphere.r*2+(bw/sw)*ez;
	
	setCameraPosition(0,-1,m->bmax[AXIS_Z]*0.45f);
	setCameraTarget(0,0,camPos[AXIS_Z]);
	setCameraDistance(Az+pad+m->bSphere.r);
}
void OgreWidget::wheelEvent(QWheelEvent *e)
{
    Ogre::Vector3 zTranslation(0,0, -e->delta() / 60);

    if(e->modifiers().testFlag(Qt::ControlModifier))
    {
        zTranslation.z *= turboModifier;
    }

    const Ogre::Vector3 &actualCamPos = ogreCamera->getPosition();
    setCameraPosition(actualCamPos + zTranslation);

    e->accept();
}
Exemple #13
0
/*!
  Copy constructor
*/
vpImageSimulator::vpImageSimulator(const vpImageSimulator &text)
  : cMt(), pt(), ptClipped(), interp(SIMPLE), normal_obj(), normal_Cam(), normal_Cam_optim(),
    distance(1.), visible_result(1.), visible(false), X0_2_optim(NULL),
    euclideanNorm_u(0.), euclideanNorm_v(0.), vbase_u(), vbase_v(),
    vbase_u_optim(NULL), vbase_v_optim(NULL), Xinter_optim(NULL), listTriangle(),
    colorI(GRAY_SCALED), Ig(), Ic(), rect(), cleanPrevImage(false),
    setBackgroundTexture(false), bgColor(vpColor::white), focal(), needClipping(false)
{
  pt.resize(4);
  for(unsigned int i=0;i<4;i++)
  {
    X[i] = text.X[i];
    pt[i] = text.pt[i];
  }

  for(int i=0;i<4;i++)
    X2[i].resize(3);
  
  Ic = text.Ic;
  Ig = text.Ig;
  
  focal.resize(3);
  focal=0;
  focal[2]=1;

  normal_obj = text.normal_obj;
  euclideanNorm_u = text.euclideanNorm_u;
  euclideanNorm_v = text.euclideanNorm_v;
  
  normal_Cam.resize(3);
  vbase_u.resize(3);
  vbase_v.resize(3);
  
  
  normal_Cam_optim = new double[3];
  X0_2_optim = new double[3];
  vbase_u_optim = new double[3];
  vbase_v_optim = new double[3];
  Xinter_optim = new double[3];
  
  colorI = text.colorI;
  interp = text.interp;
  bgColor = text.bgColor;
  cleanPrevImage = text.cleanPrevImage;
  setBackgroundTexture = false;
  
  setCameraPosition(text.cMt);
}
void GLElbowFlexWidget::paintGL() {

    reset();

    setCameraPosition();

    setState();

    sideView();

    writeData();

    planView();

    frontView();
}
bool RobotWindow::animateReset() {
	// definição empírica de uma desaceleração da queda
	double niceApproximation = (abs(cameraRadius - DEFAUL_RADIUS) / 20) + 0.3;
	// anima a reposição para o raio inicial
	bool action1 = approximate(cameraRadius, niceApproximation, DEFAUL_RADIUS);
	// anima a reposição para a longitude inicial
	bool action2 = circularApproximate(cameraLongitude, 1.5, DEFAULT_LONGITUDE);
	// anima a reposição para a latitude inicial
	bool action3 = circularApproximate(cameraLatitude, 1.5, DEFAULT_LATITUDE);
	// anima a reposição inicial das parte do robô
	bool action4 = robot.animateGoingInitialPosition();
	// se qualquer animação que afeta a câmera foi feita
	if (action1 || action2 || action3) {
		// ajusta a posição da câmera
		setCameraPosition(cameraLongitude, cameraLatitude);
	}
	// retorna indicando se ainda existe animação sendo feita
	return (action1 || action2 || action3 || action4);
}
Exemple #16
0
/*!
  Copy constructor
*/
vpImageSimulator::vpImageSimulator(const vpImageSimulator &text)
{
  for(int i=0;i<4;i++)
  {
    X[i] = text.X[i];
    pt[i] = text.pt[i];
  }

  for(int i=0;i<4;i++)
    X2[i].resize(3);
  
  Ic = text.Ic;
  Ig = text.Ig;
  
  focal.resize(3);
  focal=0;
  focal[2]=1;

  normal_obj = text.normal_obj;
  euclideanNorm_u = text.euclideanNorm_u;
  euclideanNorm_v = text.euclideanNorm_v;
  
  normal_Cam.resize(3);
  vbase_u.resize(3);
  vbase_v.resize(3);
  
  
  normal_Cam_optim = new double[3];
  X0_2_optim = new double[3];
  vbase_u_optim = new double[3];
  vbase_v_optim = new double[3];
  Xinter_optim = new double[3];
  
  colorI = text.colorI;
  interp = text.interp;
  bgColor = text.bgColor;
  cleanPrevImage = text.cleanPrevImage;
  
  setCameraPosition(text.cMt);
}
	static void render()
	{
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //clear the draw buffer

		glEnable( GL_BLEND );

		currentCamera->setAspectRatio(resolution.x/resolution.y);
		setCameraTransMatrix(currentCamera->getCameraTransformationMatrix());
		setPerspectiveMatrix(currentCamera->getPerspectiveMatrix());
		setCameraPosition(currentCamera->getTranslate());
		setLights(wLights,LIGHT_COUNT);
		setAmbientLightColor(vec3(.1,.05,.075));
		setAmbientLightColor(vec3(.1,.1,.2));

		//
		//Draw non-transparent models, pushing transparent ones onto a max-heap
		TransparencyQueue transparencyQueue;
		drawOpaqueEntities(wEntities, transparencyQueue); //Draw Every GameEntity
		drawOpaqueEntities(wWalls, transparencyQueue); //Draw Every Wall
		drawOpaqueEntities(wSoftEntities, transparencyQueue);

		//Draw transparent models, furthest from camera first
		//Disable updating the z-buffer, but still conduct the
		//test so that nearer opaque objects completely occlude
		//farther transparent objects.

		glEnable( GL_BLEND );
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glDepthMask(GL_FALSE);
		while(!transparencyQueue.empty()) {
			transparencyQueue.top()->draw();
			transparencyQueue.pop();
		}
		glDepthMask(GL_TRUE);

		glDisable(GL_BLEND);
	}
/**
 * trata evento de teclados (ASCII)
 */
void RobotWindow::keyboard(unsigned char key, int x, int y) {
	switch(key) {
	// evento de reset da câmera e das posições iniciais
	case 'R':
	case 'r':
		newEvent(EVENT_RESET, interval);
		break;
    // event to go to home posisiton, 6/6/13
    case 'H':
    case 'h':
//        newEvent(EVENT_RESET, interval);
// INSERT CODE HERE
        break;
// event to move as line/circular motion, 6/6/13
    case 'M':
    case 'm':
//        newEvent(EVENT_RESET, interval);
// INSERT CODE HERE
       break;
    // evento de afastamento da câmera
	case 'v':
	case 'V':
		cameraRadius += 0.5;
		setCameraPosition(cameraLongitude, cameraLatitude);
		break;
	// evento de aproximação da câmera
	case 'f':
	case 'F':
		if (cameraRadius >= MIN_CAM_RADIUS) {
			cameraRadius -= 0.5;
			setCameraPosition(cameraLongitude, cameraLatitude);
		}
		break;
	// rotação da base do braço do robô
	case 'z':
	case 'Z':
		if (!robot.isFlying())
			robot.armBase.rotate(1);
		break;
	case 'c':
	case 'C':
		if (!robot.isFlying())
			robot.armBase.rotate(-1);
		break;
    // rotate the base of the claw of robot
    // Added 6/6/13
    case ',':
    case '<':
        if (!robot.isFlying())
            robot.clawBase.rotate(1);
        break;
    case '.':
    case '>':
        if (!robot.isFlying())
            robot.clawBase.rotate(-1);
        break;
    // rotação do braço do robô
	case 'q':
	case 'Q':
		if (!robot.isFlying())
			robot.arm.rotate(1);
		break;
	case 'a':
	case 'A':
		if (!robot.isFlying())
			robot.arm.rotate(-1);
		break;
	// rotação da garra do robô (inclui toda a hélice e os dedos da garra)
	case 'e':
	case 'E':
		if (!robot.isFlying())
			robot.claw.rotate(1);
		break;
	case 'd':
	case 'D':
		if (!robot.isFlying())
			robot.claw.rotate(-1);
		break;
	// rotação dos dedos da garra
	case 'x':
	case 'X':
		robot.claw.finger.rotate(1);
		break;
	case 's':
	case 'S':
		robot.claw.finger.rotate(-1);
		break;
	// alterna estado do robô entre de voando, pousando sobre a base ou resgate
	case 't':
	case 'T':
		// se  o robô está voando
		if (robot.isFlying()) {
			// e já está tentando pousar
			if (getEventId(eventFlying) == EVENT_LANDING) {
				deleteEvent(eventFlying);
				// ativa o modo de resgate
				eventFlying = newEvent(EVENT_RESCUE, interval);
			} else {
				deleteEvent(eventFlying);
				// se está voando, ativa o modo de pouso
				eventFlying = newEvent(EVENT_LANDING, interval);
			}
		} else {
			// se não está voando, inicia o modo de "voando"
			robot.startFlying();
			deleteEvent(eventFlying);
			eventFlying = newEvent(EVENT_START_FLY, interval);
		}
		break;
	// faz uma animação de pouso do robô até sua posição inicial
	case 'y':
	case 'Y':
		if (robot.isFlying()) {
			if (getEventId(eventFlying) == EVENT_FLYING) {
				deleteEvent(eventFlying);
				eventFlying = newEvent(EVENT_SAFE_LANDING, interval);
			}
		}
		break;
	// sobe o robô, caso esteja flutuando (após as animações de início do voo)
	case 'g':
	case 'G':
		robot.moveUp();
		break;
	// desce o robô, caso esteja flutuando (após as animações de início do voo)
	case 'b':
	case 'B':
		robot.moveDown();
		break;
	// modifica o ângulo entre as garras (que formam a hélice)
	case 'i':
	case 'I':
		if (!robot.isFlying())
			robot.claw.rotateAngle(1);
		break;
	case 'k':
	case 'K':
		if (!robot.isFlying())
			robot.claw.rotateAngle(-1);
		break;
	// modifica o ângulo de cada garras (simulando o ângulo de ataque da hélice)
	case 'o':
	case 'O':
		if (!robot.isFlying())
			robot.claw.rotateAttack(0.25);
		break;
	case 'l':
	case 'L':
		if (!robot.isFlying())
			robot.claw.rotateAttack(-0.25);
		break;
	// liga/desliga o desenho da grade de limíte espacial do jogo
	case 'p':
	case 'P':
		drawCage = !drawCage;
		break;
	// modifica o ângulo de deslocamento (usado na rotação das hélices)
	case '+':
	case '=':
		robot.aceleratePropeller(1);
		break;
	case '-':
	case '_':
		robot.aceleratePropeller(-1);
		break;
	default:
		// se não for nenhuma das teclas de comando, retorna sem fazer nada
		return;

	}
	// agenda a renderização do próxim frame
	glutPostRedisplay();
}
Exemple #19
0
int Scenegraph::setCameraPosition(float x, float y, float z)
{
    return setCameraPosition(currentcamera, x, y, z);
}
/**
 * trata os eventos da roda do mouse (equivalentes ao zoom dos pads)
 * aumentando ou diminuindo o raio que representa a distância entre o robô
 * e a câmera
 */
void RobotWindow::mouseWheel(int wheel, int direction, int x, int y) {
	cameraRadius -= direction * 0.2;
	if (cameraRadius < MIN_CAM_RADIUS) cameraRadius = MIN_CAM_RADIUS;
	setCameraPosition(cameraLongitude, cameraLatitude);
	glutPostRedisplay();
}
void WindowManager::MoveCamera(sf::Vector2f direction)
{
	CameraPosition += direction;
	setCameraPosition(CameraPosition);
}
/**
 * realiza a renderização de um frame do jogo
 */
void RobotWindow::display() {

	// ajusta para a matriz de modelo e zera as transformações
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

	// obtém a posição do robô e ajusta câmera para apontar para essa direção
    robot.configureLookAt(lookAt);
    setCameraPosition(cameraLongitude, cameraLatitude);
    gluLookAt(eye.x, eye.y, eye.z, lookAt.x, lookAt.y, lookAt.z, 0.0, 1.0, 0.0);

    // limpa o atual buffer de renderização
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // verifica se o jogo terminou (o robo tem vidas?)
    if (robot.getLives() == 0) {
    	// desenha o Game Over e paralisa a aplicação
    	textGameOver.draw2D();
    	glutSwapBuffers();
    	disableEvents();
    	return;
    } else // senão existem vidas
    	// verifica se o robot deve ser revivido
    	if (!robot.isAlive()) {
    		robot.revive();
    		newEvent(EVENT_RESET, interval);
    	}

    // verifica se deve desenhar o limite espacial do jogo
    if (drawCage) {
    	//glPushMatrix();
    	borderland.draw();
    	//glPopMatrix();
    }

    // desenha a plataforma
    //glPushMatrix();
    glColor4dv(platformColor.getVect());
    platform.draw();
    //glPopMatrix();

    /*/ Desenha uma pequena esfera na posição lookAt para referência visual
    glPushMatrix();
    glTranslated(lookAt.x, lookAt.y, lookAt.z);
    glColor3dv(laranja.getVect());
    glutSolidSphere(0.1, 20, 20);
    glPopMatrix();
	/*/

    // desenha o robô
    //glPushMatrix();
    robot.draw();
    //glPopMatrix();

    // desenha o número de vidas
    textLives.setText("Vidas: %d", robot.getLives());
    textLives.draw2D();

    // desenha o número de Frames Per Second
	textFps.setText("FPS: %d", getFps());
	textFps.draw2D();

	// solicita a saída em vídeo do quadro renderizado
    glutSwapBuffers();
}
Exemple #23
0
void CameraSettings::setDefaultCameraPosition( const Vector3f& position )
{
    defaultCameraPosition_ = position;
    setCameraPosition( position );
}
// inicia os valores padrão da posição da câmera
void RobotWindow::resetCamera() {
	cameraRadius = DEFAUL_RADIUS;
	setCameraPosition(DEFAULT_LONGITUDE, DEFAULT_LATITUDE);
	glutPostRedisplay();
}
	void callbackDisplay() {
		//Render all the TVCameras.
		CameraEntity* const originalCamera = currentCamera;
		for(TVCameraList::iterator i = wTVCameras.begin(); i != wTVCameras.end(); ++i) {
			currentCamera = &(*i)->cameraEntity;
			(*i)->framebuffer.render(&render, 160, 160);
		}
		currentCamera = originalCamera;

		//Render to the screen.
		render();

		//UI hack
		glEnable(GL_BLEND);

		setAmbientLightColor(vec3(1,1,1));
		setCameraTransMatrix(mat4());
		setPerspectiveMatrix(currentCamera->getOrthographicMatrix());
		setCameraPosition(vec3(0,0,.5));

		Wall w=Wall();
		w.translate(-(.4)*(resolution.x/resolution.y),.48,-10);
		w.scale((Globals::getPlayer()->getHealth()/Player::MAX_HEALTH)*.5,.025,.1);

		DrawableEntity d=DrawableEntity(NULL,"Resources/cube.obj");
		d.translate(.5,0,0);
		d.setAlpha(.75);

		w.setModel(d);
		w.draw();

		w.translate(0,-.02,0);
		w.setScale((Globals::getPlayer()->getShieldCharge()/Player::MAX_SHIELD)*.5,.01,.1);
		w.draw();

		glDisable(GL_BLEND);

		//Draw UI Text
		if(useText) {
			Globals::setModelTransMatrix(mat4());
			Text2D n; 
			n.draw_stuff("HEALTH",vec4(1,1,1,1), -0.495*(resolution.x/resolution.y), .4725 );
			n.draw_stuff("SHIELD",vec4(1,1,1,1), -0.495*(resolution.x/resolution.y), .449 );

			char* weaponText="";
			switch(getPlayer()->getWeapon()){
			case 2:
				weaponText="CURVY BULLET";
				break;
			case 0:
				weaponText="MACHINE GUN";
				break;
			case 1:
				weaponText="MORTAR";
				break;

			}
			n.draw_stuff(weaponText,vec4(1,1,1,1), -0.495*(resolution.x/resolution.y), .449-(.4725-.449) );

			if(wScenes[currentLevel]->_beaten){
				n.draw_stuff("You Won!!",vec4(1,1,1,1),-.025,.05);
				n.draw_stuff("Press 'esc' to quit",vec4(1,1,1,1),-.1,0);
			}
		}

		glutSwapBuffers();
	}
void SpaceNavigatorSSM::updateCameraAndMovement()
{	
	// get space navigator and update it
	SpaceNavigatorOSGClient* spaceNavigator = SpaceNavigatorOSGClient::Instance();
	spaceNavigator->update();

	// get walk navigator
	WalkNavigator* wnav = _navigator.getWalkNavigator();

	switch(this->getNavigator()->getMode())
	{
	// walk mode
	case Navigator::WALK:

		// transform picked object
		if(_pickedObjectNode != NullFC)
		{
			/*
			// some dummy variables necessary for Node::getToWorld()
			// only the quaternion rotation is used
			Vec3f dummy1, dummy2;
			Quaternion rotation, dummy3;

			// get the camera rotation in world coordinates
			Matrix camToWorld = getCamera()->getBeacon()->getToWorld();
			camToWorld.getTransform(dummy1, rotation, dummy2, dummy3);
			camToWorld.setIdentity();
			camToWorld.setRotate(rotation);

			// get the transpose of the old object rotation in world coordinates
			Matrix objectToWorld = _pickedObjectNode->getToWorld();
			objectToWorld.getTransform(dummy1, rotation, dummy2, dummy3);
			objectToWorld.setIdentity();
			objectToWorld.setRotate(rotation);	
			objectToWorld.transpose();

			// build the translation vector from the SpaceNavigator input
			Vec3f dv;
			if(_zUpAxis)
				dv.setValues(spaceNavigator->x * transFactor, spaceNavigator->z * transFactor, spaceNavigator->y * transFactor);
			else
				dv.setValues(spaceNavigator->x * transFactor, spaceNavigator->y * transFactor, spaceNavigator->z * transFactor);
			Vec3f dvworld;
			Vec3f dvobject;

			// get the camera to object transformation (only rotation) through multiplying
			// the transposed object to world-rotation with inversed transposed camera to
			// world-rotation
			Matrix camToObject;
			camToObject.setIdentity();
			camToObject.mult(objectToWorld);
			camToObject.mult(camToWorld);
			
			// get translation vector in object coordinates
			camToObject.mult(dv, dvobject);

			// scale should have no effect on translation sensitivity
			dvobject.setValues(dvobject[0] / dummy2[0], dvobject[1] / dummy2[1], dvobject[2]/ dummy2[2]);

			// define the rotation axes in camera coordinates
			Vec3f cameraRE1(1, 0, 0);
			Vec3f cameraRE2(0, 1, 0);
			Vec3f cameraRE3(0, 0, 1);

			// compute the rotation axes in object space through transforming the axes
			// in camera space width camera to object transformation.
			// then a quaternion is created with the transformed axis and value from
			// the SpaceNavigator data
			Vec3f objectRE1;
			Vec3f objectRE2;
			Vec3f objectRE3;
			camToObject.mult(cameraRE1, objectRE1);
			camToObject.mult(cameraRE2, objectRE2);
			camToObject.mult(cameraRE3, objectRE3);
			Quaternion qx(objectRE1, spaceNavigator->rx * rotFactorObject);
			Quaternion qy, qz;
			if(_zUpAxis)
			{
				qy.setValueAsAxisRad(objectRE2, spaceNavigator->rz * rotFactorObject);
				qz.setValueAsAxisRad(objectRE3, spaceNavigator->ry * rotFactorObject);
			}
			else
			{
				qy.setValueAsAxisRad(objectRE2, spaceNavigator->ry * rotFactorObject);
				qz.setValueAsAxisRad(objectRE3, spaceNavigator->rz * rotFactorObject);
			}


			// get the old rotation from the picked object and multiply it with the
			// three quaternions built from the SpaceNavigator data
			Matrix transform = (TransformPtr::dcast(_pickedObjectNode->getCore()))->getMatrix();
			transform.getTransform(dummy1, rotation, dummy2, dummy3);
			rotation.mult(qx);
			rotation.mult(qy);
			rotation.mult(qz);

			// Build the final transformation matrix
			// old transformation * new translation * new rotation (in object coordinates)
			Matrix m;
			m.identity();
			m.setTranslate(dvobject);
			transform.mult(m);
			transform.setRotate(rotation);
			
			// set transformation for ComponentTransforms
			if(_pickedObjectNode->getCore()->getType().isDerivedFrom(ComponentTransform::getClassType()))
			{
				// set translation and rotation separately
				ComponentTransformPtr compTrans = ComponentTransformPtr::dcast(_pickedObjectNode->getCore());
				beginEditCP(compTrans);
					compTrans->setTranslation(Vec3f(transform[3][0], transform[3][1], transform[3][2]));	
					compTrans->setRotation(rotation);
				endEditCP(compTrans);
			}
			// set transformation for normal Transforms
			else if(_pickedObjectNode->getCore()->getType().isDerivedFrom(Transform::getClassType()))
			{
				// set final matrix
				TransformPtr transCore = TransformPtr::dcast(_pickedObjectNode->getCore());
				beginEditCP(transCore, Transform::MatrixFieldMask);
					transCore->setMatrix(transform);
				endEditCP(transCore, Transform::MatrixFieldMask);
			}
			*/
		}
		// camera movement
		else
		{
			// update the camera orientation and position	
			Vec3f trans = spaceNavigator->getTranslation();
			Vec3f rot = spaceNavigator->getRotation();
			
			if(spaceNavigator->getZUpAxis())
			{
				wnav->rotate(-rot.z(), -rot.x());
				wnav->forward(trans.y());
			}
			else
			{
				wnav->rotate(-rot.y(), -rot.x());
				wnav->forward(trans.z());
			}
			wnav->right(-trans.x());

			// update the distance to the ground
			if(spaceNavigator->getHeightControl())
			{
				if(spaceNavigator->getZUpAxis())
					_groundDistance += trans.z();
				else
					_groundDistance += trans.y();
				
				// make sure we never get below the ground
				if(_groundDistance < 0.1f) _groundDistance = 0.1f;
				wnav->setGroundDistance(_groundDistance);
			}

			if(_useElevationGrid)
			{
				Pnt3f pos = getNavigator()->getFrom();
				if(spaceNavigator->getZUpAxis())
					setCameraPosition(Pnt3f(pos[0], pos[1], _grid->GetZ(pos[0], pos[1]) + _groundDistance));
				else
					setCameraPosition(Pnt3f(pos[0], _grid->GetZ(pos[0], pos[2]) + _groundDistance, pos[2]));
			}

		}
		break;

	// normal trackball mode
	case Navigator::TRACKBALL:

		break;
	}
}