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

321 lines
12 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>
2023-11-06 14:47:21 +01:00
#include <format>
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;
2023-12-02 10:55:00 +01:00
std::string materialName = std::format("{0}{1}{2}", baseName, material->GetName().C_Str(), char(i+'a'));
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;
matCode["profile"] = "BlinnPhong"; //TODO: other shading models
aiString texPath;
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(
{
{ "exp", "BRDF" },
{ "profile", "BlinnPhong" },
{ "values", {
{"baseColor", "float3(1, 1, 1)"}
}}
}
);
}
else
{
AssetImporter::importTexture(TextureImportArgs{
.filePath = meshDirectory / texPath.C_Str(),
.importPath = importPath,
});
matCode["params"]["diffuseTexture"] =
2023-02-24 22:09:07 +01:00
{
2023-12-02 10:55:00 +01:00
{"type", "Texture2D"},
{"default", texFilename.string()}
};
matCode["params"]["diffuseSampler"] =
2023-02-24 22:09:07 +01:00
{
2023-12-02 10:55:00 +01:00
{"type", "Sampler"}
};
matCode["code"].push_back(
{
{ "exp", "Sample" },
{ "texture", "diffuseTexture" },
{ "sampler", "diffuseSampler" },
{ "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)
{
}
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
});
2023-11-07 16:55:13 +01:00
PMaterialAsset baseMat = AssetRegistry::findMaterial(matCode["name"].get<std::string>());
globalMaterials[i] = baseMat->instantiate(InstantiationParameter{
.name = std::format("{0}_Inst_0", baseMat->getName()),
.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];
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();
2023-11-07 16:55:13 +01:00
for (uint32 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);
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-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
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-11-01 13:38:49 +01:00
Array<Meshlet> meshlets;
meshlets.reserve(indices.size() / (3ull * Gfx::numPrimitivesPerMeshlet));
2023-11-22 13:18:54 +01:00
Meshlet::buildFromIndexBuffer(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;
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-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)
{
2023-11-05 10:36:01 +01:00
meshes.add(std::move(globalMeshes[meshNode->mMeshes[i]]));
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
}