void GameBodyObject::DumpNodes(NxOgre::StringPairList &l, Ogre::Node *n, int level, int nid) 
	{

		Ogre::SceneNode::ObjectIterator object_it = ((Ogre::SceneNode *)n)->getAttachedObjectIterator();
		Ogre::Node::ChildNodeIterator node_it = n->getChildIterator();
		
		Ogre::MovableObject *m;
		Ogre::Entity *e;

		if (level != 0) 
		{
			l.insert(
				"Node" + 
				Ogre::StringConverter::toString(nid) + 
				"-Position", 
				Ogre::StringConverter::toString(n->getPosition()));
		}
		
		int i=0;
		while(object_it.hasMoreElements()) 
		{
			
			m = object_it.getNext();
			
			if (m->getMovableType() == "Entity") 
			{
				e = static_cast<Ogre::Entity*>(m);
				NxOgre::NxString entitySuffix = "";
				
				
				if (i > 0)
				{
					entitySuffix = Ogre::StringConverter::toString(i);
				}
					
				if (level == 0) 
				{
					l.insert("Entity" + entitySuffix, e->getMesh()->getName());
				}
				
				else 
				{
					l.insert(
							"Node" + 
							Ogre::StringConverter::toString(nid) +
							"-Entity" +
							entitySuffix,
							e->getMesh()->getName()
						);
				}
			}
			i++;
		}

		while(node_it.hasMoreElements()) 
		{
			DumpNodes(l, node_it.getNext(), level + 1, nid++);
		}

	}
void OLMeshTracker::UpdateSubNodes(Ogre::Node* regionNode, Ogre::Node* node, bool recurse, Ogre::MeshPtr meshP) {
	if (recurse && node->numChildren() > 0) {
		// if node has more children nodes, visit them recursivily
		Ogre::SceneNode::ChildNodeIterator nodeChildIterator = node->getChildIterator();
		while (nodeChildIterator.hasMoreElements()) {
			Ogre::Node* nodeChild = nodeChildIterator.getNext();
			// 'false' causes it to not visit sub-children which are included in parent and pos relative to parent
			UpdateSubNodes(regionNode, nodeChild, true, meshP);
		}
	}
	// children taken care of... check for attached objects to this node
	Ogre::SceneNode* snode = (Ogre::SceneNode*)node;
	Ogre::SceneNode::ObjectIterator snodeObjectIterator = snode->getAttachedObjectIterator();
	while (snodeObjectIterator.hasMoreElements()) {
		Ogre::MovableObject* snodeObject = snodeObjectIterator.getNext();
		if (snodeObject->getMovableType() == "Entity") {
			Ogre::Entity* snodeEntity = (Ogre::Entity*)snodeObject;
			Ogre::MeshPtr entityMesh = snodeEntity->getMesh();
			if (entityMesh == meshP) {
				snode->needUpdate(true);
				// LG::Log("OLMeshTracker::UpdateSubNodes: setting node update for %s", snode->getName().c_str());
			}
		}
	}
	return;
}
 Ogre::Entity* EC_OgreAnimationController::GetEntity()
 {
     if (!mesh_entity_)
         return 0;
     
     OgreRenderer::EC_OgreMesh &mesh = *checked_static_cast<OgreRenderer::EC_OgreMesh*>(mesh_entity_.get());
     Ogre::Entity* entity = mesh.GetEntity();
     if (!entity)
         return 0;
     
     if (entity->getMesh()->getName() != mesh_name_)
     {
         mesh_name_ = entity->getMesh()->getName();
         ResetState();
     }
     
     return entity;
 }
Esempio n. 4
0
Ogre::Entity *VLogicModel::_createEntity(const VString &meshName)
{
    Ogre::Entity *entity = VNULL;

    loadMesh(meshName, Ogre::StringUtil::BLANK, Ogre::StringUtil::BLANK, DEFAULT_RESOURCE_GROUP_NAME);

    VString entityName = mModelMainNode->getName() + "_Entity" + "_" + meshName +
                         Ogre::StringConverter::toString(mCreatedEntityCount++);

    VGraphicsSystem *system = VENGINE.getGfxSystem();
    entity = system->getSceneManager()->createEntity(entityName, meshName);

    mModelMainNode->attachObject(entity);

    if (!entity->getMesh()->getSkeleton().isNull())
    {
        if (VNULL == mSkeletonEntity)
        {
            const Ogre::MeshPtr &originMesh = entity->getMesh();
            assert(!originMesh.isNull());
            const Ogre::SkeletonPtr &originSke = originMesh->getSkeleton();
            assert(!originSke.isNull());

            _createSkeletonEntity(originSke);
        }

        assert(mSkeletonEntity);

        entity->shareSkeletonInstanceWith(mSkeletonEntity);
    }

// 	_convertEntityToCharacterMaterial(entity);

    if (mSkeletonEntity && !mSkeleton)
    {
        mSkeleton = mSkeletonEntity->getSkeleton();
        mSkeleton->setBlendMode(Ogre::ANIMBLEND_CUMULATIVE);
    }

    entity->setCastShadows(mShadowCastable && !isShadowUncastable(meshName));

    return entity;
}
Esempio n. 5
0
SceneNode* Bridge::createObject( SceneNode* parentNode,str name,str matName,str meshName, 
								Ogre::Vector3 pos /*= Ogre::Vector3::ZERO*/, 
								Ogre::Quaternion rot /*= Ogre::Quaternion::IDENTITY*/ )
{
	SceneNode* node = parentNode->createChildSceneNode(name+"Node",pos,rot);
	Ogre::Entity* entity = game->visualSystem.getSceneMgr()->createEntity(name,meshName);
	entity->setMaterialName(matName);
	entity->setCastShadows(false);
	entity->getMesh()->buildTangentVectors();
	node->attachObject(entity);
	return node;
}
Esempio n. 6
0
void ManipulatorEffect::OnFrameMove( float dt )
{
	Ogre::Entity* ent = ManipulatorSystem.GetObject().GetSelection();
	if (ent && ent->hasSkeleton())
	{
		auto iter = m_effectTemplates.find(ent->getMesh()->getName());
		if (iter != m_effectTemplates.end())
		{
			Kratos::EffectController* controller = iter->second;
			controller->Update(dt);
		}
	}
}
Esempio n. 7
0
CollisionModel3D *EditorFrameHandler::GetCollisionModel(const char *modelname)
{	
	CollisionModel3D *hashres=NULL, *CollisionModel = NULL;
	bool bres = CollisionModels.Find(modelname, &hashres);

    if (!bres)
    {
        CollisionModel = newCollisionModel3D(false);

        size_t vertex_count,index_count;
        Ogre::Vector3* vertices;
        unsigned long* indices;

        Ogre::SceneManager *SceneMgr = CommonDeclarations::GetSceneManager();

        Ogre::Entity *entity = SceneMgr->createEntity("tmpcollis", modelname);

		Collidable::getMeshInformation(entity->getMesh().getPointer(),vertex_count,vertices,index_count,indices,Ogre::Vector3(0,0,0),Ogre::Quaternion::IDENTITY,Ogre::Vector3(1,1,1));

        SceneMgr->destroyEntity(entity);

        size_t index;
        int numTris = (int)index_count / 3;
        CollisionModel->setTriangleNumber(numTris);
        for (unsigned i=0;i<index_count;i+=3)
        {
            index = indices[i];
            CollisionModel->addTriangle(vertices[indices[i+0]].x,vertices[indices[i+0]].y,vertices[indices[i+0]].z,
                vertices[indices[i+1]].x,vertices[indices[i+1]].y,vertices[indices[i+1]].z,
                vertices[indices[i+2]].x,vertices[indices[i+2]].y,vertices[indices[i+2]].z);
        }
        CollisionModel->finalize();

        delete[] vertices;
        delete[] indices;

		CollisionModels.Insert(modelname,CollisionModel);

    } else
    {
        CollisionModel = hashres;
    }
	return CollisionModel;
}
Esempio n. 8
0
std::vector<std::wstring> ManipulatorEffect::GetLocatorNames() const
{
	Ogre::Entity* ent = ManipulatorSystem.GetObject().GetSelection();
	assert(ent);

	std::vector<std::wstring> ret;
	//M3模型从max导出时locator命名为Ref_xxx形式
	Ogre::SkeletonPtr skel = ent->getMesh()->getSkeleton();
	Ogre::Skeleton::BoneIterator iter = skel->getBoneIterator();

	while (iter.hasMoreElements())
	{
		Ogre::Bone* pBone = iter.peekNext();
		if(pBone->getName().find("Ref_") != Ogre::String::npos)
			ret.push_back(Utility::EngineToUnicode(pBone->getName()));

		iter.getNext();
	}

	return std::move(ret);
}
Esempio n. 9
0
void ManipulatorObject::Serialize( rapidxml::xml_document<>* doc, rapidxml::xml_node<>* XMLNode )
{
	using namespace rapidxml;

	const String count = Ogre::StringConverter::toString(m_objects.size());
	XMLNode->append_attribute(doc->allocate_attribute("count", doc->allocate_string(count.c_str())));

	for (auto iter=m_objects.begin(); iter!=m_objects.end(); ++iter)
	{
		Ogre::Entity* pObj = iter->first;
		xml_node<>* objNode =   doc->allocate_node(node_element, "entity");

		//meshname
		const String& strMesh = pObj->getMesh()->getName();
		objNode->append_attribute(doc->allocate_attribute("meshname", doc->allocate_string(strMesh.c_str())));
		//add to navmesh
		const String& strIsNavMesh = Ogre::StringConverter::toString((iter->second)->m_bAddToNavmesh);
		objNode->append_attribute(doc->allocate_attribute("isnavmesh", doc->allocate_string(strIsNavMesh.c_str())));
		//is building
		const String& strIsBuilding = Ogre::StringConverter::toString((iter->second)->m_bIsBuilding);
		objNode->append_attribute(doc->allocate_attribute("isbuilding", doc->allocate_string(strIsBuilding.c_str())));
		//building name
		if(strIsBuilding == "true")
			objNode->append_attribute(doc->allocate_attribute("buildingname", doc->allocate_string((iter->second)->m_buildingName.c_str())));
		//is resource
		const String& strIsResource = Ogre::StringConverter::toString((iter->second)->m_bIsResource);
		objNode->append_attribute(doc->allocate_attribute("isresource", doc->allocate_string(strIsResource.c_str())));
		//position
		String strPos = Ogre::StringConverter::toString(pObj->getParentSceneNode()->_getDerivedPosition());
		objNode->append_attribute(doc->allocate_attribute("position", doc->allocate_string(strPos.c_str())));
		//orientation
		String strOrient = Ogre::StringConverter::toString(pObj->getParentSceneNode()->_getDerivedOrientation());
		objNode->append_attribute(doc->allocate_attribute("orientation", doc->allocate_string(strOrient.c_str())));
		//scale
		String strScale = Ogre::StringConverter::toString(pObj->getParentSceneNode()->_getDerivedScale());
		objNode->append_attribute(doc->allocate_attribute("scale", doc->allocate_string(strScale.c_str())));

		XMLNode->append_node(objNode);
	}
}
Esempio n. 10
0
void BoneCollisionManager::checkMesh(Ogre::String outFileName, Ogre::SceneNode* node)
{
	std::ofstream file(outFileName.c_str());
	if (file)
	{
		Ogre::Entity* ent = (Ogre::Entity*)node->getAttachedObject(0);
		Ogre::SkeletonInstance* skeletonInst = ent->getSkeleton();
		Ogre::Skeleton::BoneIterator boneI=skeletonInst->getBoneIterator();

		//file<<"Creating bone length information from:\n";
		file<<"Mesh name: "<<ent->getMesh()->getName()<<"\n";
		file<<"Skeleton name: "<<skeletonInst->getName()<<"\n\n";

		while(boneI.hasMoreElements())
		{
			Ogre::Bone* bone=boneI.getNext();
			Ogre::String bName=bone->getName();

			if (bone->getChild(0))
			{
				Ogre::Vector3 curr = bone->_getDerivedPosition();
				Ogre::Vector3 next = bone->getChild(0)->_getDerivedPosition();

				Ogre::Vector3 difference = next-curr;

				//length of bone
				Ogre::Real lenght = difference.length();

				file<<bName<<":\nLength\t\t\t=\t"<<Ogre::StringConverter::toString(lenght,3)<<"\n"<<
					"Position"<<"\t\t=\t"<<Ogre::StringConverter::toString(curr.x,1)<<", "<<
					Ogre::StringConverter::toString(curr.y,1)<<", "<<
					Ogre::StringConverter::toString(curr.z,1)<<"\n";
				if (!bone->getParent())
					file<<bName<<" is a Root Bone!\n\n";
				else
					file<<"\n\n";
			}
		}
	}
}
	NxOgre::StringPairList GameBodyObject::saveCustom()
	{
		
		NxOgre::StringPairList l;
		l.insert("ActorType", "Body");

		if (mNode == 0)
		{
			return l;
		}

		if (mNode->numChildren() > 0) 
		{
			DumpNodes(l, mNode, 0, 1);
		}
		else 
		{
			Ogre::Entity* entity = static_cast<Ogre::Entity*>(mNode->getAttachedObject(0));
			l.insert("Entity", entity->getMesh()->getName());
		}
		
		return l;
	}
