示例#1
0
void wxOgre::cameraTrackNode(Ogre::SceneNode* target)
{
	static const wxString camCalcPosCaption(wxT("CalcCamPos:X:%08.4f, Y:%08.4f, Z:%08.4f"));
	static const wxString camRealPosCaption(wxT("CalcCamPos:X:%08.4f, Y:%08.4f, Z:%08.4f"));

	// TODO: Position camera somwehere sensible relative to object
	if (target)
	{
		Ogre::LogManager* logMgr = Ogre::LogManager::getSingletonPtr();
		Ogre::Log* log(logMgr->getDefaultLog());
		mTarget = target;
		Ogre::Vector3 size( target->getAttachedObject(0)->getBoundingBox().getSize() );
		Ogre::Vector3 camPos(target->getPosition() + size * 1.2f); 
		setZoomScale(size.length() / 30.0f);
		mCameraNode->setPosition(camPos);
		mCamera->lookAt(target->getPosition());
		mDebugPanelOverlay->show();
		wxString msg(wxString::Format(camCalcPosCaption, camPos.x, camPos.y, camPos.x));
		log->logMessage(Ogre::String(msg.mb_str(wxConvUTF8)));
		Ogre::Vector3 camRealPos(mCamera->getRealPosition());
		msg = wxString(wxString::Format(camCalcPosCaption, camRealPos.x, camRealPos.y, camRealPos.x));
		log->logMessage(Ogre::String(msg.mb_str(wxConvUTF8)));
	} else {
		mTarget = NULL;
	}

}
示例#2
0
int CcdChapter::OnUpdateGame()
{
	Vector3 camPos(Vector3::ZERO);
	if( m_nKeyState & 1 )
		camPos.z -= 5.f;
	else if( m_nKeyState & 2 )
		camPos.z += 5.f;

	if( m_nKeyState & 4 )
		camPos.x -= 5.f;
	else if( m_nKeyState & 8 )
		camPos.x += 5.f;

	m_pkCamera->moveRelative(camPos);

	if( m_nMouseState & 2 )
	{
		POINT pt;
		GetCursorPos( &pt );
		m_pkCamera->pitch( Degree(m_MousePos.y-pt.y) );
		m_pkCamera->yaw( Degree(m_MousePos.x-pt.x) );
		SetCursorPos(m_MousePos.x, m_MousePos.y);
	}
	return 0;
}
示例#3
0
double Rectangle::intersect(Vector rayVec, Camera camera) const {
  Position vecPos = camera.pos;
  this->applyTransformations(vecPos, rayVec);
  Vector normal(-this->width, 0, this->height);
  Vector objPos(pos.x, pos.y, pos.z);
  Vector camPos(vecPos.x, vecPos.y, vecPos.z);
  Vector B(this->width, 0, this->height);
  double r, d, n;

  d = normal.dot(rayVec);
  n = normal.dot(objPos) - normal.dot(camPos);
  if (d == 0)
    return -1;
  r = n / d;
  if (r < 0)
    return -1;
  return r;
  Position inter;
  inter.x = vecPos.x + r * rayVec.x;
  inter.y = vecPos.y + r * rayVec.y;
  inter.z = vecPos.z + r * rayVec.z;
  Vector interVec(pos.x - inter.x, pos.y - inter.y, pos.z - inter.z);
  interVec.makeUnit();
  B.makeUnit();
  double p = interVec.dot(B);
  // std::cout << p << "\n";
  if (p >= -0.000001 && p <= 0.000001)
    return r;
  return -1;
}
bool CD3DGraphics11::RenderBumpMapShdaer(D3DXMATRIX world, int numIndices, CMaterialDX11 mat)
{
	CGameScene& scene = SYSTEM::PROJECT::GetScene();
	CGameobjectList l = scene.GetLightList();
	int n_l = l.GetNumObjects();
	CCamera* c = scene.GetCamera(0);

	if (!c)
		return false;

	D3DXVECTOR4 amb(mat.GetAmbientColor().r, mat.GetAmbientColor().g, mat.GetAmbientColor().b, mat.GetAmbientColor().a);
	D3DXVECTOR4 spec(mat.GetSpecularColor().r, mat.GetSpecularColor().g, mat.GetSpecularColor().b, mat.GetSpecularColor().a);
	D3DXVECTOR3 camPos(c->GetTransform().GetTranslation().x, c->GetTransform().GetTranslation().y,
		c->GetTransform().GetTranslation().z);

	ID3D11ShaderResourceView* difTex = mat.GetDiffuseTexture();
	ID3D11ShaderResourceView* specTex = mat.GetSpecularMap();
	ID3D11ShaderResourceView* bumpTex = mat.GetBumpMap();

	if (!difTex)
		difTex = m_pDefaultTexture;
	if (!specTex)
		specTex = m_pDefaultTexture;
	if (!bumpTex)
		bumpTex = m_pDefaultTexture;

	return m_bumpMapShader.Render(*this, numIndices, m_matrices.view, world, m_matrices.projection, difTex, specTex, bumpTex, 
		l, n_l,amb, camPos, spec, 64.0f);

	return true;
}
示例#5
0
bool GameRenderer::Initialize(MaterialHandler* mtlHandlerPtr, MeshHandler* meshHandlerPtr, TextureHandler* texHandlerPtr, TransformHandler* transformHandlerPtr)
{
	materialHandler = mtlHandlerPtr;
	meshHandler = meshHandlerPtr;
	textureHandler = texHandlerPtr;
	transformHandler = transformHandlerPtr;

	glfwWindow = glfwGetCurrentContext();

	glfwGetFramebufferSize(glfwWindow, &screenWidth, &screenHeight);

	float ratio = (float)screenWidth / (float) screenHeight;
	glViewport(0, 0, screenWidth, screenHeight);
	glClearColor(0.4f, 0.4f, 0.5f, 1.0f);

	glm::vec3 camPos(0.0f, 25.0f, -70.0f);
	glm::vec3 treePos(0.0f, 0.0f, 0.0f);
	glm::vec3 scalingVector(1.5f);
	glm::vec3 targetOffset = glm::vec3(0.0f, 6.0f, 0.0f) * scalingVector;

	scaleMatrix = glm::scale(glm::mat4(), scalingVector);

	wvpMatrixStruct.projMatrix = glm::perspective(45.0f, ratio, 0.25f, 300.0f);
	wvpMatrixStruct.viewMatrix = glm::lookAt(	
		camPos,
		treePos+targetOffset,
		glm::vec3(0.0f, 1.0f, 0.0f)
		);


	glGenBuffers(1, &matrixUBO);
	glBindBuffer(GL_UNIFORM_BUFFER, matrixUBO);
	glBufferData(GL_UNIFORM_BUFFER, sizeof(Matrices), (void *)(&wvpMatrixStruct), GL_DYNAMIC_DRAW);
	glBindBuffer(GL_UNIFORM_BUFFER, 0);

	SetupRenderPasses();

	//Loading and compiling all shaders etc
	if(!shaderManager.Initialize())
	{
		return false;
	}

	Shader* genericShader = nullptr;
	if(!shaderManager.GetShader("objshader", &genericShader))
	{
		LOG(ERROR) << "Couldn't fetch objshader from shadermanager. Aborting.";
		return false;
	}
	else
	{
		objShader = static_cast<OBJShader*>(genericShader);
		objShader->SetupBuffers(matrixUBO, 0);
	}

	return true;
}
void AppMain()
{
	Vector3 camFr(0.476459, -0.334238, 0.813186);
	Vector3 camUp(00.168968, 0.942489, 0.288382);
	Vector3 camRi = camUp ^ camFr;
	Vector3 camPos(-6, 10, -13);

	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(50,
				   (float)SCREEN_W / (float)SCREEN_H, // Aspect ratio
				   0.1, 1000); // Far plane

	while (!g_keys[KEY_ESC])
	{
		glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

		float camPosMag = camPos.Mag();
		float moveSpeed = 0.01f * camPosMag;
		int velx, vely;
		get_mouse_mickeys(&velx, &vely);
		if (mouse_b & 2)
		{
			camFr.RotateAroundY((float)-velx / 100.0f);
			camUp.RotateAroundY((float)-velx / 100.0f);
			camRi = camUp ^ camFr;
			camFr.RotateAround(camRi, (float)vely / 100.0f);
			camUp.RotateAround(camRi, (float)vely / 100.0f);
			moveSpeed *= 3.0f;
		}

		if (key[KEY_W])	camPos += camFr * moveSpeed;
		if (key[KEY_S])	camPos -= camFr * moveSpeed;
		if (key[KEY_A])	camPos += camRi * moveSpeed;
		if (key[KEY_D])	camPos -= camRi * moveSpeed;
		if (key[KEY_Q]) camPos.y -= moveSpeed;
		if (key[KEY_E]) camPos.y += moveSpeed;

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		Vector3 lookAtPos = camPos + camFr;
		gluLookAt(camPos.x, camPos.y, camPos.z,
				  lookAtPos.x, lookAtPos.y, lookAtPos.z,
				  camUp.x, camUp.y, camUp.z);
	
		DrawGrid(camPos);

		// *** Do the maths we actually want to test
		MainUserLoop();

		allegro_gl_flip();
	}

	return 0;
}
示例#7
0
void OmniMapD3D::LoadAndPush_ProjectiveTexturing_Matricies()
{
  D3DXMATRIX matView;
  D3DXVECTOR3 camPos( ProjectorPosition.pos.x, ProjectorPosition.pos.y, ProjectorPosition.pos.z ); // Camera position
  D3DXVECTOR3 camLookat( ProjectorPosition.lookAtpos.x, ProjectorPosition.lookAtpos.y, ProjectorPosition.lookAtpos.z );   // Look-at point
  D3DXVECTOR3 camUp( ProjectorPosition.headsUp.x, ProjectorPosition.headsUp.y, ProjectorPosition.headsUp.z ); // Up vector

  D3DXMatrixOrthoRH(&worldViewProjection, 2.0, 2.0, 0.0, 1.0f);
  D3DXMatrixLookAtRH( &worldView, &camPos, &camLookat, &camUp);
}
示例#8
0
bool wxOgre::frameEnded(const Ogre::FrameEvent& evt)
{
	static const wxString camPosCaption(wxT("CamPos:X:%06.3f, Y:%06.3f, Z:%06.3f"));
	Ogre::OverlayElement* guiCurr  = Ogre::OverlayManager::getSingleton().getOverlayElement("TextAreaOverlayElement");
	Ogre::Vector3 camPos(mCamera->getRealPosition());
	wxString camText(wxString::Format(camPosCaption, camPos.x, camPos.y, camPos.z));
	guiCurr->setCaption(Ogre::String(camText.mb_str(wxConvUTF8)));
	return true;
		
}
示例#9
0
void getcamPose(cv::Point3f & campose)
{
	cv::Mat invR(3,3,CV_64F);
	invR=rotateMat.t();
	cv::Mat camPos(3,1,CV_64F);	//正交阵求逆
	camPos=invR*tranVector;

   // std::cout<<"invR="<<invR<<std::endl;
	//std::cout<<"camPos"<<camPos<<std::endl;
	campose.x=-1*camPos.at<double>(0,0);
	campose.y=-1*camPos.at<double>(1,0);
	campose.z=-1*camPos.at<double>(2,0);

}
示例#10
0
void ObjcetControl::cameraMove( float x,float y,float z )
{
	//根据箭头与摄像机的距离,动态调整箭头的大小
	Ogre::Vector3 camPos(x,y,z);
	camPos-=mArrowNode->getPosition();
	float camDistance=camPos.squaredLength();
	camDistance/=5000;
	if (camDistance<=1)
	{
		camDistance=1;
	}

	mArrowNode->setScale(camDistance,camDistance,camDistance);
}
示例#11
0
// Disables the game and ship
void ShipRace::DisableGame()
{
	D3DXVECTOR3 camPos(0.0f, 0.0f, -1000.0f);
	gEngine->GetCamera()->SetCamPos(camPos);
	endScreen->SetVisible(true);
	raceTrack->SetTrackStatus(false);
	ship->SetShipStatus(false);
	mIsGameOver = true;

	for (int i = 0; i < 9; ++i)
	{
		mObstacles[i]->SetActive(false);
	}
}
示例#12
0
void CCameraController::update(float dtime)
{
	if (m_active && m_object != nullptr && m_camera != nullptr)
	{
		// Update camera movement
		glm::vec3 pos = m_object->getPosition();
		glm::vec3 forward = m_object->getForward();

		// Where the camera should be
		glm::vec3 camPos(pos.x - forward.x * 8.f, pos.y * 0.95f + 3.f, pos.z - forward.z * 8.f);
		m_camera->setPosition(camPos);

		// Init on first update
		if (m_first)
		{
			m_first = false;
			m_prevLookAt = pos + forward * 3.f;
		}
		// 
		glm::vec3 targetLookAt = pos + forward * 3.f;

		float distance = glm::distance(targetLookAt, m_prevLookAt);
		glm::vec3 d = glm::normalize(targetLookAt - m_prevLookAt);
		
		if (distance > 5.f)
		{
			m_speed = 26.f;
		}
		if (distance < 2.f)
		{
			m_speed = 20.f;
		}
		float move = m_speed * dtime;
		if (move >= distance || distance > 8.f)
		{
			m_prevLookAt = targetLookAt;
		}
		else
		{
			m_prevLookAt += d * move;
		}

		m_camera->lookAt(m_prevLookAt, glm::vec3(0.f, 1.f, 0.f));
	}
}
void OgreWidget::initOgreSystem()
{
    ogreRoot = new Ogre::Root();

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

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

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

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

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

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

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

        setupNLoadResources();
        createScene();
}
示例#14
0
void DistanceSensor::drawObject(const VisualizationParameterSet& visParams)
{
  if(visParams.visualizeSensors && !visParams.drawForSensor)
  {
    glColor3d(visualizationColor.v[0],
      visualizationColor.v[1],
      visualizationColor.v[2]);
    Vector3d camPos(position);
    if(projection == SPHERICAL_PROJECTION)
    {
      glBegin(GL_LINES);
        for(unsigned int i=0; i< sensorDataSize; i++)
        {
          Vector3d distanceVec(sensorReading.data.doubleArray[i],0,0);
          double maxAngle(angleX);
          double zRotation(maxAngle/(double)resolutionX);
          zRotation *= (double)i;
          zRotation -= maxAngle/2.0;
          distanceVec.rotateZ(zRotation);
          distanceVec.rotate(rotation);
          distanceVec+=position;
          glVertex3d (camPos.v[0], camPos.v[1], camPos.v[2]);
          glVertex3d (distanceVec.v[0], distanceVec.v[1], distanceVec.v[2]);
        }
      glEnd();
    }
    else
    {
      Vector3d distanceVec(sensorReading.data.doubleArray[0],0,0);
      distanceVec.rotate(rotation);
      distanceVec+=position;
      //Draw distance vector
      glBegin(GL_LINES);
        glVertex3d (camPos.v[0], camPos.v[1], camPos.v[2]);
        glVertex3d (distanceVec.v[0], distanceVec.v[1], distanceVec.v[2]);
      glEnd();
    }
  }
}
示例#15
0
inline void flua_setCamera(float x, float y, float z, float camAngleX, float camAngleY) {
    glm::vec3 lookat(0, 0, 0);

    lookat.x = sinf(camAngleX) * cosf(camAngleY);
    lookat.y = sinf(camAngleY);
    lookat.z = -cosf(camAngleX) * cosf(camAngleY);

    glm::vec3 camPos(x, y, z);
    glm::vec3 camUp(0.0, 1.0, 0.0);

#ifdef _WIN32
    int nWidth = glutGet(GLUT_WINDOW_WIDTH);
    int nHeight = glutGet(GLUT_WINDOW_HEIGHT);

    if(flua_width != nWidth || flua_height != nHeight) {
        flua_onReshape(nWidth, nHeight);
    }
#endif

    flua_viewMatrix = glm::lookAt(camPos, camPos + lookat, camUp);
    flua_viewAndProjectionMatrix = flua_projectionMatrix * flua_viewMatrix;
}
void SegmentedRayCastingRenderer::preRender() {
    _tfTex->bind(1);

    _shader->setUniform2f("imageScale", 1.0f / (float)_renderWindow->width(), 1.0f / (float)_renderWindow->height());
    _shader->setUniform1f("sampleInterval", (*_ps)["sampleStep"].toFloat() * _model->scaledDim().length());
    _shader->setUniform4f("lightParam", (*_ps)["ambient"].toFloat(), (*_ps)["diffuse"].toFloat(), (*_ps)["specular"].toFloat(), (*_ps)["shininess"].toFloat());
    Vector3 v = _renderWindow->getCamera().getCamPosition();
    Vector3f camPos((float)v.x(), (float)v.y(), (float)v.z());
    _shader->setUniform3f("viewVec", camPos);

    _visOrder.clear();
    for (int i = 0; i < _model->blockCount(); i++) {
        RegularGridDataBlock &dataBlock = _model->volumeDataBlock(i, (*_ps)["timestep"].toInt() - 1, (*_ps)["compIdx"].toInt());
        float dist = (dataBlock.boxCenter() - camPos).length();
        _visOrder.append(std::pair<float, int>(dist, i));
    }
    std::sort(_visOrder.begin(), _visOrder.end());

    for (int i = 0; i < _visOrder.size(); i++)
        qDebug("%d: (%f, %d)", i, _visOrder[i].first, _visOrder[i].second);

}
示例#17
0
vaEngine::Vector cubiverse::VoxelEditor::checkCollision(float p_x, float p_y, float p_z) {
	float matrix[16];
	glGetFloatv( GL_MODELVIEW_MATRIX, matrix );
	vaEngine::Vector camera( matrix[2], matrix[6], matrix[10] );
	camera = camera / 2.0f;

	vaEngine::Vector camPos(p_x, p_y, p_z);

	cout << "X:" << camera[0] << " Y:" << camera[1] << " Z:" << camera[2] << endl;
	if(p_y > 20 && camera.y > 0) {
		bool run = true;
		while(camPos.y > 20 && run) {
			camPos = camPos - camera;
			for(int mesh = 0; mesh < meshs.size(); mesh++) {
				if(hasVoxel(camPos.x,camPos.y,camPos.z, mesh)) run = false;
			}
		}
		cout << "FOUND POS:" << camPos.x  << " : " << camPos.z << endl;
		return camPos;
	}			
	

}
示例#18
0
void Camera::aim()
{
	// Get the window size
	int width, height;
	glfwGetWindowSize(&width, &height);
	// Make sure that height is non-zero to avoid division by zero
	height = height < 1 ? 1 : height;

	glViewport(0, 0, width, height);

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Set up the projection matrix  
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	// Window aspect (assumes square pixels)
	float aspectRatio = (float)width / (float)height;
	// Set perspective view
	gluPerspective(mFov, aspectRatio, mNearPlane, mFarPlane);

	vec3 camPos(mLookX + mRadius * std::cos(DEG2RAD(mHead)) * std::cos(DEG2RAD(mPitch)),
				mLookY + mRadius * std::sin(DEG2RAD(mHead)),
				mLookZ + mRadius * std::cos(DEG2RAD(mHead)) * std::sin(DEG2RAD(mPitch)));

	mForward = vec3(mLookX - camPos.x, mLookY - camPos.y, mLookZ - camPos.z);
	mForward = glm::normalize(mForward);
	vec3 up = vec3(0.0f, (std::cos(DEG2RAD(mHead)) > 0.0f) ? 1.0f : -1.0f, 0.0f);
	mSide = glm::cross(mForward, up);
	mUp = glm::cross(mSide, mForward);

	// Set up modelview matrix
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	gluLookAt(camPos.x, camPos.y, camPos.z,
		mLookX, mLookY, mLookZ,
		up.x, up.y, up.z); 
}
示例#19
0
void SeleneDev::CGame::Tick(float deltaTime)
{
	Selene::CVirtualFileSystem* pVfs = GetSupervisor()->GetVFS();
	Selene::CGraphics* pGraphics = GetSupervisor()->GetGraphics();

	// test
	//
	m_ElapsedTime += deltaTime;
	float period = 8.0f;
	float phaseTime = fmodf(m_ElapsedTime, period);
	float phase = phaseTime / period;
	float radius = 10.0f;
	float pi = 3.141592f;
	Selene::Vector3 camPos(13.0f, 10.0, 4.0f);
	Selene::Vector3 lookAt(-1.5f, 1.0f, -5.0f);
	Selene::Vector3 camUp(0.0f, 1.0f, 0.0f);
	camPos.m_X = cosf(pi * 2.0f * phase) * radius + lookAt.m_X;
	camPos.m_Z = sinf(pi * 2.0f * phase) * radius + lookAt.m_Z;
	//pGraphics->GetActiveCamera()->Look(camPos, lookAt, camUp);

	m_pTestNode->Update(deltaTime);
	m_pFpsNode->Update(deltaTime);
	m_pHudNode->Update(deltaTime);
}
示例#20
0
bool CD3DGraphics11::RenderTextureLightingShader(D3DXMATRIX world, int numIndices, CMaterialDX11 mat)
{
	CGameScene& scene = SYSTEM::PROJECT::GetScene();
	CGameobjectList l = scene.GetLightList();
	int n_l = l.GetNumObjects();
	CCamera* c = scene.GetCamera(0);

	if(!c)
		return false;

	D3DXVECTOR4 amb(mat.GetAmbientColor().r,mat.GetAmbientColor().g,mat.GetAmbientColor().b,mat.GetAmbientColor().a);
	D3DXVECTOR4 spec(mat.GetSpecularColor().r,mat.GetSpecularColor().g,mat.GetSpecularColor().b,mat.GetSpecularColor().a);
	D3DXVECTOR3 camPos(c->GetTransform().GetTranslation().x,c->GetTransform().GetTranslation().y,
		c->GetTransform().GetTranslation().z);

	if (mat.GetDiffuseTexture())
		return m_textureLightingShader.Render(*this, numIndices, m_matrices.view, world, m_matrices.projection, mat.GetDiffuseTexture(),
			l, n_l, amb, camPos, spec, 64.0f);
	else
		return m_textureLightingShader.Render(*this, numIndices, m_matrices.view, world, m_matrices.projection, m_pDefaultTexture,
			l, n_l, amb, camPos, spec, 64.0f);

	return true;
}
示例#21
0
bool CameraMan::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
	// update accelerations
	Ogre::Vector3 accel = calculateAccelerations();

	// if accelerating, try to reach top speed in a certain time
	Ogre::Real topSpeed = mFastMove ? mTopSpeed * 2 : mTopSpeed;
	double y_tmp = mVelocity.y;
	if (accel.squaredLength() != 0)
	{
		accel.normalise();
		mVelocity += accel * topSpeed * evt.timeSinceLastFrame * 10;
	}
	// if not accelerating, try to stop in a certain time
	else 
	{
		mVelocity -= mVelocity * evt.timeSinceLastFrame * 10;
	}
	mVelocity.y = y_tmp;

	// vertical movement
	if (mJump) mVelocity.y = jumpSpeed;
	mJump = false;
	mVelocity.y -= gravityAccel * evt.timeSinceLastFrame;

	Ogre::Real tooSmall = std::numeric_limits<Ogre::Real>::epsilon();

	y_tmp = mVelocity.y;
	mVelocity.y = 0;
	// keep camera velocity below top speed and above epsilon
	if (mVelocity.squaredLength() > topSpeed * topSpeed)
	{
		mVelocity.normalise();
		mVelocity *= topSpeed;
	}
	else if (mVelocity.squaredLength() < tooSmall * tooSmall)
	{
		mVelocity = Ogre::Vector3::ZERO;
	}
	mVelocity.y = y_tmp;

	// terrain handling, raycast each unit direction
	PolyVox::RaycastResult resultXH;
	PolyVox::RaycastResult resultXL;
	PolyVox::RaycastResult resultY;
	PolyVox::RaycastResult resultZH;
	PolyVox::RaycastResult resultZL;

	double width = 0.5;
	PolyVox::Vector3DFloat cameraPos( mCamera->getPosition().x, mCamera->getPosition().y,						mCamera->getPosition().z );
	PolyVox::Vector3DFloat cameraPosH( mCamera->getPosition().x, mCamera->getPosition().y + width,				mCamera->getPosition().z );
	PolyVox::Vector3DFloat cameraPosL( mCamera->getPosition().x, mCamera->getPosition().y - charHeight + width,	mCamera->getPosition().z );

	if( mVelocity.x > 0 )
	{
		mTerrain->raycast( cameraPosH, PolyVox::Vector3DFloat( width, 0, 0), resultXH);
		mTerrain->raycast( cameraPosL, PolyVox::Vector3DFloat( width, 0, 0), resultXL);
	}
	else if( mVelocity.x < 0 )
	{
		mTerrain->raycast( cameraPosH, PolyVox::Vector3DFloat(-width, 0, 0), resultXH);
		mTerrain->raycast( cameraPosL, PolyVox::Vector3DFloat(-width, 0, 0), resultXL);
	}
	else
	{
		resultXH.foundIntersection = false;
		resultXL.foundIntersection = false;
	}

	if( mVelocity.y > 0 )
	{
		mTerrain->raycast( cameraPosH, PolyVox::Vector3DFloat( 0, width, 0), resultY);
	}
	else if( mVelocity.y < 0 )
	{
		mTerrain->raycast( cameraPosL, PolyVox::Vector3DFloat( 0,-width, 0), resultY);
	}
	else
	{
		resultY.foundIntersection = false;
	}

	if( mVelocity.z > 0 )
	{
		mTerrain->raycast( cameraPosH, PolyVox::Vector3DFloat( 0, 0, width), resultZH);
		mTerrain->raycast( cameraPosL, PolyVox::Vector3DFloat( 0, 0, width), resultZL);
	}
	else if( mVelocity.z < 0 )
	{
		mTerrain->raycast( cameraPosH, PolyVox::Vector3DFloat( 0, 0,-width), resultZH);
		mTerrain->raycast( cameraPosL, PolyVox::Vector3DFloat( 0, 0,-width), resultZL);
	}
	else
	{
		resultZH.foundIntersection = false;
		resultZL.foundIntersection = false;
	}

	Ogre::Vector3 camPos( mCamera->getPosition() );
	// handle horizontal movement
	if( resultXH.foundIntersection || resultXL.foundIntersection )
	{
		mVelocity.x = 0;
		
		if( resultXH.foundIntersection )
		{
			camPos.x = resultXH.previousVoxel.getX();
		}
		else
		{
			camPos.x = resultXL.previousVoxel.getX();
		}
	}
	if( resultZH.foundIntersection || resultZL.foundIntersection )
	{
		mVelocity.z = 0;

		if( resultZH.foundIntersection )
		{
			camPos.z = resultZH.previousVoxel.getZ();
		}
		else
		{
			camPos.z = resultZL.previousVoxel.getZ();
		}
	}

	// handle ground/ceiling
	if( resultY.foundIntersection )
	{
		camPos.y = resultY.previousVoxel.getY();
		if( mVelocity.y < 0 )
		{
			camPos.y += charHeight - 1.0;
		}

		mVelocity.y = 0;
	}
	else
	{
		if( mVelocity.y < -fallSpeedMax )
		{
			mVelocity.y = -fallSpeedMax;
		}
	}

	// set new position, not in a voxel
	mCamera->setPosition( camPos );

	if (mVelocity != Ogre::Vector3::ZERO) mCamera->move(mVelocity * evt.timeSinceLastFrame);

	return true;
}
示例#22
0
void Mesh::Draw(Shader shader, bool drawFBO)
{
	// Bind appropriate textures
	GLuint diffuseNr = 1;
	GLuint specularNr = 1;
	GLuint reflectionNr = 1;

	//设备坐标系->纹理坐标系
	glm::mat4 biasMatrix(
		0.5, 0.0, 0.0, 0.0,
		0.0, 0.5, 0.0, 0.0,
		0.0, 0.0, 0.5, 0.0,
		0.5, 0.5, 0.5, 1.0
		);

	for (GLuint i = 0; i < this->textures.size(); i++)
	//int i = 1;
	{
		//float w = this->cam_pos[this->textures[i].id].at<float>(3, 0);
		glm::vec3 imageNorm(this->img_norm[this->textures[i].id].at<float>(0, 0), this->img_norm[this->textures[i].id].at<float>(1, 0), 
			this->img_norm[this->textures[i].id].at<float>(2, 0));
		glm::vec3 camPos(this->cam_pos[this->textures[i].id].at<float>(0, 0), this->cam_pos[this->textures[i].id].at<float>(1, 0), 
			this->cam_pos[this->textures[i].id].at<float>(2, 0));
		
		//cv::Mat VM = this->viewMatrices[i] * this->modelMatrix;// .inv() * this->modelMatrix.inv();
		cv::Mat VM = this->viewMatrices[i].inv() * this->modelMatrix.inv();

		cv::Mat vVM(VM, cv::Rect(3, 0, 1, 4));

		glm::vec3 cam(vVM.at<float>(0, 0), vVM.at<float>(1, 0), vVM.at<float>(2, 0));

		// Compute the MVP matrix from the light's point of view
		glm::mat4 depthProjectionMatrix = glm::perspective<float>(45.0f, 1.0f, near_plane, far_plane);

		glm::vec3 origin(0, 0, 0);
		glm::mat4 depthViewMatrix = glm::lookAt(camPos, origin, glm::vec3(0, 1, 0));//glm::lookAt(lightInvDir, glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
		
		glm::mat4 depthModelMatrix;
		
		depthModelMatrix = glm::scale(depthModelMatrix, glm::vec3(0.01f, 0.01f, 0.01f));	// It's a bit too big for our scene, so scale it down
		glm::mat4 depthMVP = depthProjectionMatrix * depthViewMatrix * depthModelMatrix;

		
		if (drawFBO == false)
		{
			
			glActiveTexture(GL_TEXTURE0 + i); // Active proper texture unit before binding
			// Retrieve texture number (the N in diffuse_textureN)
			stringstream ss;
			string number;
			string name = this->textures[i].type;
			if (name == "texture_diffuse")
				ss << diffuseNr++; // Transfer GLuint to stream
			
			number = ss.str();
			// Now set the sampler to the correct texture unit
			glUniform1i(glGetUniformLocation(shader.Program, ( name).c_str()), i);

			glUniform3fv(glGetUniformLocation(shader.Program, "imgNorm" ), 1, glm::value_ptr(imageNorm));

			glUniform3fv(glGetUniformLocation(shader.Program, "camPos"), 1, glm::value_ptr(camPos));

			// And finally bind the texture
			glBindTexture(GL_TEXTURE_2D, i+1);
			
			glm::mat4 depthBiasMVP = biasMatrix*depthMVP;
			glUniformMatrix4fv(glGetUniformLocation(shader.Program, "DepthBiasMVP"), 1, GL_FALSE, glm::value_ptr(depthBiasMVP));

			//zhongyao
			int d = this->textures.size() + i;
			glActiveTexture(GL_TEXTURE0 + d);
			glBindTexture(GL_TEXTURE_2D, in.depthTexture[i]);
			glUniform1i(glGetUniformLocation(shader.Program, "shadowMap"), d);

			glEnable(GL_CULL_FACE);
			glCullFace(GL_BACK); // Cull back-facing triangles -> draw only front-facing triangles
			glBindVertexArray(this->VAO[textures[i].id]);
			glDrawElements(GL_TRIANGLES, this->indices4draw[textures[i].id].size(), GL_UNSIGNED_INT, 0);
			glCullFace(GL_FRONT); // Cull back-facing triangles -> draw only front-facing triangles
			glBindVertexArray(0);
		}
		else
		{
			glBindFramebuffer(GL_DRAW_FRAMEBUFFER, in.depthMapFBO[i]);
			
			// Clear the screen
			glClear(GL_DEPTH_BUFFER_BIT);

			glm::mat4 shadowProj = glm::perspective(90.0f, 1.0f, 1.0f, 25.0f);

			glm::mat4 depthMVPD = shadowProj *
				glm::lookAt(camPos, camPos + glm::vec3(1.0, 0.0, 0.0), glm::vec3(0.0, -1.0, 0.0));
			glUniformMatrix4fv(glGetUniformLocation(shader.Program, "depthMVP"), 1, GL_FALSE, glm::value_ptr(depthMVPD));
			
			glEnable(GL_CULL_FACE);
			glCullFace(GL_BACK); // Cull back-facing triangles -> draw only front-facing triangles
			glBindVertexArray(this->VAO[textures[i].id]);
			glDrawElements(GL_TRIANGLES, this->indices4draw[textures[i].id].size(), GL_UNSIGNED_INT, 0);
			glCullFace(GL_FRONT);
			glBindVertexArray(0);
			
		}
		glActiveTexture(GL_TEXTURE0);	
	}
}
//--------------------------------------------------------------------------------------------------
std::vector<PointData> generateImagePoints( const cv::Mat& cameraWorldMtx, const cv::Mat& cameraCalibMtx,
        int32_t imageWidth, int32_t imageHeight, const cv::Mat& chessboardPoseMtx )
{
    std::vector<PointData> points;
    points.reserve( imageWidth*imageHeight );

    cv::Mat camAxisX( cameraWorldMtx, cv::Rect( 0, 0, 1, 3 ) );
    cv::Mat camAxisY( cameraWorldMtx, cv::Rect( 1, 0, 1, 3 ) );
    cv::Mat camAxisZ( cameraWorldMtx, cv::Rect( 2, 0, 1, 3 ) );
    cv::Mat camPos( cameraWorldMtx, cv::Rect( 3, 0, 1, 3 ) );

    cv::Mat chessboardAxisX( chessboardPoseMtx, cv::Rect( 0, 0, 1, 3 ) );
    cv::Mat chessboardAxisY( chessboardPoseMtx, cv::Rect( 1, 0, 1, 3 ) );
    cv::Mat chessboardAxisZ( chessboardPoseMtx, cv::Rect( 2, 0, 1, 3 ) );
    cv::Mat chessboardPos( chessboardPoseMtx, cv::Rect( 3, 0, 1, 3 ) );

    double chessboardPlaneDist = cv::Mat( chessboardPos.t()*chessboardAxisZ ).at<double>( 0 );

    // Used to calculate plane intersection
    double intersectionConstant = chessboardPlaneDist - cv::Mat(camPos.t()*chessboardAxisZ).at<double>( 0 );

    // Generate the image points using very simple ray tracing
    for ( int32_t y = 0; y < imageHeight; y++ )
    {
        for ( int32_t x = 0; x < imageWidth; x++ )
        {
            double imagePlaneX = (x - cameraCalibMtx.at<double>( 0, 2 )) / cameraCalibMtx.at<double>( 0, 0 );
            double imagePlaneY = (y - cameraCalibMtx.at<double>( 1, 2 )) / cameraCalibMtx.at<double>( 1, 1 );
            cv::Mat rayDir = camAxisZ + imagePlaneX*camAxisX + imagePlaneY*camAxisY;

            double cosOfAngleToChessboard = cv::Mat(rayDir.t()*chessboardAxisZ).at<double>( 0 );
            if ( 0.0 != cosOfAngleToChessboard )
            {
                double distanceToBoard = intersectionConstant/cosOfAngleToChessboard;

                if ( distanceToBoard > 0.0 )
                {
                    cv::Mat intersectionPos = camPos + rayDir*distanceToBoard;
                    cv::Mat fromCentreVec = intersectionPos - chessboardPos;

                    double chessX = cv::Mat(chessboardAxisX.t()*fromCentreVec).at<double>( 0 );
                    double chessY = cv::Mat(chessboardAxisY.t()*fromCentreVec).at<double>( 0 );

                    ePixelColour pixelColour = ePC_None;

                    if ( gbDrawCircles )
                    {
                        double boardU = chessX + 0.5*CHESSBOARD_TOTAL_WIDTH;
                        double boardV = chessY + 0.5*CHESSBOARD_TOTAL_HEIGHT;
                        pixelColour = getCircleboardPixelColour( boardU, boardV );
                    }
                    else
                    {
                        double u = chessX/CHESSBOARD_TOTAL_WIDTH + 0.5;
                        double v = chessY/CHESSBOARD_TOTAL_HEIGHT + 0.5;
                        pixelColour = getChessboardPixelColour( u, v );
                    }

                    if ( ePC_None != pixelColour )
                    {
                        PointData pointData;
                        pointData.mPixelX = x;
                        pointData.mPixelY = y;
                        pointData.mWorldX = intersectionPos.at<double>( 0 );
                        pointData.mWorldY = intersectionPos.at<double>( 1 );
                        pointData.mWorldZ = intersectionPos.at<double>( 2 );
                        pointData.mPixelColour = pixelColour;

                        points.push_back( pointData );
                    }
                }
            }
        }
    }

    return points;
}
示例#24
0
void ScatterSky::_render( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
{
   if ( overrideMat || (!mShader && !_initShader()) )
      return;

   GFXTransformSaver saver;

   if ( mVB.isNull() || mPrimBuffer.isNull() )
      _initVBIB();

   GFX->setShader( mShader );
   GFX->setShaderConstBuffer( mShaderConsts );

   Point4F sphereRadii( mSphereOuterRadius, mSphereOuterRadius * mSphereOuterRadius,
                        mSphereInnerRadius, mSphereInnerRadius * mSphereInnerRadius );

   Point4F scatteringCoeffs( mRayleighScattering * mSkyBrightness, mRayleighScattering4PI,
                             mMieScattering * mSkyBrightness, mMieScattering4PI );

   Point4F invWavelength(  1.0f / mWavelength4[0],
                           1.0f / mWavelength4[1],
                           1.0f / mWavelength4[2], 1.0f );

   Point3F camPos( 0, 0, smViewerHeight );
   Point4F miscParams( camPos.z, camPos.z * camPos.z, mScale, mScale / mRayleighScaleDepth );

   Frustum frust = state->getFrustum();
   frust.setFarDist( smEarthRadius + smAtmosphereRadius );
   MatrixF proj( true );
   frust.getProjectionMatrix( &proj );

   Point3F camPos2 = state->getCameraPosition();
   MatrixF xfm(true);
   xfm.setPosition(camPos2);//-Point3F( 0, 0, 200000.0f));
   GFX->multWorld(xfm);
   MatrixF xform(proj);//GFX->getProjectionMatrix());
   xform *= GFX->getViewMatrix();
   xform *=  GFX->getWorldMatrix();

   mShaderConsts->setSafe( mModelViewProjSC, xform );
   mShaderConsts->setSafe( mMiscSC, miscParams );
   mShaderConsts->setSafe( mSphereRadiiSC, sphereRadii );
   mShaderConsts->setSafe( mScatteringCoefficientsSC, scatteringCoeffs );
   mShaderConsts->setSafe( mCamPosSC, camPos );
   mShaderConsts->setSafe( mLightDirSC, mLightDir );
   mShaderConsts->setSafe( mSunDirSC, mSunDir );
   mShaderConsts->setSafe( mNightColorSC, mNightColor );
   mShaderConsts->setSafe( mInverseWavelengthSC, invWavelength );
   mShaderConsts->setSafe( mNightInterpolantAndExposureSC, Point2F( mExposure, mNightInterpolant ) );
   mShaderConsts->setSafe( mColorizeSC, mColorize*mColorizeAmt );

   if ( GFXDevice::getWireframe() )
   {
      GFXStateBlockDesc desc( mStateBlock->getDesc() );
      desc.setFillModeWireframe();
      GFX->setStateBlockByDesc( desc );
   }
   else
      GFX->setStateBlock( mStateBlock );

   if ( mUseNightCubemap && mNightCubemap )
   {
      mShaderConsts->setSafe( mUseCubemapSC, 1.0f );

      if ( !mNightCubemap->mCubemap )
         mNightCubemap->createMap();

      GFX->setCubeTexture( 0, mNightCubemap->mCubemap );
   }
   else
   {
      GFX->setCubeTexture( 0, NULL );
      mShaderConsts->setSafe( mUseCubemapSC, 0.0f );
   }

	GFX->setPrimitiveBuffer( mPrimBuffer );
   GFX->setVertexBuffer( mVB );

   GFX->drawIndexedPrimitive( GFXTriangleList, 0, 0, mVertCount, 0, mPrimCount );
}
示例#25
0
	bool operator()(Chunk* c1, Chunk* c2) {
		glm::vec3 chunkPos1(c1->GetPos().x,c1->GetPos().y,c1->GetPos().z);
		glm::vec3 chunkPos2(c2->GetPos().x,c2->GetPos().y,c2->GetPos().z);
		glm::vec3 camPos((int)floor(Engine::m_pCameraInstance->GetPos().x / Chunk::CHUNKSIZEX), (int)floor(Engine::m_pCameraInstance->GetPos().y / Chunk::CHUNKSIZEY), (int)floor(Engine::m_pCameraInstance->GetPos().z / Chunk::CHUNKSIZEZ));
		return glm::distance(chunkPos1, camPos) < glm::distance(chunkPos2, camPos);
	}