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

423 lines
15 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>
2024-01-16 19:24:49 +01:00
#include <fmt/core.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>
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-11-05 10:36:01 +01:00
OMeshAsset asset = new MeshAsset(args.importPath, assetPath.stem().string());
PMeshAsset ref = asset;
2021-11-11 20:12:50 +01:00
asset->setStatus(Asset::Status::Loading);
2023-11-05 10:36:01 +01:00
AssetRegistry::get().registerMesh(std::move(asset));
import(args, ref);
2020-06-02 11:46:18 +02:00
}
2023-11-07 16:55:13 +01:00
void MeshLoader::loadMaterials(const aiScene* scene, const std::string& baseName, const std::filesystem::path& meshDirectory, const std::string& importPath, Array<PMaterialInstanceAsset>& globalMaterials)
{
using json = nlohmann::json;
for(uint32 i = 0; i < scene->mNumMaterials; ++i)
{
aiMaterial* material = scene->mMaterials[i];
json matCode;
2024-01-16 19:24:49 +01:00
std::string materialName = fmt::format("{0}{1}{2}", baseName, material->GetName().C_Str(), i);
2023-11-08 23:27:21 +01:00
materialName.erase(std::remove(materialName.begin(), materialName.end(), '.'), materialName.end()); // dots break adding the .asset extension later
matCode["name"] = materialName;
2024-01-02 16:48:03 +01:00
matCode["profile"] = "CelShading";
aiString texPath;
2023-12-03 00:29:02 +01:00
uint32 baseColorIndex = 0;
uint32 normalIndex = 0;
int32 codeIndex = -1;
if(material->GetTexture(aiTextureType_DIFFUSE, 0, &texPath) == AI_SUCCESS)
{
2023-12-02 10:55:00 +01:00
auto texFilename = std::filesystem::path(texPath.C_Str()).stem();
if (texFilename == "white")
2023-11-12 14:46:22 +01:00
{
2023-12-02 10:55:00 +01:00
matCode["code"].push_back(
{
2023-12-03 00:29:02 +01:00
{ "exp", "Const" },
{ "value", "float3(1, 1, 1)"}
2023-12-02 10:55:00 +01:00
}
);
2023-12-03 00:29:02 +01:00
baseColorIndex = ++codeIndex;
2023-12-02 10:55:00 +01:00
}
else
{
AssetImporter::importTexture(TextureImportArgs{
.filePath = meshDirectory / texPath.C_Str(),
.importPath = importPath,
});
matCode["params"]["diffuseTexture"] =
2023-02-24 22:09:07 +01:00
{
2024-04-26 11:42:28 +02:00
{"type", "Sampler2D"},
2024-04-24 23:25:34 +02:00
{"default", fmt::format("{0}/{1}", importPath, texFilename.string())}
2023-12-02 10:55:00 +01:00
};
matCode["code"].push_back(
{
{ "exp", "Sample" },
2024-04-26 11:42:28 +02:00
{ "sampler", "diffuseTexture" },
2023-12-03 00:29:02 +01:00
{ "coords", "input.texCoords"}
2023-12-02 10:55:00 +01:00
}
);
2023-12-03 00:29:02 +01:00
++codeIndex;
2023-12-02 10:55:00 +01:00
matCode["code"].push_back(
{
{ "exp", "Swizzle" },
2023-12-03 00:29:02 +01:00
{ "target", codeIndex },
2023-12-02 10:55:00 +01:00
{ "comp", json::array({0, 1, 2}) },
}
);
2023-12-03 00:29:02 +01:00
baseColorIndex = ++codeIndex;
2023-12-02 10:55:00 +01:00
}
}
2022-11-30 10:19:45 +01:00
else
{
2023-02-24 22:09:07 +01:00
matCode["code"].push_back(
{
2023-12-03 00:29:02 +01:00
{ "exp", "Const" },
{ "value", "input.vertexColor.xyz" }
2023-02-24 22:09:07 +01:00
}
);
2023-12-03 00:29:02 +01:00
baseColorIndex = ++codeIndex;
}
if(material->GetTexture(aiTextureType_NORMALS, 0, &texPath) == AI_SUCCESS)
{
2023-12-03 00:29:02 +01:00
auto texFilename = std::filesystem::path(texPath.C_Str()).stem();
AssetImporter::importTexture(TextureImportArgs{
.filePath = meshDirectory / texPath.C_Str(),
.importPath = importPath,
});
matCode["params"]["normalTexture"] =
{
2024-04-26 11:42:28 +02:00
{"type", "Sampler2D"},
2024-04-24 23:25:34 +02:00
{"default", fmt::format("{0}/{1}", importPath, texFilename.string())}
2023-12-03 00:29:02 +01:00
};
matCode["code"].push_back(
{
{ "exp", "Sample" },
2024-04-26 11:42:28 +02:00
{ "sampler", "normalTexture" },
2023-12-03 00:29:02 +01:00
{ "coords", "input.texCoords" }
}
);
++codeIndex;
matCode["code"].push_back(
{
{ "exp", "Swizzle" },
{ "target", codeIndex },
{ "comp", json::array({0, 1, 2}) },
}
);
++codeIndex;
matCode["code"].push_back(
{
{ "exp", "Mul" },
{ "lhs", "2" },
{ "rhs", codeIndex },
}
);
++codeIndex;
matCode["code"].push_back(
{
{ "exp", "Sub" },
{ "lhs", codeIndex },
{ "rhs", "float3(1, 1, 1)"},
}
);
normalIndex = ++codeIndex;
}
2023-12-03 00:29:02 +01:00
else
{
matCode["code"].push_back(
{
{ "exp", "Const" },
{ "value", "float3(0, 0, 1)" }
}
);
normalIndex = ++codeIndex;
}
matCode["code"].push_back(
{
{ "exp", "BRDF" },
2024-01-02 16:48:03 +01:00
{ "profile", matCode["profile"]},
2023-12-03 00:29:02 +01:00
{ "values", {
{ "baseColor", baseColorIndex },
{ "normal", normalIndex },
}}
}
);
2023-12-02 10:55:00 +01:00
std::string outMatFilename = materialName.append(".json");
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
});
2024-04-23 17:08:39 +02:00
std::string materialAsset;
if (importPath.empty())
{
materialAsset = matCode["name"].get<std::string>();
}
else
{
materialAsset = fmt::format("{0}/{1}", importPath, matCode["name"].get<std::string>());
}
PMaterialAsset baseMat = AssetRegistry::findMaterial(materialAsset);
2023-11-07 16:55:13 +01:00
globalMaterials[i] = baseMat->instantiate(InstantiationParameter{
2024-01-16 19:24:49 +01:00
.name = fmt::format("{0}_Inst_0", baseMat->getName()),
2023-11-07 16:55:13 +01:00
.folderPath = baseMat->getFolderPath(),
});
}
}
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-11-07 16:55:13 +01:00
void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialInstanceAsset>& materials, Array<OMesh>& globalMeshes, Component::Collider& collider)
2020-06-08 01:44:47 +02:00
{
for (uint32 meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex)
{
2023-11-07 16:55:13 +01:00
aiMesh* mesh = scene->mMeshes[meshIndex];
2024-04-23 17:08:39 +02:00
if (!(mesh->mPrimitiveTypes & aiPrimitiveType_TRIANGLE))
continue;
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);
2023-11-11 22:39:17 +01:00
Array<Vector> colors(mesh->mNumVertices);
2023-10-31 16:16:23 +01:00
StaticMeshVertexData* vertexData = StaticMeshVertexData::getInstance();
2024-04-23 23:21:30 +02:00
#pragma omp parallel for
for (int32 i = 0; i < mesh->mNumVertices; ++i)
2023-01-21 18:43:21 +01:00
{
2023-10-31 16:16:23 +01:00
positions[i] = Vector(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z);
2024-04-23 17:08:39 +02:00
if (mesh->HasTextureCoords(0))
{
texCoords[i] = Vector2(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y);
}
else
{
texCoords[i] = Vector2(0, 0);
}
2023-10-31 16:16:23 +01:00
normals[i] = Vector(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z);
2024-04-23 17:08:39 +02:00
if (mesh->HasTangentsAndBitangents())
{
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);
}
else
{
tangents[i] = Vector(0, 0, 1);
biTangents[i] = Vector(1, 0, 0);
}
2023-11-11 22:39:17 +01:00
if(mesh->HasVertexColors(0))
{
colors[i] = Vector(mesh->mColors[0][i].r, mesh->mColors[0][i].g, mesh->mColors[0][i].b);
}
else
{
colors[i] = Vector(1, 1, 1);
}
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);
2023-11-11 22:39:17 +01:00
vertexData->loadColors(id, colors);
2020-06-08 01:44:47 +02:00
2024-04-07 16:33:32 +02:00
Array<uint32> indices(mesh->mNumFaces * 3);
2024-04-23 23:21:30 +02:00
#pragma omp parallel for
for (int32 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-11-01 13:38:49 +01:00
Array<Meshlet> meshlets;
meshlets.reserve(indices.size() / (3ull * Gfx::numPrimitivesPerMeshlet));
2023-12-23 18:26:54 +01:00
Meshlet::build(positions, indices, meshlets);
2023-11-26 11:27:39 +01:00
vertexData->loadMesh(id, indices, meshlets);
2023-11-07 16:55:13 +01:00
2023-10-31 16:16:23 +01:00
collider.physicsMesh.addCollider(positions, indices, Matrix4(1.0f));
2023-01-21 18:43:21 +01:00
2023-11-01 13:38:49 +01:00
globalMeshes[meshIndex] = new Mesh();
globalMeshes[meshIndex]->vertexData = vertexData;
globalMeshes[meshIndex]->id = id;
2023-11-07 16:55:13 +01:00
globalMeshes[meshIndex]->referencedMaterial = materials[mesh->mMaterialIndex];
2023-11-01 13:38:49 +01:00
globalMeshes[meshIndex]->meshlets = std::move(meshlets);
2023-11-10 22:01:58 +01:00
globalMeshes[meshIndex]->indices = std::move(indices);
2023-11-05 11:47:22 +01:00
globalMeshes[meshIndex]->vertexCount = mesh->mNumVertices;
2020-06-08 01:44:47 +02:00
}
}
2023-11-01 13:38:49 +01: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;
2024-04-24 23:25:34 +02:00
texPngPath.append(fmt::format("{0}.{1}", texPath.filename().string(), tex->achFormatHint));
if (!std::filesystem::exists(texPngPath))
2020-06-08 01:44:47 +02:00
{
2024-04-24 23:25:34 +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;
}
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 {
2024-04-24 23:25:34 +02:00
.filePath = texPngPath,
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
}
}
2024-04-23 23:21:30 +02:00
Matrix4 convertMatrix(aiMatrix4x4 matrix)
{
return Matrix4(
2024-04-24 23:25:34 +02:00
matrix.a1, matrix.b1, matrix.c1, matrix.d1,
matrix.a2, matrix.b2, matrix.c2, matrix.d2,
matrix.a3, matrix.b3, matrix.c3, matrix.d3,
matrix.a4, matrix.b4, matrix.c4, matrix.d4
2024-04-23 23:21:30 +02:00
);
}
2024-04-24 23:25:34 +02:00
aiMatrix4x4 loadNodeTransform(aiNode* node)
2024-04-23 23:21:30 +02:00
{
2024-04-24 23:25:34 +02:00
aiMatrix4x4 parent = aiMatrix4x4();
2024-04-23 23:21:30 +02:00
if (node->mParent != nullptr)
{
parent = loadNodeTransform(node->mParent);
}
2024-04-24 23:25:34 +02:00
return node->mTransformation * parent;
2024-04-23 23:21:30 +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)(
aiProcess_JoinIdenticalVertices |
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 |
2024-04-24 23:25:34 +02:00
aiProcess_ImproveCacheLocality |
2020-06-08 01:44:47 +02:00
aiProcess_GenUVCoords |
2023-01-21 18:43:21 +01:00
aiProcess_FindDegenerates));
2024-04-23 17:08:39 +02:00
const aiScene *scene = importer.ApplyPostProcessing(aiProcess_CalcTangentSpace);
2024-04-24 23:25:34 +02:00
std::cout << importer.GetErrorString() << std::endl;
2023-11-07 16:55:13 +01:00
Array<PMaterialInstanceAsset> globalMaterials(scene->mNumMaterials);
2023-02-13 14:56:13 +01:00
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
2023-11-05 10:36:01 +01:00
Array<OMesh> 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
2023-11-05 10:36:01 +01:00
Array<OMesh> meshes;
2020-06-08 01:44:47 +02:00
for (auto meshNode : meshNodes)
{
for(uint32 i = 0; i < meshNode->mNumMeshes; ++i)
{
2024-04-23 23:21:30 +02:00
if (globalMeshes[meshNode->mMeshes[i]] == nullptr)
{
continue;
}
2023-11-05 10:36:01 +01:00
meshes.add(std::move(globalMeshes[meshNode->mMeshes[i]]));
2024-04-24 23:25:34 +02:00
meshes.back()->transform = convertMatrix(loadNodeTransform(meshNode));
2020-06-08 01:44:47 +02:00
}
}
2023-11-05 10:36:01 +01:00
meshAsset->meshes = std::move(meshes);
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
}