Loading logic moved to Asset classes

This commit is contained in:
Dynamitos
2020-06-08 01:44:47 +02:00
parent 356e6058fe
commit ab4a3b5e23
50 changed files with 966 additions and 558 deletions
-2
View File
@@ -89,7 +89,5 @@ if (ASSIMP_FOUND)
set(ASSIMP_INCLUDE_DIRS ${ASSIMP_INCLUDE_DIR}) set(ASSIMP_INCLUDE_DIRS ${ASSIMP_INCLUDE_DIR})
endif() endif()
message(STATUS BINARY: ${ASSIMP_BINARY})
# Hide some variables # Hide some variables
mark_as_advanced(ASSIMP_INCLUDE_DIR ASSIMP_LIBRARY) mark_as_advanced(ASSIMP_INCLUDE_DIR ASSIMP_LIBRARY)
-2
View File
@@ -46,8 +46,6 @@ if (WIN32)
${GLFW_ROOT}/src ${GLFW_ROOT}/src
PATH_SUFFIXES Debug Release) PATH_SUFFIXES Debug Release)
message(STATUS cant find ${GLFW_LIBRARY_NAME} in ${GLFW_ROOT}/src)
unset(GLFW_LIBRARY_NAME) unset(GLFW_LIBRARY_NAME)
find_file( find_file(
-4
View File
@@ -19,10 +19,6 @@ Asset::Asset(const std::filesystem::path& path)
name = fullPath.stem(); name = fullPath.stem();
extension = fullPath.extension(); extension = fullPath.extension();
} }
Asset::Asset(const std::string &fullPath)
: Asset(std::filesystem::path(fullPath))
{
}
Asset::Asset(const std::string &directory, const std::string &fileName) Asset::Asset(const std::string &directory, const std::string &fileName)
: Asset(std::filesystem::path(directory + fileName)) : Asset(std::filesystem::path(directory + fileName))
+6 -4
View File
@@ -13,12 +13,12 @@ public:
Ready Ready
}; };
Asset(); Asset();
Asset(const std::filesystem::path& path);
Asset(const std::string& directory, const std::string& name); Asset(const std::string& directory, const std::string& name);
Asset(const std::string& fullPath); Asset(const std::filesystem::path& path);
virtual ~Asset(); virtual ~Asset();
std::ifstream& getReadStream();
std::ofstream& getWriteStream(); virtual void save() = 0;
virtual void load() = 0;
// returns the name of the file, without extension // returns the name of the file, without extension
std::string getFileName(); std::string getFileName();
@@ -38,6 +38,8 @@ public:
} }
protected: protected:
std::mutex lock; std::mutex lock;
std::ifstream& getReadStream();
std::ofstream& getWriteStream();
private: private:
Status status; Status status;
std::filesystem::path fullPath; std::filesystem::path fullPath;
+15 -13
View File
@@ -7,6 +7,7 @@
#include "Material/Material.h" #include "Material/Material.h"
#include "Graphics/Graphics.h" #include "Graphics/Graphics.h"
#include "graphics/WindowManager.h" #include "graphics/WindowManager.h"
#include <filesystem>
using namespace Seele; using namespace Seele;
@@ -21,21 +22,22 @@ void AssetRegistry::init(const std::string& rootFolder)
void AssetRegistry::importFile(const std::string &filePath) void AssetRegistry::importFile(const std::string &filePath)
{ {
std::string extension = filePath.substr(filePath.find_last_of(".") + 1); std::filesystem::path fsPath = std::filesystem::path(filePath);
std::string extension = fsPath.extension().string();
std::cout << extension << std::endl; std::cout << extension << std::endl;
if (extension.compare("fbx") == 0 if (extension.compare(".fbx") == 0
|| extension.compare("obj") == 0) || extension.compare(".obj") == 0)
{ {
get().registerMesh(filePath); get().registerMesh(fsPath);
} }
if (extension.compare("png") == 0 if (extension.compare(".png") == 0
|| extension.compare("jpg") == 0) || extension.compare(".jpg") == 0)
{ {
get().registerTexture(filePath); get().registerTexture(fsPath);
} }
if (extension.compare("semat") == 0) if (extension.compare(".semat") == 0)
{ {
get().registerMaterial(filePath); get().registerMaterial(fsPath);
} }
} }
@@ -64,7 +66,7 @@ AssetRegistry::AssetRegistry()
{ {
} }
void AssetRegistry::init(const std::string &rootFolder, Gfx::PGraphics graphics) void AssetRegistry::init(const std::filesystem::path &rootFolder, Gfx::PGraphics graphics)
{ {
AssetRegistry &reg = get(); AssetRegistry &reg = get();
reg.rootFolder = rootFolder; reg.rootFolder = rootFolder;
@@ -73,17 +75,17 @@ void AssetRegistry::init(const std::string &rootFolder, Gfx::PGraphics graphics)
reg.materialLoader = new MaterialLoader(graphics); reg.materialLoader = new MaterialLoader(graphics);
} }
void AssetRegistry::registerMesh(const std::string &filePath) void AssetRegistry::registerMesh(const std::filesystem::path &filePath)
{ {
meshLoader->importAsset(filePath); meshLoader->importAsset(filePath);
} }
void AssetRegistry::registerTexture(const std::string &filePath) void AssetRegistry::registerTexture(const std::filesystem::path &filePath)
{ {
textureLoader->importAsset(filePath); textureLoader->importAsset(filePath);
} }
void AssetRegistry::registerMaterial(const std::string &filePath) void AssetRegistry::registerMaterial(const std::filesystem::path &filePath)
{ {
materialLoader->queueAsset(filePath); materialLoader->queueAsset(filePath);
} }
+5 -5
View File
@@ -27,13 +27,13 @@ private:
static AssetRegistry& get(); static AssetRegistry& get();
AssetRegistry(); AssetRegistry();
void init(const std::string& rootFolder, Gfx::PGraphics graphics); void init(const std::filesystem::path& rootFolder, Gfx::PGraphics graphics);
void registerMesh(const std::string& filePath); void registerMesh(const std::filesystem::path& filePath);
void registerTexture(const std::string& filePath); void registerTexture(const std::filesystem::path& filePath);
void registerMaterial(const std::string& filePath); void registerMaterial(const std::filesystem::path& filePath);
std::string rootFolder; std::filesystem::path rootFolder;
Map<std::string, PTextureAsset> textures; Map<std::string, PTextureAsset> textures;
Map<std::string, PMeshAsset> meshes; Map<std::string, PMeshAsset> meshes;
Map<std::string, PMaterialAsset> materials; Map<std::string, PMaterialAsset> materials;
+3 -2
View File
@@ -14,9 +14,10 @@ MaterialLoader::~MaterialLoader()
{ {
} }
PMaterial MaterialLoader::queueAsset(const std::string& filePath) PMaterial MaterialLoader::queueAsset(const std::filesystem::path& filePath)
{ {
PMaterial result = new Material(filePath); PMaterial result = new Material(filePath);
//TODO // TODO: There is actually no real reason to import a standalone material,
// maybe in the future there could be a substance loader or something
return result; return result;
} }
+1 -1
View File
@@ -13,7 +13,7 @@ class MaterialLoader
public: public:
MaterialLoader(Gfx::PGraphics graphic); MaterialLoader(Gfx::PGraphics graphic);
~MaterialLoader(); ~MaterialLoader();
PMaterial queueAsset(const std::string& filePath); PMaterial queueAsset(const std::filesystem::path& filePath);
private: private:
List<std::future<void>> futures; List<std::future<void>> futures;
PMaterial placeholderMaterial; PMaterial placeholderMaterial;
+14 -1
View File
@@ -7,11 +7,24 @@ using namespace Seele;
MeshAsset::MeshAsset() MeshAsset::MeshAsset()
{ {
} }
MeshAsset::MeshAsset(const std::string& directory, const std::string& name) MeshAsset::MeshAsset(const std::string& directory, const std::string& name)
: Asset(directory, name) : Asset(directory, name)
{ {
} }
MeshAsset::MeshAsset(const std::string& fullPath) MeshAsset::MeshAsset(const std::filesystem::path& fullPath)
: Asset(fullPath) : Asset(fullPath)
{ {
} }
MeshAsset::~MeshAsset()
{
}
void MeshAsset::save()
{
//TODO:
}
void MeshAsset::load()
{
//TODO:
}
+13 -4
View File
@@ -4,19 +4,28 @@
namespace Seele namespace Seele
{ {
DECLARE_REF(Mesh); DECLARE_REF(Mesh);
DECLARE_REF(MaterialAsset);
class MeshAsset : public Asset class MeshAsset : public Asset
{ {
public: public:
MeshAsset(); MeshAsset();
MeshAsset(const std::string& directory, const std::string& name); MeshAsset(const std::string& directory, const std::string& name);
MeshAsset(const std::string& fullPath); MeshAsset(const std::filesystem::path& fullPath);
void setMesh(PMesh mesh) virtual ~MeshAsset();
virtual void save() override;
virtual void load() override;
void addMesh(PMesh mesh)
{ {
std::scoped_lock lck(lock); std::scoped_lock lck(lock);
this->mesh = mesh; meshes.add(mesh);
}
const Array<PMesh> getMeshes() const
{
return meshes;
} }
private: private:
PMesh mesh; Array<PMesh> meshes;
Array<PMaterialAsset> referencedMaterials;
}; };
DEFINE_REF(MeshAsset); DEFINE_REF(MeshAsset);
} // namespace Seele } // namespace Seele
+219 -17
View File
@@ -1,10 +1,18 @@
#include "MeshLoader.h" #include "MeshLoader.h"
#include "Graphics/Graphics.h" #include "Graphics/Graphics.h"
#include "Graphics/GraphicsResources.h"
#include "MeshAsset.h" #include "MeshAsset.h"
#include "Graphics/Mesh.h" #include "Graphics/Mesh.h"
#include "AssetRegistry.h"
#include <filesystem>
#include <fstream>
#include <nlohmann/json.hpp>
#include <stb_image_write.h>
#include <assimp/config.h>
#include <assimp/Importer.hpp> #include <assimp/Importer.hpp>
#include <assimp/scene.h> #include <assimp/scene.h>
#include <assimp/postprocess.h> #include <assimp/postprocess.h>
#include <assimp/material.h>
using namespace Seele; using namespace Seele;
@@ -17,45 +25,239 @@ MeshLoader::~MeshLoader()
{ {
} }
void MeshLoader::importAsset(const std::string& path) void MeshLoader::importAsset(const std::filesystem::path &path)
{ {
futures.add(std::async(std::launch::async, &MeshLoader::import, this, path)); futures.add(std::async(std::launch::async, &MeshLoader::import, this, path));
} }
void findMeshRoots(aiNode* node, List<aiNode*>& meshNodes) void findMeshRoots(aiNode *node, List<aiNode *> &meshNodes)
{ {
if(node->mNumMeshes > 0) if (node->mNumMeshes > 0)
{ {
meshNodes.add(node); meshNodes.add(node);
return; return;
} }
for(uint32 i = 0; i < node->mNumChildren; ++i) for (uint32 i = 0; i < node->mNumChildren; ++i)
{ {
findMeshRoots(node->mChildren[i], meshNodes); findMeshRoots(node->mChildren[i], meshNodes);
} }
} }
void loadToBuffer(Array<Vector>& buffer, const aiVector3D* sourceData, uint32 size)
{
buffer.resize(size);
for(uint32 i = 0; i < size; ++i)
{
buffer[i] = Vector(sourceData[i].x, sourceData[i].y, sourceData[i].z);
}
}
Gfx::VertexStream createVertexStream(uint32 size, aiVector3D* sourceData, Gfx::PGraphics graphics)
{
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;
vbInfo.resourceData.size = buffer.size();
Gfx::PVertexBuffer vertexBuffer = graphics->createVertexBuffer(vbInfo);
auto stream = Gfx::VertexStream(vbInfo.vertexSize, 0, false, vertexBuffer);
stream.addVertexElement(Gfx::VertexElement(0, Gfx::SE_FORMAT_R32G32_SFLOAT, 0));
return stream;
}
Gfx::VertexStream createVertexStream(uint32 size, aiVector2D* sourceData, Gfx::PGraphics graphics)
{
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;
vbInfo.resourceData.size = buffer.size();
Gfx::PVertexBuffer vertexBuffer = graphics->createVertexBuffer(vbInfo);
auto stream = Gfx::VertexStream(vbInfo.vertexSize, 0, false, vertexBuffer);
stream.addVertexElement(Gfx::VertexElement(0, Gfx::SE_FORMAT_R32G32B32_SFLOAT, 0));
return stream;
}
void loadGlobalMeshes(const aiScene* scene, Array<PMesh>& globalMeshes, Gfx::PGraphics graphics)
{
for (uint32 meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex)
{
aiMesh *mesh = scene->mMeshes[meshIndex];
void MeshLoader::import(const std::string& path) MeshDescription description;
Gfx::PVertexDeclaration declaration = new Gfx::VertexDeclaration();
declaration->addVertexStream(createVertexStream(mesh->mNumVertices, mesh->mVertices, graphics));
description.layout.add(VertexAttribute::POSITION);
for(uint32 i = 0; i < MAX_TEX_CHANNELS; ++i)
{
if(mesh->HasTextureCoords(i))
{
declaration->addVertexStream(createVertexStream(mesh->mNumVertices, mesh->mTextureCoords[i], graphics));
description.layout.add(VertexAttribute::TEXCOORD);
}
}
if(mesh->HasNormals())
{
declaration->addVertexStream(createVertexStream(mesh->mNumVertices, mesh->mNormals, graphics));
description.layout.add(VertexAttribute::NORMAL);
}
if(mesh->HasTangentsAndBitangents())
{
declaration->addVertexStream(createVertexStream(mesh->mNumVertices, mesh->mVertices, graphics));
declaration->addVertexStream(createVertexStream(mesh->mNumVertices, mesh->mVertices, graphics));
description.layout.add(VertexAttribute::TANGENT);
description.layout.add(VertexAttribute::BITANGENT);
}
description.declaration = declaration;
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;
idxInfo.resourceData.size = indices.size();
Gfx::PIndexBuffer indexBuffer = graphics->createIndexBuffer(idxInfo);
indexBuffer->transferOwnership(Gfx::QueueType::GRAPHICS);
globalMeshes[meshIndex] = new Mesh(description, indexBuffer);
}
}
void convertAssimpARGB(unsigned char* dst, aiTexel* src, uint32 numPixels)
{
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;
}
}
void loadTextures(const aiScene* scene, Gfx::PGraphics graphics, const std::filesystem::path& meshPath)
{
for (uint32 i = 0; i < scene->mNumTextures; ++i)
{
aiTexture* tex = scene->mTextures[i];
auto texPath = std::filesystem::path(tex->mFilename.C_Str());
auto texPngPath = meshPath.parent_path().append(texPath.filename().string());
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 loadMaterials(const aiScene* scene, 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
std::vector<std::string> code;
aiString texPath;
//TODO make samplers based on used textures
matCode["params"]["texSampler"] =
{
{"type", "SamplerState"}
};
if(material->GetTexture(aiTextureType_DIFFUSE, 0, &texPath) == AI_SUCCESS)
{
std::string texFilename = std::filesystem::path(texPath.C_Str()).stem().string();
matCode["params"]["diffuseTexture"] =
{
{"type", "Texture2D"},
{"default", texFilename}
};
code.push_back("result.baseColor = diffuseTexture.Sample(textureSampler, geometry.texCoord).xyz;\n");
}
if(material->GetTexture(aiTextureType_SPECULAR, 0, &texPath) == AI_SUCCESS)
{
std::string texFilename = std::filesystem::path(texPath.C_Str()).stem().string();
matCode["params"]["specularTexture"] =
{
{"type", "Texture2D"},
{"default", texFilename}
};
code.push_back("result.specular = specularTexture.Sample(textureSampler, geometry.texCoord).xyz;\n");
}
if(material->GetTexture(aiTextureType_NORMALS, 0, &texPath) == AI_SUCCESS)
{
std::string texFilename = std::filesystem::path(texPath.C_Str()).stem().string();
matCode["params"]["normalTexture"] =
{
{"type", "Texture2D"},
{"default", texFilename}
};
code.push_back("float3 bumpMapNormal = normalTexture.Sample(textureSampler, geometry.texCoord).xyz;\n");
code.push_back("bumpMapNormal = 2.0 * bumpMapNormal - float3(1.0f, 1.0f, 1.0f);\n");
code.push_back("result.normal = geometry.transformLocalToWorld(bumpMapNormal);\n");
}
code.push_back("return result;\n");
matCode["code"] = code;
std::ofstream outMatFile(material->GetName().C_Str());
outMatFile << std::setw(4) << matCode;
outMatFile.flush();
}
}
void MeshLoader::import(const std::filesystem::path &path)
{ {
PMeshAsset asset = new MeshAsset(path);
asset->setStatus(Asset::Status::Loading);
Assimp::Importer importer; Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(path.c_str(), importer.ReadFile(path.string().c_str(),
aiProcess_CalcTangentSpace |
aiProcess_FlipUVs | aiProcess_FlipUVs |
aiProcess_ImproveCacheLocality | aiProcess_ImproveCacheLocality |
aiProcess_OptimizeMeshes | aiProcess_OptimizeMeshes |
aiProcess_GenBoundingBoxes | aiProcess_GenBoundingBoxes |
aiProcessPreset_TargetRealtime_Fast); aiProcess_Triangulate |
aiProcess_SortByPType |
aiProcess_GenSmoothNormals |
aiProcess_GenUVCoords |
aiProcess_FindDegenerates |
aiProcess_EmbedTextures);
const aiScene *scene = importer.ApplyPostProcessing(aiProcess_CalcTangentSpace);
Array<PMesh> globalMeshes(scene->mNumMeshes);
loadGlobalMeshes(scene, globalMeshes, graphics);
loadTextures(scene, graphics, path);
loadMaterials(scene, graphics);
List<aiNode*> meshNodes; List<aiNode *> meshNodes;
findMeshRoots(scene->mRootNode, meshNodes); findMeshRoots(scene->mRootNode, meshNodes);
for(auto meshNode : meshNodes) for (auto meshNode : meshNodes)
{ {
std::cout << "Test:" << meshNode->mNumMeshes << std::endl; std::string fileName = std::string(meshNode->mName.C_Str()).append(".asset");
PMeshAsset meshAsset = new MeshAsset(fileName);
for(uint32 i = 0; i < meshNode->mNumMeshes; ++i)
{
meshAsset->addMesh(globalMeshes[meshNode->mMeshes[i]]);
}
AssetRegistry::get().meshes[meshAsset->getFileName()] = meshAsset;
} }
PMesh mesh = new Mesh(nullptr, nullptr);
asset->setMesh(mesh);
asset->setStatus(Asset::Status::Ready);
} }
+2 -2
View File
@@ -13,9 +13,9 @@ class MeshLoader
public: public:
MeshLoader(Gfx::PGraphics graphic); MeshLoader(Gfx::PGraphics graphic);
~MeshLoader(); ~MeshLoader();
void importAsset(const std::string& filePath); void importAsset(const std::filesystem::path& filePath);
private: private:
void import(const std::string& path); void import(const std::filesystem::path& path);
List<std::future<void>> futures; List<std::future<void>> futures;
Gfx::PGraphics graphics; Gfx::PGraphics graphics;
}; };
+36 -1
View File
@@ -1,5 +1,9 @@
#include "TextureAsset.h" #include "TextureAsset.h"
#include "Graphics/GraphicsResources.h" #include "Graphics/GraphicsResources.h"
#include "Graphics/Graphics.h"
#include "Graphics/WindowManager.h"
#include <stb_image.h>
#include <stb_image_write.h>
using namespace Seele; using namespace Seele;
@@ -11,7 +15,38 @@ TextureAsset::TextureAsset(const std::string& directory, const std::string& name
: Asset(directory, name) : Asset(directory, name)
{ {
} }
TextureAsset::TextureAsset(const std::string& fullPath) TextureAsset::TextureAsset(const std::filesystem::path& fullPath)
: Asset(fullPath) : Asset(fullPath)
{ {
} }
TextureAsset::~TextureAsset()
{
}
void TextureAsset::save()
{
//TODO: make this an actual file, not just a png wrapper
}
void TextureAsset::load()
{
setStatus(Status::Loading);
int x, y, n;
unsigned char* data = stbi_load(getFullPath().c_str(), &x, &y, &n, 4);
TextureCreateInfo createInfo;
//TODO: support other formats
createInfo.format = Gfx::SE_FORMAT_R8G8B8A8_UINT;
createInfo.resourceData.data = data;
createInfo.resourceData.size = x * y * 4 * sizeof(unsigned char);
createInfo.resourceData.owner = Gfx::QueueType::DEDICATED_TRANSFER;
createInfo.width = x;
createInfo.height = y;
Gfx::PTexture2D texture = WindowManager::getGraphics()->createTexture2D(createInfo);
stbi_image_free(data);
texture->transferOwnership(Gfx::QueueType::GRAPHICS);
setTexture(texture);
setStatus(Asset::Status::Ready);
}
+4 -1
View File
@@ -8,7 +8,10 @@ class TextureAsset : public Asset
public: public:
TextureAsset(); TextureAsset();
TextureAsset(const std::string& directory, const std::string& name); TextureAsset(const std::string& directory, const std::string& name);
TextureAsset(const std::string& fullPath); TextureAsset(const std::filesystem::path& fullPath);
virtual ~TextureAsset();
virtual void save() override;
virtual void load() override;
void setTexture(Gfx::PTexture texture) void setTexture(Gfx::PTexture texture)
{ {
std::scoped_lock lck(lock); std::scoped_lock lck(lock);
+12 -24
View File
@@ -4,6 +4,8 @@
#include "AssetRegistry.h" #include "AssetRegistry.h"
#define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h> #include <stb_image.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb_image_write.h>
using namespace Seele; using namespace Seele;
@@ -18,44 +20,30 @@ TextureLoader::~TextureLoader()
{ {
} }
void TextureLoader::importAsset(const std::string& filePath) void TextureLoader::importAsset(const std::filesystem::path& filePath)
{ {
futures.add(std::async(std::launch::async, &TextureLoader::import, this, filePath)); futures.add(std::async(std::launch::async, &TextureLoader::import, this, filePath));
} }
void TextureLoader::import(const std::string& path) void TextureLoader::import(const std::filesystem::path& path)
{ {
PTextureAsset asset = new TextureAsset(path); std::filesystem::path assetPath = path.stem().append(".asset");
AssetRegistry::get().textures[path] = asset; PTextureAsset asset = new TextureAsset(assetPath);
asset->setStatus(Asset::Status::Loading); asset->setStatus(Asset::Status::Loading);
int x, y, n; int x, y, n;
const std::string fullPath = std::string(asset->getFullPath()); const std::string fullPath = std::string(asset->getFullPath());
unsigned char* data = stbi_load(fullPath.c_str(), &x, &y, &n, 0); unsigned char* data = stbi_load(path.string().c_str(), &x, &y, &n, 4);
TextureCreateInfo createInfo; TextureCreateInfo createInfo;
createInfo.format = Gfx::SE_FORMAT_R8G8B8A8_UINT;
createInfo.resourceData.data = data; createInfo.resourceData.data = data;
createInfo.resourceData.size = x * y * n * sizeof(unsigned char); createInfo.resourceData.size = x * y * 4 * sizeof(unsigned char);
createInfo.resourceData.owner = Gfx::QueueType::DEDICATED_TRANSFER;
createInfo.width = x; createInfo.width = x;
createInfo.height = y; createInfo.height = y;
switch (n)
{
case 1:
createInfo.format = Gfx::SE_FORMAT_R8_UINT;
break;
case 2:
createInfo.format = Gfx::SE_FORMAT_R8G8_UINT;
break;
case 3:
createInfo.format = Gfx::SE_FORMAT_R8G8B8_UINT;
break;
case 4:
createInfo.format = Gfx::SE_FORMAT_R8G8B8A8_UINT;
break;
default:
break;
}
createInfo.resourceData.owner = Gfx::QueueType::DEDICATED_TRANSFER;
Gfx::PTexture2D texture = graphics->createTexture2D(createInfo); Gfx::PTexture2D texture = graphics->createTexture2D(createInfo);
stbi_image_free(data);
texture->transferOwnership(Gfx::QueueType::GRAPHICS); texture->transferOwnership(Gfx::QueueType::GRAPHICS);
asset->setTexture(texture); asset->setTexture(texture);
asset->setStatus(Asset::Status::Ready); asset->setStatus(Asset::Status::Ready);
AssetRegistry::get().textures[assetPath.string()] = asset;
} }
+2 -2
View File
@@ -13,9 +13,9 @@ class TextureLoader
public: public:
TextureLoader(Gfx::PGraphics graphic); TextureLoader(Gfx::PGraphics graphic);
~TextureLoader(); ~TextureLoader();
void importAsset(const std::string& filePath); void importAsset(const std::filesystem::path& filePath);
private: private:
void import(const std::string& path); void import(const std::filesystem::path& path);
Gfx::PGraphics graphics; Gfx::PGraphics graphics;
List<std::future<void>> futures; List<std::future<void>> futures;
PTextureAsset placeholderTexture; PTextureAsset placeholderTexture;
+57 -20
View File
@@ -10,16 +10,16 @@
namespace Seele namespace Seele
{ {
template <typename T> template <typename T>
struct Array struct Array
{ {
public: public:
Array() Array()
: allocated(DEFAULT_ALLOC_SIZE), arraySize(0) : allocated(DEFAULT_ALLOC_SIZE), arraySize(0)
{ {
_data = new T[DEFAULT_ALLOC_SIZE]; _data = new T[DEFAULT_ALLOC_SIZE];
assert(_data != nullptr); assert(_data != nullptr);
memset(_data, 0, sizeof(T) * DEFAULT_ALLOC_SIZE); //std::memset(_data, 0, sizeof(T) * DEFAULT_ALLOC_SIZE);
refreshIterators(); refreshIterators();
} }
Array(uint32 size, T value = T()) Array(uint32 size, T value = T())
@@ -190,19 +190,19 @@ public:
} }
return endIt; return endIt;
} }
Iterator begin()
{
return beginIt;
}
Iterator begin() const Iterator begin() const
{ {
return beginIt; return beginIt;
} }
Iterator end() Iterator end() const
{ {
return endIt; return endIt;
} }
Iterator end() const ConstIterator cbegin() const
{
return beginIt;
}
ConstIterator cend() const
{ {
return endIt; return endIt;
} }
@@ -226,6 +226,26 @@ public:
refreshIterators(); refreshIterators();
return _data[arraySize - 1]; return _data[arraySize - 1];
} }
template<typename... args>
T &emplace(args...)
{
if (arraySize == allocated)
{
uint32 newSize = arraySize + 1;
allocated = calculateGrowth(newSize);
T *tempArray = new T[allocated];
assert(tempArray != nullptr);
for (uint32 i = 0; i < arraySize; ++i)
{
tempArray[i] = _data[i];
}
delete[] _data;
_data = tempArray;
}
_data[arraySize++] = T(args...);
refreshIterators();
return _data[arraySize - 1];
}
void remove(Iterator it, bool keepOrder = true) void remove(Iterator it, bool keepOrder = true)
{ {
remove(it - beginIt, keepOrder); remove(it - beginIt, keepOrder);
@@ -287,6 +307,7 @@ public:
void pop() void pop()
{ {
arraySize--; arraySize--;
refreshIterators();
} }
T &operator[](uint32 index) T &operator[](uint32 index)
{ {
@@ -315,7 +336,7 @@ public:
return this->operator[]((uint32)index); return this->operator[]((uint32)index);
} }
private: private:
uint32 calculateGrowth(uint32 newSize) const uint32 calculateGrowth(uint32 newSize) const
{ {
const uint32 oldCapacity = capacity(); const uint32 oldCapacity = capacity();
@@ -344,12 +365,12 @@ private:
Iterator beginIt; Iterator beginIt;
Iterator endIt; Iterator endIt;
T *_data; T *_data;
}; };
template <typename T, uint32 N> template <typename T, uint32 N>
struct StaticArray struct StaticArray
{ {
public: public:
StaticArray() StaticArray()
{ {
beginIt = Iterator(_data); beginIt = Iterator(_data);
@@ -376,7 +397,7 @@ public:
{ {
return _data; return _data;
} }
inline const T* data() const inline const T *data() const
{ {
return _data; return _data;
} }
@@ -443,9 +464,25 @@ public:
typedef IteratorBase<T> Iterator; typedef IteratorBase<T> Iterator;
typedef IteratorBase<const T> ConstIterator; typedef IteratorBase<const T> ConstIterator;
private: Iterator begin()
{
return beginIt;
}
Iterator end()
{
return endIt;
}
ConstIterator begin() const
{
return beginIt;
}
ConstIterator end() const
{
return beginIt;
}
private:
T _data[N]; T _data[N];
Iterator beginIt; Iterator beginIt;
Iterator endIt; Iterator endIt;
}; };
} // namespace Seele } // namespace Seele
+1
View File
@@ -2,6 +2,7 @@
#include "MinimalEngine.h" #include "MinimalEngine.h"
#include "GraphicsResources.h" #include "GraphicsResources.h"
#include "Containers/Array.h" #include "Containers/Array.h"
#include "RenderPass/VertexFactory.h"
namespace Seele namespace Seele
{ {
+1 -1
View File
@@ -5,7 +5,7 @@ namespace Seele
namespace Gfx namespace Gfx
{ {
static constexpr bool useAsyncCompute = true; static constexpr bool useAsyncCompute = true;
static constexpr bool waitIdleOnSubmit = false; static constexpr bool waitIdleOnSubmit = true;
static constexpr uint32 numFramesBuffered = 3; static constexpr uint32 numFramesBuffered = 3;
typedef uint32_t SeFlags; typedef uint32_t SeFlags;
+4 -2
View File
@@ -126,8 +126,10 @@ IndexBuffer::IndexBuffer(PGraphics graphics, uint32 size, Gfx::SeIndexType index
IndexBuffer::~IndexBuffer() IndexBuffer::~IndexBuffer()
{ {
} }
VertexStream::VertexStream(uint32 stride, uint8 instanced) VertexStream::VertexStream()
: stride(stride), instanced(instanced) {}
VertexStream::VertexStream(uint32 stride, uint32 offset, uint8 instanced, Gfx::PVertexBuffer vertexBuffer)
: stride(stride), instanced(instanced), offset(offset), vertexBuffer(vertexBuffer)
{ {
} }
VertexStream::~VertexStream() VertexStream::~VertexStream()
+4 -4
View File
@@ -13,7 +13,7 @@
namespace Seele namespace Seele
{ {
struct VertexInputStream;
namespace Gfx namespace Gfx
{ {
DECLARE_REF(Graphics); DECLARE_REF(Graphics);
@@ -297,8 +297,8 @@ DEFINE_REF(StructuredBuffer);
class VertexStream class VertexStream
{ {
public: public:
VertexStream() {} VertexStream();
VertexStream(uint32 stride, uint8 instanced); VertexStream(uint32 stride, uint32 offset, uint8 instanced, Gfx::PVertexBuffer vertexBuffer);
~VertexStream(); ~VertexStream();
void addVertexElement(VertexElement element); void addVertexElement(VertexElement element);
const Array<VertexElement> getVertexDescriptions() const; const Array<VertexElement> getVertexDescriptions() const;
@@ -363,7 +363,7 @@ public:
virtual ~RenderCommand(); virtual ~RenderCommand();
virtual void bindPipeline(Gfx::PGraphicsPipeline pipeline) = 0; virtual void bindPipeline(Gfx::PGraphicsPipeline pipeline) = 0;
virtual void bindDescriptor(Gfx::PDescriptorSet set) = 0; virtual void bindDescriptor(Gfx::PDescriptorSet set) = 0;
virtual void bindVertexBuffer(Gfx::PVertexBuffer vertexBuffer) = 0; virtual void bindVertexBuffer(const Array<VertexInputStream>& streams) = 0;
virtual void bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) = 0; virtual void bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) = 0;
virtual void draw(const MeshBatchElement& data) = 0; virtual void draw(const MeshBatchElement& data) = 0;
}; };
+2 -2
View File
@@ -2,8 +2,8 @@
using namespace Seele; using namespace Seele;
Mesh::Mesh(Gfx::PVertexBuffer vertexBuffer, Gfx::PIndexBuffer indexBuffer) Mesh::Mesh(MeshDescription description, Gfx::PIndexBuffer indexBuffer)
: vertexBuffer(vertexBuffer) : description(description)
, indexBuffer(indexBuffer) , indexBuffer(indexBuffer)
{ {
} }
+42 -3
View File
@@ -3,15 +3,54 @@
namespace Seele namespace Seele
{ {
#define MAX_TEX_CHANNELS 4
enum class VertexAttribute
{
POSITION,
TEXCOORD,
NORMAL,
TANGENT,
BITANGENT
};
struct MeshDescription
{
Array<VertexAttribute> layout;
Gfx::PVertexDeclaration declaration;
uint32 getStride() const
{
return getNumFloats() * sizeof(float);
}
uint32 getNumFloats() const
{
uint32 vertexSize = 0;
for(auto a : layout)
{
switch (a)
{
case VertexAttribute::POSITION:
case VertexAttribute::NORMAL:
case VertexAttribute::TANGENT:
case VertexAttribute::BITANGENT:
vertexSize += 3;
break;
case VertexAttribute::TEXCOORD:
vertexSize += 2;
break;
}
}
return vertexSize;
}
};
DECLARE_REF(MaterialAsset);
class Mesh class Mesh
{ {
public: public:
Mesh(Gfx::PVertexBuffer vertexBuffer, Gfx::PIndexBuffer indexBuffer); Mesh(MeshDescription description, Gfx::PIndexBuffer indexBuffer);
~Mesh(); ~Mesh();
private:
Gfx::PVertexBuffer vertexBuffer;
Gfx::PIndexBuffer indexBuffer; Gfx::PIndexBuffer indexBuffer;
MeshDescription description;
PMaterialAsset referencedMaterial;
}; };
DEFINE_REF(Mesh); DEFINE_REF(Mesh);
} // namespace Seele } // namespace Seele
+3 -3
View File
@@ -50,11 +50,11 @@ struct MeshBatch
uint8 isCastingShadow : 1; uint8 isCastingShadow : 1;
uint8 useWireframe : 1; uint8 useWireframe : 1;
const Gfx::SePrimitiveTopology topology; Gfx::SePrimitiveTopology topology;
const PVertexFactory vertexFactory; PVertexFactory vertexFactory;
const PMaterial material; PMaterial material;
inline int32 getNumPrimitives() const inline int32 getNumPrimitives() const
{ {
+1
View File
@@ -24,6 +24,7 @@ void Seele::RenderCore::init()
sceneViewInfo.offsetX = 0; sceneViewInfo.offsetX = 0;
sceneViewInfo.offsetY = 0; sceneViewInfo.offsetY = 0;
PSceneView sceneView = new SceneView(windowManager->getGraphics(), window, sceneViewInfo); PSceneView sceneView = new SceneView(windowManager->getGraphics(), window, sceneViewInfo);
window->addView(sceneView);
} }
void Seele::RenderCore::renderLoop() void Seele::RenderCore::renderLoop()
@@ -15,9 +15,11 @@ MeshProcessor::~MeshProcessor()
{ {
} }
void MeshProcessor::buildMeshDrawCommands( void MeshProcessor::buildMeshDrawCommand(
const MeshBatch& meshBatch, const MeshBatch& meshBatch,
const PPrimitiveComponent primitiveComponent, const PPrimitiveComponent primitiveComponent,
const Gfx::PRenderPass renderPass,
Gfx::PRenderCommand drawCommand,
PMaterial material, PMaterial material,
Gfx::PVertexShader vertexShader, Gfx::PVertexShader vertexShader,
Gfx::PControlShader controlShader, Gfx::PControlShader controlShader,
@@ -37,6 +39,7 @@ void MeshProcessor::buildMeshDrawCommands(
pipelineInitializer.evalShader = evaluationShader; pipelineInitializer.evalShader = evaluationShader;
pipelineInitializer.geometryShader = geometryShader; pipelineInitializer.geometryShader = geometryShader;
pipelineInitializer.fragmentShader = fragmentShader; pipelineInitializer.fragmentShader = fragmentShader;
pipelineInitializer.renderPass = renderPass;
VertexInputStreamArray vertexStreams; VertexInputStreamArray vertexStreams;
if(positionOnly) if(positionOnly)
@@ -47,8 +50,12 @@ void MeshProcessor::buildMeshDrawCommands(
{ {
vertexFactory->getStreams(vertexStreams); vertexFactory->getStreams(vertexStreams);
} }
if(vertexShader != nullptr) drawCommand->bindVertexBuffer(vertexStreams);
Gfx::PGraphicsPipeline pipeline = graphics->createGraphicsPipeline(pipelineInitializer);
drawCommand->bindPipeline(pipeline);
for(auto element : meshBatch.elements)
{ {
drawCommand->bindIndexBuffer(element.indexBuffer);
drawCommand->draw(element);
} }
} }
@@ -18,9 +18,11 @@ private:
const MeshBatch& meshBatch, const MeshBatch& meshBatch,
const PPrimitiveComponent primitiveComponent, const PPrimitiveComponent primitiveComponent,
int32 staticMeshId = -1) = 0; int32 staticMeshId = -1) = 0;
void buildMeshDrawCommands( void buildMeshDrawCommand(
const MeshBatch& meshBatch, const MeshBatch& meshBatch,
const PPrimitiveComponent primitiveComponent, const PPrimitiveComponent primitiveComponent,
const Gfx::PRenderPass renderPass,
Gfx::PRenderCommand drawCommand,
PMaterial material, PMaterial material,
Gfx::PVertexShader vertexShader, Gfx::PVertexShader vertexShader,
Gfx::PControlShader controlShader, Gfx::PControlShader controlShader,
@@ -1,7 +1,44 @@
#include "VertexFactory.h" #include "VertexFactory.h"
#include "Graphics/Mesh.h"
#include <memory>
using namespace Seele; using namespace Seele;
List<PVertexFactory> VertexFactory::registeredVertexFactories;
std::mutex VertexFactory::registeredVertexFactoryLock;
VertexFactory::VertexFactory()
{
std::scoped_lock lock(registeredVertexFactoryLock);
registeredVertexFactories.add(this);
}
VertexFactory::VertexFactory(MeshDescription description)
: declaration(description.declaration)
{
auto declStreams = declaration->getVertexStreams();
std::copy(declStreams.begin(), declStreams.end(), streams.begin());
uint32 positionStreamIndex = 0;
positionDeclaration = new Gfx::VertexDeclaration();
for (uint32 i = 0; i < declStreams.size(); i++)
{
if(description.layout[i] == VertexAttribute::POSITION)
{
positionStream[positionStreamIndex++] = declStreams[i];
positionDeclaration->addVertexStream(declStreams[i]);
}
}
std::scoped_lock lock(registeredVertexFactoryLock);
registeredVertexFactories.add(this);
}
VertexFactory::~VertexFactory()
{
registeredVertexFactories.remove(registeredVertexFactories.find(this));
}
void VertexFactory::getStreams(VertexInputStreamArray& outVertexStreams) const void VertexFactory::getStreams(VertexInputStreamArray& outVertexStreams) const
{ {
for(uint32 i = 0; i < streams.size(); ++i) for(uint32 i = 0; i < streams.size(); ++i)
@@ -35,7 +35,7 @@ struct VertexInputStream
} }
}; };
struct VertexStreamComponent /*struct VertexStreamComponent
{ {
const Gfx::PVertexBuffer vertexBuffer = nullptr; const Gfx::PVertexBuffer vertexBuffer = nullptr;
@@ -68,21 +68,25 @@ struct VertexStreamComponent
, type(type) , type(type)
{ {
} }
}; };*/
typedef Array<VertexInputStream> VertexInputStreamArray; typedef Array<VertexInputStream> VertexInputStreamArray;
struct MeshDescription;
DECLARE_REF(VertexFactory);
class VertexFactory class VertexFactory
{ {
public: public:
VertexFactory() VertexFactory();
{ VertexFactory(MeshDescription description);
} ~VertexFactory();
void getStreams(VertexInputStreamArray& outVertexStreams) const; void getStreams(VertexInputStreamArray& outVertexStreams) const;
void getPositionOnlyStream(VertexInputStreamArray& outVertexStreams) const; void getPositionOnlyStream(VertexInputStreamArray& outVertexStreams) const;
virtual bool supportsTesselation() { return false; } virtual bool supportsTesselation() { return false; }
Gfx::PVertexDeclaration getDeclaration() const {return declaration;} Gfx::PVertexDeclaration getDeclaration() const {return declaration;}
Gfx::PVertexDeclaration getPositionDeclaration() const {return positionDeclaration;} Gfx::PVertexDeclaration getPositionDeclaration() const {return positionDeclaration;}
private: private:
static List<PVertexFactory> registeredVertexFactories;
static std::mutex registeredVertexFactoryLock;
StaticArray<Gfx::VertexStream, 16> streams; StaticArray<Gfx::VertexStream, 16> streams;
StaticArray<Gfx::VertexStream, 16> positionStream; StaticArray<Gfx::VertexStream, 16> positionStream;
Gfx::PVertexDeclaration declaration; Gfx::PVertexDeclaration declaration;
+5
View File
@@ -1,12 +1,17 @@
#include "SceneRenderPath.h" #include "SceneRenderPath.h"
#include "Scene/Scene.h" #include "Scene/Scene.h"
#include "Material/Material.h" #include "Material/Material.h"
#include "Asset/AssetRegistry.h"
using namespace Seele; using namespace Seele;
SceneRenderPath::SceneRenderPath(Gfx::PGraphics graphics, Gfx::PViewport target) SceneRenderPath::SceneRenderPath(Gfx::PGraphics graphics, Gfx::PViewport target)
: RenderPath(graphics, target) : RenderPath(graphics, target)
{ {
scene = new Scene();
PMeshAsset asset = AssetRegistry::findMesh("Unbenannt");
PActor rootActor = new Actor();
PPrimitiveComponent primitiveComponent = new PrimitiveComponent();
} }
SceneRenderPath::~SceneRenderPath() SceneRenderPath::~SceneRenderPath()
+1
View File
@@ -1,5 +1,6 @@
#include "SceneView.h" #include "SceneView.h"
#include "SceneRenderPath.h" #include "SceneRenderPath.h"
#include "Scene/Scene.h"
#include "Window.h" #include "Window.h"
Seele::SceneView::SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo &createInfo) Seele::SceneView::SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo &createInfo)
+1 -1
View File
@@ -129,7 +129,7 @@ void Buffer::executeOwnershipBarrier(Gfx::QueueType newOwner)
dynamicBarriers[i] = barrier; dynamicBarriers[i] = barrier;
dynamicBarriers[i].buffer = buffers[i].buffer; dynamicBarriers[i].buffer = buffers[i].buffer;
dynamicBarriers[i].offset = 0; dynamicBarriers[i].offset = 0;
dynamicBarriers[i].size = buffers[i].allocation->getSize(); dynamicBarriers[i].size = size;
} }
vkCmdPipelineBarrier(srcCommand, srcStage, dstStage, 0, 0, nullptr, numBuffers, dynamicBarriers, 0, nullptr); vkCmdPipelineBarrier(srcCommand, srcStage, dstStage, 0, 0, nullptr, numBuffers, dynamicBarriers, 0, nullptr);
vkCmdPipelineBarrier(dstCommand, srcStage, dstStage, 0, 0, nullptr, numBuffers, dynamicBarriers, 0, nullptr); vkCmdPipelineBarrier(dstCommand, srcStage, dstStage, 0, 0, nullptr, numBuffers, dynamicBarriers, 0, nullptr);
@@ -163,12 +163,17 @@ void SecondaryCmdBuffer::bindDescriptor(Gfx::PDescriptorSet descriptorSet)
VkDescriptorSet setHandle = descriptorSet.cast<DescriptorSet>()->getHandle(); VkDescriptorSet setHandle = descriptorSet.cast<DescriptorSet>()->getHandle();
vkCmdBindDescriptorSets(handle, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->getLayout(), descriptorSet->getSetIndex(), 1, &setHandle, 0, nullptr); vkCmdBindDescriptorSets(handle, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->getLayout(), descriptorSet->getSetIndex(), 1, &setHandle, 0, nullptr);
} }
void SecondaryCmdBuffer::bindVertexBuffer(Gfx::PVertexBuffer vertexBuffer) void SecondaryCmdBuffer::bindVertexBuffer(const Array<VertexInputStream>& streams)
{ {
PVertexBuffer buf = vertexBuffer.cast<VertexBuffer>(); Array<VkBuffer> buffers(streams.size());
const VkBuffer bufHandle[1] = {buf->getHandle()}; Array<VkDeviceSize> offsets(streams.size());
const VkDeviceSize offsets[1] = {0}; for(uint32 i = 0; i < streams.size(); ++i)
vkCmdBindVertexBuffers(handle, 0, 1, bufHandle, offsets); {
PVertexBuffer buf = streams[i].vertexBuffer.cast<VertexBuffer>();
buffers[i] = buf->getHandle();
offsets[i] = streams[i].offset;
};
vkCmdBindVertexBuffers(handle, 0, streams.size(), buffers.data(), offsets.data());
} }
void SecondaryCmdBuffer::bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) void SecondaryCmdBuffer::bindIndexBuffer(Gfx::PIndexBuffer indexBuffer)
{ {
@@ -181,7 +186,7 @@ void SecondaryCmdBuffer::draw(const MeshBatchElement& data)
} }
CommandBufferManager::CommandBufferManager(PGraphics graphics, PQueue queue) CommandBufferManager::CommandBufferManager(PGraphics graphics, PQueue queue)
: graphics(graphics), queue(queue) : graphics(graphics), queue(queue), queueFamilyIndex(queue->getFamilyIndex())
{ {
VkCommandPoolCreateInfo info = VkCommandPoolCreateInfo info =
init::CommandPoolCreateInfo(); init::CommandPoolCreateInfo();
@@ -4,6 +4,7 @@
namespace Seele namespace Seele
{ {
struct VertexInputStream;
namespace Vulkan namespace Vulkan
{ {
DECLARE_REF(RenderPass); DECLARE_REF(RenderPass);
@@ -75,7 +76,7 @@ public:
void end(); void end();
virtual void bindPipeline(Gfx::PGraphicsPipeline pipeline) override; virtual void bindPipeline(Gfx::PGraphicsPipeline pipeline) override;
virtual void bindDescriptor(Gfx::PDescriptorSet descriptorSet) override; virtual void bindDescriptor(Gfx::PDescriptorSet descriptorSet) override;
virtual void bindVertexBuffer(Gfx::PVertexBuffer vertexBuffer) override; virtual void bindVertexBuffer(const Array<VertexInputStream>& streams) override;
virtual void bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) override; virtual void bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) override;
virtual void draw(const MeshBatchElement& data) override; virtual void draw(const MeshBatchElement& data) override;
+40 -23
View File
@@ -21,12 +21,6 @@ Graphics::Graphics()
Graphics::~Graphics() Graphics::~Graphics()
{ {
allocator = nullptr;
stagingManager = nullptr;
graphicsCommands = nullptr;
computeCommands = nullptr;
transferCommands = nullptr;
dedicatedTransferCommands = nullptr;
viewports.clear(); viewports.clear();
vkDestroyDevice(handle, nullptr); vkDestroyDevice(handle, nullptr);
DestroyDebugReportCallbackEXT(instance, nullptr, callback); DestroyDebugReportCallbackEXT(instance, nullptr, callback);
@@ -41,10 +35,6 @@ void Graphics::init(GraphicsInitializer initInfo)
createDevice(initInfo); createDevice(initInfo);
allocator = new Allocator(this); allocator = new Allocator(this);
stagingManager = new StagingManager(this, allocator); stagingManager = new StagingManager(this, allocator);
graphicsCommands = new CommandBufferManager(this, graphicsQueue);
computeCommands = new CommandBufferManager(this, computeQueue);
transferCommands = new CommandBufferManager(this, transferQueue);
dedicatedTransferCommands = new CommandBufferManager(this, dedicatedTransferQueue);
pipelineCache = new PipelineCache(this, "pipeline.cache"); pipelineCache = new PipelineCache(this, "pipeline.cache");
} }
@@ -79,12 +69,12 @@ void Graphics::beginRenderPass(Gfx::PRenderPass renderPass)
{ {
framebuffer = found->value; framebuffer = found->value;
} }
graphicsCommands->getCommands()->beginRenderPass(rp, framebuffer); getGraphicsCommands()->getCommands()->beginRenderPass(rp, framebuffer);
} }
void Graphics::endRenderPass() void Graphics::endRenderPass()
{ {
graphicsCommands->getCommands()->endRenderPass(); getGraphicsCommands()->getCommands()->endRenderPass();
} }
void Graphics::executeCommands(Array<Gfx::PRenderCommand> commands) void Graphics::executeCommands(Array<Gfx::PRenderCommand> commands)
@@ -96,7 +86,7 @@ void Graphics::executeCommands(Array<Gfx::PRenderCommand> commands)
buf->end(); buf->end();
cmdBuffers[i] = buf->getHandle(); cmdBuffers[i] = buf->getHandle();
} }
vkCmdExecuteCommands(graphicsCommands->getCommands()->getHandle(), cmdBuffers.size(), cmdBuffers.data()); vkCmdExecuteCommands(getGraphicsCommands()->getCommands()->getHandle(), cmdBuffers.size(), cmdBuffers.data());
} }
Gfx::PTexture2D Graphics::createTexture2D(const TextureCreateInfo &createInfo) Gfx::PTexture2D Graphics::createTexture2D(const TextureCreateInfo &createInfo)
@@ -129,7 +119,7 @@ Gfx::PIndexBuffer Graphics::createIndexBuffer(const IndexBufferCreateInfo &bulkD
} }
Gfx::PRenderCommand Graphics::createRenderCommand() Gfx::PRenderCommand Graphics::createRenderCommand()
{ {
PSecondaryCmdBuffer cmdBuffer = graphicsCommands->createSecondaryCmdBuffer(); PSecondaryCmdBuffer cmdBuffer = getGraphicsCommands()->createSecondaryCmdBuffer();
cmdBuffer->begin(getGraphicsCommands()->getCommands()); cmdBuffer->begin(getGraphicsCommands()->getCommands());
return cmdBuffer; return cmdBuffer;
} }
@@ -199,33 +189,60 @@ PCommandBufferManager Graphics::getQueueCommands(Gfx::QueueType queueType)
switch (queueType) switch (queueType)
{ {
case Gfx::QueueType::GRAPHICS: case Gfx::QueueType::GRAPHICS:
return graphicsCommands; return getGraphicsCommands();
case Gfx::QueueType::COMPUTE: case Gfx::QueueType::COMPUTE:
return computeCommands; return getComputeCommands();
case Gfx::QueueType::TRANSFER: case Gfx::QueueType::TRANSFER:
return transferCommands; return getTransferCommands();
case Gfx::QueueType::DEDICATED_TRANSFER: case Gfx::QueueType::DEDICATED_TRANSFER:
return dedicatedTransferCommands; return getDedicatedTransferCommands();
default: default:
throw new std::logic_error("invalid queue type"); throw new std::logic_error("invalid queue type");
} }
} }
std::mutex graphicsCommandLock;
PCommandBufferManager Graphics::getGraphicsCommands() PCommandBufferManager Graphics::getGraphicsCommands()
{ {
return graphicsCommands; std::scoped_lock lock(graphicsCommandLock);
auto id = std::this_thread::get_id();
if(graphicsCommands.find(id) == graphicsCommands.end())
{
graphicsCommands[id] = new CommandBufferManager(this, graphicsQueue);
}
return graphicsCommands[id];
} }
std::mutex computeCommandLock;
PCommandBufferManager Graphics::getComputeCommands() PCommandBufferManager Graphics::getComputeCommands()
{ {
return computeCommands; std::scoped_lock lock(computeCommandLock);
auto id = std::this_thread::get_id();
if(computeCommands.find(id) == computeCommands.end())
{
computeCommands[id] = new CommandBufferManager(this, computeQueue);
}
return computeCommands[id];
} }
std::mutex transferCommandLock;
PCommandBufferManager Graphics::getTransferCommands() PCommandBufferManager Graphics::getTransferCommands()
{ {
return transferCommands; std::scoped_lock lock(transferCommandLock);
auto id = std::this_thread::get_id();
if(transferCommands.find(id) == transferCommands.end())
{
transferCommands[id] = new CommandBufferManager(this, transferQueue);
}
return transferCommands[id];
} }
std::mutex dedicatedCommandLock;
PCommandBufferManager Graphics::getDedicatedTransferCommands() PCommandBufferManager Graphics::getDedicatedTransferCommands()
{ {
return dedicatedTransferCommands; std::scoped_lock lock(dedicatedCommandLock);
auto id = std::this_thread::get_id();
if(dedicatedTransferCommands.find(id) == dedicatedTransferCommands.end())
{
dedicatedTransferCommands[id] = new CommandBufferManager(this, dedicatedTransferQueue);
}
return dedicatedTransferCommands[id];
} }
PAllocator Graphics::getAllocator() PAllocator Graphics::getAllocator()
{ {
+4 -4
View File
@@ -80,10 +80,10 @@ protected:
PQueue dedicatedTransferQueue; PQueue dedicatedTransferQueue;
QueueOwnedResourceDeletion deletionQueue; QueueOwnedResourceDeletion deletionQueue;
PPipelineCache pipelineCache; PPipelineCache pipelineCache;
PCommandBufferManager graphicsCommands; Map<std::thread::id, PCommandBufferManager> graphicsCommands;
PCommandBufferManager computeCommands; Map<std::thread::id, PCommandBufferManager> computeCommands;
PCommandBufferManager transferCommands; Map<std::thread::id, PCommandBufferManager> transferCommands;
PCommandBufferManager dedicatedTransferCommands; Map<std::thread::id, PCommandBufferManager> dedicatedTransferCommands;
VkPhysicalDeviceProperties props; VkPhysicalDeviceProperties props;
VkPhysicalDeviceFeatures features; VkPhysicalDeviceFeatures features;
VkDebugReportCallbackEXT callback; VkDebugReportCallbackEXT callback;
@@ -78,6 +78,7 @@ TextureHandle::TextureHandle(PGraphics graphics, VkImageViewType viewType,
default: default:
break; break;
} }
info.initialLayout = layout; info.initialLayout = layout;
info.mipLevels = mipLevels; info.mipLevels = mipLevels;
info.arrayLayers = arrayCount * layerCount; info.arrayLayers = arrayCount * layerCount;
+1 -1
View File
@@ -15,7 +15,7 @@ Material::Material(const std::string& directory, const std::string& name)
{ {
} }
Material::Material(const std::string& fullPath) Material::Material(const std::filesystem::path& fullPath)
: MaterialAsset(fullPath) : MaterialAsset(fullPath)
{ {
} }
+2 -1
View File
@@ -10,12 +10,13 @@ class Material : public MaterialAsset
public: public:
Material(); Material();
Material(const std::string &directory, const std::string &name); Material(const std::string &directory, const std::string &name);
Material(const std::string &fullPath); Material(const std::filesystem::path& fullPath);
~Material(); ~Material();
inline std::string getMaterialName() const {return materialName;} inline std::string getMaterialName() const {return materialName;}
private: private:
void compile(); void compile();
std::string materialName; std::string materialName;
Array<std::string> materialCode;
friend class MaterialLoader; friend class MaterialLoader;
}; };
DEFINE_REF(Material); DEFINE_REF(Material);
+1 -1
View File
@@ -11,7 +11,7 @@ MaterialAsset::MaterialAsset(const std::string& directory, const std::string& na
{ {
} }
MaterialAsset::MaterialAsset(const std::string& fullPath) MaterialAsset::MaterialAsset(const std::filesystem::path& fullPath)
: Asset(fullPath) : Asset(fullPath)
{ {
} }
+1 -1
View File
@@ -9,7 +9,7 @@ class MaterialAsset : public Asset
public: public:
MaterialAsset(); MaterialAsset();
MaterialAsset(const std::string &directory, const std::string &name); MaterialAsset(const std::string &directory, const std::string &name);
MaterialAsset(const std::string &fullPath); MaterialAsset(const std::filesystem::path &fullPath);
~MaterialAsset(); ~MaterialAsset();
protected: protected:
//For now its simply the collection of parameters, since there is no point for expressions //For now its simply the collection of parameters, since there is no point for expressions
+5
View File
@@ -17,6 +17,11 @@ MaterialInstance::MaterialInstance(const std::string& fullPath)
{ {
} }
MaterialInstance::MaterialInstance(const std::filesystem::path& fullPath)
: Asset(fullPath)
{
}
MaterialInstance::~MaterialInstance() MaterialInstance::~MaterialInstance()
{ {
} }
+1
View File
@@ -11,6 +11,7 @@ public:
MaterialInstance(); MaterialInstance();
MaterialInstance(const std::string& directory, const std::string& name); MaterialInstance(const std::string& directory, const std::string& name);
MaterialInstance(const std::string& fullPath); MaterialInstance(const std::string& fullPath);
MaterialInstance(const std::filesystem::path& fullPath);
~MaterialInstance(); ~MaterialInstance();
PMaterial getBaseMaterial() const; PMaterial getBaseMaterial() const;
Gfx::PDescriptorSet getDescriptor(); Gfx::PDescriptorSet getDescriptor();
+1
View File
@@ -1,3 +1,4 @@
#include "MinimalEngine.h" #include "MinimalEngine.h"
Seele::Map<void *, void *> registeredObjects; Seele::Map<void *, void *> registeredObjects;
std::mutex registeredObjectsLock;
+2
View File
@@ -25,6 +25,7 @@
} }
extern Seele::Map<void *, void *> registeredObjects; extern Seele::Map<void *, void *> registeredObjects;
extern std::mutex registeredObjectsLock;
namespace Seele namespace Seele
{ {
template <typename T> template <typename T>
@@ -34,6 +35,7 @@ public:
RefObject(T *ptr) RefObject(T *ptr)
: handle(ptr), refCount(1) : handle(ptr), refCount(1)
{ {
std::scoped_lock lock(registeredObjectsLock);
registeredObjects[ptr] = this; registeredObjects[ptr] = this;
} }
RefObject(const RefObject &rhs) RefObject(const RefObject &rhs)
@@ -1,6 +1,8 @@
#include "PrimitiveComponent.h" #include "PrimitiveComponent.h"
#include "Scene/Scene.h" #include "Scene/Scene.h"
#include "Material/MaterialInstance.h" #include "Material/MaterialInstance.h"
#include "Asset/MeshAsset.h"
#include "Graphics/RenderPass/VertexFactory.h"
using namespace Seele; using namespace Seele;
@@ -8,6 +10,10 @@ PrimitiveComponent::PrimitiveComponent()
{ {
} }
PrimitiveComponent::PrimitiveComponent(PMeshAsset asset)
{
}
PrimitiveComponent::~PrimitiveComponent() PrimitiveComponent::~PrimitiveComponent()
{ {
} }
@@ -2,24 +2,25 @@
#include "Component.h" #include "Component.h"
#include "Graphics/GraphicsResources.h" #include "Graphics/GraphicsResources.h"
#include "Graphics/Mesh.h" #include "Graphics/Mesh.h"
#include "Material/MaterialInstance.h" #include "Material/MaterialAsset.h"
#include "Graphics/MeshBatch.h" #include "Graphics/MeshBatch.h"
namespace Seele namespace Seele
{ {
DECLARE_REF(MeshAsset);
class PrimitiveComponent : public Component class PrimitiveComponent : public Component
{ {
public: public:
PrimitiveComponent(); PrimitiveComponent();
PrimitiveComponent(PMeshAsset asset);
~PrimitiveComponent(); ~PrimitiveComponent();
virtual void notifySceneAttach(PScene scene) override; virtual void notifySceneAttach(PScene scene) override;
Matrix4 getRenderMatrix(); Matrix4 getRenderMatrix();
private: private:
Array<PMaterialInstance> materials; Array<PMaterialAsset> materials;
Gfx::PUniformBuffer uniformBuffer; Gfx::PUniformBuffer uniformBuffer;
Array<StaticMeshBatch> staticMeshes; Array<StaticMeshBatch> staticMeshes;
PMesh mesh;
friend class Scene; friend class Scene;
}; };
DEFINE_REF(PrimitiveComponent); DEFINE_REF(PrimitiveComponent);
+3 -19
View File
@@ -32,31 +32,15 @@ void Scene::addPrimitiveComponent(PPrimitiveComponent comp)
primitives.add(comp); primitives.add(comp);
} }
Map<PMaterial, MeshBatch> Scene::getMeshBatches() Array<MeshBatch> Scene::getMeshBatches()
{ {
meshBatches.clear(); meshBatches.clear();
for (auto primitive : primitives) for (auto primitive : primitives)
{ {
/* Array<PMaterial> materials = primitive->materials; for(auto batch : primitive->staticMeshes)
PMaterialInstance matInstance = primitive->;
PMaterial mat = matInstance->getBaseMaterial();
MeshBatch inst;
inst.instance = primitive->instance;
inst.vertexBuffer = primitive->vertexBuffer;
inst.indexBuffer = primitive->indexBuffer;
inst.modelMatrix = primitive->getRenderMatrix();
if (meshBatches.find(mat) != meshBatches.end())
{ {
MeshBatchElement &state = meshBatches[mat]; meshBatches.add(batch);
state.instances.add(inst);
} }
else
{
MeshBatchElement state;
state.instances.add(inst);
meshBatches[mat] = state;
}*/
} }
return meshBatches; return meshBatches;
} }
+2 -2
View File
@@ -20,11 +20,11 @@ public:
void addPrimitiveComponent(PPrimitiveComponent comp); void addPrimitiveComponent(PPrimitiveComponent comp);
private: private:
Map<PMaterial, MeshBatch> meshBatches; Array<MeshBatch> meshBatches;
Array<PActor> rootActors; Array<PActor> rootActors;
Array<PPrimitiveComponent> primitives; Array<PPrimitiveComponent> primitives;
const static int constant = 10; const static int constant = 10;
public: public:
Map<PMaterial, MeshBatch> getMeshBatches(); Array<MeshBatch> getMeshBatches();
}; };
} // namespace Seele } // namespace Seele
+2 -2
View File
@@ -5,8 +5,8 @@ int main()
{ {
RenderCore core; RenderCore core;
core.init(); core.init();
AssetRegistry::init("./"); AssetRegistry::init("D:\\Private\\Programming\\C++\\TestSeeleProject");
AssetRegistry::importFile("D:\\Private\\Programming\\Unreal Engine\\Assets\\TestAssets\\Unbenannt.fbx"); AssetRegistry::importFile("D:\\Private\\Programming\\Unreal Engine\\Assets\\Arissa\\Arissa.fbx");
core.renderLoop(); core.renderLoop();
core.shutdown(); core.shutdown();
return 0; return 0;