Files
Seele/src/Engine/Asset/MeshLoader.cpp
T

262 lines
10 KiB
C++
Raw Normal View History

2020-06-02 11:46:18 +02:00
#include "MeshLoader.h"
2020-06-08 01:44:47 +02:00
#include "Graphics/GraphicsResources.h"
#include "Graphics/Graphics.h"
2020-06-02 11:46:18 +02:00
#include "MeshAsset.h"
#include "Graphics/Mesh.h"
2020-09-19 14:36:50 +02:00
#include "Graphics/StaticMeshVertexInput.h"
2020-06-08 01:44:47 +02:00
#include "AssetRegistry.h"
#include "Material/Material.h"
2020-06-08 01:44:47 +02:00
#include <fstream>
2020-09-19 14:36:50 +02:00
#include <iostream>
2020-06-08 01:44:47 +02:00
#include <nlohmann/json.hpp>
#include <stb_image_write.h>
#include <assimp/config.h>
2020-06-02 11:46:18 +02:00
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
2020-06-08 01:44:47 +02:00
#include <assimp/material.h>
2020-06-02 11:46:18 +02:00
using namespace Seele;
MeshLoader::MeshLoader(Gfx::PGraphics graphics)
: graphics(graphics)
{
}
MeshLoader::~MeshLoader()
{
}
2020-06-08 01:44:47 +02:00
void MeshLoader::importAsset(const std::filesystem::path &path)
2020-06-02 11:46:18 +02:00
{
2021-03-31 12:18:16 +02:00
futures.add(std::async(std::launch::async, &MeshLoader::import, this, path));
2020-06-02 11:46:18 +02:00
}
2020-10-03 11:00:10 +02:00
void MeshLoader::loadMaterials(const aiScene* scene, Array<PMaterialAsset>& globalMaterials, Gfx::PGraphics graphics)
{
using json = nlohmann::json;
for(uint32 i = 0; i < scene->mNumMaterials; ++i)
{
aiMaterial* material = scene->mMaterials[i];
json matCode;
matCode["name"] = material->GetName().C_Str();
matCode["profile"] = "BlinnPhong"; //TODO: other shading models
aiString texPath;
//TODO make samplers based on used textures
2021-01-19 15:30:00 +01:00
matCode["params"]["textureSampler"] =
{
{"type", "SamplerState"}
};
if(material->GetTexture(aiTextureType_DIFFUSE, 0, &texPath) == AI_SUCCESS)
{
2021-01-19 15:30:00 +01:00
std::string texFilename = std::filesystem::path(texPath.C_Str()).replace_extension("asset").stem().string();
matCode["params"]["diffuseTexture"] =
{
{"type", "Texture2D"},
2021-01-19 15:30:00 +01:00
{"default", texFilename}
};
2021-01-19 15:30:00 +01:00
matCode["code"]["baseColor"] = "return diffuseTexture.Sample(textureSampler, input.texCoords[0]).xyz;";
}
if(material->GetTexture(aiTextureType_SPECULAR, 0, &texPath) == AI_SUCCESS)
{
2021-01-19 15:30:00 +01:00
std::string texFilename = std::filesystem::path(texPath.C_Str()).replace_extension("asset").stem().string();
matCode["params"]["specularTexture"] =
{
{"type", "Texture2D"},
2021-01-19 15:30:00 +01:00
{"default", texFilename}
};
2021-01-19 15:30:00 +01:00
matCode["code"]["specular"] = "return specularTexture.Sample(textureSampler, input.texCoords[0]).x;";
}
if(material->GetTexture(aiTextureType_NORMALS, 0, &texPath) == AI_SUCCESS)
{
2021-01-19 15:30:00 +01:00
std::string texFilename = std::filesystem::path(texPath.C_Str()).replace_extension("asset").stem().string();
matCode["params"]["normalTexture"] =
{
{"type", "Texture2D"},
2021-01-19 15:30:00 +01:00
{"default", texFilename}
};
2021-01-19 15:30:00 +01:00
matCode["code"]["normal"] = "return normalTexture.Sample(textureSampler, input.texCoords[0]).xyz;";
}
2020-09-19 14:36:50 +02:00
std::string outMatFilename = matCode["name"].get<std::string>().append(".asset");
std::ofstream outMatFile = AssetRegistry::createWriteStream(outMatFilename);
outMatFile << std::setw(4) << matCode;
outMatFile.flush();
2020-09-19 14:36:50 +02:00
outMatFile.close();
//TODO: let the material loader handle this instead
2020-10-03 11:00:10 +02:00
//std::cout << matCode << std::endl;
PMaterial result = new Material(outMatFilename);
result->compile();
graphics->getShaderCompiler()->registerMaterial(result);
AssetRegistry::get().registerMaterial(result);
PMaterialAsset asset = AssetRegistry::findMaterial(result->getFileName());
globalMaterials[i] = asset;
}
}
2020-06-08 01:44:47 +02:00
void findMeshRoots(aiNode *node, List<aiNode *> &meshNodes)
2020-06-02 11:46:18 +02:00
{
2020-06-08 01:44:47 +02:00
if (node->mNumMeshes > 0)
2020-06-02 11:46:18 +02:00
{
meshNodes.add(node);
return;
}
2020-06-08 01:44:47 +02:00
for (uint32 i = 0; i < node->mNumChildren; ++i)
2020-06-02 11:46:18 +02:00
{
findMeshRoots(node->mChildren[i], meshNodes);
}
}
2020-09-19 14:36:50 +02:00
VertexStreamComponent createVertexStream(uint32 size, aiVector3D* sourceData, Gfx::PGraphics graphics)
2020-06-08 01:44:47 +02:00
{
Array<Vector> buffer(size);
for(uint32 i = 0; i < size; ++i)
{
buffer[i] = Vector(sourceData[i].x, sourceData[i].y, sourceData[i].z);
}
VertexBufferCreateInfo vbInfo;
vbInfo.numVertices = size;
vbInfo.vertexSize = sizeof(Vector);
vbInfo.resourceData.data = (uint8 *)buffer.data();
vbInfo.resourceData.owner = Gfx::QueueType::DEDICATED_TRANSFER;
2021-03-31 12:18:16 +02:00
vbInfo.resourceData.size = sizeof(Vector) * (uint32)buffer.size();
2020-10-23 01:47:56 +02:00
return VertexStreamComponent(graphics->createVertexBuffer(vbInfo), 0, vbInfo.vertexSize, Gfx::SE_FORMAT_R32G32B32_SFLOAT);
2020-06-08 01:44:47 +02:00
}
2020-09-19 14:36:50 +02:00
VertexStreamComponent createVertexStream(uint32 size, aiVector2D* sourceData, Gfx::PGraphics graphics)
2020-06-08 01:44:47 +02:00
{
Array<Vector2> buffer(size);
for(uint32 i = 0; i < size; ++i)
{
buffer[i] = Vector2(sourceData[i].x, sourceData[i].y);
}
VertexBufferCreateInfo vbInfo;
vbInfo.numVertices = size;
vbInfo.vertexSize = sizeof(Vector2);
vbInfo.resourceData.data = (uint8 *)buffer.data();
vbInfo.resourceData.owner = Gfx::QueueType::DEDICATED_TRANSFER;
2021-03-31 12:18:16 +02:00
vbInfo.resourceData.size = sizeof(Vector2) * (uint32)buffer.size();
2020-10-23 01:47:56 +02:00
return VertexStreamComponent(graphics->createVertexBuffer(vbInfo), 0, vbInfo.vertexSize, Gfx::SE_FORMAT_R32G32_SFLOAT);
2020-06-08 01:44:47 +02:00
}
2020-10-14 01:49:43 +02:00
void MeshLoader::loadGlobalMeshes(const aiScene* scene, Array<PMesh>& globalMeshes, const Array<PMaterialAsset>& materials, Gfx::PGraphics graphics)
2020-06-08 01:44:47 +02:00
{
for (uint32 meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex)
{
aiMesh *mesh = scene->mMeshes[meshIndex];
2020-06-02 11:46:18 +02:00
2020-09-19 14:36:50 +02:00
PStaticMeshVertexInput vertexShaderInput = new StaticMeshVertexInput(std::string(mesh->mName.C_Str()));
2020-10-03 11:00:10 +02:00
StaticMeshDataType data;
data.positionStream = createVertexStream(mesh->mNumVertices, mesh->mVertices, graphics);
2020-06-08 01:44:47 +02:00
2020-09-19 14:36:50 +02:00
for(uint32 i = 0; i < MAX_TEXCOORDS; ++i)
2020-06-08 01:44:47 +02:00
{
if(mesh->HasTextureCoords(i))
{
2020-10-03 11:00:10 +02:00
data.textureCoordinates.add(createVertexStream(mesh->mNumVertices, mesh->mTextureCoords[i], graphics));
2020-06-08 01:44:47 +02:00
}
}
if(mesh->HasNormals())
{
2020-10-03 11:00:10 +02:00
data.tangentBasisComponents[0] = createVertexStream(mesh->mNumVertices, mesh->mNormals, graphics);
2020-06-08 01:44:47 +02:00
}
if(mesh->HasTangentsAndBitangents())
{
2020-09-19 14:36:50 +02:00
//TODO: use bitangent to calculate sign for 4th coordinate of tangentstream
2020-10-03 11:00:10 +02:00
data.tangentBasisComponents[1] = createVertexStream(mesh->mNumVertices, mesh->mTangents, graphics);
2020-06-08 01:44:47 +02:00
}
2020-10-03 11:00:10 +02:00
if(mesh->HasVertexColors(0))
{
//data.colorComponent = createVertexStream(mesh->mNumVertices, mesh->mColors[0], graphics);
}
2020-10-14 01:49:43 +02:00
vertexShaderInput->setData(std::move(data));
2020-10-03 11:00:10 +02:00
vertexShaderInput->init(graphics);
2020-06-08 01:44:47 +02:00
Array<uint32> indices(mesh->mNumFaces * 3);
for (uint32 faceIndex = 0; faceIndex < mesh->mNumFaces; ++faceIndex)
{
indices[faceIndex * 3 + 0] = mesh->mFaces[faceIndex].mIndices[0];
indices[faceIndex * 3 + 1] = mesh->mFaces[faceIndex].mIndices[1];
indices[faceIndex * 3 + 2] = mesh->mFaces[faceIndex].mIndices[2];
}
IndexBufferCreateInfo idxInfo;
idxInfo.indexType = Gfx::SE_INDEX_TYPE_UINT32;
idxInfo.resourceData.data = (uint8 *)indices.data();
idxInfo.resourceData.owner = Gfx::QueueType::DEDICATED_TRANSFER;
2021-03-31 12:18:16 +02:00
idxInfo.resourceData.size = sizeof(uint32) * (uint32)indices.size();
2020-06-08 01:44:47 +02:00
Gfx::PIndexBuffer indexBuffer = graphics->createIndexBuffer(idxInfo);
indexBuffer->transferOwnership(Gfx::QueueType::GRAPHICS);
2020-09-19 14:36:50 +02:00
globalMeshes[meshIndex] = new Mesh(vertexShaderInput, indexBuffer);
globalMeshes[meshIndex]->referencedMaterial = materials[mesh->mMaterialIndex];
2020-06-08 01:44:47 +02:00
}
}
2020-10-03 11:00:10 +02:00
void MeshLoader::convertAssimpARGB(unsigned char* dst, aiTexel* src, uint32 numPixels)
2020-06-08 01:44:47 +02:00
{
for(uint32 i = 0; i < numPixels; ++i)
{
dst[i * 4 + 0] = src[i].r;
dst[i * 4 + 1] = src[i].g;
dst[i * 4 + 2] = src[i].b;
dst[i * 4 + 3] = src[i].a;
}
}
2021-04-01 16:40:14 +02:00
void MeshLoader::loadTextures(const aiScene* scene, const std::filesystem::path& meshDirectory)
2020-06-08 01:44:47 +02:00
{
for (uint32 i = 0; i < scene->mNumTextures; ++i)
{
aiTexture* tex = scene->mTextures[i];
auto texPath = std::filesystem::path(tex->mFilename.C_Str());
2021-01-19 15:30:00 +01:00
auto texPngPath = meshDirectory;
texPngPath.append(texPath.filename().string());
2020-06-08 01:44:47 +02:00
if(tex->mHeight == 0)
{
// already compressed, just dump it to the disk
std::ofstream file(texPngPath, std::ios::binary);
file.write((const char*)tex->pcData, tex->mWidth);
file.flush();
}
else
{
// recompress data so that the TextureLoader can read it
unsigned char* texData = new unsigned char[tex->mWidth * tex->mHeight * 4];
convertAssimpARGB(texData, tex->pcData, tex->mWidth * tex->mHeight);
stbi_write_png(texPngPath.string().c_str(), tex->mWidth, tex->mHeight, 4, tex->pcData, tex->mWidth * 32);
delete texData;
}
AssetRegistry::importFile(texPngPath.string());
}
}
void MeshLoader::import(const std::filesystem::path &path)
2020-06-02 11:46:18 +02:00
{
Assimp::Importer importer;
2020-06-08 01:44:47 +02:00
importer.ReadFile(path.string().c_str(),
2020-06-02 11:46:18 +02:00
aiProcess_FlipUVs |
2020-06-08 01:44:47 +02:00
aiProcess_Triangulate |
aiProcess_SortByPType |
aiProcess_GenSmoothNormals |
aiProcess_GenUVCoords |
2020-10-23 01:47:56 +02:00
aiProcess_FindDegenerates);
2020-06-08 01:44:47 +02:00
const aiScene *scene = importer.ApplyPostProcessing(aiProcess_CalcTangentSpace);
2020-09-19 14:36:50 +02:00
Array<PMaterialAsset> globalMaterials(scene->mNumMaterials);
2021-04-01 16:40:14 +02:00
loadTextures(scene, path.parent_path());
2020-09-19 14:36:50 +02:00
loadMaterials(scene, globalMaterials, graphics);
Array<PMesh> globalMeshes(scene->mNumMeshes);
loadGlobalMeshes(scene, globalMeshes, globalMaterials, graphics);
2020-06-02 11:46:18 +02:00
2020-06-08 01:44:47 +02:00
List<aiNode *> meshNodes;
findMeshRoots(scene->mRootNode, meshNodes);
2020-09-19 14:36:50 +02:00
std::filesystem::path filePath = path.filename();
filePath.replace_extension("asset");
PMeshAsset meshAsset = new MeshAsset(filePath.generic_string());
2020-06-08 01:44:47 +02:00
for (auto meshNode : meshNodes)
{
for(uint32 i = 0; i < meshNode->mNumMeshes; ++i)
{
meshAsset->addMesh(globalMeshes[meshNode->mMeshes[i]]);
}
}
2020-09-19 14:36:50 +02:00
meshAsset->save();
AssetRegistry::get().registerMesh(meshAsset);
2020-06-02 11:46:18 +02:00
}