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

345 lines
13 KiB
C++
Raw Normal View History

2020-06-02 11:46:18 +02:00
#include "MeshLoader.h"
#include "Graphics/Graphics.h"
2023-02-24 22:09:07 +01:00
#include "Asset/MeshAsset.h"
2020-06-02 11:46:18 +02:00
#include "Graphics/Mesh.h"
2023-10-31 16:16:23 +01:00
#include "Graphics/StaticMeshVertexData.h"
2023-02-24 22:09:07 +01:00
#include "Asset/AssetImporter.h"
#include "Asset/MaterialAsset.h"
2023-10-31 16:16:23 +01:00
#include <set>
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>
2023-02-01 22:13:04 +01:00
#include <Asset/MaterialLoader.h>
#include <Asset/TextureLoader.h>
2020-06-02 11:46:18 +02:00
using namespace Seele;
MeshLoader::MeshLoader(Gfx::PGraphics graphics)
: graphics(graphics)
{
}
MeshLoader::~MeshLoader()
{
}
2023-02-01 22:13:04 +01:00
void MeshLoader::importAsset(MeshImportArgs args)
2020-06-02 11:46:18 +02:00
{
2023-02-01 22:13:04 +01:00
std::filesystem::path assetPath = args.filePath.filename();
2021-04-13 23:09:16 +02:00
assetPath.replace_extension("asset");
2023-02-13 14:56:13 +01:00
PMeshAsset asset = new MeshAsset(args.importPath, assetPath.stem().string());
2021-11-11 20:12:50 +01:00
asset->setStatus(Asset::Status::Loading);
2023-02-13 14:56:13 +01:00
AssetRegistry::get().registerMesh(asset);
2023-02-01 22:13:04 +01:00
import(args, asset);
2020-06-02 11:46:18 +02:00
}
2023-02-13 14:56:13 +01:00
void MeshLoader::loadMaterials(const aiScene* scene, const std::string& baseName, const std::filesystem::path& meshDirectory, const std::string& importPath, Array<PMaterialAsset>& globalMaterials)
{
using json = nlohmann::json;
for(uint32 i = 0; i < scene->mNumMaterials; ++i)
{
aiMaterial* material = scene->mMaterials[i];
json matCode;
2023-02-13 14:56:13 +01:00
matCode["name"] = baseName + 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}
};
2023-02-24 22:09:07 +01:00
matCode["code"].push_back(
{
{ "exp", "Sample" },
{ "texture", "diffuseTexture" },
{ "sampler", "textureSampler" },
{ "coords", "input.texCoords[0]"}
}
);
matCode["code"].push_back(
{
{ "exp", "Swizzle" },
{ "target", 0 },
{ "comp", json::array({0, 1, 2}) },
}
);
matCode["code"].push_back(
{
{ "exp", "BRDF" },
{ "profile", "BlinnPhong" },
{ "values", {
{"baseColor", 1}
}}
}
);
}
2022-11-30 10:19:45 +01:00
else
{
2023-02-24 22:09:07 +01:00
matCode["code"].push_back(
{
{ "exp", "BRDF" },
{ "profile", "BlinnPhong" },
{ "values", {
{"baseColor", "input.vertexColor.xyz"}
}}
}
);
2022-11-30 10:19:45 +01:00
}
if(material->GetTexture(aiTextureType_SPECULAR, 0, &texPath) == AI_SUCCESS)
{
}
if(material->GetTexture(aiTextureType_NORMALS, 0, &texPath) == AI_SUCCESS)
{
}
2020-09-19 14:36:50 +02:00
std::string outMatFilename = matCode["name"].get<std::string>().append(".asset");
2023-02-13 14:56:13 +01:00
std::ofstream outMatFile = std::ofstream(meshDirectory / outMatFilename);
outMatFile << std::setw(4) << matCode;
outMatFile.flush();
2020-09-19 14:36:50 +02:00
outMatFile.close();
2021-10-15 23:12:29 +02:00
std::cout << "writing json to " << outMatFilename << std::endl;
2023-02-24 22:09:07 +01:00
AssetImporter::importMaterial(MaterialImportArgs{
2023-02-13 14:56:13 +01:00
.filePath = meshDirectory / outMatFilename,
.importPath = importPath,
2023-02-01 22:13:04 +01:00
});
2023-02-13 14:56:13 +01:00
globalMaterials[i] = AssetRegistry::findMaterial(matCode["name"].get<std::string>());
}
}
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);
}
}
2023-10-31 16:16:23 +01:00
2023-02-13 14:56:13 +01:00
void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialAsset>& materials, Array<PMesh>& globalMeshes, Component::Collider& collider)
2020-06-08 01:44:47 +02:00
{
for (uint32 meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex)
{
aiMesh *mesh = scene->mMeshes[meshIndex];
2023-01-21 18:43:21 +01:00
collider.boundingbox.adjust(Vector(mesh->mAABB.mMin.x, mesh->mAABB.mMin.y, mesh->mAABB.mMin.z));
collider.boundingbox.adjust(Vector(mesh->mAABB.mMax.x, mesh->mAABB.mMax.y, mesh->mAABB.mMax.z));
2023-10-31 16:16:23 +01:00
// assume static mesh for now
Array<Vector> positions(mesh->mNumVertices);
Array<Vector2> texCoords(mesh->mNumVertices);
Array<Vector> normals(mesh->mNumVertices);
Array<Vector> tangents(mesh->mNumVertices);
Array<Vector> biTangents(mesh->mNumVertices);
StaticMeshVertexData* vertexData = StaticMeshVertexData::getInstance();
2023-01-21 18:43:21 +01:00
for(uint32 i = 0; i < mesh->mNumVertices; ++i)
{
2023-10-31 16:16:23 +01:00
positions[i] = Vector(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z);
texCoords[i] = Vector2(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].x);
normals[i] = Vector(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z);
tangents[i] = Vector(mesh->mTangents[i].x, mesh->mTangents[i].y, mesh->mTangents[i].z);
biTangents[i] = Vector(mesh->mBitangents[i].x, mesh->mBitangents[i].y, mesh->mBitangents[i].z);
2023-01-21 18:43:21 +01:00
}
2023-10-31 16:16:23 +01:00
MeshId id = vertexData->allocateVertexData(mesh->mNumVertices);
vertexData->loadPositions(id, positions);
vertexData->loadTexCoords(id, texCoords);
vertexData->loadNormals(id, normals);
vertexData->loadTangents(id, tangents);
vertexData->loadBiTangents(id, biTangents);
2020-06-08 01:44:47 +02:00
Array<uint32> indices(mesh->mNumFaces * 3);
2023-10-31 16:16:23 +01:00
for (size_t faceIndex = 0; faceIndex < mesh->mNumFaces; ++faceIndex)
2020-06-08 01:44:47 +02:00
{
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];
}
2023-01-21 18:43:21 +01:00
2023-10-31 16:16:23 +01:00
if (Gfx::useMeshShading)
{
Array<Meshlet> meshlets;
meshlets.reserve(indices.size() / (3ull * Gfx::numPrimitivesPerMeshlet));
std::set<uint32> uniqueVertices;
Meshlet current = {
.numVertices = 0,
.numPrimitives = 0,
};
auto insertAndGetIndex = [&uniqueVertices, &current](uint32 index) -> int8_t
{
auto [it, inserted] = uniqueVertices.insert(index);
if (inserted)
{
if (current.numVertices == Gfx::numVerticesPerMeshlet)
{
return -1;
}
current.uniqueVertices[current.numVertices] = index;
return current.numVertices++;
}
else
{
for (uint32 i = 0; i < current.numVertices; ++i)
{
if (current.uniqueVertices[i] == index)
{
return i;
}
}
assert(false);
}
};
auto completeMeshlet = [&meshlets, &current, &uniqueVertices]() {
meshlets.add(current);
current = {
.numVertices = 0,
.numPrimitives = 0,
};
uniqueVertices.clear();
};
for (size_t faceIndex = 0; faceIndex < mesh->mNumFaces; ++faceIndex)
{
auto i1 = insertAndGetIndex(mesh->mFaces[faceIndex].mIndices[0]);
auto i2 = insertAndGetIndex(mesh->mFaces[faceIndex].mIndices[1]);
auto i3 = insertAndGetIndex(mesh->mFaces[faceIndex].mIndices[2]);
if (i1 == -1 || i2 == -1 || i3 == -1)
{
completeMeshlet();
}
current.primitiveLayout[current.numPrimitives * 3 + 0] = i1;
current.primitiveLayout[current.numPrimitives * 3 + 1] = i2;
current.primitiveLayout[current.numPrimitives * 3 + 2] = i3;
current.numPrimitives++;
if (current.numPrimitives == Gfx::numPrimitivesPerMeshlet)
{
completeMeshlet();
}
}
}
else
{
// \! todo
}
collider.physicsMesh.addCollider(positions, indices, Matrix4(1.0f));
2023-01-21 18:43:21 +01:00
2020-06-08 01:44:47 +02:00
IndexBufferCreateInfo idxInfo;
idxInfo.indexType = Gfx::SE_INDEX_TYPE_UINT32;
idxInfo.resourceData.data = (uint8 *)indices.data();
idxInfo.resourceData.owner = Gfx::QueueType::DEDICATED_TRANSFER;
idxInfo.resourceData.size = sizeof(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;
}
}
2023-02-13 14:56:13 +01:00
void MeshLoader::loadTextures(const aiScene* scene, const std::filesystem::path& meshDirectory, const std::string& importPath)
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);
2023-01-29 18:58:59 +01:00
delete[] texData;
2020-06-08 01:44:47 +02:00
}
2021-10-15 23:12:29 +02:00
std::cout << "Loading model texture " << texPngPath.string() << std::endl;
2023-02-24 22:09:07 +01:00
AssetImporter::importTexture(TextureImportArgs {
2023-02-01 22:13:04 +01:00
.filePath = texPath,
2023-02-13 14:56:13 +01:00
.importPath = importPath,
2023-02-01 22:13:04 +01:00
});
2020-06-08 01:44:47 +02:00
}
}
2023-02-01 22:13:04 +01:00
void MeshLoader::import(MeshImportArgs args, PMeshAsset meshAsset)
2020-06-02 11:46:18 +02:00
{
2023-02-01 22:13:04 +01:00
std::cout << "Starting to import "<<args.filePath<< std::endl;
2021-04-13 23:09:16 +02:00
meshAsset->setStatus(Asset::Status::Loading);
2020-06-02 11:46:18 +02:00
Assimp::Importer importer;
2023-02-01 22:13:04 +01:00
importer.ReadFile(args.filePath.string().c_str(), (uint32)(
2020-06-02 11:46:18 +02:00
aiProcess_FlipUVs |
2020-06-08 01:44:47 +02:00
aiProcess_Triangulate |
aiProcess_SortByPType |
2023-01-21 18:43:21 +01:00
aiProcess_GenBoundingBoxes |
2020-06-08 01:44:47 +02:00
aiProcess_GenSmoothNormals |
aiProcess_GenUVCoords |
2023-01-21 18:43:21 +01: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
2023-02-13 14:56:13 +01:00
Array<PMaterialAsset> globalMaterials(scene->mNumMaterials);
loadTextures(scene, args.filePath.parent_path(), args.importPath);
loadMaterials(scene, args.filePath.stem().string(), args.filePath.parent_path(), args.importPath, globalMaterials);
2020-09-19 14:36:50 +02:00
Array<PMesh> globalMeshes(scene->mNumMeshes);
2023-01-21 18:43:21 +01:00
Component::Collider collider;
loadGlobalMeshes(scene, globalMaterials, globalMeshes, collider);
2020-06-02 11:46:18 +02:00
2020-06-08 01:44:47 +02:00
List<aiNode *> meshNodes;
findMeshRoots(scene->mRootNode, meshNodes);
2021-04-13 23:09:16 +02:00
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]]);
}
}
2023-01-21 18:43:21 +01:00
meshAsset->physicsMesh = std::move(collider);
2023-07-31 21:43:20 +02:00
auto stream = AssetRegistry::createWriteStream((std::filesystem::path(meshAsset->getFolderPath()) / meshAsset->getName()).replace_extension("asset").string(), std::ios::binary);
ArchiveBuffer archive;
Serialization::save(archive, MeshAsset::IDENTIFIER);
Serialization::save(archive, meshAsset->getName());
Serialization::save(archive, meshAsset->getFolderPath());
meshAsset->save(archive);
archive.writeToStream(stream);
2021-04-13 23:09:16 +02:00
meshAsset->setStatus(Asset::Status::Ready);
2023-07-31 21:43:20 +02:00
std::cout << "Finished loading " << args.filePath << std::endl;
2020-06-02 11:46:18 +02:00
}