Beispiel #1
0
bool DirectxEngine::UpdateShader(const MeshData& mesh, 
                                 const IScene& scene,
                                 bool alphaBlend, 
                                 float timer)
{
    const int index = mesh.ShaderID();
    if (index != NO_INDEX)
    {
        auto& shader = m_data->shaders[index];
        if(index != m_data->selectedShader)
        {
            SetSelectedShader(index);
            SendLights(scene.Lights());
            shader->UpdateConstantMatrix("viewProjection", m_data->viewProjection);
            shader->UpdateConstantFloat("cameraPosition", &m_data->cameraPosition.x, 3);
            shader->UpdateConstantFloat("depthNear", &scene.Post().DepthNear(), 1);
            shader->UpdateConstantFloat("depthFar", &scene.Post().DepthFar(), 1);

            if (index == WATER_SHADER)
            {
                shader->UpdateConstantFloat("timer", &timer, 1);
            }
        }

        SendTextures(mesh.TextureIDs());
        SetRenderState(mesh.BackfaceCull(), m_data->isWireframe);
        EnableAlphaBlending(alphaBlend, false);
        return true;
    }
    return false;
}
Beispiel #2
0
bool POD3DLayer::OnExit()
{
	IScene* scene = SceneManager::Instance().Current();
	auto camera= ResolutionAdapter::Instance().DefaultCamera2D();
	scene->SetCamera(camera);
	return true;
}
bool ParaEngine::CEffectFileOpenGL::begin(bool bApplyParam /*= true*/, DWORD flag /*= 0*/)
{
	IScene* pScene = CGlobals::GetEffectManager()->GetScene();
	auto program = GetGLProgram();
	if (program != 0)
	{
		if (m_programs.size() == 1)
			program->use();
		else
		{
			// TODO: multiple pass effect in opengl is implemented as shader arrays.
			// uniform values are currently NOT shared among different passes like directX.
			// hence DO NOT set any uniform between begin() and beginPass().
			// TODO: In future: uniform values should be cached until Commit() is called.
			program->use();
		}

		if (bApplyParam)
		{
			// set the lighting parameters
			// from the global light manager
			applyGlobalLightingData(pScene->GetSunLight());

			// set the camera matrix
			applyCameraMatrices();
		}

		m_bIsBegin = true;
		return true;
	}
	else
		return false;
}
bool CEffectFileDirectX::begin(bool bApplyParam, DWORD dwFlag, bool bForceBegin )
{
	IScene* pScene = CGlobals::GetEffectManager()->GetScene();
	if(m_pEffect!=NULL)
	{
		if(bApplyParam)
		{
			// set the lighting parameters
			// from the global light manager
			applyGlobalLightingData(pScene->GetSunLight());

			// set the camera matrix
			applyCameraMatrices();
		}
		
		if(bForceBegin|| !m_bSharedMode)
		{
			HRESULT result = m_pEffect->Begin(0, dwFlag);
			if( SUCCEEDED( result ) )
			{
				m_bIsBegin = true;
				return true;
			}
			else
			{
				OUTPUT_LOG("error: CEffectFileDirectX::begin failed: %s \n", m_filename.c_str());
				return false;
			}
		}
		return true;
	}
	else
		return false;
}
	virtual bool deserialize(UniverseContext& ctx,
							 InputBlob& serializer) override
	{
		SerializedEngineHeader header;
		serializer.read(header);
		if (header.m_magic != SERIALIZED_ENGINE_MAGIC)
		{
			g_log_error.log("engine") << "Wrong or corrupted file";
			return false;
		}
		if (header.m_version > SerializedEngineVersion::LATEST)
		{
			g_log_error.log("engine") << "Unsupported version";
			return false;
		}
		if (!hasSerializedPlugins(serializer))
		{
			return false;
		}
		g_path_manager.deserialize(serializer);
		ctx.m_universe->deserialize(serializer);
		ctx.m_hierarchy->deserialize(serializer);
		m_plugin_manager->deserialize(serializer);
		int32_t scene_count;
		serializer.read(scene_count);
		for (int i = 0; i < scene_count; ++i)
		{
			char tmp[32];
			serializer.readString(tmp, sizeof(tmp));
			IScene* scene = ctx.getScene(crc32(tmp));
			scene->deserialize(serializer);
		}
		g_path_manager.clear();
		return true;
	}