Esempio n. 12
0
	RegionEntity::RegionEntity(const char *name, const char *meshName)
		: Entity(name, meshName) {
		Ogre::Entity *physicsEnt = Core::GetInstance().ogreSceneMgr->createEntity(name, meshName);

		size_t vertexCount, indexCount;
		Ogre::Vector3* vertices;
		unsigned* indices;

		Utils::GetMeshInformation(physicsEnt->getMesh(), vertexCount, vertices, indexCount, indices);
		btTriangleIndexVertexArray *vertexArray = new btTriangleIndexVertexArray(
			indexCount / 3,
			(int *)(indices),
			12,
			vertexCount,
			(btScalar *)(vertices),
			12
		);

		collisionShape = new btBvhTriangleMeshShape(vertexArray, true);

		btDefaultMotionState *levelMotionState = new btDefaultMotionState(
			btTransform(btQuaternion(0,0,0,1),btVector3(0,0,0))
			);

		ghostObject = new btPairCachingGhostObject();
		ghostObject->setWorldTransform(btTransform(btQuaternion(0,0,0,1),btVector3(0,0,0)));
		ghostObject->setCollisionShape(collisionShape);
		ghostObject->setCollisionFlags(btCollisionObject::CF_NO_CONTACT_RESPONSE);

		Core::GetInstance().bulWorld->addCollisionObject(ghostObject,
				btBroadphaseProxy::SensorTrigger | btBroadphaseProxy::StaticFilter,
				btBroadphaseProxy::AllFilter);

		Core::GetInstance().ogreSceneMgr->destroyEntity(physicsEnt);

		callback = NULL;
	}
Esempio n. 13
0
	void SceneObject::updateData()
	{
		clear();

		Ogre::Entity* entity = getSceneManager()->getEntity(mEntityName);
		if (entity != nullptr && !mMaterialName.empty())
		{
			mVertexCount = 0;
			mIndexCount = 0;
			GetMeshInformation(entity->getMesh(), mVertexCount, mVertices, mIndexCount, mIndices, mTextureCoords, Ogre::Vector3::ZERO, Ogre::Quaternion::IDENTITY, Ogre::Vector3::UNIT_SCALE, mMaterialName);

			Ogre::MaterialPtr material = (Ogre::MaterialPtr)Ogre::MaterialManager::getSingleton().getByName(mMaterialName);
			if (!material.isNull())
			{
				mTextureUnit = material->getTechnique(0)->getPass(0)->getTextureUnitState("gui");
				if (mTextureUnit)
				{
					mTextureUnit->setTextureName(mTextureName);
					mUScale = mTextureUnit->getTextureUScale();
					mVScale = mTextureUnit->getTextureVScale();
				}
			}
		}
	}
