void GraphicsResourceMesh::setMaterialNames(GraphicsResourceMesh* resourcePtr)
{
  Ogre::ResourcePtr meshResource = Ogre::MeshManager::getSingleton().getByName(resourcePtr->getID());
  Ogre::Mesh* meshPtr = static_cast<Ogre::Mesh *>(&*meshResource);
  Ogre::Mesh::SubMeshIterator currSubMeshIter = meshPtr->getSubMeshIterator();

  while (currSubMeshIter.hasMoreElements()) {
    Ogre::SubMesh *curSubMesh = currSubMeshIter.getNext();

    if (!OPTION_ENABLE_TEXTURES->as<bool>()) {
      curSubMesh->setMaterialName("BaseWhiteTexture");
    }
    else {
      const Ogre::String& curMatName = curSubMesh->getMaterialName();
      int pos = curMatName.find_last_of(':');
      if (pos != -1) {
        String start = curMatName.substr(0, pos);
        String ending = curMatName.substr(pos);
        std::map<String, String>::iterator itr = resourcePtr->mMaterialNames.find(start);
        if (itr != resourcePtr->mMaterialNames.end())
          curSubMesh->setMaterialName(itr->second + ending);
      }
    }
  }
}
Esempio n. 2
0
unsigned GfxBody::getSubMeshByOriginalMaterialName (const std::string &n)
{
    for (unsigned i=0 ; i<mesh->getNumSubMeshes() ; ++i) {
        Ogre::SubMesh *sm = mesh->getSubMesh(i);
        if (sm->getMaterialName() == n) {
            return i;
        }
    }
    CERR << "Mesh did not contain material \""<<n<<"\"" <<std::endl;
    return 0;
}
// unload all about this mesh. The mesh itself and the textures.
// BETWEEN FRAME OPERATION
void VisCalcFrustDist::unloadTheMesh(Ogre::MeshPtr meshP) {
	if (m_shouldCullTextures) {
		Ogre::Mesh::SubMeshIterator smi = meshP->getSubMeshIterator();
		while (smi.hasMoreElements()) {
			Ogre::SubMesh* oneSubMesh = smi.getNext();
			Ogre::String subMeshMaterialName = oneSubMesh->getMaterialName();
			Ogre::MaterialPtr subMeshMaterial = (Ogre::MaterialPtr)Ogre::MaterialManager::getSingleton().getByName(subMeshMaterialName);
			if (!subMeshMaterial.isNull()) {
				Ogre::Material::TechniqueIterator techIter = subMeshMaterial->getTechniqueIterator();
				while (techIter.hasMoreElements()) {
					Ogre::Technique* oneTech = techIter.getNext();
					Ogre::Technique::PassIterator passIter = oneTech->getPassIterator();
					while (passIter.hasMoreElements()) {
						Ogre::Pass* onePass = passIter.getNext();
						Ogre::Pass::TextureUnitStateIterator tusIter = onePass->getTextureUnitStateIterator();
						while (tusIter.hasMoreElements()) {
							Ogre::TextureUnitState* oneTus = tusIter.getNext();
							Ogre::String texName = oneTus->getTextureName();
							Ogre::TexturePtr texP = (Ogre::TexturePtr)Ogre::TextureManager::getSingleton().getByName(texName);
							if (!texP.isNull()) {
								// if (texP.useCount() <= 1) {
									texP->unload();
									LG::IncStat(LG::StatCullTexturesUnloaded);
									// LG::Log("unloadTheMesh: unloading texture %s", texName.c_str());
								// }
							}
						}
					}
				}
			}
		}
	}
	if (m_shouldCullMeshes) {
		LG::OLMeshTracker::Instance()->MakeUnLoaded(meshP->getName(), Ogre::String(), NULL);
		LG::IncStat(LG::StatCullMeshesUnloaded);
		// LG::Log("unloadTheMesh: unloading mesh %s", mshName.c_str());
	}
}
Esempio n. 4
0
void GfxBody::reinitialise (void)
{
    APP_ASSERT(mesh->isLoaded());

    destroyGraphics();

    for (unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i) {
        Ogre::SubMesh *sm = mesh->getSubMesh(i);
        Sub* sub = new Sub(this, sm);
        subList.push_back(sub);
        GFX_MAT_SYNC;
        std::string matname = apply_map(initialMaterialMap, sm->getMaterialName());
        if (!gfx_material_has(matname)) {
            CERR << "Mesh \"/"<<mesh->getName()<<"\" references non-existing material "
                 << "\""<<matname<<"\""<<std::endl;
            matname = "/system/FallbackMaterial";
        }
        sub->material = gfx_material_get(matname);
    }


    if (!mesh->getSkeleton().isNull()) {
        skeleton = OGRE_NEW Ogre::SkeletonInstance(mesh->getSkeleton());
        skeleton->load();
        numBoneMatrixes = skeleton->getNumBones();
        boneMatrixes      = static_cast<Ogre::Matrix4*>(OGRE_MALLOC_SIMD(sizeof(Ogre::Matrix4) * numBoneMatrixes, Ogre::MEMCATEGORY_ANIMATION));
        boneWorldMatrixes = static_cast<Ogre::Matrix4*>(OGRE_MALLOC_SIMD(sizeof(Ogre::Matrix4) * numBoneMatrixes, Ogre::MEMCATEGORY_ANIMATION));

        mesh->_initAnimationState(&animationState);
    } else {
        skeleton = NULL;
        numBoneMatrixes = 0;
        boneMatrixes      = NULL;
        boneWorldMatrixes = NULL;
    }

    updateBones();
}
Esempio n. 5
0
    bool OgreMeshResource::SetData(Foundation::AssetPtr source)
    {
        if (!source)
        {
            OgreRenderingModule::LogError("Null source asset data pointer");     
            return false;
        }
        if (!source->GetSize())
        {
            OgreRenderingModule::LogError("Zero sized mesh asset");     
            return false;
        }
                
        try
        {
            if (ogre_mesh_.isNull())
            {   
                ogre_mesh_ = Ogre::MeshManager::getSingleton().createManual(
                    id_, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
                if (ogre_mesh_.isNull())
                {
                    OgreRenderingModule::LogError("Failed to create mesh " + id_);
                    return false; 
                }   
                ogre_mesh_->setAutoBuildEdgeLists(false);
            }

            Ogre::DataStreamPtr stream(new Ogre::MemoryDataStream((void*)source->GetData(), source->GetSize(), false));
            Ogre::MeshSerializer serializer;
            serializer.importMesh(stream, ogre_mesh_.getPointer());
            
            // Generate tangents to mesh
            try
            {
                unsigned short src, dest;
                if (!ogre_mesh_->suggestTangentVectorBuildParams(Ogre::VES_TANGENT, src, dest))
                    ogre_mesh_->buildTangentVectors(Ogre::VES_TANGENT, src, dest);
            }
            catch (...) {}
            
            // Generate extremity points to submeshes, 1 should be enough
            try
            {
                for(uint i = 0; i < ogre_mesh_->getNumSubMeshes(); ++i)
                {
                    Ogre::SubMesh *smesh = ogre_mesh_->getSubMesh(i);
                    if (smesh)
                        smesh->generateExtremes(1);
                }
            }
            catch (...) {}
            
            // Assign default materials that won't complain
            original_materials_.clear();
            for (uint i = 0; i < ogre_mesh_->getNumSubMeshes(); ++i)
            {
                Ogre::SubMesh* submesh = ogre_mesh_->getSubMesh(i);
                if (submesh)
                {
                    original_materials_.push_back(submesh->getMaterialName());
                    submesh->setMaterialName("UnlitTextured");
                }
            }
            
        }
        catch (Ogre::Exception &e)
        {
            OgreRenderingModule::LogError("Failed to create mesh " + id_ + ": " + std::string(e.what()));
            RemoveMesh();
            return false;
        }

        OgreRenderingModule::LogDebug("Ogre mesh " + id_ + " created");
        return true;
    }
void LIRenAttachmentEntity::update (float secs)
{
	/* Check if background loading has finished. */
	if (loaded)
		return;
	lisys_assert (entity == NULL);

	/* Wait for the mesh to load. */
	if (!mesh->isLoaded ())
	{
		if (loading_mesh)
			return;
		loading_mesh = true;
#ifdef LIREN_BACKGROUND_LOADING
		Ogre::ResourceBackgroundQueue::getSingleton ().load (
			"Mesh", mesh->getName (), mesh->getGroup ());
#else
		mesh->load ();
#endif
		return;
	}

	/* Start loading dependencies. */
	if (!loading_deps)
	{
		loading_deps = true;
		for (size_t i = 0 ; i < mesh->getNumSubMeshes () ; i++)
		{
			Ogre::SubMesh* sub = mesh->getSubMesh (i);
			if (sub->isMatInitialised ())
			{
				Ogre::MaterialManager& mgr = Ogre::MaterialManager::getSingleton ();
				Ogre::MaterialPtr material = mgr.getByName (sub->getMaterialName (), mesh->getGroup ());
				if (!material.isNull ())
				{
					resources.push_back (material);
#ifdef LIREN_BACKGROUND_LOADING
					Ogre::ResourceBackgroundQueue::getSingleton ().load (
						"Material", material->getName (), material->getGroup ());
#else
					material->load (true);
#endif
				}
			}
		}
		return;
	}

	// Wait for the dependencies to load.
	for (size_t i = 0 ; i < resources.size () ; i++)
	{
		Ogre::ResourcePtr& resource = resources[i];
		if (!resource->isLoaded ())
			return;
	}

	// Create the entity.
	Ogre::String e_name = render->id.next ();
	entity = render->scene_manager->createEntity (e_name, mesh->getName (), LIREN_RESOURCES_TEMPORARY);
	object->node->attachObject (entity);

	// Create the skeleton and its pose buffer.
	if (create_skeleton ())
	{
		LIRenModelData* model = get_model ();
		lisys_assert (pose_buffer == NULL);
		if (model != NULL)
		{
			pose_buffer = limdl_pose_buffer_new_copy (model->rest_pose_buffer);
			lisys_assert (pose_buffer != NULL);
			lisys_assert (pose_buffer->bones.count == entity->getSkeleton ()->getNumBones ());
		}
	}

	// Set the entity flags.
	entity->setCastShadows (object->get_shadow_casting ());

	// Trigger queued texture replacements.
	//
	// This needs to be done before showing the entity in order to avoid
	// the textures flickering for a few frames.
	for (size_t i = 0 ; i < queued_texture_replaces.size () ; ++i)
	{
		LIRenTextureReplace& repl = queued_texture_replaces[i];
		replace_texture_now (repl.name, repl.texture);
	}
	queued_texture_replaces.clear();

	// Set entity visibility.
	//
	// If a visible entity is added to a hidden scene node, the entity is
	// still rendered. Hence, newly added entities needs to be explicitly
	// hidden or Ogre will render our invisible objects. */
	entity->setVisible (object->get_visible ());

	// Apply queued settings.
	update_settings ();

	// Clear the now useless dependency list.
	resources.clear ();
	loading_mesh = false;
	loading_deps = false;
	loaded = true;
}
Esempio n. 7
0
	void SceneObject::GetMeshInformation(
		const Ogre::MeshPtr mesh,
		size_t& vertex_count,
		Ogre::Vector3* &vertices,
		size_t& index_count,
		unsigned long* &indices,
		Ogre::Vector2* &coords,
		const Ogre::Vector3& position,
		const Ogre::Quaternion& orient,
		const Ogre::Vector3& scale,
		const std::string& _material)
	{
		bool added_shared = false;
		size_t current_offset = 0;
		//size_t shared_offset = 0;
		size_t next_offset = 0;
		size_t index_offset = 0;

		vertex_count = index_count = 0;

		// Calculate how many vertices and indices we're going to need
		for (unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i)
		{
			Ogre::SubMesh* submesh = mesh->getSubMesh( i );
			if (submesh->getMaterialName() != _material)
				continue;

			// We only need to add the shared vertices once
			if (submesh->useSharedVertices)
			{
				if ( !added_shared )
				{
					vertex_count += mesh->sharedVertexData->vertexCount;
					added_shared = true;
				}
			}
			else
			{
				vertex_count += submesh->vertexData->vertexCount;
			}

			// Add the indices
			index_count += submesh->indexData->indexCount;
		}


		// Allocate space for the vertices and indices
		vertices = new Ogre::Vector3[vertex_count];
		indices = new unsigned long[index_count];
		coords = new Ogre::Vector2[vertex_count];

		added_shared = false;

		// Run through the submeshes again, adding the data into the arrays
		for ( unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i)
		{
			Ogre::SubMesh* submesh = mesh->getSubMesh(i);
			if (submesh->getMaterialName() != _material)
				continue;

			Ogre::VertexData* vertex_data = submesh->useSharedVertices ? mesh->sharedVertexData : submesh->vertexData;

			if ((!submesh->useSharedVertices) || (submesh->useSharedVertices && !added_shared))
			{
				if (submesh->useSharedVertices)
				{
					added_shared = true;
					//shared_offset = current_offset;
				}

				const Ogre::VertexElement* coordElem =
					vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_TEXTURE_COORDINATES);

				const Ogre::VertexElement* posElem =
					vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_POSITION);

				Ogre::HardwareVertexBufferSharedPtr vbuf =
					vertex_data->vertexBufferBinding->getBuffer(posElem->getSource());

				unsigned char* vertex =
					static_cast<unsigned char*>(vbuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY));

				// There is _no_ baseVertexPointerToElement() which takes an Ogre::Real or a double
				//  as second argument. So make it float, to avoid trouble when Ogre::Real will
				//  be comiled/typedefed as double:
				//      Ogre::Real* pReal;
				float* pReal;

				for ( size_t j = 0; j < vertex_data->vertexCount; ++j, vertex += vbuf->getVertexSize())
				{
					posElem->baseVertexPointerToElement(vertex, &pReal);

					Ogre::Vector3 pt(pReal[0], pReal[1], pReal[2]);

					vertices[current_offset + j] = (orient * (pt * scale)) + position;

					posElem->baseVertexPointerToElement(vertex + coordElem->getOffset() - posElem->getOffset(), &pReal);
					Ogre::Vector2 coord(pReal[0], pReal[1]);
					coords[current_offset + j] = coord;
				}

				vbuf->unlock();
				next_offset += vertex_data->vertexCount;
			}


			Ogre::IndexData* index_data = submesh->indexData;
			size_t numTris = index_data->indexCount / 3;
			Ogre::HardwareIndexBufferSharedPtr ibuf = index_data->indexBuffer;

			bool use32bitindexes = (ibuf->getType() == Ogre::HardwareIndexBuffer::IT_32BIT);

			unsigned long*  pLong = static_cast<unsigned long*>(ibuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY));
			unsigned short* pShort = reinterpret_cast<unsigned short*>(pLong);


			//size_t offset = (submesh->useSharedVertices)? shared_offset : current_offset;

			// Ogre 1.6 patch (commenting the static_cast...) - index offsets start from 0 for each submesh
			if ( use32bitindexes )
			{
				for ( size_t k = 0; k < numTris * 3; ++k)
				{
					indices[index_offset++] = pLong[k];/*+ static_cast<unsigned long>(offset)*/
				}
			}
			else
			{
				for ( size_t k = 0; k < numTris * 3; ++k)
				{
					indices[index_offset++] = static_cast<unsigned long>(pShort[k]);/*+
						static_cast<unsigned long>(offset)*/
				}
			}

			ibuf->unlock();
			current_offset = next_offset;
		}
	}