Beispiel #6
0
bool HelloWorldLayer::Enter()
{
	auto winSize = ResolutionAdapter::Instance().WinSize();
	auto* camera = CameraFactory::Instance().CreateFromModel("Camera01", "Scene.pod", winSize, false);
	IScene* scene = (IScene*)mParent;
	scene->SetCamera(camera);
	return true;
}
Beispiel #7
0
void DirectxEngine::Render(const IScene& scene, float timer)
{
    RenderSceneMap(scene, timer);
    RenderPreEffects(scene.Post());
    RenderBlur(scene.Post());
    RenderPostProcessing(scene.Post());
    m_data->swapchain->Present(0, 0);
}
Beispiel #8
0
void 
PhysicsManager::eventReceived(const std::string & sender, const std::string & eventType, const std::shared_ptr<IEventData>& evt) {

	if (m_PhysInst && eventType == "SCENE_TRANSFORM") {
		std::string * strEvt = (std::string*) evt->getData();
		IScene * scene = RENDERMANAGER->getScene(*strEvt).get();
		m_PhysInst->setSceneTransform(scene->getName(), (float *)scene->getTransform().getMatrix());
	}
}
Beispiel #9
0
void InputManager::UpdateInputPassingRecursively()
{
	RETURN_IF_FALSE(mIsDirty);
	IScene* scene = SceneManager::Instance().RunningScene();
	scene->ResetInputPassing();

	FOR_EACH_COLLECTION(i, mDispatchers)
	{
		INode* node = *i;
		node->EnableInputPassing();
	}
Beispiel #10
0
bool ScenesStack::push(FunctSceneFactory factory, SceneArguments const& args) {
    IScene *scene = factory(args);

    if (!scene->initialize()) {
        delete scene;
        return false;
    }
    else {
        m_stack.push(scene);
        return true;
    }
}
Beispiel #11
0
	bool deserialize(UniverseContext& ctx, InputBlob& serializer) override
	{
		SerializedEngineHeader header;
		serializer.read(header);
		if (header.m_magic != SERIALIZED_ENGINE_MAGIC)
		{
			g_log_error.log("engine") << "Wrong or corrupted file";
			return false;
		}
		if (header.m_version > SerializedEngineVersion::LATEST)
		{
			g_log_error.log("engine") << "Unsupported version";
			return false;
		}
		if (!hasSerializedPlugins(serializer))
		{
			return false;
		}
		if (header.m_version > SerializedEngineVersion::SCENE_VERSION_CHECK &&
			!hasSupportedSceneVersions(serializer, ctx))
		{
			return false;
		}

		m_path_manager.deserialize(serializer);
		ctx.m_universe->deserialize(serializer);

		if (header.m_version <= SerializedEngineVersion::HIERARCHY_COMPONENT)
		{
			ctx.getScene(HIERARCHY_HASH)->deserialize(serializer, 0);
		}

		m_plugin_manager->deserialize(serializer);
		int32 scene_count;
		serializer.read(scene_count);
		for (int i = 0; i < scene_count; ++i)
		{
			char tmp[32];
			serializer.readString(tmp, sizeof(tmp));
			IScene* scene = ctx.getScene(crc32(tmp));
			int scene_version = -1;
			if (header.m_version > SerializedEngineVersion::SCENE_VERSION)
			{
				serializer.read(scene_version);
			}
			scene->deserialize(serializer, scene_version);
		}
		m_path_manager.clear();
		return true;
	}
void DlgTerrainHeight::OnBnClickedButtonDeleteterrain()
{
	IScene *scene = TerrainEditorPlugin::getSingleton().getWorldEditor()->getMapManager()->getScene();

	// 检查是否已经创建
	if(!scene->hasSceneObject("Terrain_0_0"))
	{
		AfxMessageBox("地形已经不存在,删除失败。");
		return;
	}
	if(AfxMessageBox("是否真的要删除地形?" , MB_YESNOCANCEL) == IDYES)
	{
		TerrainEditorPlugin::getSingleton().deactivateTerrain();
		scene->destroySceneObject("Terrain_0_0");
	}
}
void CEffectFileDirectX::applyWorldMatrices()
{
	IScene* pScene = CGlobals::GetEffectManager()->GetScene();

	CBaseCamera* pCamera = pScene->GetCurrentCamera();
	if (pCamera)
	{
		const Matrix4* pWorld = &(CGlobals::GetEffectManager()->GetWorldTransform());
		const Matrix4* pView = &(CGlobals::GetEffectManager()->GetViewTransform());
		const Matrix4* pProj = &(CGlobals::GetEffectManager()->GetProjTransform());
		Matrix4 ViewProj;
		// set the world matrix
		if (isMatrixUsed(k_worldMatrix))
		{
			setMatrix(k_worldMatrix, pWorld);
		}

		// set the world inverse matrix
		if (isMatrixUsed(k_worldInverseMatrix))
		{
			Matrix4 mWorldInverse;
			mWorldInverse = pWorld->inverse();
			setMatrix(k_worldInverseMatrix, &mWorldInverse);
		}
		// set the world view matrix
		if (isMatrixUsed(k_worldViewMatrix))
		{
			Matrix4 mWorldView;
			ParaMatrixMultiply(&mWorldView, pWorld, pView);
			setMatrix(k_worldViewMatrix, &mWorldView);
		}
		// set the world view projection matrix
		if (isMatrixUsed(k_worldViewProjMatrix))
		{
			ParaMatrixMultiply(&ViewProj, pView, pProj);
			Matrix4 mWorldViewProj;
			ParaMatrixMultiply(&mWorldViewProj, pWorld, &ViewProj);
			setMatrix(k_worldViewProjMatrix, &mWorldViewProj);
		}
	}
}
Beispiel #14
0
bool DirectxEngine::UpdateShader(const Emitter& emitter, const IScene& scene)
{
    const int index = emitter.ShaderID();
    if (index != NO_INDEX)
    {
        auto& shader = m_data->shaders[index];
        if (index != m_data->selectedShader)
        {
            SetSelectedShader(index);
            shader->UpdateConstantFloat("depthNear", &scene.Post().DepthNear(), 1);
            shader->UpdateConstantFloat("depthFar", &scene.Post().DepthFar(), 1);
        }

        shader->UpdateConstantFloat("tint", &emitter.Tint().r, 4);

        SetRenderState(false, m_data->isWireframe);
        EnableAlphaBlending(true, false);

        return true;
    }
    return false;
}
Beispiel #15
0
void RiftAppSkeleton::initGL()
{
    for (std::vector<IScene*>::iterator it = m_scenes.begin();
        it != m_scenes.end();
        ++it)
    {
        IScene* pScene = *it;
        if (pScene != NULL)
        {
            pScene->initGL();
        }
    }

    m_presentFbo.initProgram("presentfbo");
    _initPresentFbo();
    m_presentDistMeshL.initProgram("presentmesh");
    m_presentDistMeshR.initProgram("presentmesh");
    // Init the present mesh VAO *after* initVR, which creates the mesh

    // sensible initial value?
    allocateFBO(m_renderBuffer, 800, 600);
    m_fm.Init();
}
DWORD COctreeSceneManager::OnRemoveSceneObject( DWORD size, void* params )
{
	VERIFY_MESSAGE_SIZE(sizeof(SCENEOBJECTPARAMS), size);
	SCENEOBJECTPARAMS *sop = (SCENEOBJECTPARAMS *)params;

	if (sop->bBoundedObject)
	{
		ISceneNode *pSceneNode = sop->pObject->GetSceneNode();
		if (pSceneNode)
		{
			pSceneNode->RemoveObject( sop->pObject );
		}
	}
	else
	{
		IScene *pScene = sop->pObject->GetScene();
		if (pScene)
		{
			pScene->RemoveGlobalObject( sop->pObject );
		}
	}

	return MSG_HANDLED_PROCEED;
}
Beispiel #17
0
void 
PassOptix::addScene (const std::string &sceneName)
{
	if (m_SceneVector.end() == std::find (m_SceneVector.begin(), m_SceneVector.end(), sceneName)) {
	
		m_SceneVector.push_back (sceneName);
	
		std::set<std::string> *materialNames = new std::set<std::string>;
		RENDERMANAGER->getScene(sceneName)->getMaterialNames(materialNames);
		
		std::set<std::string>::iterator iter;
		iter = materialNames->begin();
		for ( ; iter != materialNames->end(); ++iter) {
			
			if (m_MaterialMap.count((*iter)) == 0)
				m_MaterialMap[(*iter)] = MaterialID(DEFAULTMATERIALLIBNAME, (*iter));
		}
		delete materialNames;


		IScene *sc = RENDERMANAGER->getScene(sceneName);
		sc->compile();

/*		std::vector<SceneObject *> objs = sc->getAllObjects();
		for (unsigned int i = 0; i < objs.size(); ++i) {

			IRenderable &r = objs[i]->getRenderable();
			VertexData &v = r.getVertexData();
			// just to make sure we get this data compiled
			//r.getVertexData().compile();

			// which attrs should we send to optix?
			unsigned int id = v.getBufferID(0);
			// clear OpenGL Errors so far; otherwise Optix won't work
			int e = glGetError();

			optix::Buffer buffers[VertexData::MaxAttribs];
			try {
				for (unsigned int b = 0; b < VertexData::MaxAttribs; ++b) { 
					if (v.getBufferID(b)) {
						buffers[b] = o_Context->createBufferFromGLBO(RT_BUFFER_INPUT,v.getBufferID(b));
						buffers[b]->setFormat(RT_FORMAT_FLOAT4);
						buffers[b]->setSize(v.getDataOf(0).size());
					}
				}
			}
			catch ( optix::Exception& e ) {
				NAU_THROW("Optix Error: Adding scene %s to pass %s (creating buffers from VBOs) [%s]",
										sc->getName().c_str(), m_Name.c_str(),e.getErrorString().c_str()); 
			}

			std::vector<IMaterialGroup *> mg = r.getMaterialGroups();
			for (unsigned int g = 0; g < mg.size(); ++g) {

				if (mg[g]->getNumberOfPrimitives() > 0) {
					try {
						optix::Geometry geom = o_Context->createGeometry();
						geom->setPrimitiveCount(mg[g]->getNumberOfPrimitives());
						geom->setBoundingBoxProgram(o_BoundingBoxProgram);
						geom->setIntersectionProgram(o_GeometryIntersectionProgram);

						geom["vertex_buffer"]->setBuffer(buffers[0]);
						for (unsigned int b = 1; b < VertexData::MaxAttribs; ++b) {
							if (v.getBufferID(b))
								geom[VertexData::Syntax[b]]->setBuffer(buffers[b]);
						}
						id = mg[g]->getIndexData().getBufferID();
						optix::Buffer indices = o_Context->createBufferFromGLBO(RT_BUFFER_INPUT, id);
						indices->setFormat(RT_FORMAT_UNSIGNED_INT);
						indices->setSize(mg[g]->getIndexData().getIndexSize());

						geom["index_buffer"]->setBuffer(indices);
						o_Material = o_Context->createMaterial();
						o_Material->setClosestHitProgram(0, o_ClosestHitProgram);
						
						o_Material["diffuse"]->set4fv(MATERIALLIBMANAGER->getMaterial(this->m_MaterialMap[mg[g]->getMaterialName()])->getColor().getDiffuse());

						o_GeomInstances.push_back(o_Context->createGeometryInstance());
						o_GeomInstances[o_GeomInstances.size()-1]->setMaterialCount(1);
						o_GeomInstances[o_GeomInstances.size()-1]->setMaterial(0, o_Material);
						o_GeomInstances[o_GeomInstances.size()-1]->setGeometry(geom);
					}
					catch ( optix::Exception& e ) {
						NAU_THROW("Optix Error: Adding scene %s to pass %s (adding material groups) [%s]",
												sc->getName().c_str(), m_Name.c_str(),e.getErrorString().c_str()); 
					}
				}
			}
		}
		try {
			o_GeomGroup->setChildCount(o_GeomInstances.size());
			for (unsigned int i = 0; i < o_GeomInstances.size(); ++i) {
				o_GeomGroup->setChild(i,o_GeomInstances[i]);
			}

			o_GeomGroup->setAcceleration(o_Context->createAcceleration("Bvh","Bvh"));
		}
		catch ( optix::Exception& e ) {
			NAU_THROW("Optix Error: Adding scene %s to pass %s (adding instances to geometry group) [%s]",
												sc->getName().c_str(), m_Name.c_str(),e.getErrorString().c_str()); 
		}

		//o_Context["geometry"]->set(o_GeomGroup);






*/		

	}
}
Beispiel #18
0
void
PassOptix::optixInit() {

	glGetError();

	// Can these be removed due to texture count?
	o_TexLib.addTexture(1);
	o_Context["tex0"]->set(o_TexLib.getTexture(1));

	std::set<std::string> *materialNames = new std::set<std::string>;
	
	std::vector<std::string>::iterator scenesIter;
	scenesIter = m_SceneVector.begin();
	for ( ; scenesIter != m_SceneVector.end(); ++scenesIter) {

		IScene *aScene = RENDERMANAGER->getScene (*scenesIter);
		aScene->compile();

		// Adding Materials to optix lib
		aScene->getMaterialNames(materialNames);
		std::set<std::string>::iterator matIter;
		matIter = materialNames->begin();
		for( ; matIter != materialNames->end(); ++matIter) {
		
			o_MatLib.addMaterial(m_MaterialMap[*matIter]);
		}

		materialNames->clear();


		std::vector<SceneObject *> objs = aScene->getAllObjects();
		std::vector<nau::scene::SceneObject*>::iterator objsIter;

		objsIter = objs.begin();
		for ( ; objsIter != objs.end(); ++objsIter) {
			o_GeomLib.addSceneObject(*objsIter, m_MaterialMap);
//			o_GeomLib.addSceneObject((*objsIter)->getId(), m_MaterialMap);
		}
	}
	o_GeomLib.buildGeometryGroup();
	o_Context["top_object"]->set(o_GeomLib.getGeometryGroup());

	o_MatLib.applyMissPrograms();


	std::map<std::string, std::string>::iterator iter;
	iter = o_InputBuffers.begin();
	for ( ; iter != o_InputBuffers.end(); ++iter) {
		try {
			unsigned int id = RESOURCEMANAGER->getTexture(iter->second)->getPropi(ITexture::ID);
			if (RESOURCEMANAGER->getTexture(iter->second)->getPrope(ITexture::DIMENSION) == GL_TEXTURE_2D) {
				optix::TextureSampler rtWorldSpaceTexture = o_Context->createTextureSamplerFromGLImage(id, RT_TARGET_GL_TEXTURE_2D);
				rtWorldSpaceTexture->setWrapMode(0, RT_WRAP_CLAMP_TO_EDGE);
				rtWorldSpaceTexture->setWrapMode(1, RT_WRAP_CLAMP_TO_EDGE);
				rtWorldSpaceTexture->setIndexingMode(RT_TEXTURE_INDEX_ARRAY_INDEX);
				rtWorldSpaceTexture->setReadMode(RT_TEXTURE_READ_ELEMENT_TYPE);
				rtWorldSpaceTexture->setMaxAnisotropy(1.0f);
				rtWorldSpaceTexture->setFilteringModes(RT_FILTER_NEAREST, RT_FILTER_NEAREST, RT_FILTER_NONE);
				o_Context[iter->first]->setTextureSampler(rtWorldSpaceTexture);
			}
		}
		catch(optix::Exception& e) {
			NAU_THROW("Optix Error: Input Buffer preparation in pass %s [%s]", m_Name.c_str(), e.getErrorString().c_str());
		}
	}

	std::map<std::string, databuffer>::iterator iter2;
	iter2 = o_OutputDataBuffer.begin();
	ITexture *texID;

	for ( ; iter2 != o_OutputDataBuffer.end() ; ++iter2) {

		texID = RESOURCEMANAGER->getTexture(iter2->second.texName);
//		int format = texID->getPrope(ITexture::FORMAT);
		int tex = texID->getPropi(ITexture::ID);

		unsigned int pbo;
		glGenBuffers(1, &pbo);
		glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
		// need to allow different types
		glBufferData(GL_PIXEL_UNPACK_BUFFER, texID->getPropi(ITexture::WIDTH)*texID->getPropi(ITexture::HEIGHT)*texID->getPropi(ITexture::ELEMENT_SIZE), 0, GL_STREAM_READ);
		glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);

		optix::Buffer ob = o_Context->createBufferFromGLBO(RT_BUFFER_OUTPUT, pbo);
		ob->setSize(texID->getPropi(ITexture::WIDTH), texID->getPropi(ITexture::HEIGHT));
		// same here (types)
		ob->setFormat(getOptixFormat(texID));

		o_Context[iter2->first]->setBuffer(ob);

		o_OutputDataBuffer[iter2->first].pbo = pbo;
		//
	}

#if (TEST == 2)
	try {
		unsigned int id = RESOURCEMANAGER->getTexture("Deferred Render Targets::pos")->getId();
		optix::ITextureSampler rtWorldSpaceTexture = o_Context->createTextureSamplerFromGLImage(id, RT_TARGET_GL_TEXTURE_2D);
		rtWorldSpaceTexture->setWrapMode(0, RT_WRAP_CLAMP_TO_EDGE);
		rtWorldSpaceTexture->setWrapMode(1, RT_WRAP_CLAMP_TO_EDGE);
		rtWorldSpaceTexture->setIndexingMode(RT_TEXTURE_INDEX_ARRAY_INDEX);
		rtWorldSpaceTexture->setReadMode(RT_TEXTURE_READ_ELEMENT_TYPE);
		rtWorldSpaceTexture->setMaxAnisotropy(1.0f);
		rtWorldSpaceTexture->setFilteringModes(RT_FILTER_NEAREST, RT_FILTER_NEAREST, RT_FILTER_NONE);
		o_Context["pos_buffer"]->setTextureSampler(rtWorldSpaceTexture);
	}
	catch(optix::Exception& e) {
		NAU_THROW("Optix Error: Input Buffer preparation in pass %s [%s]", m_Name.c_str(), e.getErrorString().c_str());
	}
#endif
	o_OptixIsPrepared = true;
}
Beispiel #19
0
int main(int argc, char *argv[])
{
	IMagicX *mx = CreateMagicX(RDT_OPENGL, 0, 0, 1280, 768);
	ISceneManager *sceneManager = mx->GetSceneManager();
	IKeyEvent *event = CEventManager::Instance()->GetKeyEvent();
	IScene *scene = sceneManager->GetCurrentScene();
	IDevice *device = mx->GetDevice();

	IRenderObject *pRenderObject = new CReflectObject();

	CSphereEntity *pSphere = nullptr;
	ICamera *camera = nullptr;
	if (scene)
	{		
		pSphere = new CSphereEntity(pRenderObject, 5, 52, 26);
		

		CVector3 vDir(0, 0, -1);
		CVector3 vUp(0, 1, 0);
		//camera = scene->SetupCamera(CVector3(0, 0, 5), vDir, vUp, PI / 6, 1.0f * device->GetWindowWidth() / device->GetWindowHeight(), 1.0f, 5000.0f);
		camera = scene->SetupCamera(30, pSphere, vDir, vUp, PI / 3, 1.0f * device->GetWindowWidth() / device->GetWindowHeight(), 1.0f, 5000.0f);
		//scene->SetupSkyBox("texture/pos_x.tga", "texture/neg_x.tga", "texture/pos_y.tga", "texture/neg_y.tga", "texture/pos_z.tga", "texture/neg_z.tga", 1024);
		scene->SetupSkyBox("texture/FullMoonLeft.tga", "texture/FullMoonRight.tga", "texture/FullMoonUp.tga", "texture/FullMoonDown.tga", "texture/FullMoonFront.tga", "texture/FullMoonBack.tga", 512);
		//scene->SetupSkyBox("texture/CloudyLightRaysLeft2048.tga", "texture/CloudyLightRaysRight2048.tga", "texture/CloudyLightRaysUp2048.tga", "texture/CloudyLightRaysDown2048.tga", "texture/CloudyLightRaysFront2048.tga", "texture/CloudyLightRaysBack2048.tga", 512);
		//scene->SetupSkyBox("texture/DarkStormyLeft2048.tga", "texture/DarkStormyRight2048.tga", "texture/DarkStormyUp2048.tga", "texture/DarkStormyDown2048.tga", "texture/DarkStormyFront2048.tga", "texture/DarkStormyBack2048.tga", 512);
		//scene->SetupSkyBox("texture/SunSetLeft2048.tga", "texture/SunSetRight2048.tga", "texture/SunSetUp2048.tga", "texture/SunSetDown2048.tga", "texture/SunSetFront2048.tga", "texture/SunSetBack2048.tga", 512);
		//scene->SetupSkyBox("texture/ThickCloudsWaterLeft2048.tga", "texture/ThickCloudsWaterRight2048.tga", "texture/ThickCloudsWaterUp2048.tga", "texture/ThickCloudsWaterDown2048.tga", "texture/ThickCloudsWaterFront2048.tga", "texture/ThickCloudsWaterBack2048.tga", 512);
		//scene->SetupSkyBox("texture/TropicalSunnyDayLeft2048.tga", "texture/TropicalSunnyDayRight2048.tga", "texture/TropicalSunnyDayUp2048.tga", "texture/TropicalSunnyDayDown2048.tga", "texture/TropicalSunnyDayFront2048.tga", "texture/TropicalSunnyDayBack2048.tga", 512);

		pSphere->Create();
		pSphere->SetPosition(CVector3(0, 0, 0));
		scene->GetRootNode()->AddChild(pSphere);
	}

	uint next_game_tick = GetTickCount();
	int sleep_time = 0;

	bool bQuit = false;
	while (device->Run())
	{
		uint cur_time = GetTickCount();
		sleep_time = next_game_tick - cur_time;
		if (sleep_time <= 0)
		{
			if (event)
			{
				static int lastX;
				static int lastY;

				int currentX = event->GetMousePositonX();
				int currentY = event->GetMousePositionY();

				float rotY = (currentX - lastX) * 2.0f * PI / device->GetWindowWidth();
				float rotX = (currentY - lastY) * 2.0f * PI / device->GetWindowHeight();

				CVector3 camDir = camera->GetDirection();
				CVector3 curRot = pSphere->GetRotation();
				if (event->IsPress(EKP_MOUSE_LBUTTON))
				{				
					if (!ISZERO(rotX) || !ISZERO(rotY))
					{
						CVector3 rot(rotX + curRot.x, curRot.y + rotY, 0);
						pSphere->SetRotation(rot);
					}
				}
				if (event->IsPress(EKP_MOUSE_RBUTTON))
				{		
					if (!ISZERO(rotX) || !ISZERO(rotY))
					{
						camDir.rotateXZBy(-rotY);
						CMatrix4 rotMat4;												
						rotMat4.SetRotationRadians(rotX, (-camDir).crossProduct(CVector3(0, 1.0f, 0)));
						rotMat4.TransformVect(camDir);
						
						camDir.normalize();
						camera->SetDirection(camDir);
					}

				}				
				
				if (event->IsPress(EKP_KEYBOARD_A))
				{
					CVector3 leftDir = camDir;
					leftDir.rotateXZBy(PI / 2);
					pSphere->SetPosition(pSphere->GetPosition() + leftDir * 1.0f);
				}

				if (event->IsPress(EKP_KEYBOARD_D))
				{
					CVector3 rightDir = camDir;
					rightDir.rotateXZBy(PI / 2);
					pSphere->SetPosition(pSphere->GetPosition() - rightDir * 1.0f);
				}

				if (event->IsPress(EKP_KEYBOARD_W))
				{
					pSphere->SetPosition(pSphere->GetPosition() + camDir * 1.0f);
				}

				if (event->IsPress(EKP_KEYBOARD_S))
				{
					pSphere->SetPosition(pSphere->GetPosition() - camDir * 1.0f);
				}

				if (event->IsPress(EKP_KEYBOARD_ESC))
				{
					exit(1);
				}

				lastX = event->GetMousePositonX();
				lastY = event->GetMousePositionY();
			}

			next_game_tick = GetTickCount() + SKIP_TICKS;

			sceneManager->Update(SKIP_TICKS - sleep_time);
			sceneManager->Draw();
			device->SwapBuffers();
		}
		else
		{
			device->Sleep(sleep_time);
		}


	}

	delete pSphere;
	delete pRenderObject;
	DestroyMagicX();
	return 0;
}
Camera::Camera (const std::string &name) :
	SceneObject(),

	m_Float4Props(COUNT_FLOAT4PROPERTY),
	m_FloatProps(COUNT_FLOATPROPERTY),
	m_Mat4Props(COUNT_MAT4PROPERTY),

	m_IsDynamic (false),
	m_pViewport (0),
	m_LookAt(false),
	m_LookAtPoint(0.0f, 0.0f, 0.0f),
	m_Spherical((float)M_PI,0.0f),
	m_PositionOffset (0.0f),
	m_IsOrtho (false)
{

	//mFloatAttribs.add(AttribFloat(FOV, 60.0f));
	//mFloatAttribs.add(AttribFloat(NEARP, 1.0f));
	//mFloatAttribs.add(AttribFloat(FARP, 10000.0f));
	//mFloatAttribs.add(AttribFloat(LEFT, -1.0f));
	//mFloatAttribs.add(AttribFloat(RIGHT, 1.0f));
	//mFloatAttribs.add(AttribFloat(TOP, 1.0f));
	//mFloatAttribs.add(AttribFloat(BOTTOM, -1.0f));

	//mVec4Attribs.add(AttribVec4(POSITION, 0.0f, 0.0f, 0.0f, 1.0f));
	//mVec4Attribs.add(AttribVec4(VIEW_VEC, 0.0f, 0.0f, -1.0f, 0.0f));
	//mVec4Attribs.add(AttribVec4(NORMALIZED_VIEW_VEC, 0.0f, 0.0f, -1.0f, 0.0f, true));
	//mVec4Attribs.add(AttribVec4(NORMALIZED_RIGHT_VEC, 1.0f, 0.0f, 0.0f, 0.0f, true));
	//mVec4Attribs.add(AttribVec4(UP_VEC, 0.0f, 1.0f, 0.0f, 0.0f));
	//mVec4Attribs.add(AttribVec4(NORMALIZED_UP_VEC, 0.0f, 1.0f, 0.0f, 0.0f, true));
	//mVec4Attribs.add(AttribVec4(LOOK_AT_POINT, 0.0f, 0.0f, -1.0, 1.0));

	m_Id = 0;
	m_Name = name;
	m_pViewport = CURITIBA->getDefaultViewport();

	m_Float4Props[POSITION].set(0.0f, 0.0f, 0.0f, 1.0f);
	m_Float4Props[VIEW_VEC].set(0.0f, 0.0f, -1.0f, 0.0f);
	m_Float4Props[NORMALIZED_VIEW_VEC].set(0.0f, 0.0f, -1.0f, 0.0f);

	m_Float4Props[NORMALIZED_RIGHT_VEC].set(1.0f, 0.0f, 0.0f, 0.0f);

	m_Float4Props[UP_VEC].set(0.0f, 1.0f, 0.0f, 0.0f);
	m_Float4Props[NORMALIZED_UP_VEC].set(0.0f, 1.0f, 0.0f, 0.0f);

	m_Float4Props[LOOK_AT_POINT].set(0.0f, 0.0f, -1.0f, 1.0f);

	m_FloatProps[FOV] = 60.0f;
	m_FloatProps[TOP] = 1.0f;
	m_FloatProps[BOTTOM] = -1.0f;
	m_FloatProps[LEFT] = -1.0f;
	m_FloatProps[RIGHT] = 1.0f;
	m_FloatProps[NEARP] = 1.0f;
	m_FloatProps[FARP] = 10000.0f;

	buildViewMatrix();
	buildViewMatrixInverse();

	m_StaticCondition = false;

	m_BoundingVolume = new BoundingBox;
	m_Transform = new SimpleTransform;
	setVectorsFromSpherical();

	// Adding a Mesh with the frustum lines
	Mesh *renderable =  (Mesh *)RESOURCEMANAGER->createRenderable("Mesh", m_Name, "Camera");
	renderable->setDrawingPrimitive(curitiba::render::IRenderer::LINES);
	std::vector<VertexData::Attr> *vertices = new std::vector<VertexData::Attr>(8);
	VertexData &vertexData = renderable->getVertexData();
	vertexData.setDataFor (VertexData::getAttribIndex("position"), vertices);

	MaterialGroup *aMaterialGroup = new MaterialGroup;
	
	std::vector<unsigned int> *indices = new std::vector<unsigned int>(16);
	indices->at (0) = Camera::TOP_LEFT_NEAR;		indices->at (1) = Camera::TOP_LEFT_FAR;
	indices->at (2) = Camera::TOP_RIGHT_NEAR;		indices->at (3) = Camera::TOP_RIGHT_FAR;
	indices->at (4) = Camera::BOTTOM_RIGHT_NEAR;	indices->at (5) = Camera::BOTTOM_RIGHT_FAR;
	indices->at (6) = Camera::BOTTOM_LEFT_NEAR;		indices->at (7) = Camera::BOTTOM_LEFT_FAR;

	indices->at (8) = Camera::TOP_LEFT_FAR;			indices->at (9) = Camera::TOP_RIGHT_FAR;
	indices->at (10) = Camera::TOP_RIGHT_FAR;		indices->at (11) = Camera::BOTTOM_RIGHT_FAR;
	indices->at (12) = Camera::BOTTOM_RIGHT_FAR;	indices->at (13) = Camera::BOTTOM_LEFT_FAR;
	indices->at (14) = Camera::BOTTOM_LEFT_FAR;		indices->at (15) = Camera::TOP_LEFT_FAR;

	aMaterialGroup->setIndexList (indices);
	aMaterialGroup->setParent (renderable);
	aMaterialGroup->setMaterialName("__Emission White");

	renderable->addMaterialGroup (aMaterialGroup);
	m_Transform = & m_Mat4Props[VIEW_INVERSE_MATRIX];
	setRenderable (renderable);

	aMaterialGroup = new MaterialGroup;
	indices = new std::vector<unsigned int>(8);
	indices->at (0) = Camera::TOP_LEFT_NEAR;		indices->at (1) = Camera::TOP_RIGHT_NEAR;
	indices->at (2) = Camera::TOP_RIGHT_NEAR;		indices->at (3) = Camera::BOTTOM_RIGHT_NEAR;
	indices->at (4) = Camera::BOTTOM_RIGHT_NEAR;	indices->at (5) = Camera::BOTTOM_LEFT_NEAR;
	indices->at (6) = Camera::BOTTOM_LEFT_NEAR;		indices->at (7) = Camera::TOP_LEFT_NEAR;

	aMaterialGroup->setIndexList (indices);
	aMaterialGroup->setParent (renderable);
	aMaterialGroup->setMaterialName("__Emission Red");

	renderable->addMaterialGroup (aMaterialGroup);
	setRenderable (renderable);

	IScene *s = RENDERMANAGER->createScene(name, "SceneAux");
	s->add(this);

	EVENTMANAGER->addListener("VIEWPORT_CHANGED", this);
}
void ParaEngine::CEffectFileOpenGL::applyCameraMatrices()
{
	IScene* pScene = CGlobals::GetEffectManager()->GetScene();

	CBaseCamera* pCamera = pScene->GetCurrentCamera();
	if (pCamera)
	{
		const Matrix4* pWorld = &(CGlobals::GetEffectManager()->GetWorldTransform());
		const Matrix4* pView = &(CGlobals::GetEffectManager()->GetViewTransform());
		const Matrix4* pProj = &(CGlobals::GetEffectManager()->GetProjTransform());
		Matrix4 ViewProj;
		// set the world matrix
		if (isMatrixUsed(k_worldMatrix))
		{
			setMatrix(k_worldMatrix, pWorld);
		}

		// set the world inverse matrix
		if (isMatrixUsed(k_worldInverseMatrix))
		{
			Matrix4 mWorldInverse;
			mWorldInverse = pWorld->inverse();
			setMatrix(k_worldInverseMatrix, &mWorldInverse);
		}
		// set the world view matrix
		if (isMatrixUsed(k_worldViewMatrix))
		{
			Matrix4 mWorldView;
			ParaMatrixMultiply(&mWorldView, pWorld, pView);
			setMatrix(k_worldViewMatrix, &mWorldView);
		}

		// set the combined matrix
		if (isMatrixUsed(k_viewProjMatrix))
		{
			ParaMatrixMultiply(&ViewProj, pView, pProj);
			setMatrix(k_viewProjMatrix, &ViewProj);
		}

		// set the world view projection matrix
		if (isMatrixUsed(k_worldViewProjMatrix))
		{
			if (!isMatrixUsed(k_viewProjMatrix))
				ParaMatrixMultiply(&ViewProj, pView, pProj);
			Matrix4 mWorldViewProj;
			ParaMatrixMultiply(&mWorldViewProj, pWorld, &ViewProj);
			setMatrix(k_worldViewProjMatrix, &mWorldViewProj);
		}

		// set the view matrix
		if (isMatrixUsed(k_viewMatrix))
		{
			setMatrix(k_viewMatrix, pView);
		}

		// set the projection matrix
		if (isMatrixUsed(k_projMatrix))
		{
			setMatrix(k_projMatrix, pProj);
		}

		// set the tex world view projection matrix
		if (CGlobals::GetEffectManager()->IsUsingShadowMap() && isMatrixUsed(k_TexWorldViewProjMatrix))
		{
			Matrix4 mTex;
			ParaMatrixMultiply(&mTex, pWorld, CGlobals::GetEffectManager()->GetTexViewProjMatrix());
			setMatrix(k_TexWorldViewProjMatrix, &mTex);
		}

		// set the world camera position
		if (isParameterUsed(k_cameraPos))
		{
			Vector3 vEye = pCamera->GetRenderEyePosition() - pScene->GetRenderOrigin();
			setParameter(k_cameraPos, &vEye);
		}
		// set the world camera facing vector
		if (isParameterUsed(k_cameraFacing))
		{
			Vector3 v = pCamera->GetWorldAhead();
			setParameter(k_cameraFacing, &v);
		}
	}
}
void CEffectFileDirectX::applyCameraMatrices()
{
	IScene* pScene = CGlobals::GetEffectManager()->GetScene();

	CBaseCamera* pCamera = pScene->GetCurrentCamera();
	if (pCamera)
	{
		const Matrix4* pWorld = &(CGlobals::GetEffectManager()->GetWorldTransform());
		const Matrix4* pView = &(CGlobals::GetEffectManager()->GetViewTransform());
		const Matrix4* pProj = &(CGlobals::GetEffectManager()->GetProjTransform());
		Matrix4 ViewProj;
		// set the world matrix
		if (isMatrixUsed(k_worldMatrix))
		{
			setMatrix(k_worldMatrix, pWorld);
		}

		// set the world inverse matrix
		if (isMatrixUsed(k_worldInverseMatrix))
		{
			Matrix4 mWorldInverse;
			mWorldInverse = pWorld->inverse();
			setMatrix(k_worldInverseMatrix, &mWorldInverse);
		}
		// set the world view matrix
		if (isMatrixUsed(k_worldViewMatrix))
		{
			Matrix4 mWorldView;
			ParaMatrixMultiply(&mWorldView, pWorld, pView);
			setMatrix(k_worldViewMatrix, &mWorldView);
		}

		// set the combined matrix
		if (isMatrixUsed(k_viewProjMatrix))
		{
			ParaMatrixMultiply(&ViewProj, pView, pProj);
			setMatrix(k_viewProjMatrix, &ViewProj);
		}

		// set the world view projection matrix
		if (isMatrixUsed(k_worldViewProjMatrix))
		{
			if(!isMatrixUsed(k_viewProjMatrix))
				ParaMatrixMultiply(&ViewProj, pView, pProj);
			Matrix4 mWorldViewProj;
			ParaMatrixMultiply(&mWorldViewProj, pWorld, &ViewProj);
			setMatrix(k_worldViewProjMatrix, &mWorldViewProj);
		}

		// set the view matrix
		if (isMatrixUsed(k_viewMatrix))
		{
			setMatrix(k_viewMatrix, pView);
		}

		// set the projection matrix
		if (isMatrixUsed(k_projMatrix))
		{
			setMatrix(k_projMatrix, pProj);
		}

		// set the tex world view projection matrix
		if (CGlobals::GetEffectManager()->IsUsingShadowMap() && isMatrixUsed(k_TexWorldViewProjMatrix))
		{
			Matrix4 mTex;
			ParaMatrixMultiply(&mTex, pWorld, CGlobals::GetEffectManager()->GetTexViewProjMatrix());
			setMatrix(k_TexWorldViewProjMatrix, &mTex);
		}
		
		// set the world camera position
		if (isParameterUsed(k_cameraPos))
		{
			Vector3 vEye = pCamera->GetRenderEyePosition() - pScene->GetRenderOrigin();
			setParameter(k_cameraPos, &Vector4(vEye.x,vEye.y, vEye.z, 1.0f));
		}
		// set the world camera facing vector
		if (isParameterUsed(k_cameraFacing))
		{
			setParameter(k_cameraFacing, &pCamera->GetWorldAhead());
		}

		//// set the matrix used by sky boxes
		//if (isMatrixUsed(k_skyBoxMatrix))
		//{
		//	setMatrix(k_skyBoxMatrix, &pCamera->skyBoxMatrix());
		//}

		/*cVector4 camDistances(
			pCamera->nearPlane(),
			pCamera->farPlane(),
			pCamera->viewDistance(),
			pCamera->invFarPlane());
			
		if (isParameterUsed(k_cameraDistances))
		{
			setParameter(k_cameraDistances, &camDistances);
		}*/
	}
}
Beispiel #23
0
bool DirectxEngine::InitialiseScene(const IScene& scene)
{
    m_data->shadows = std::make_unique<DxQuadMesh>(scene.Shadows(),
        [this](const D3DXMATRIX& world, int texture){ UpdateShader(world, texture); });

    m_data->textures.reserve(scene.Textures().size());
    for(const auto& texture : scene.Textures())
    {
        m_data->textures.push_back(std::unique_ptr<DxTexture>(
            new DxTexture(*texture)));
    }

    m_data->shaders.reserve(scene.Shaders().size());
    for(const auto& shader : scene.Shaders())
    {
        m_data->shaders.push_back(std::unique_ptr<DxShader>(
            new DxShader(*shader)));
    }

    m_data->meshes.reserve(scene.Meshes().size());
    for(const auto& mesh : scene.Meshes())
    {
        m_data->meshes.push_back(std::unique_ptr<DxMesh>(new DxMesh(*mesh,
            [this](const D3DXMATRIX& world, int texture){ UpdateShader(world, texture); })));
    }

    m_data->terrain.reserve(scene.Terrains().size());
    for(const auto& terrain : scene.Terrains())
    {
        m_data->terrain.push_back(std::unique_ptr<DxMesh>(new DxMesh(*terrain,
            [this](const D3DXMATRIX& world, int texture){ UpdateShader(world, texture); })));
    }

    m_data->waters.reserve(scene.Waters().size());
    for(const auto& water : scene.Waters())
    {
        m_data->waters.push_back(std::unique_ptr<DxMesh>(new DxMesh(*water,
            [this](const D3DXMATRIX& world, int texture){ UpdateShader(world, texture); })));
    }

    m_data->emitters.reserve(scene.Emitters().size());
    for(const auto& emitter : scene.Emitters())
    {
        m_data->emitters.push_back(std::unique_ptr<DxEmitter>(new DxEmitter(*emitter,
            [this](const D3DXMATRIX& world, const Particle& data){ UpdateShader(world, data); })));
    }

    return ReInitialiseScene();
}
Beispiel #24
0
void RiftAppSkeleton::timestep(float dt)
{
    for (std::vector<IScene*>::iterator it = m_scenes.begin();
        it != m_scenes.end();
        ++it)
    {
        IScene* pScene = *it;
        if (pScene != NULL)
        {
            pScene->timestep(dt);
        }
    }

    glm::vec3 hydraMove = glm::vec3(0.0f, 0.0f, 0.0f);
#ifdef USE_SIXENSE
    const sixenseAllControllerData& state = m_fm.GetCurrentState();
    for (int i = 0; i<2; ++i)
    {
        const sixenseControllerData& cd = state.controllers[i];
        const float moveScale = pow(10.0f, cd.trigger);
        hydraMove.x += cd.joystick_x * moveScale;

        const FlyingMouse::Hand h = static_cast<FlyingMouse::Hand>(i);
        if (m_fm.IsPressed(h, SIXENSE_BUTTON_JOYSTICK)) ///@note left hand does not work
            hydraMove.y += cd.joystick_y * moveScale;
        else
            hydraMove.z -= cd.joystick_y * moveScale;
    }

    if (m_fm.WasJustPressed(FlyingMouse::Right, SIXENSE_BUTTON_START))
    {
        ToggleShaderWorld();
    }

    // Adjust cinemascope feel with left trigger
    // Mouse wheel will still work if Hydra is not present or not pressed(0.0 trigger value).
    const float trigger = m_fm.GetTriggerValue(FlyingMouse::Left); // [0,1]
    if (trigger > 0.0f)
    {
        const float deadzone = 0.1f;
        const float topval = 0.95f;
        const float trigScaled = (trigger - deadzone) / (1.0f - deadzone);
        m_cinemaScopeFactor = std::max(0.0f, topval * trigScaled);
    }
#endif

    const glm::vec3 move_dt = m_headSize * (m_keyboardMove + m_joystickMove + m_mouseMove + hydraMove) * dt;
    ovrVector3f kbm;
    kbm.x = move_dt.x;
    kbm.y = move_dt.y;
    kbm.z = move_dt.z;

    // Move in the direction the viewer is facing.
    const OVR::Matrix4f rotmtx = 
          OVR::Matrix4f::RotationY(-m_chassisYaw)
        * OVR::Matrix4f(m_eyeOri);
    const OVR::Vector3f kbmVec = rotmtx.Transform(OVR::Vector3f(kbm));

    m_chassisPos.x += kbmVec.x;
    m_chassisPos.y += kbmVec.y;
    m_chassisPos.z += kbmVec.z;

    m_chassisYaw += (m_keyboardYaw + m_joystickYaw + m_mouseDeltaYaw) * dt;

    m_fm.updateHydraData();
    m_hyif.updateHydraData(m_fm, 1.0f);
}
bool TwoAxisTraslationGizmo::MouseDrag(const int &x0, const int &y0, const int &x1, const int &y1, const cpw::MouseButtonsState &mbs)
{
  IScene *scene = cpw::ApplicationScene::GetInstance()->GetScene();
  EntityRegistry *entity_reg =EntityRegistry::GetInstance();
  const float dist_mult = 0.0025f;
  float increment = 0.0f;
  float increment_x, increment_y;
  int traslation=0;
	

  increment_y = increment_x = 0.0f;

  if ((GetEntityTarget() == NULL) || (scene == NULL))
    return false;

  Element *entity = (Element *) GetEntityTarget();

  float new_x = entity->GetUtm(0); 
  float new_y = entity->GetUtm(1); 
  float new_z = entity->GetUtm(2);

  cpw::Point3d<double> camera_view = GetCameraView();

  int traslation_x = x1 - x0;
  int traslation_y = y1 - y0;

  if ((traslation_x == 0) && (traslation_y == 0))
    return false;
	
  float distance = cpw::Math::DistanceBetweenTwoPoints(cpw::Point3d<double>(new_x, new_y, new_z), GetCameraPos());

  cpw::Point3d<float> ip;

  GetNavigatorManager()->GetFocusedOrFirstNavigator()->SetKeepMouseInsideCanvas(false);

  //if (!GetNavigatorManager()->GetFocusedOrFirstNavigator()->IntersectMouseWithScene(x1, y1, ix, iy, iz))
  if (entity->GetAdjustToTerrainHeight())
    {
      if (!GetNavigatorManager()->GetFocusedOrFirstNavigator()->IntersectMouseWithScene2(x1, y1, ip))
	{
	  /*std::stringstream cc;
	    cc << "collision failed " << x1 << ", " << y1;
	    if (cpw::ApplicationLog::GetInstance()->GetLogger() != NULL)
	    cpw::ApplicationLog::GetInstance()->GetLogger()->NewLogMessage(cc.str());*/
	
	  return false;
	}
    }
  else
    {
      if (!GetNavigatorManager()->GetFocusedOrFirstNavigator()->IntersectMouseWithHorizontalPlane(x1, y1, ip, entity->GetUtm(2)))
	return false;
    }

  new_x = ip.x;
  new_y = ip.y;
  //new_x = ix;
  //new_y = iy;
	
  //check if we should intersect against the terrain
  if (entity->GetAdjustToTerrainHeight() || entity->GetAllowUnderTerrain())
    {
      cpw::Point3d<float> i_point;
      if (scene->IntersectRayWithTerrain(cpw::Point3d<float>(new_x, new_y, 10000.0f),
					 cpw::Point3d<float>(new_x, new_y, -10000.0f),
					 i_point, true))
	{
	  if (entity->GetAllowUnderTerrain())
	    {
	      if (new_z < i_point.z)
		new_z = i_point.z;
	    }

	  if (entity->GetAdjustToTerrainHeight())
	    new_z = i_point.z;
	}
    }
	
  entity->SetUtm(new_x, new_y, new_z);
	
  entity->GraphicUpdate();
	
  IHandler::AdaptHandlerAndBrothersToModel();	
	
  return true;
}