Esempio n. 14
0
bool CollisionTools::raycast(const Ray &ray, Vector3 &result,unsigned long &target,float &closest_distance, const uint32 queryMask)
{
	target = NULL;

    // check we are initialised
    if (mRaySceneQuery != NULL)
    {
        // create a query object
        mRaySceneQuery->setRay(ray);
		mRaySceneQuery->setSortByDistance(true);
		mRaySceneQuery->setQueryMask(queryMask);
        // execute the query, returns a vector of hits
        if (mRaySceneQuery->execute().size() <= 0)
        {
            // raycast did not hit an objects bounding box
            return (false);
        }
    }
    else
    {
        //LOG_ERROR << "Cannot raycast without RaySceneQuery instance" << ENDLOG;
        return (false);
    }   

    // at this point we have raycast to a series of different objects bounding boxes.
    // we need to test these different objects to see which is the first polygon hit.
    // there are some minor optimizations (distance based) that mean we wont have to
    // check all of the objects most of the time, but the worst case scenario is that
    // we need to test every triangle of every object.
    //Ogre::Real closest_distance = -1.0f;
	closest_distance = -1.0f;
    Ogre::Vector3 closest_result;
    Ogre::RaySceneQueryResult &query_result = mRaySceneQuery->getLastResults();
    for (size_t qr_idx = 0; qr_idx < query_result.size(); qr_idx++)
    {
        // stop checking if we have found a raycast hit that is closer
        // than all remaining entities
        if ((closest_distance >= 0.0f) &&
            (closest_distance < query_result[qr_idx].distance))
        {
            break;
        }

        // only check this result if its a hit against an entity
        if ((query_result[qr_idx].movable != NULL)  &&
            (query_result[qr_idx].movable->getMovableType().compare("Entity") == 0)) 
        {
            // get the entity to check
			Ogre::Entity *pentity = static_cast<Ogre::Entity*>(query_result[qr_idx].movable); 			
						
            // mesh data to retrieve         
            size_t vertex_count;
            size_t index_count;
            Ogre::Vector3 *vertices;
            unsigned long *indices;

            // get the mesh information
			GetMeshInformation(pentity->getMesh(), vertex_count, vertices, index_count, indices,             
                              pentity->getParentNode()->_getDerivedPosition(),
                              pentity->getParentNode()->_getDerivedOrientation(),
                              pentity->getParentNode()->getScale());

            // test for hitting individual triangles on the mesh
            bool new_closest_found = false;
            for (int i = 0; i < static_cast<int>(index_count); i += 3)
            {
                // check for a hit against this triangle
                std::pair<bool, Ogre::Real> hit = Ogre::Math::intersects(ray, vertices[indices[i]],
                    vertices[indices[i+1]], vertices[indices[i+2]], true, false);

                // if it was a hit check if its the closest
                if (hit.first)
                {
                    if ((closest_distance < 0.0f) ||
                        (hit.second < closest_distance))
                    {
                        // this is the closest so far, save it off
                        closest_distance = hit.second;
                        new_closest_found = true;
                    }
                }
            }

			// free the verticies and indicies memory
            delete[] vertices;
            delete[] indices;

            // if we found a new closest raycast for this object, update the
            // closest_result before moving on to the next object.
            if (new_closest_found)
            {
				target = (unsigned long)pentity;
                closest_result = ray.getPoint(closest_distance);               
            }
        }       
    }

    // return the result
    if (closest_distance >= 0.0f)
    {
        // raycast success
		result = closest_result;
        return (true);
    }
    else
    {
        // raycast failed
        return (false);
    } 
}
Esempio n. 15
0
void MeshCollisionDetector::testCollision(Ogre::Ray& ray, CollisionResult& result)
{

    // at this point we have raycast to a series of different objects bounding boxes.
    // we need to test these different objects to see which is the first polygon hit.
    // there are some minor optimizations (distance based) that mean we wont have to
    // check all of the objects most of the time, but the worst case scenario is that
    // we need to test every triangle of every object.
    Ogre::Real closest_distance = -1.0f;
    Ogre::Vector3 closest_result = Ogre::Vector3::ZERO;
    const Model::Model::SubModelSet& submodels = mModel->getSubmodels();
    for (Model::Model::SubModelSet::const_iterator I = submodels.begin(); I != submodels.end(); ++I)
    {
        Ogre::Entity* pentity = (*I)->getEntity();
        if (pentity->isVisible() && pentity->getParentNode()) {
            // mesh data to retrieve
            size_t vertex_count;
            size_t index_count;
            Ogre::Vector3 *vertices;
            unsigned long *indices;

            // get the mesh information
            getMeshInformation(pentity->getMesh(), vertex_count, vertices, index_count, indices,
                               pentity->getParentNode()->_getDerivedPosition(),
                               pentity->getParentNode()->_getDerivedOrientation(),
                               pentity->getParentNode()->getScale());

            // test for hitting individual triangles on the mesh
            bool new_closest_found = false;
            for (int i = 0; i < static_cast<int>(index_count); i += 3)
            {
                // check for a hit against this triangle
                std::pair<bool, Ogre::Real> hit = Ogre::Math::intersects(ray, vertices[indices[i]],
                                                  vertices[indices[i+1]], vertices[indices[i+2]], true, false);

                // if it was a hit check if its the closest
                if (hit.first)
                {
                    if ((closest_distance < 0.0f) ||
                            (hit.second < closest_distance))
                    {
                        // this is the closest so far, save it off
                        closest_distance = hit.second;
                        new_closest_found = true;
                    }
                }
            }

            // free the verticies and indicies memory
            delete[] vertices;
            delete[] indices;

            // if we found a new closest raycast for this object, update the
            // closest_result before moving on to the next object.
            if (new_closest_found)
            {
                closest_result = ray.getPoint(closest_distance);
            }
        }
    }


    // return the result
    if (closest_distance >= 0.0f)
    {
        // raycast success
        result.collided = true;
        result.position = closest_result;
        result.distance = closest_distance;
    }
    else
    {
        // raycast failed
        result.collided = false;
    }
}
Esempio n. 16
0
Ogre::Entity* RaycastToPolygon( const Ogre::Real& x, const Ogre::Real& y,
	Ogre::RaySceneQuery* Query, Ogre::Camera* Camera )
{
	Ogre::Ray MouseRay = Camera->getCameraToViewportRay( x, y );
	Query->setRay( MouseRay );
	Query->setSortByDistance( true );

	Ogre::RaySceneQueryResult& QueryResult = Query->execute();

	if( QueryResult.size() == 0 )
	{
		return NULL;
	}

	// at this point we have raycast to a series of different objects bounding boxes. 
	// we need to test these different objects to see which is the first polygon hit. 
	// there are some minor optimizations (distance based) that mean we wont have to 
	// check all of the objects most of the time, but the worst case scenario is that 
	// we need to test every triangle of every object. 
	Ogre::Real ClosestDistance = -1.0f;
	Ogre::Entity* ClosestResult;

	for( size_t QRIndex = 0; QRIndex < QueryResult.size(); QRIndex++ ) 
	{ 
		// stop checking if we have found a raycast hit that is closer 
		// than all remaining entities 
		if( ( ClosestDistance >= 0.0f ) && 
			( ClosestDistance < QueryResult[QRIndex].distance ) )
			break; 
		
		// only check this result if its a hit against an entity 
		if( ( QueryResult[QRIndex].movable != NULL ) && 
			( QueryResult[QRIndex].movable->getMovableType().compare("Entity") == 0 ) &&
			QueryResult[QRIndex].movable->getName() != OVISE_SelectionBoxName ) 
		{ 
			// get the entity to check 
			Ogre::Entity* PEntity = static_cast<Ogre::Entity*>(QueryResult[QRIndex].movable);
			
			// mesh data to retrieve
			size_t VertexCount; 
			size_t IndexCount; 
			Ogre::Vector3* Vertices; 
			unsigned long* Indices;  
			
			// get the mesh information 
			GetMeshInformation( PEntity->getMesh(), 
				VertexCount, 
				Vertices, 
				IndexCount, 
				Indices, 
				PEntity->getParentSceneNode()->_getDerivedPosition(),
				PEntity->getParentSceneNode()->_getDerivedOrientation(), 
				PEntity->getParentSceneNode()->_getDerivedScale() );

			// test for hitting individual triangles on the mesh 
			bool NewClosestFound = false;
			if( IndexCount == 0 ) // no triangles, e.g. pointcloud
			{
				NewClosestFound = true;
				ClosestDistance = QueryResult[QRIndex].distance;
			}
			else
			{
				for( int i = 0; i < static_cast<int>(IndexCount); i += 3 ) 
				{ 
					// check for a hit against this triangle 
					std::pair<bool, Ogre::Real> Hit = 
						Ogre::Math::intersects( MouseRay, 
						Vertices[Indices[i]], 
						Vertices[Indices[i+1]], 
						Vertices[Indices[i+2]], 
						true, false);  
					// if it was a hit check if its the closest 
					if( Hit.first ) 
					{ 
						if( ( ClosestDistance < 0.0f ) || 
							( Hit.second < ClosestDistance ) ) 
						{ 
							// this is the closest so far, save it off 
							ClosestDistance = Hit.second; 
							NewClosestFound = true; 
						} 
					} 
				}
			}

			// free the verticies and indicies memory 
			delete[] Vertices;
			delete[] Indices;

			// if we found a new closest raycast for this object, update the 
			// closest_result before moving on to the next object. 
			if( NewClosestFound ) 
				ClosestResult = PEntity;
		}  
	}

	if( ClosestDistance < 0.0f ) 
	{
		// raycast failed 
		ClosestResult = NULL;
	}

	return ClosestResult;
}
Esempio n. 17
0
	void RenderBoxWrap::synchronizeSceneNode(Ogre::SceneNode* _newNode, Ogre::SceneNode* _fromNode)
	{
		if (_newNode == nullptr || _fromNode == nullptr)
		{
			MYGUI_ASSERT(_newNode == nullptr || _fromNode == nullptr,"Synchronize scene node error.");
			return;
		}

		_newNode->setPosition(_fromNode->getPosition());
		_newNode->setOrientation(_fromNode->getOrientation());

		int i = 0;

		while (i < _newNode->numAttachedObjects())
		{
			Ogre::MovableObject * object = _newNode->getAttachedObject(i);
			Ogre::Entity* entity = object->getMovableType() == "Entity" ? static_cast<Ogre::Entity*>(object) : nullptr;

			if(entity)
			{
				object = findMovableObject(_fromNode, entity->getName());
				Ogre::Entity* oldEntity = (object != nullptr && object->getMovableType() == "Entity") ? static_cast<Ogre::Entity*>(object) : nullptr;

				if(!oldEntity)
				{
					removeEntity(entity->getName());
					continue;
				}
			}
			i++;
		}

		for(i = 0; i < _fromNode->numAttachedObjects(); i++)
		{
			Ogre::MovableObject * object = _fromNode->getAttachedObject(i);
			Ogre::Entity* entity = object->getMovableType() == "Entity" ? static_cast<Ogre::Entity*>(object) : nullptr;

			if(entity)
			{
				object = findMovableObject(_newNode, entity->getName());
				Ogre::Entity* newEntity = (object != nullptr && object->getMovableType() == "Entity") ? static_cast<Ogre::Entity*>(object) : nullptr;

				if(!newEntity)
				{
					//System::Console::WriteLine("create new entity {0}", gcnew System::String(entity->getName().c_str()));

					newEntity = mScene->createEntity(entity->getName(), entity->getMesh()->getName());//new Ogre::Entity(entity->getName(), (Ogre::MeshPtr)entity->getMesh().get()->getHandle());
					_newNode->attachObject(newEntity);

					mVectorEntity.push_back(newEntity);

					if(mEntity == nullptr)
					{
						mEntity = newEntity;
					}
				}
			}
		}

		i = 0;

		while (i < _newNode->numChildren())
		{
			Ogre::SceneNode* oldNode = findSceneNodeObject(_fromNode, _newNode->getChild(i)->getName());

			if(!oldNode)
			{
				Ogre::SceneNode* forDelete = (Ogre::SceneNode*)_newNode->getChild(i);

				removeNode(forDelete);
			}else
			{
				i++;
			}
		}

		for(i = 0; i < _fromNode->numChildren(); i++)
		{
			if(_fromNode->getChild(i)->numChildren() != 0 &&
				((Ogre::SceneNode*)_fromNode->getChild(i))->numAttachedObjects() != 0)
			{
				Ogre::SceneNode* newChildNode = findSceneNodeObject(_newNode, _fromNode->getChild(i)->getName());

				if(!newChildNode)
				{
					//System::Console::WriteLine("create new node {0}", gcnew System::String(_fromNode->getChild(i)->getName().c_str()));
					newChildNode = _newNode->createChildSceneNode(_fromNode->getChild(i)->getName(), _fromNode->getChild(i)->getPosition(), _fromNode->getChild(i)->getOrientation());
				}

				synchronizeSceneNode(newChildNode, (Ogre::SceneNode*)_fromNode->getChild(i));
			}
		}
	}
