Example #1
0
int main(int argc,char* argv[])
{
    IO::FilePtr matFile(IO::openFile(argv[1],IO::File::ReadOnly));
    matFile->setEndianness(Misc::LittleEndian);
    matFile->skip<double>(4*4);
    double mat[4][4];
    for(int i=0; i<4; ++i)
        for(int j=0; j<4; ++j)
            mat[i][j]=matFile->read<double>();

    for(int i=0; i<4; ++i)
    {
        std::cout<<std::setw(12)<<mat[i][0];
        for(int j=1; j<4; ++j)
            std::cout<<"   "<<std::setw(12)<<mat[i][j];
        std::cout<<std::endl;
    }

    return 0;
}
Example #2
0
void GeomLoader::loadMaterial(const std::string& filename, DataWriter& dataWriter)
{
	std::ifstream matFile(filename);
	if (!matFile.is_open()) return;

	Json::Value root;
	Json::Reader reader;
	bool parsingSuccessful = reader.parse(matFile, root);
	matFile.close();
	if (!parsingSuccessful) return;

	for (size_t i = 0; i < root.size(); i++)
	{
		Data::Material mat;
		mat.diffuseMapFilename = root[i]["diffuseMap"].asString();
		mat.normalMapFilename = root[i]["normalMap"].asString();
		mat.specularMapFilename = root[i]["specularMap"].asString();

		if (i < dataWriter.getMeshesRef().size())
		{
			dataWriter.getMeshesRef()[i].material = mat;
		}
	}
}
Example #3
0
bool OBJExporter::exportModel(Model * m, std::string target)
{
  WoWModel * model = dynamic_cast<WoWModel *>(m);

  if(!model)
    return false;

  // prepare obj file
  QString targetFile = QString::fromStdString(target);

  QFile file(targetFile);
  if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
  {
    LOG_ERROR << "Unable to open" << targetFile;
    return false;
  }

  LOG_INFO << "Exporting" << model->modelname.c_str() << "in" << targetFile;

  // prepare mtl file
  QString matFilename = QFileInfo(target.c_str()).completeBaseName();
  matFilename += ".mtl";
  matFilename = QFileInfo(target.c_str()).absolutePath () + "/" + matFilename;

  LOG_INFO << "Exporting" << model->modelname.c_str() << "materials in" << matFilename;

  QFile matFile(matFilename);
  if (!matFile.open(QIODevice::WriteOnly | QIODevice::Text))
  {
    LOG_ERROR << "Unable to open" << matFilename;
    return false;
  }

  QTextStream obj(&file);
  QTextStream mtl(&matFile);

  obj << "# Wavefront OBJ exported by " << QString::fromStdString(GLOBALSETTINGS.appName()) << " " << QString::fromStdString(GLOBALSETTINGS.appVersion()) << "\n";
  obj << "\n";
  obj << "mtllib " <<  QFileInfo(matFile).fileName() << "\n";
  obj << "\n";


  mtl << "#" << "\n";
  mtl << "# mtl file for " << QFileInfo(targetFile).fileName() << " obj file" << "\n";
  mtl << "#" << "\n";
  mtl << "\n";

  int counter=1;

  // export main model
  if(!exportModelVertices(model, obj, counter))
  {
    LOG_ERROR << "Error during obj export for model" << model->modelname.c_str();
    return false;
  }

  if(!exportModelMaterials(model, mtl, matFilename))
  {
    LOG_ERROR << "Error during materials export for model" << model->modelname.c_str();
    return false;
  }

  // export equipped items
  if(!GLOBALSETTINGS.bInitPoseOnlyExport)
  {

    for(WoWModel::iterator it = model->begin();
        it != model->end();
        ++it)
    {
      std::map<POSITION_SLOTS, WoWModel *> itemModels = (*it)->itemModels;
      if(!itemModels.empty())
      {
        obj << "# " << "\n";
        obj << "# " << (*it)->name() << "\n";
        obj << "# " << "\n";
        for(std::map<POSITION_SLOTS, WoWModel *>::iterator it = itemModels.begin() ;
            it != itemModels.end();
            ++it)
        {
          WoWModel * itemModel = it->second;
          LOG_INFO << "Exporting attached item" << itemModel->modelname.c_str();

          // find matrix
          int l = model->attLookup[it->first];
          Matrix m;
          Vec3D pos;
          if (l>-1)
          {
            m = model->bones[model->atts[l].bone].mat;
            pos = model->atts[l].pos;
          }

          if(!exportModelVertices(itemModel, obj, counter, m, pos))
          {
            LOG_ERROR << "Error during obj export for model" << itemModel->modelname.c_str();
            return false;
          }

          if(!exportModelMaterials(itemModel, mtl, matFilename))
          {
            LOG_ERROR << "Error during materials export for model" << itemModel->modelname.c_str();
            return false;
          }
        }
      }
    }
  }

  file.close();
  matFile.close();

  return true;
}
void QEmitterNode::addRepresentation()
{	
	m_matResource = h3dAddResource(H3DResTypes::Material, qPrintable(m_xmlNode.attribute("material")), 0);

	// Load resource immediately since a later call to loadResourceFromDisk results in a bad behaviour of the Horde3D engine
	QString resourceName = h3dutGetResourcePath(H3DResTypes::Material);
	if( !resourceName.isEmpty() && !resourceName.endsWith('/') && !resourceName.endsWith('\\') )
		resourceName += '/';
	resourceName += m_xmlNode.attribute("material");

	QFile matFile(QFileInfo(resourceName).absoluteFilePath());
	if (!matFile.open(QIODevice::ReadOnly))
		qWarning("Error opening resource %s", qPrintable(m_xmlNode.attribute("material")));

	// Stupid return value, if false it can also be the case that the resource was loaded before instead of that their was an error



	h3dLoadResource(m_matResource, matFile.readAll().append('\0').constData(), matFile.size() + 1);
	matFile.close();

	m_effectResource = h3dAddResource(H3DResTypes::ParticleEffect, qPrintable(m_xmlNode.attribute("particleEffect")), 0);

	// Load resource immediately since a later call to loadResourceFromDisk results in a bad behaviour of the Horde3D engine
	resourceName = h3dutGetResourcePath(H3DResTypes::ParticleEffect);
	if (!resourceName.isEmpty() && !resourceName.endsWith('/') && !resourceName.endsWith('\\'))
		resourceName += '/';
	resourceName += m_xmlNode.attribute("particleEffect");

	QFile effectFile(QFileInfo(resourceName).absoluteFilePath());
	if (!effectFile.open(QIODevice::ReadOnly))
		qWarning("Error opening resource %s", qPrintable(m_xmlNode.attribute("particleEffect")));

	// Stupid return value, if false it can also be the case that the resource was loaded before instead of that their was an error
	h3dLoadResource(m_effectResource, effectFile.readAll().append('\0').constData(), effectFile.size()+1);
	effectFile.close();

	QSceneNode* parentNode = static_cast<QSceneNode*>(parent());
	unsigned int rootID = parentNode ? parentNode->hordeId() : H3DRootNode;

	m_hordeID = h3dAddEmitterNode(
		rootID, 
		qPrintable(m_xmlNode.attribute("name", "ATTENTION No Node Name")), 
		m_matResource, 
		m_effectResource, 
		m_xmlNode.attribute("maxCount").toUInt(),
		m_xmlNode.attribute("respawnCount").toInt()
	);

	h3dSetNodeParamF(m_hordeID, H3DEmitter::ForceF3, 0, m_xmlNode.attribute("forceX", "0.0").toFloat());
	h3dSetNodeParamF(m_hordeID, H3DEmitter::ForceF3, 1, m_xmlNode.attribute("forceY", "0.0").toFloat());
	h3dSetNodeParamF(m_hordeID, H3DEmitter::ForceF3, 2, m_xmlNode.attribute("forceZ", "0.0").toFloat());
	h3dSetNodeParamF(m_hordeID, H3DEmitter::DelayF, 0, m_xmlNode.attribute("delay", "0.0").toFloat());
	h3dSetNodeParamF(m_hordeID, H3DEmitter::SpreadAngleF, 0, m_xmlNode.attribute("spreadAngle", "0.0").toFloat());
	h3dSetNodeParamF(m_hordeID, H3DEmitter::EmissionRateF, 0, m_xmlNode.attribute("emissionRate", "0.0").toFloat());

	// load transformation from file...
	float x, y, z, rx, ry, rz, sx, sy, sz;
	getTransformation(x,y,z,rx,ry,rz,sx,sy,sz);
	// ...and update scene representation
	h3dSetNodeTransform(m_hordeID, x, y, z, rx, ry, rz, sx, sy, sz);
	
	// Attachment
	QDomElement attachment = m_xmlNode.firstChildElement("Attachment");	
	SceneTreeModel* model = static_cast<SceneTreeModel*>(m_model);
	AttachmentPlugIn* plugIn = model->nodeFactory()->attachmentPlugIn();
	if (!attachment.isNull() &&  plugIn != 0)
		plugIn->initNodeAttachment(this);

	startTimer(100);
}
Example #5
0
bool SkinnedModel::Init(std::string filename, VulkanInterface * vulkan, VulkanCommandBuffer * cmdBuffer)
{
	VulkanDevice * vulkanDevice = vulkan->GetVulkanDevice();

	// Uniform buffer init
	vertexUniformBuffer.worldMatrix = glm::mat4(1.0f);
	vertexUniformBuffer.MVP = glm::mat4();
	for (unsigned int i = 0; i < MAX_BONES; i++)
		boneUniformBufferData.bones[i] = glm::mat4();

	// Vertex shader - Uniform buffer
	skinnedVS_UBO = new VulkanBuffer();
	if (!skinnedVS_UBO->Init(vulkanDevice, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, &vertexUniformBuffer,
		sizeof(vertexUniformBuffer), false))
		return false;

	// Vertex shader - Bone Uniform buffer
	skinnedVS_bone_UBO = new VulkanBuffer();
	if (!skinnedVS_bone_UBO->Init(vulkanDevice, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, &boneUniformBufferData,
		sizeof(boneUniformBufferData), false))
		return false;

	// Open .rcs file
	FILE * file = fopen(filename.c_str(), "rb");
	if (file == NULL)
	{
		gLogManager->AddMessage("ERROR: Model file not found! (" + filename + ")");
		return false;
	}

	// Open .mat file
	size_t pos = filename.rfind('.');
	filename.replace(pos, 4, ".mat");

	std::ifstream matFile(filename.c_str());
	if (!matFile.is_open())
	{
		gLogManager->AddMessage("ERROR: Model .mat file not found! (" + filename + ")");
		return false;
	}

	unsigned int meshCount;
	fread(&meshCount, sizeof(unsigned int), 1, file);

	for (unsigned int i = 0; i < meshCount; i++)
	{
		// Create and read mesh data
		char meshIdentifier[16];
		sprintf(meshIdentifier, "_mesh%d", i);

		SkinnedMesh * mesh = new SkinnedMesh();
		if (!mesh->Init(vulkan, file, filename + meshIdentifier))
		{
			gLogManager->AddMessage("ERROR: Failed to init a mesh!");
			return false;
		}
		meshes.push_back(mesh);

		std::string texturePath;
		char diffuseTextureName[64];
		char normalTextureName[64];

		// Init mesh material
		Material * material = new Material();

		// Read diffuse texture
		fread(diffuseTextureName, sizeof(char), 64, file);
		if (strcmp(diffuseTextureName, "NONE") == 0)
			texturePath = "data/textures/default_diffuse.rct";
		else
			texturePath = "data/textures/" + std::string(diffuseTextureName);

		Texture * diffuse = gTextureManager->RequestTexture(texturePath, vulkan->GetVulkanDevice(), cmdBuffer);
		if (diffuse == nullptr)
			return false;

		textures.push_back(diffuse);

		material->SetDiffuseTexture(diffuse);

		// Read normal texture if available
		fread(normalTextureName, sizeof(char), 64, file);
		if (strcmp(normalTextureName, "NONE") != 0)
		{
			texturePath = "data/textures/" + std::string(normalTextureName);

			Texture * normal = gTextureManager->RequestTexture(texturePath, vulkan->GetVulkanDevice(), cmdBuffer);
			if (normal == nullptr)
				return false;

			textures.push_back(normal);

			material->SetNormalTexture(normal);
		}

		std::string matName, matTextureName;
		float metallicOffset, roughnessOffset;
		matFile >> matName >> matTextureName >> metallicOffset >> roughnessOffset;
		
		// Read material texture
		if (matTextureName == "NONE")
			texturePath = "data/textures/default_material.rct";
		else
			texturePath = "data/textures/" + matTextureName;

		Texture * matTexture = gTextureManager->RequestTexture(texturePath, vulkan->GetVulkanDevice(), cmdBuffer);
		if (matTexture == nullptr)
			return false;

		textures.push_back(matTexture);

		material->SetMaterialTexture(matTexture);
		material->SetMetallicOffset(metallicOffset);
		material->SetRoughnessOffset(roughnessOffset);

		materials.push_back(material);
		meshes[i]->SetMaterial(material);

		// Init draw command buffers for each meash
		VulkanCommandBuffer * drawCmdBuffer = new VulkanCommandBuffer();
		if (!drawCmdBuffer->Init(vulkanDevice, vulkan->GetVulkanCommandPool(), false))
		{
			gLogManager->AddMessage("ERROR: Failed to create a draw command buffer!");
			return false;
		}
		drawCmdBuffers.push_back(drawCmdBuffer);
	}

	matFile.close();

	// Read bone offsets
	fread(&numBones, sizeof(unsigned int), 1, file);
	boneOffsets.resize(numBones);
	fread(boneOffsets.data(), sizeof(aiMatrix4x4), numBones, file);

	// Read bone mappings
	for (unsigned int i = 0; i < numBones; i++)
	{
		unsigned int strSize;
		char * str;
		std::string boneName;
		uint32_t id;

		fread(&strSize, sizeof(unsigned int), 1, file);
		str = new char[strSize+1];
		fread(str, sizeof(char), strSize, file);
		fread(&id, sizeof(uint32_t), 1, file);

		str[strSize] = 0;
		boneName = str;
		boneMapping[boneName] = id;
	}

	fclose(file);

	return true;
}