Esempio n. 18
0
std::pair<bool, Real>
rayCollide(const Ogre::Ray& ray,
           Ogre::MovableObject* movable,
           bool accurate,
           CullingMode cullingMode,
           bool allowAnimable)
{
    // Get local space axis aligned bounding box
    const Ogre::AxisAlignedBox& aabb = movable->getBoundingBox();

    // Matrix4 to transform local space to world space
    const Ogre::Matrix4& localToWorld = movable->_getParentNodeFullTransform();

    // Matrix4 to transform world space to local space
    Ogre::Matrix4 worldToLocal = localToWorld.inverse();

    // Matrix3 to transform world space normal to local space
    Ogre::Matrix3 worldToLocalN;
    worldToLocal.extract3x3Matrix(worldToLocalN);

    // Convert world space ray to local space ray
    // Note:
    //      By preserving the scale between world space and local space of the
    //      direction, we don't need to recalculate the distance later.
    Ogre::Ray localRay;
    localRay.setOrigin(worldToLocal * ray.getOrigin());
    localRay.setDirection(worldToLocalN * ray.getDirection());

    // Intersect with axis aligned bounding box, but because we transformed
    // ray to local space of the bounding box, so this test just like test
    // with oriented bounding box.
    std::pair<bool, Real> ret = localRay.intersects(aabb);

    // Do accurate test if hitted bounding box and user required.
    if (ret.first && accurate)
    {
        if (movable->getMovableType() == Ogre::EntityFactory::FACTORY_TYPE_NAME ||
            allowAnimable && movable->getMovableType() == Ogre::AutoAnimationEntityFactory::FACTORY_TYPE_NAME)
        {
            Ogre::Entity* entity = static_cast<Ogre::Entity*>(movable);
            if (!entity->_isAnimated())
            {
                // Static entity

                // Get the entity mesh
                const Ogre::MeshPtr& mesh = entity->getMesh();

                // Get the collision mode
                CollisionModelPtr collisionModel = CollisionModelManager::getSingleton().getCollisionModel(mesh);

                ret = doPicking(localRay, *collisionModel, cullingMode);
            }
            else if (allowAnimable)
            {
                // Animation entity

                bool addedSoftwareAnimation = false;
                if (entity->getSoftwareAnimationRequests() <= 0)
                {
                    entity->addSoftwareAnimationRequest(false);
                    entity->_updateAnimation();
                    addedSoftwareAnimation = true;
                }

                CollisionModel collisionModel;
                collisionModel.addEntity(entity);
                collisionModel.build(true);

                ret = doPicking(localRay, collisionModel, cullingMode);

                if (addedSoftwareAnimation)
                {
                    entity->removeSoftwareAnimationRequest(false);
                }
            }
        }
    }

    return ret;
}
void CSaveSceneView::SceneNodeExplore(Ogre::SceneNode *SceneNode)
{
	Ogre::Entity *Entity = NULL;
	Ogre::Camera *Camera = NULL;
	Ogre::Light *Light = NULL;
	Ogre::ParticleSystem *ParticleSystem = NULL;
	Ogre::ManualObject *ManualObject = NULL;
	Ogre::BillboardSet *BillboardSet = NULL;

	xmlTextWriterStartElement(m_XmlWriter, BAD_CAST "SceneNode");
	
	Ogre::String SceneNodeName = SceneNode->getName();

	xmlTextWriterWriteAttribute(m_XmlWriter, 
										BAD_CAST "SceneNodeName",
										BAD_CAST SceneNodeName.c_str());

	Ogre::SceneNode::ObjectIterator obji = SceneNode->getAttachedObjectIterator();

	while (obji.hasMoreElements())
	{
		Ogre::MovableObject* mobj = obji.getNext();
	
		Ogre::String Type = mobj->getMovableType();
	
		if (Type == "Entity")
		{
			Entity = (Ogre::Entity *)(mobj);
			Ogre::String EntityName = Entity->getName();
			xmlTextWriterStartElement(m_XmlWriter, BAD_CAST "Entity");
			xmlTextWriterWriteAttribute(m_XmlWriter, 
										BAD_CAST "EntityName",
										BAD_CAST EntityName.c_str());

			Ogre::MeshPtr Mesh = Entity->getMesh();
			Ogre::String MeshName = Mesh->getName();
			xmlTextWriterWriteAttribute(m_XmlWriter, 
										BAD_CAST "MeshName",
										BAD_CAST MeshName.c_str());
			xmlTextWriterEndElement(m_XmlWriter); 
		}
		
		if (Type == "Camera")
		{
			Camera = (Ogre::Camera *)(mobj);
			Ogre::String CameraName = Camera->getName();
			xmlTextWriterStartElement(m_XmlWriter, BAD_CAST "Camera");
			
			xmlTextWriterWriteAttribute(m_XmlWriter, 
										BAD_CAST "CameraName",
										BAD_CAST CameraName.c_str());
			
			Ogre::Vector3 CameraPosition = Camera->getPosition();
			
			xmlTextWriterWriteFormatAttribute(m_XmlWriter, 
										BAD_CAST "XPosition",
										"%f",CameraPosition.x);
			xmlTextWriterWriteFormatAttribute(m_XmlWriter, 
										BAD_CAST "YPosition",
										"%f",CameraPosition.y);
			xmlTextWriterWriteFormatAttribute(m_XmlWriter, 
										BAD_CAST "ZPosition",
										"%f",CameraPosition.z);

			Ogre::Vector3 CameraDirection = Camera->getDirection();

			xmlTextWriterWriteFormatAttribute(m_XmlWriter, 
										BAD_CAST "XDirection",
										"%f",CameraDirection.x);
			xmlTextWriterWriteFormatAttribute(m_XmlWriter, 
										BAD_CAST "YDirection",
										"%f",CameraDirection.y);
			xmlTextWriterWriteFormatAttribute(m_XmlWriter, 
										BAD_CAST "ZDirection",
										"%f",CameraDirection.z);

			xmlTextWriterEndElement(m_XmlWriter); 
		}

		if (Type == "Light")
		{
			Light = (Ogre::Light *)(mobj);
		}

		if (Type == "ParticleSystem")
		{
			ParticleSystem = (Ogre::ParticleSystem *)(mobj);
		}

		if (Type == "ManualObject")
		{
			ManualObject = (Ogre::ManualObject *)(mobj);
		}

		if (Type == "BillboardSet")
		{
			BillboardSet = (Ogre::BillboardSet *)(mobj);
		}

	}

	Ogre::Node::ChildNodeIterator nodei = SceneNode->getChildIterator();

	while (nodei.hasMoreElements())
	{
		Ogre::SceneNode* node = (Ogre::SceneNode*)(nodei.getNext());
			// Add this subnode and its children...
		SceneNodeExplore(node);
	}

	xmlTextWriterEndElement(m_XmlWriter); //end SceneNode
}
void CBlendingAnimationsView::EngineSetup(void)
{
	Ogre::Root *Root = ((CBlendingAnimationsApp*)AfxGetApp())->m_Engine->GetRoot();
	Ogre::SceneManager *SceneManager = NULL;
	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "Walking");
 
    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

    Ogre::NameValuePairList parms;
    parms["externalWindowHandle"] = Ogre::StringConverter::toString((long)m_hWnd);
    parms["vsync"] = "true";

	CRect   rect;
    GetClientRect(&rect);
	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("Mouse Input");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("Mouse Input", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
	m_Camera->setPosition(Ogre::Vector3(/*20*/0.0, /*5*/0.0, 100.0));
	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.8f, 0.8f, 0.8f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));

	Ogre::SceneNode *RobotNode = SceneManager->getRootSceneNode()->createChildSceneNode("Robot", Ogre::Vector3(50,0,0));
	Ogre::Entity *RobotEntity = SceneManager->createEntity("Robot", "robot.mesh");
	Ogre::MeshPtr Mesh = RobotEntity->getMesh();

	RobotNode->attachObject(RobotEntity);
	RobotEntity->getParentNode()->scale(0.2,0.2,0.2);

	m_Camera->lookAt(Ogre::Vector3(0.0, 0.0, 0.0));
	
	RobotEntity->setDisplaySkeleton(true);
	m_Camera->setPolygonMode(Ogre::PolygonMode::PM_WIREFRAME);
	 
	m_WalkAnimation = RobotEntity->getAnimationState("Walk");
	m_WalkAnimation->setEnabled(true);

	m_SlumpAnimation = RobotEntity->getAnimationState("Slump");
	m_SlumpAnimation->setEnabled(true);

	if (m_WeightDlg == NULL)
	{
		m_WeightDlg = new CWeightDlg();
		m_WeightDlg->Create(IDD_WEIGHT_CONTROL);
	}

	m_WeightDlg->ShowWindow(SW_SHOW);

	Root->renderOneFrame();
}
Esempio n. 21
0
void World::Init()
{
	using namespace Ogre;

	SceneManager* sm = m_pRenderSystem->m_pSceneMgr;
	Camera* cam = m_pRenderSystem->m_pMainCamera;

	m_pSceneQuery = sm->createAABBQuery(AxisAlignedBox());
	m_pRaySceneQuery = sm->createRayQuery(Ray());
	m_pRaySceneQuery->setSortByDistance(true);

	Ogre::MovableObject::setDefaultQueryFlags(eQueryType_Default);

	m_cameraMan = new OgreBites::SdkCameraMan(cam);
	m_cameraMan->setStyle(OgreBites::CS_FREELOOK);

	//RTS锁死视角
	cam->setPosition(0, 24, 0);
	cam->lookAt(0, 0, 8);
	//cam->setFOVy(Degree(30));

	//初始化行为库
	aiBehaviorTreeTemplateManager& btMgr = aiBehaviorTreeTemplateManager::GetSingleton();
	btMgr.AddBehavior("Idle", new aiBehaviorIdle);
	btMgr.AddBehavior("MoveToEnemyBase", new aiBehaviorMoveToEnemyBase);
	//加载所有行为树模板
	btMgr.LoadAll();

	//测试两个AI
	m_player[eGameRace_Terran] = new FactionAI(eGameRace_Terran);
	m_player[eGameRace_Zerg] = new FactionAI(eGameRace_Zerg);
	m_player[eGameRace_Terran]->SetEnemy(m_player[eGameRace_Zerg]);
	m_player[eGameRace_Zerg]->SetEnemy(m_player[eGameRace_Terran]);
	m_player[eGameRace_Terran]->SetTeamColor(COLOR::Blue);
	m_player[eGameRace_Zerg]->SetTeamColor(COLOR::Red);

	GameDataDefManager::GetSingleton().LoadAllData();

	//初始化Recast库
	OgreRecastConfigParams recastParams = OgreRecastConfigParams();
	recastParams.setCellSize(1);
	recastParams.setCellHeight(0.16f);
	recastParams.setAgentMaxSlope(15);
	recastParams.setAgentHeight(1.5f);
	recastParams.setAgentMaxClimb(0.5f);
	recastParams.setAgentRadius(0.4f);
	recastParams.setEdgeMaxLen(2);
	recastParams.setEdgeMaxError(1.3f);
	recastParams.setVertsPerPoly(6);
	recastParams.setRegionMinSize(2);
	recastParams.setRegionMergeSize(3);
	recastParams.setDetailSampleDist(6);
	recastParams.setDetailSampleMaxError(1);

	m_pRecast = new OgreRecast(sm, recastParams);
	m_pDetourTileCache = new OgreDetourTileCache(m_pRecast);

	//加载编辑器导出的导航网格数据
	Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(
		"NavMesh.Bin", "General", false);
	assert(m_pDetourTileCache->loadAll(stream));

	//m_pDetourTileCache->drawNavMesh();

	//初始化Detour寻路库
	m_pDetourCrowd = new OgreDetourCrowd(m_pRecast);

	g_Environment.m_pRecast = m_pRecast;
	g_Environment.m_pCrowd = m_pDetourCrowd;

	//加载测试场景
	m_pTestScene = new Kratos::Scene();
	m_pTestScene->Load("MyStarCraft.Scene", "General", this);

	//UI for test
	Ogre::Entity* pEntConsole = m_pRenderSystem->CreateEntityWithTangent("ConsoleTerran_0.mesh", sm);
	pEntConsole->setRenderQueueGroup(Ogre::RENDER_QUEUE_WORLD_GEOMETRY_2);
	pEntConsole->setCastShadows(false);
	m_pUISceneNode1 = sm->getRootSceneNode()->createChildSceneNode("UIConsoleNode");
	m_pUISceneNode1->attachObject(pEntConsole);
	m_pConsoleAnim1 = pEntConsole->getAnimationState("Birth");
	assert(m_pConsoleAnim1);
	(const_cast<Ogre::AxisAlignedBox&>(pEntConsole->getMesh()->getBounds())).setInfinite();

	pEntConsole = m_pRenderSystem->CreateEntityWithTangent("ConsoleTerran_1.mesh", sm);
	pEntConsole->setRenderQueueGroup(Ogre::RENDER_QUEUE_WORLD_GEOMETRY_2);
	pEntConsole->setCastShadows(false);
	m_pUISceneNode2 = m_pUISceneNode1->createChildSceneNode("InfoPanelNode");
	m_pUISceneNode2->attachObject(pEntConsole);
	m_pConsoleAnim2 = pEntConsole->getAnimationState("Birth");
	assert(m_pConsoleAnim2);
	(const_cast<Ogre::AxisAlignedBox&>(pEntConsole->getMesh()->getBounds())).setInfinite();

	pEntConsole = m_pRenderSystem->CreateEntityWithTangent("ConsoleTerran_2.mesh", sm);
	pEntConsole->setRenderQueueGroup(Ogre::RENDER_QUEUE_WORLD_GEOMETRY_2);
	pEntConsole->setCastShadows(false);
	m_pUISceneNode3 = m_pUISceneNode1->createChildSceneNode("CmdPanelNode");
	m_pUISceneNode3->attachObject(pEntConsole);
	(const_cast<Ogre::AxisAlignedBox&>(pEntConsole->getMesh()->getBounds())).setInfinite();

	pEntConsole = m_pRenderSystem->CreateEntityWithTangent("ConsoleProtoss_6.mesh", sm);
	pEntConsole->setRenderQueueGroup(Ogre::RENDER_QUEUE_WORLD_GEOMETRY_2);
	pEntConsole->setCastShadows(false);
	m_pUISceneNode4 = m_pUISceneNode1->createChildSceneNode("PortraitPanelNode");
	m_pUISceneNode4->attachObject(pEntConsole);
	(const_cast<Ogre::AxisAlignedBox&>(pEntConsole->getMesh()->getBounds())).setInfinite();

	m_cmdPanel->Init();
	m_infoPanel->Init();
	m_portraitPanel->Init();

	CEGUI::WindowManager& wndMgr = CEGUI::WindowManager::getSingleton();
	CEGUI::Window* pRoot = wndMgr.getWindow("Root");
	assert(pRoot);
	GUIMANAGER.SetGUISheet(pRoot);
	pRoot->addChildWindow(wndMgr.getWindow("InfoPanelFrame"));
}
Esempio n. 22
0
//!
//! Clones an Ogre::MovableObject.
//!
//! Is needed because OGRE does not provide clone functions for cameras and
//! lights.
//!
//! \param movableObject The object to clone.
//! \param name The name to use for the object.
//! \param sceneManager The scene manager to use for creating the object.
//! \return The cloned object.
//!
Ogre::MovableObject * OgreTools::cloneMovableObject ( Ogre::MovableObject *movableObject, const QString &name, Ogre::SceneManager *sceneManager /* =  0 */ )
{
    // make sure the given object is valid
    if (!movableObject) {
        Log::error("The given movable object is invalid.", "OgreTools::cloneMovableObject");
        return 0;
    }

    // make sure a valid scene manager is available
    if (!sceneManager)
        sceneManager = movableObject->_getManager();
    if (!sceneManager) {
        Log::error("No valid scene manager available.", "OgreTools::cloneMovableObject");
        return 0;
    }

    Ogre::MovableObject *result = 0;
    Ogre::String typeName = movableObject->getMovableType();
    if (typeName == "Entity") {
        // clone entity
        Ogre::Entity *entity = dynamic_cast<Ogre::Entity *>(movableObject);
        //movableObjectCopy = entity->clone(name.toStdString());
        Ogre::Entity *entityCopy = sceneManager->createEntity(name.toStdString(), entity->getMesh()->getName());
        Ogre::AnimationStateSet *animationStateSet = entity->getAllAnimationStates();
        Ogre::AnimationStateSet *animationStateSetCopy  = entityCopy->getAllAnimationStates();
        // set the same blend mode on entity copy
        if (entity && entityCopy) {
            if (entity->hasSkeleton() && entityCopy->hasSkeleton()) {
                Ogre::Skeleton *skeleton = entity->getSkeleton();
                Ogre::Skeleton *skeletonCopy = entityCopy->getSkeleton();
                skeletonCopy->setBlendMode(skeleton->getBlendMode());
            }
        }
        // copy all animation states
        if (animationStateSet && animationStateSetCopy) {
            Ogre::AnimationStateIterator animationStateIter = animationStateSet->getAnimationStateIterator();
            Ogre::AnimationStateIterator animationStateCopyIter = animationStateSetCopy->getAnimationStateIterator();
            while (animationStateIter.hasMoreElements()) {
                if (!animationStateCopyIter.hasMoreElements())
                    break;
                Ogre::AnimationState *animationState = animationStateIter.getNext();
                Ogre::AnimationState *animationStateCopy = animationStateCopyIter.getNext();
                animationStateCopy->setLoop(animationState->getLoop());
                //bool enabled = animationState->getEnabled();
                //animationStateCopy->setEnabled(animationState->getEnabled());
                animationStateCopy->setEnabled(true);
                animationStateCopy->setTimePosition(animationState->getTimePosition());
            }
        }

        // create a new container for the cloned entity
        OgreContainer *entityCopyContainer = new OgreContainer(entityCopy);
        entityCopy->setUserAny(Ogre::Any(entityCopyContainer));
        if (!entity->getUserAny().isEmpty()) {
            OgreContainer *entityContainer = Ogre::any_cast<OgreContainer *>(entity->getUserAny());
			if (entityContainer) {
                QObject::connect(entityContainer, SIGNAL(animationStateUpdated(const QString &, double)), entityCopyContainer, SLOT(updateAnimationState(const QString &, double)));
				QObject::connect(entityContainer, SIGNAL(boneTransformUpdated(const QString &, double, double, double, double, double, double)), entityCopyContainer, SLOT(updateBoneTransform(const QString &, double, double, double, double, double, double)));
			}
        }
        result = dynamic_cast<Ogre::MovableObject *>(entityCopy);
    } else if (typeName == "Light") {
        // clone light
        Ogre::Light *light = dynamic_cast<Ogre::Light *>(movableObject);
        Ogre::Light *lightCopy = sceneManager->createLight(name.toStdString());
        lightCopy->setType(light->getType());
        lightCopy->setDiffuseColour(light->getDiffuseColour());
        lightCopy->setSpecularColour(light->getSpecularColour());
        lightCopy->setAttenuation(light->getAttenuationRange(), light->getAttenuationConstant(), light->getAttenuationLinear(), light->getAttenuationQuadric());
        lightCopy->setPosition(light->getPosition());
        lightCopy->setDirection(light->getDirection());
        if (lightCopy->getType() == Ogre::Light::LT_SPOTLIGHT)
            lightCopy->setSpotlightRange(light->getSpotlightInnerAngle(), light->getSpotlightOuterAngle(), light->getSpotlightFalloff());
        lightCopy->setPowerScale(light->getPowerScale());
        lightCopy->setCastShadows(light->getCastShadows());

        // create a new container for the cloned light
        OgreContainer *lightCopyContainer = new OgreContainer(lightCopy);
        lightCopy->setUserAny(Ogre::Any(lightCopyContainer));
        if (!light->getUserAny().isEmpty()) {
            OgreContainer *lightContainer = Ogre::any_cast<OgreContainer *>(light->getUserAny());
            if (lightContainer)
                QObject::connect(lightContainer, SIGNAL(sceneNodeUpdated()), lightCopyContainer, SLOT(updateLight()));
        }
        result = dynamic_cast<Ogre::MovableObject *>(lightCopy);
    } else if (typeName == "Camera") {
        // clone camera
        Ogre::Camera *camera = dynamic_cast<Ogre::Camera *>(movableObject);
        Ogre::Camera *cameraCopy = sceneManager->createCamera(name.toStdString());
        //cameraCopy->setCustomParameter(0, camera->getCustomParameter(0));
        cameraCopy->setAspectRatio(camera->getAspectRatio());
        cameraCopy->setAutoAspectRatio(camera->getAutoAspectRatio());
        //cameraCopy->setAutoTracking(...);
        cameraCopy->setCastShadows(camera->getCastsShadows());
        //cameraCopy->setCullingFrustum(camera->getCullingFrustum());
        //cameraCopy->setCustomParameter(...);
        //cameraCopy->setCustomProjectionMatrix(..);
        //cameraCopy->setCustomViewMatrix(..);
        //cameraCopy->setDebugDisplayEnabled(...);
        //cameraCopy->setDefaultQueryFlags(...);
        //cameraCopy->setDefaultVisibilityFlags(...);
        cameraCopy->setDirection(camera->getDirection());
        //cameraCopy->setFixedYawAxis(...);
        cameraCopy->setFocalLength(camera->getFocalLength());
        cameraCopy->setFOVy(camera->getFOVy());

        //Ogre::Real left;
        //Ogre::Real right;
        //Ogre::Real top;
        //Ogre::Real bottom;
        //camera->getFrustumExtents(left, right, top, bottom);
        //cameraCopy->setFrustumExtents(left, right, top, bottom);
        //cameraCopy->setFrustumOffset(camera->getFrustumOffset());
        //cameraCopy->setListener(camera->getListener());
        cameraCopy->setLodBias(camera->getLodBias());
        //cameraCopy->setLodCamera(camera->getLodCamera());
        cameraCopy->setNearClipDistance(camera->getNearClipDistance());
        cameraCopy->setFarClipDistance(camera->getFarClipDistance());
        cameraCopy->setOrientation(camera->getOrientation());
        //cameraCopy->setOrthoWindow(...);
        //cameraCopy->setOrthoWindowHeight(...);
        //cameraCopy->setOrthoWindowWidth(...);
        cameraCopy->setPolygonMode(camera->getPolygonMode());
        cameraCopy->setPolygonModeOverrideable(camera->getPolygonModeOverrideable());
        cameraCopy->setPosition(camera->getPosition());
        cameraCopy->setProjectionType(camera->getProjectionType());
        cameraCopy->setQueryFlags(camera->getQueryFlags());
        cameraCopy->setRenderingDistance(camera->getRenderingDistance());
        cameraCopy->setRenderQueueGroup(camera->getRenderQueueGroup());
        //cameraCopy->setRenderSystemData(camera->getRenderSystemData());
        cameraCopy->setUseIdentityProjection(camera->getUseIdentityProjection());
        cameraCopy->setUseIdentityView(camera->getUseIdentityView());
        //cameraCopy->setUserAny(camera->getUserAny());
        cameraCopy->setUseRenderingDistance(camera->getUseRenderingDistance());
        //cameraCopy->setUserObject(camera->getUserObject());
        cameraCopy->setVisibilityFlags(camera->getVisibilityFlags());
        cameraCopy->setVisible(camera->getVisible());
        //cameraCopy->setWindow(...);

        if (!movableObject->getUserAny().isEmpty()) {
            CameraInfo *sourceCameraInfo = Ogre::any_cast<CameraInfo *>(movableObject->getUserAny());
            if (sourceCameraInfo) {
                CameraInfo *targetCameraInfo = new CameraInfo();
                targetCameraInfo->width = sourceCameraInfo->width;
                targetCameraInfo->height = sourceCameraInfo->height;
                dynamic_cast<Ogre::MovableObject *>(cameraCopy)->setUserAny(Ogre::Any(targetCameraInfo));
            }
        }

        //// Setup connections for instances
        //SceneNode *targetSceneNode = new SceneNode(cameraCopy);
        //((Ogre::MovableObject *)cameraCopy)->setUserAny(Ogre::Any(targetSceneNode));
        //if (!((Ogre::MovableObject *)camera)->getUserAny().isEmpty()) {
        //    SceneNode *sourceSceneNode = Ogre::any_cast<SceneNode *>(((Ogre::MovableObject *)camera)->getUserAny());
        //    if (sourceSceneNode) {
        //        QObject::connect(sourceSceneNode, SIGNAL(sceneNodeUpdated()), targetSceneNode, SLOT(updateSceneNode()));
        //    }
        //}

        result = dynamic_cast<Ogre::MovableObject *>(cameraCopy);
    }

    if (!result)
        Log::error(QString("Could not clone movable object \"%1\" of type \"%2\".").arg(movableObject->getName().c_str()).arg(typeName.c_str()), "OgreTools::cloneMovableObject");

    return result;
}
Esempio n. 23
0
void saveAsDotScene(const QString& path, QFile& file, Ogre::SceneManager* sceneManager)
{
    Ogre::MeshSerializer* mMeshSerializer = new Ogre::MeshSerializer();
    Ogre::MaterialSerializer* mMaterialSerializer = new Ogre::MaterialSerializer();

    int idCounter = 3;
    if (!file.open(QIODevice::WriteOnly))
    {
        /* show wrror message if not able to open file */
        QMessageBox::warning(0, "Read only", "The file is in read only mode");
    }
    else
    {
        Ogre::SceneManager::MovableObjectIterator iterator = sceneManager->getMovableObjectIterator("Entity");
        QXmlStreamWriter* xmlWriter = new QXmlStreamWriter();
        xmlWriter->setAutoFormatting(true);
        xmlWriter->setDevice(&file);
        xmlWriter->writeStartElement("scene");
        xmlWriter->writeAttribute("formatVersion","");

        xmlWriter->writeStartElement("nodes");
        while(iterator.hasMoreElements())
        {
            Ogre::Entity* e = static_cast<Ogre::Entity*>(iterator.getNext());
            Ogre::Any any = e->getParentNode()->getUserAny();
            Ogre::String widgetType("");
            if(!any.isEmpty()){
                widgetType = any_cast<Ogre::String>(any);
            }
            Ogre::String tmp(widgetType + ":" + e->getParentNode()->getName());
            QString nodeName(tmp.c_str());
            xmlWriter->writeStartElement("node");
            xmlWriter->writeAttribute("name", nodeName);
            xmlWriter->writeAttribute("id", QString::number(idCounter++));


            xmlWriter->writeStartElement("position");
            xmlWriter->writeAttribute("x", QString::number(e->getParentNode()->getPosition().x));
            xmlWriter->writeAttribute("y", QString::number(e->getParentNode()->getPosition().y));
            xmlWriter->writeAttribute("z", QString::number(e->getParentNode()->getPosition().z));
            xmlWriter->writeEndElement();

            xmlWriter->writeStartElement("scale");
            xmlWriter->writeAttribute("x", QString::number(e->getParentNode()->getScale().x));
            xmlWriter->writeAttribute("y", QString::number(e->getParentNode()->getScale().y));
            xmlWriter->writeAttribute("z", QString::number(e->getParentNode()->getScale().z));
            xmlWriter->writeEndElement();

            xmlWriter->writeStartElement("entity");
            xmlWriter->writeAttribute("name", nodeName);
            xmlWriter->writeAttribute("meshFile", nodeName.toLower() + QString(".mesh") );
            xmlWriter->writeAttribute("static", QString("false"));
            xmlWriter->writeEndElement();

            const Mesh* mesh = e->getMesh().getPointer();


            mMeshSerializer->exportMesh(mesh,String(path.toStdString() +
                                                    nodeName.toLower().toStdString() +
                                                    ".mesh" ));


            std::cout << "numeber" <<  mesh->getNumSubMeshes() << std::endl;


            for(int i = 0; i < e->getNumSubEntities(); i++){


                Ogre::Material *mat = static_cast<Ogre::Material*>
                        (Ogre::MaterialManager::getSingletonPtr()->getByName(e->getSubEntity(i)->getMaterialName()).getPointer());

                //e->getMesh().get()->getSubMesh()
                if(mat->getTechnique(0)->getPass(0)->getNumTextureUnitStates() !=0){
                Ogre::String str = mat->getTechnique(0)->getPass(0)->getTextureUnitState(0)->getTextureName();

            Ogre::MaterialPtr mMatPtr =e->getSubEntity(i)->getMaterial()    ;

            mMaterialSerializer->exportMaterial(mMatPtr ,
                                                String(path.toStdString() +
                                                       nodeName.toLower().toStdString() +
                                                       QString::number(i).toStdString() + ".material" ));
            Ogre::TexturePtr* mTexPtr = new Ogre::TexturePtr(Ogre::TextureManager::getSingletonPtr()->getByName(str));
            Ogre::Texture* mTex = mTexPtr->getPointer();
            Ogre::PixelFormat pxf = mTex->getFormat();
            Ogre::Image mImage;
            mTex->convertToImage(mImage);
            std::cout << str << std::endl;
            mImage.save(String(path.toStdString() +
                                 str));
                }
}
            //material file merge

            for(int i = 0; i < e->getNumSubEntities(); i++){
                Ogre::Material *mat = static_cast<Ogre::Material*>
                        (Ogre::MaterialManager::getSingletonPtr()->getByName(e->getSubEntity(i)->getMaterialName()).getPointer());


                QString mMatFilePath = QString((path.toStdString() +
                                               nodeName.toLower().toStdString() +
                                                ".material").c_str()) ;


                 QFile mFile(mMatFilePath);
                 if (!mFile.open(QIODevice::Append))
                 {
                     /* show wrror message if not able to open file */
                     QMessageBox::warning(0, "Read only", "The file is in read only mode");
                 }
                 else{
                     QTextStream out(&mFile);

                     QString mTempMatPath = QString((path + nodeName.toLower() + QString::number(i) + ".material"));

                     QFile mTempMatFile(mTempMatPath);
                     mTempMatFile.open(QIODevice::ReadOnly);

                     QTextStream src(&mTempMatFile);

                     mFile.write(src.readAll().toStdString().c_str());
                     mTempMatFile.remove();

                 }



            }


            xmlWriter->writeEndElement();


        }

        xmlWriter->writeEndElement();
        xmlWriter->writeEndDocument();
        delete xmlWriter;
    }

    delete mMeshSerializer;
    delete mMaterialSerializer;
}
Esempio n. 24
0
void World::LoadSceneFile(string sceneFile)
{

    Ogre::LogManager::getSingleton().setLogDetail(Ogre::LL_LOW);
    Ogre::SceneNode* worldNode = m_sceneMgr->getRootSceneNode()->createChildSceneNode();
    worldNode->rotate(Ogre::Vector3::UNIT_X, Ogre::Degree(-90.0f));

    string meshName;
    float fDrawDistance;
    bool bIsLod;
    Ogre::Vector3 position;
    Ogre::Quaternion rotation;

    ifstream sceneStream(sceneFile);
    // skip the title and the table title of the file
    string strline;

    int i = 0;
    while (!sceneStream.eof())
    {
        getline(sceneStream, strline);

        if (strline.length() == 0)
            continue;

        std::istringstream ss(strline);
        std::string token;

        getline(ss, token, ',');
        boost::trim(token);
        meshName = token;

        getline(ss, token, ',');
        boost::trim(token);
        fDrawDistance = lexical_cast<float>(token);

        getline(ss, token, ',');
        boost::trim(token);
        bIsLod = lexical_cast<bool>(token);

        getline(ss, token, ',');
        boost::trim(token);
        position.x = lexical_cast<float>(token);
        getline(ss, token, ',');
        boost::trim(token);
        position.y = lexical_cast<float>(token);
        getline(ss, token, ',');
        boost::trim(token);
        position.z = lexical_cast<float>(token);

        getline(ss, token, ',');
        boost::trim(token);
        rotation.w = lexical_cast<float>(token);
        getline(ss, token, ',');
        boost::trim(token);
        rotation.x = lexical_cast<float>(token);
        getline(ss, token, ',');
        boost::trim(token);
        rotation.y = lexical_cast<float>(token);
        getline(ss, token, ',');
        boost::trim(token);
        rotation.z = lexical_cast<float>(token);

		
        Ogre::MeshPtr mesh;
		Ogre::Entity* entity;
	
		Ogre::Entity* realEntity = m_sceneMgr->createEntity(meshName);
		
		if (fDrawDistance > 300.0f && !bIsLod)
			continue;
		
        if (bIsLod)
        {
            mesh = Ogre::MeshManager::getSingleton().createManual(meshName + "lod" + std::to_string(i), "General"); // empty mesh
			mesh->createManualLodLevel(0, "NULL");
			mesh->createManualLodLevel(700, meshName);
			mesh->_setBounds( realEntity->getMesh()->getBounds());
			mesh->_setBoundingSphereRadius(realEntity->getMesh()->getBoundingSphereRadius());
			mesh->load();
			entity->setRenderingDistance(fDrawDistance);
			entity = m_sceneMgr->createEntity(mesh->getName());
        }
        else
        {
            mesh = Ogre::MeshManager::getSingleton().getByName(meshName);
			entity = m_sceneMgr->createEntity(meshName);
			entity->setRenderingDistance(fDrawDistance);
        }
        m_sceneMgr->destroyEntity(realEntity);


        Ogre::SceneNode* sceneNode = worldNode->createChildSceneNode();
        sceneNode->attachObject(entity);

        fix_gta_coord(rotation);

        sceneNode->rotate(rotation);
        sceneNode->setPosition(position);
        i++;
    }

    worldNode->setScale(5.0f, 5.0f, 5.0f);

    sceneStream.close();
    Ogre::LogManager::getSingleton().setLogDetail(Ogre::LL_NORMAL);
}
// BETWEEN FRAME OPERATION
void VisCalcFrustDist::calculateEntityVisibility(Ogre::Node* regionNode, Ogre::Node* node, bool recurse) {
	if (recurse && node->numChildren() > 0) {
		// if node has more children nodes, visit them recursivily
		Ogre::SceneNode::ChildNodeIterator nodeChildIterator = node->getChildIterator();
		while (nodeChildIterator.hasMoreElements()) {
			Ogre::Node* nodeChild = nodeChildIterator.getNext();
			// 'false' causes it to not visit sub-children which are included in parent and pos relative to parent
			calculateEntityVisibility(regionNode, nodeChild, false);
			visChildren++;
		}
	}
	visNodes++;
	// children taken care of... check fo attached objects to this node
	Ogre::SceneNode* snode = (Ogre::SceneNode*)node;
	// the camera needs to be made relative to the region
	// Ogre::Vector3 relCameraPos = LG::RendererOgre::Instance()->m_camera->getPosition() - regionNode->getPosition();
	// float snodeDistance = LG::RendererOgre::Instance()->m_camera->getPosition().distance(snode->_getWorldAABB().getCenter());
	// float snodeDistance = relCameraPos.distance(snode->getPosition());
	float snodeDistance = LG::RendererOgre::Instance()->m_camera->getDistanceFromCamera(regionNode, snode->getPosition());
	Ogre::SceneNode::ObjectIterator snodeObjectIterator = snode->getAttachedObjectIterator();
	while (snodeObjectIterator.hasMoreElements()) {
		Ogre::MovableObject* snodeObject = snodeObjectIterator.getNext();
		if (snodeObject->getMovableType() == "Entity") {
			visEntities++;
			Ogre::Entity* snodeEntity = (Ogre::Entity*)snodeObject;
			// check it's visibility if it's not world geometry (terrain and ocean)
			if ((snodeEntity->getQueryFlags() & Ogre::SceneManager::WORLD_GEOMETRY_TYPE_MASK) == 0) {
				// computation if it should be visible
				// Note: this call is overridden by derived classes that do fancier visibility rules
				bool shouldBeVisible = this->CalculateVisibilityImpl(LG::RendererOgre::Instance()->m_camera, snodeEntity, snodeDistance);
				if (snodeEntity->isVisible()) {
					// we currently think this object is visible. make sure it should stay that way
					if (shouldBeVisible) {
						// it should stay visible
						visVisToVis++;
					}
					else {
						// not visible any more... make invisible nad unload it`
						/*
						Ogre::Vector3 cPos = LG::RendererOgre::Instance()->m_camera->getPosition();
						Ogre::Vector3 rPos = regionNode->getPosition();
						Ogre::Vector3 sPos = snode->getPosition();
						LG::Log("VisToInVis: cPos=<%f,%f,%f>, rPos=<%f,%f,%f>, sPos(%s)=<%f,%f,%f>, d=%f", 
								cPos.x, cPos.y, cPos.z, 
								rPos.x, rPos.y, rPos.z, 
								snode->getName().c_str(),
								sPos.x, sPos.y, sPos.z, 
								snodeDistance);
								*/
						snodeEntity->setVisible(false);
						snode->needUpdate(true);
						visVisToInvis++;
						if (!snodeEntity->getMesh().isNull()) {
							queueMeshUnload(snodeEntity->getMesh());
						}
					}
				}
				else {
					// the entity currently thinks it's not visible.
					// check to see if it should be visible by checking a fake bounding box
					if (shouldBeVisible) {
						// it should become visible again
						if (!snodeEntity->getMesh().isNull()) {
							// queueMeshLoad(snodeEntity, snodeEntity->getMesh());
							LG::OLMeshTracker::Instance()->MakeLoaded(snodeEntity->getMesh()->getName(),
									Ogre::String(""), Ogre::String("visible"), snodeEntity);
						}
						// snodeEntity->setVisible(true);	// must happen after mesh loaded
						visInvisToVis++;
					}
					else {
						visInvisToInvis++;
					}
				}
			}
		}
	}
}
Esempio n. 26
0
/*
	Retrieves a DynamicObject from the game library.
	Returns null if no object was found that matches name.
*/
DynamicObject * GameLibrary::getDynamicObject(string name) {
	// see if an instance of the object exists in dynamicObjects map.
	// if not load it in from memory, create it, and put it in the map.

	unordered_map<string, DynamicObject*> ::iterator it = dynamicObjects.find(name);

	DynamicObject *dynObj;
 	if(it != dynamicObjects.end())
	{
		//element found;
		dynObj = it->second;

		// create a clone of it.
		return dynObj->clone(this->mSceneManager);

	} else {
		// element was not found.
		// load it in and create instance 

		std::string fileName = "../TeamProject/GameData/DynamicObjects/" + name +".json";
		FILE* pFile = fopen(fileName.c_str(), "rb");
		
		if (pFile != NULL) {
			char buffer[65536];
			rapidjson::FileReadStream is(pFile, buffer, sizeof(buffer));
			rapidjson::Document document;
			document.ParseStream<0, rapidjson::UTF8<>, rapidjson::FileReadStream>(is);

			// File was opened successfully and parsed into JSON,
			// now we create the instance

			list<Ogre::String> meshNames;
			if (document.HasMember("meshNames")) {
				for (int i = 0; i < document["meshNames"].Size(); i++) {
					meshNames.push_back(document["meshNames"][i].GetString());
				}
			} else {
				meshNames.push_back("ERROR.MESH.mesh");
			}


			// Parse data for the construction of the rigid body

			double restitution;
			if (document.HasMember("restitution")) {
				restitution = document["restitution"].GetDouble();
			} else {
				restitution = 0.0;
			}

			int massTemp;
			if (document.HasMember("mass")) {
				massTemp = document["mass"].GetInt();
			} else {
				massTemp = 1;
			}


			// Parse scale info
			Ogre::Vector3 scale = Ogre::Vector3(1, 1, 1);
			if (document.HasMember("scale")) {
				scale = parseVector3(document["scale"]);
			} else 
			{
				scale = Ogre::Vector3(1, 1, 1);
			}

			// Needed for collisions 
			// interaction legend by diana 
			// -1 = no interaction 
			// 1 = teapots meaning they disappear (for now) 
			// 2 = tuna can (ending... for now) 
			int interaction;
			if (document.HasMember("interaction")) {
				interaction = document["interaction"].GetInt();
			} else {
				interaction = -1; // this means there's no interaction 
			}


			string collisionShape;
			if (document.HasMember("collisionShape")) {
				collisionShape = document["collisionShape"].GetString();
			} else {
				collisionShape = "btBoxShape";
			}


			
			// temp vars used for parsing collision shape size data
			btVector3 colDim3 = btVector3(1,1,1);
			btScalar colScala = 1;
			btScalar colScalb = 1;

			/* Parse the CollisionShape and its size size */
			

			// if no collision shape size is specified in the json file
			// base its size off of the dimensions of the mesh
			// For simplicity, this only works if the dynamic object has
			// one mesh. 

			Ogre::Vector3 meshDimensions;
			std::string s = std::to_string(meshNames.size()); 
			

			if (!document.HasMember("collisionShapeSize")) {

				// XXX: The collision shape auto sizing functionality is experimental
				// and needs to be tested.

				Ogre::Entity* tempEntity = mSceneManager->createEntity(meshNames.front());
				colDim3 = ogreToBulletVector3(tempEntity->getMesh()->getBounds().getHalfSize());
				colScala = tempEntity->getMesh()->getBoundingSphereRadius(); // radius
				colScalb = tempEntity->getMesh()->getBounds().getSize()[1]; // height
			
				// apply scale
				colDim3 = btVector3(colDim3[0] * scale.x, colDim3[1] * scale.y, colDim3[2] * scale.z);
				colScala = colScala * scale.x;
				colScalb = colScalb * scale.y;

			} else if(document.HasMember("collisionShapeSize")) {
				/// Note: FIgure out why it keeps going into this if block instead of the first one 
				if (document["collisionShapeSize"].Size() == 3) {
					colDim3 = ogreToBulletVector3(parseVector3(document["collisionShapeSize"]));
				}
				colScala = document["collisionShapeSize"][0].GetDouble();	
				colScalb = document["collisionShapeSize"][1].GetDouble();   
			} else {
				OutputDebugString("ERROR! Need to specify the collisionshape size!");
				// default collision shape sizes
				colDim3 = btVector3(1,1,1);
				colScala = 1;
				colScalb = 1;
			}


			
			// holds the actual collision shape of the object
			btCollisionShape *colShape;
			
			if (collisionShape.compare("btSphereShape") == 0) {
				colShape = new btSphereShape(colScala);
			} else if(collisionShape.compare("btBoxShape") == 0) {
				colShape = new btBoxShape(colDim3);
			} else if(collisionShape.compare("btCylinderShape") == 0) {
				colShape = new btCylinderShape(colDim3);
			} else if(collisionShape.compare("btCapsuleShape") == 0) {
				colShape = new btCapsuleShape(colScala, colScalb);
			} else {
				// default to box shape if no valid collision shape was found
				colShape = new btBoxShape(btVector3(1,1,1));
			}
			
			// XXX: Implement these other shapes as needed!
			/*
			else if(collisionShape.compare("btConeShape") == 0) {
				
			} else if(collisionShape.compare("btMultiSphereShape") == 0) {
				
			} else if(collisionShape.compare("btConvexHullShape") == 0) {
				
			} else if(collisionShape.compare("btConvexTriangleMeshShape") == 0) {
				
			} else if(collisionShape.compare("btCompoundShape") == 0) {
				
			}
			*/
			

			// create the rigid body

			// set position to 0,0,0 later change when placing in the game
			btDefaultMotionState* fallMotionState =
				new btDefaultMotionState( btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0)));
			btScalar mass = (btScalar) massTemp;
			btVector3 fallInertia(0, 0, 0);
			colShape->calculateLocalInertia(mass, fallInertia);
				

			btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, colShape, fallInertia);
			fallRigidBodyCI.m_restitution = restitution;

			// Create the rigid body
			btRigidBody* tempRigidBody = new btRigidBody(fallRigidBodyCI);

			// New way
			DynamicObject *newD = new DynamicObject(meshNames, colShape, Ogre::Vector3(0,0,0), interaction, scale);

			// put it into the library
			dynamicObjects.emplace(name, newD);

			std::fclose(pFile);

			return newD->clone(this->mSceneManager);
		} else {
			// no file was found
			return NULL;
		}
	}
}