diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..5a4cbb1 --- /dev/null +++ b/.clang-format @@ -0,0 +1,6 @@ +BasedOnStyle: LLVM +IndentWidth: 4 +Language: Cpp +ColumnLimit: 140 +DerivePointerAlignment: false +PointerAlignment: Left \ No newline at end of file diff --git a/src/AssetViewer/main.cpp b/src/AssetViewer/main.cpp index b7ddebe..2ec84db 100644 --- a/src/AssetViewer/main.cpp +++ b/src/AssetViewer/main.cpp @@ -1,23 +1,23 @@ #include "Asset/Asset.h" -#include "Asset/MeshAsset.h" +#include "Asset/AssetRegistry.h" #include "Asset/FontAsset.h" -#include "Asset/TextureAsset.h" #include "Asset/MaterialAsset.h" #include "Asset/MaterialInstanceAsset.h" -#include "Asset/AssetRegistry.h" +#include "Asset/MeshAsset.h" +#include "Asset/TextureAsset.h" #include #include + using namespace Seele; -AssetRegistry * _instance = new AssetRegistry(); +AssetRegistry* _instance = new AssetRegistry(); -int main(int, char**) -{ - //if(argc < 2) +int main(int, char**) { + // if(argc < 2) //{ - // return -1; - //} + // return -1; + // } std::filesystem::path path = std::filesystem::path("C:\\Users\\Dynamitos\\TrackClear\\Assets\\Dirt.asset"); std::ifstream stream = std::ifstream(path, std::ios::binary); @@ -37,8 +37,7 @@ int main(int, char**) Serialization::load(buffer, folderPath); PAsset asset; - switch (identifier) - { + switch (identifier) { case TextureAsset::IDENTIFIER: asset = new TextureAsset(folderPath, name); break; diff --git a/src/Editor/Asset/AssetImporter.cpp b/src/Editor/Asset/AssetImporter.cpp index 420f052..d7de0e9 100644 --- a/src/Editor/Asset/AssetImporter.cpp +++ b/src/Editor/Asset/AssetImporter.cpp @@ -1,54 +1,46 @@ #include "AssetImporter.h" #include "FontLoader.h" -#include "TextureLoader.h" +#include "Graphics/Graphics.h" #include "MaterialLoader.h" #include "MeshLoader.h" -#include "Graphics/Graphics.h" +#include "TextureLoader.h" + using namespace Seele; -void AssetImporter::importMesh(MeshImportArgs args) -{ - if (get().registry->getOrCreateFolder(args.importPath)->meshes.contains(args.filePath.stem().string())) - { +void AssetImporter::importMesh(MeshImportArgs args) { + if (get().registry->getOrCreateFolder(args.importPath)->meshes.contains(args.filePath.stem().string())) { // skip importing duplicates return; } get().meshLoader->importAsset(args); } -void AssetImporter::importTexture(TextureImportArgs args) -{ - if (get().registry->getOrCreateFolder(args.importPath)->textures.contains(args.filePath.stem().string())) - { +void AssetImporter::importTexture(TextureImportArgs args) { + if (get().registry->getOrCreateFolder(args.importPath)->textures.contains(args.filePath.stem().string())) { // skip importing duplicates return; } get().textureLoader->importAsset(args); } -void AssetImporter::importFont(FontImportArgs args) -{ - if (get().registry->getOrCreateFolder(args.importPath)->fonts.contains(args.filePath.stem().string())) - { +void AssetImporter::importFont(FontImportArgs args) { + if (get().registry->getOrCreateFolder(args.importPath)->fonts.contains(args.filePath.stem().string())) { // skip importing duplicates return; } get().fontLoader->importAsset(args); } -void AssetImporter::importMaterial(MaterialImportArgs args) -{ - if (get().registry->getOrCreateFolder(args.importPath)->materials.contains(args.filePath.stem().string())) - { +void AssetImporter::importMaterial(MaterialImportArgs args) { + if (get().registry->getOrCreateFolder(args.importPath)->materials.contains(args.filePath.stem().string())) { // skip importing duplicates return; } get().materialLoader->importAsset(args); } -void AssetImporter::init(Gfx::PGraphics graphics) -{ +void AssetImporter::init(Gfx::PGraphics graphics) { get().registry = AssetRegistry::getInstance(); get().meshLoader = new MeshLoader(graphics); get().textureLoader = new TextureLoader(graphics); @@ -56,9 +48,7 @@ void AssetImporter::init(Gfx::PGraphics graphics) get().fontLoader = new FontLoader(graphics); } -AssetImporter& AssetImporter::get() -{ +AssetImporter& AssetImporter::get() { static AssetImporter instance; return instance; } - diff --git a/src/Editor/Asset/AssetImporter.h b/src/Editor/Asset/AssetImporter.h index 52e8429..6f3fb22 100644 --- a/src/Editor/Asset/AssetImporter.h +++ b/src/Editor/Asset/AssetImporter.h @@ -1,22 +1,22 @@ #pragma once -#include "MinimalEngine.h" #include "Asset/AssetRegistry.h" +#include "MinimalEngine.h" -namespace Seele -{ + +namespace Seele { DECLARE_REF(TextureLoader) DECLARE_REF(FontLoader) DECLARE_REF(MeshLoader) DECLARE_REF(MaterialLoader) -class AssetImporter -{ -public: +class AssetImporter { + public: static void importMesh(struct MeshImportArgs args); static void importTexture(struct TextureImportArgs args); static void importFont(struct FontImportArgs args); static void importMaterial(struct MaterialImportArgs args); static void init(Gfx::PGraphics graphics); -private: + + private: static AssetImporter& get(); UPTextureLoader textureLoader; UPFontLoader fontLoader; diff --git a/src/Editor/Asset/FontLoader.cpp b/src/Editor/Asset/FontLoader.cpp index 358e774..6caeefa 100644 --- a/src/Editor/Asset/FontLoader.cpp +++ b/src/Editor/Asset/FontLoader.cpp @@ -1,28 +1,23 @@ #include "FontLoader.h" -#include "Graphics/Graphics.h" -#include "Asset/FontAsset.h" #include "Asset/AssetRegistry.h" +#include "Asset/FontAsset.h" +#include "Graphics/Graphics.h" #include "Graphics/Resources.h" #include "Graphics/Texture.h" #include + #include FT_FREETYPE_H -#include #include +#include + using namespace Seele; -FontLoader::FontLoader(Gfx::PGraphics graphics) - : graphics(graphics) -{ - -} +FontLoader::FontLoader(Gfx::PGraphics graphics) : graphics(graphics) {} -FontLoader::~FontLoader() -{ -} +FontLoader::~FontLoader() {} -void FontLoader::importAsset(FontImportArgs args) -{ +void FontLoader::importAsset(FontImportArgs args) { std::filesystem::path assetPath = args.filePath.filename(); assetPath.replace_extension("asset"); OFontAsset asset = new FontAsset(args.importPath, assetPath.stem().string()); @@ -36,8 +31,7 @@ void FontLoader::importAsset(FontImportArgs args) // in case of the space character there is no bitmap // so we create a single pixel empty texture uint8 transparentPixel = 0; -void FontLoader::import(FontImportArgs args, PFontAsset asset) -{ +void FontLoader::import(FontImportArgs args, PFontAsset asset) { FT_Library ft; FT_Error error = FT_Init_FreeType(&ft); assert(!error); @@ -46,10 +40,8 @@ void FontLoader::import(FontImportArgs args, PFontAsset asset) assert(!error); FT_Set_Pixel_Sizes(face, 0, 48); Array usedTextures; - for(uint32 c = 0; c < 256; ++c) - { - if(FT_Load_Char(face, c, FT_LOAD_RENDER)) - { + for (uint32 c = 0; c < 256; ++c) { + if (FT_Load_Char(face, c, FT_LOAD_RENDER)) { std::cout << "error loading " << (char)c << std::endl; continue; } @@ -63,8 +55,7 @@ void FontLoader::import(FontImportArgs args, PFontAsset asset) imageData.height = face->glyph->bitmap.rows; imageData.sourceData.data = face->glyph->bitmap.buffer; imageData.sourceData.size = imageData.width * imageData.height; - if(imageData.width == 0 || imageData.height == 0) - { + if (imageData.width == 0 || imageData.height == 0) { glyph.size.x = 1; glyph.size.y = 1; glyph.bearing.x = 0; @@ -81,7 +72,8 @@ void FontLoader::import(FontImportArgs args, PFontAsset asset) FT_Done_FreeType(ft); asset->setUsedTextures(std::move(usedTextures)); - auto stream = AssetRegistry::createWriteStream((std::filesystem::path(asset->getFolderPath()) / asset->getName()).replace_extension("asset").string(), std::ios::binary); + auto stream = AssetRegistry::createWriteStream( + (std::filesystem::path(asset->getFolderPath()) / asset->getName()).replace_extension("asset").string(), std::ios::binary); ArchiveBuffer archive; Serialization::save(archive, FontAsset::IDENTIFIER); diff --git a/src/Editor/Asset/FontLoader.h b/src/Editor/Asset/FontLoader.h index 9c8b289..1daabe9 100644 --- a/src/Editor/Asset/FontLoader.h +++ b/src/Editor/Asset/FontLoader.h @@ -1,24 +1,23 @@ #pragma once -#include "MinimalEngine.h" #include "Containers/List.h" +#include "MinimalEngine.h" #include -namespace Seele -{ + +namespace Seele { DECLARE_REF(FontAsset) DECLARE_NAME_REF(Gfx, Graphics) -struct FontImportArgs -{ +struct FontImportArgs { std::filesystem::path filePath; std::string importPath; }; -class FontLoader -{ -public: +class FontLoader { + public: FontLoader(Gfx::PGraphics graphic); ~FontLoader(); void importAsset(FontImportArgs args); -private: + + private: void import(FontImportArgs args, PFontAsset asset); Gfx::PGraphics graphics; }; diff --git a/src/Editor/Asset/MaterialLoader.cpp b/src/Editor/Asset/MaterialLoader.cpp index a3a61fe..7d1eec1 100644 --- a/src/Editor/Asset/MaterialLoader.cpp +++ b/src/Editor/Asset/MaterialLoader.cpp @@ -1,37 +1,35 @@ #include "MaterialLoader.h" +#include "Asset/AssetRegistry.h" +#include "Asset/MaterialAsset.h" +#include "Asset/TextureAsset.h" #include "Graphics/Graphics.h" #include "Graphics/Shader.h" -#include "Asset/MaterialAsset.h" -#include "Asset/AssetRegistry.h" #include "Material/Material.h" -#include "Window/WindowManager.h" #include "Material/ShaderExpression.h" -#include "Asset/TextureAsset.h" -#include +#include "Window/WindowManager.h" #include -#include #include +#include +#include + using namespace Seele; using json = nlohmann::json; -MaterialLoader::MaterialLoader(Gfx::PGraphics graphics) - : graphics(graphics) -{ +MaterialLoader::MaterialLoader(Gfx::PGraphics graphics) : graphics(graphics) { OMaterialAsset placeholderAsset = new MaterialAsset(); - import(MaterialImportArgs{ - .filePath = std::filesystem::absolute("./shaders/Placeholder.json"), - .importPath = "", - }, placeholderAsset); + import( + MaterialImportArgs{ + .filePath = std::filesystem::absolute("./shaders/Placeholder.json"), + .importPath = "", + }, + placeholderAsset); AssetRegistry::get().assetRoot->materials[""] = std::move(placeholderAsset); } -MaterialLoader::~MaterialLoader() -{ -} +MaterialLoader::~MaterialLoader() {} -void MaterialLoader::importAsset(MaterialImportArgs args) -{ +void MaterialLoader::importAsset(MaterialImportArgs args) { std::filesystem::path assetPath = args.filePath.filename(); assetPath.replace_extension("asset"); OMaterialAsset asset = new MaterialAsset(args.importPath, assetPath.stem().string()); @@ -41,14 +39,13 @@ void MaterialLoader::importAsset(MaterialImportArgs args) import(args, ref); } -void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) -{ +void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) { auto jsonstream = std::ifstream(args.filePath.c_str()); json j; jsonstream >> j; std::string materialName = j["name"].get() + "Material"; Gfx::ODescriptorLayout layout = graphics->createDescriptorLayout("pMaterial"); - //Shader file needs to conform to the slang standard, which prohibits _ + // Shader file needs to conform to the slang standard, which prohibits _ materialName.erase(std::remove(materialName.begin(), materialName.end(), '_'), materialName.end()); materialName.erase(std::remove(materialName.begin(), materialName.end(), '-'), materialName.end()); @@ -59,22 +56,21 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) uint32 key = 0; uint32 auxKey = 0; Array parameters; - for(auto& param : j["params"].items()) - { + for (auto& param : j["params"].items()) { std::string type = param.value()["type"].get(); auto defaultValue = param.value().find("default"); // TODO: ALIGNMENT RULES - if(type.compare("float") == 0) - { + if (type.compare("float") == 0) { float defaultData = 0.f; - if (defaultValue != param.value().end()) - { + if (defaultValue != param.value().end()) { defaultData = std::stof(defaultValue.value().get()); } OFloatParameter p = new FloatParameter(param.key(), defaultData, uniformBufferOffset, uniformBinding); - if(uniformBinding == -1) - { - layout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = bindingCounter, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,}); + if (uniformBinding == -1) { + layout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = bindingCounter, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + }); uniformBinding = bindingCounter++; } uniformBufferOffset += 4; @@ -82,93 +78,85 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) expressions.add(std::move(p)); } // TODO: ALIGNMENT RULES - else if(type.compare("float3") == 0) - { + else if (type.compare("float3") == 0) { Vector defaultData = Vector(0, 0, 0); - if (defaultValue != param.value().end()) - { + if (defaultValue != param.value().end()) { defaultData = parseVector(defaultValue.value().get().c_str()); } OVectorParameter p = new VectorParameter(param.key(), defaultData, uniformBufferOffset, uniformBinding); - if(uniformBinding == -1) - { - layout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = bindingCounter, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,}); + if (uniformBinding == -1) { + layout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = bindingCounter, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + }); uniformBinding = bindingCounter++; } uniformBufferOffset += 16; - parameters.add(p->key); + parameters.add(p->key); expressions.add(std::move(p)); - } - else if(type.compare("Texture2D") == 0) - { + } else if (type.compare("Texture2D") == 0) { PTextureAsset texture; - if(defaultValue != param.value().end()) - { + if (defaultValue != param.value().end()) { std::string defaultString = defaultValue.value().get(); auto slashPos = defaultString.rfind("/"); std::string folder = ""; - if (slashPos != std::string::npos) - { + if (slashPos != std::string::npos) { folder = defaultString.substr(0, slashPos - 1); defaultString = defaultString.substr(slashPos, defaultString.length()); } texture = AssetRegistry::findTexture(folder, defaultString); } - if(texture == nullptr) - { + if (texture == nullptr) { texture = AssetRegistry::findTexture("", ""); // this will return placeholder texture } OTextureParameter p = new TextureParameter(param.key(), texture, bindingCounter); - layout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = bindingCounter++, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, }); + layout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = bindingCounter++, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, + }); parameters.add(p->key); expressions.add(std::move(p)); - } - else if(type.compare("Sampler") == 0) - { + } else if (type.compare("Sampler") == 0) { OSamplerParameter p = new SamplerParameter(param.key(), graphics->createSampler({}), bindingCounter); - layout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = bindingCounter++, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER,}); + layout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = bindingCounter++, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER, + }); parameters.add(p->key); expressions.add(std::move(p)); - } - else if (type.compare("Sampler2D") == 0) - { + } else if (type.compare("Sampler2D") == 0) { PTextureAsset texture; - if (defaultValue != param.value().end()) - { + if (defaultValue != param.value().end()) { std::string defaultString = defaultValue.value().get(); auto slashPos = defaultString.rfind("/"); std::string folder = ""; - if (slashPos != std::string::npos) - { + if (slashPos != std::string::npos) { folder = defaultString.substr(0, slashPos - 1); defaultString = defaultString.substr(slashPos, defaultString.length()); } texture = AssetRegistry::findTexture(folder, defaultString); } - if (texture == nullptr) - { + if (texture == nullptr) { texture = AssetRegistry::findTexture("", ""); // this will return placeholder texture } OCombinedTextureParameter p = new CombinedTextureParameter(param.key(), texture, graphics->createSampler({}), bindingCounter); - layout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = bindingCounter++, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER, }); + layout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = bindingCounter++, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER, + }); parameters.add(p->key); expressions.add(std::move(p)); - } - else - { + } else { std::cout << "Error unsupported parameter type" << std::endl; } } uint32 uniformDataSize = uniformBufferOffset; - auto referenceExpression = [¶meters, &auxKey, &expressions](json obj) -> std::string - { - if(obj.is_string()) - { + auto referenceExpression = [¶meters, &auxKey, &expressions](json obj) -> std::string { + if (obj.is_string()) { std::string str = obj.get(); - if (parameters.find(str) != parameters.end()) - { + if (parameters.find(str) != parameters.end()) { return str; } OConstantExpression c = new ConstantExpression(str, ExpressionType::UNKNOWN); @@ -176,28 +164,23 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) c->key = name; expressions.add(std::move(c)); return name; - } - else - { + } else { return fmt::format("{0}", obj.get()); } }; MaterialNode mat; - for(auto& param : j["code"].items()) - { + for (auto& param : j["code"].items()) { auto& obj = param.value(); std::string exp = obj["exp"].get(); - if (exp.compare("Const") == 0) - { + if (exp.compare("Const") == 0) { OConstantExpression p = new ConstantExpression(); std::string name = fmt::format("{0}", key++); p->key = name; p->expr = obj["value"]; expressions.add(std::move(p)); } - if(exp.compare("Add") == 0) - { + if (exp.compare("Add") == 0) { OAddExpression p = new AddExpression(); std::string name = fmt::format("{0}", key++); p->key = name; @@ -205,8 +188,7 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) p->inputs["rhs"].source = referenceExpression(obj["rhs"]); expressions.add(std::move(p)); } - if(exp.compare("Sub") == 0) - { + if (exp.compare("Sub") == 0) { OSubExpression p = new SubExpression(); std::string name = fmt::format("{0}", key++); p->key = name; @@ -214,8 +196,7 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) p->inputs["rhs"].source = referenceExpression(obj["rhs"]); expressions.add(std::move(p)); } - if(exp.compare("Mul") == 0) - { + if (exp.compare("Mul") == 0) { OMulExpression p = new MulExpression(); std::string name = fmt::format("{0}", key++); p->key = name; @@ -223,63 +204,49 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) p->inputs["rhs"].source = referenceExpression(obj["rhs"]); expressions.add(std::move(p)); } - if(exp.compare("Swizzle") == 0) - { + if (exp.compare("Swizzle") == 0) { OSwizzleExpression p = new SwizzleExpression(); std::string name = fmt::format("{0}", key++); p->key = name; p->inputs["target"].source = referenceExpression(obj["target"]); int32 i = 0; - for(auto& c : obj["comp"].items()) - { + for (auto& c : obj["comp"].items()) { p->comp[i++] = c.value().get(); } expressions.add(std::move(p)); } - if(exp.compare("Sample") == 0) - { + if (exp.compare("Sample") == 0) { OSampleExpression p = new SampleExpression(); std::string name = fmt::format("{0}", key++); p->key = name; - if (obj.contains("texture")) - { + if (obj.contains("texture")) { p->inputs["texture"].source = referenceExpression(obj["texture"]); } p->inputs["sampler"].source = referenceExpression(obj["sampler"]); p->inputs["coords"].source = referenceExpression(obj["coords"]); expressions.add(std::move(p)); } - if(exp.compare("BRDF") == 0) - { + if (exp.compare("BRDF") == 0) { mat.profile = obj["profile"].get(); - for(auto& val : obj["values"].items()) - { + for (auto& val : obj["values"].items()) { mat.variables[val.key()] = referenceExpression(val.value()); } } } layout->create(); - asset->material = new Material( - graphics, - std::move(layout), - uniformDataSize, - uniformBinding, - materialName, - std::move(expressions), - std::move(parameters), - std::move(mat) - ); + asset->material = new Material(graphics, std::move(layout), uniformDataSize, uniformBinding, materialName, std::move(expressions), + std::move(parameters), std::move(mat)); asset->material->compile(); graphics->getShaderCompiler()->registerMaterial(asset->material); asset->setStatus(Asset::Status::Ready); - if (asset->getName().empty()) - { + if (asset->getName().empty()) { return; } - auto stream = AssetRegistry::createWriteStream((std::filesystem::path(asset->folderPath) / asset->getName()).string().append(".asset"), std::ios::binary); + auto stream = AssetRegistry::createWriteStream((std::filesystem::path(asset->folderPath) / asset->getName()).string().append(".asset"), + std::ios::binary); ArchiveBuffer archive; Serialization::save(archive, MaterialAsset::IDENTIFIER); @@ -290,7 +257,4 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) ////co_return; } -PMaterialAsset MaterialLoader::getPlaceHolderMaterial() -{ - return placeholderMaterial; -} +PMaterialAsset MaterialLoader::getPlaceHolderMaterial() { return placeholderMaterial; } diff --git a/src/Editor/Asset/MaterialLoader.h b/src/Editor/Asset/MaterialLoader.h index 577a424..fd37bbd 100644 --- a/src/Editor/Asset/MaterialLoader.h +++ b/src/Editor/Asset/MaterialLoader.h @@ -1,25 +1,24 @@ #pragma once -#include "MinimalEngine.h" #include "Containers/List.h" +#include "MinimalEngine.h" #include -namespace Seele -{ + +namespace Seele { DECLARE_REF(MaterialAsset) DECLARE_NAME_REF(Gfx, Graphics) -struct MaterialImportArgs -{ +struct MaterialImportArgs { std::filesystem::path filePath; std::string importPath; }; -class MaterialLoader -{ -public: +class MaterialLoader { + public: MaterialLoader(Gfx::PGraphics graphic); ~MaterialLoader(); void importAsset(MaterialImportArgs args); PMaterialAsset getPlaceHolderMaterial(); -private: + + private: void import(MaterialImportArgs args, PMaterialAsset asset); Gfx::PGraphics graphics; PMaterialAsset placeholderMaterial; diff --git a/src/Editor/Asset/MeshLoader.cpp b/src/Editor/Asset/MeshLoader.cpp index 3e5191e..1e9f6ff 100644 --- a/src/Editor/Asset/MeshLoader.cpp +++ b/src/Editor/Asset/MeshLoader.cpp @@ -1,37 +1,32 @@ #include "MeshLoader.h" -#include "Graphics/Graphics.h" -#include "Asset/MeshAsset.h" -#include "Graphics/Mesh.h" -#include "Graphics/StaticMeshVertexData.h" #include "Asset/AssetImporter.h" #include "Asset/MaterialAsset.h" +#include "Asset/MeshAsset.h" +#include "Graphics/Graphics.h" +#include "Graphics/Mesh.h" #include "Graphics/Shader.h" -#include +#include "Graphics/StaticMeshVertexData.h" +#include +#include +#include +#include +#include +#include +#include #include #include #include +#include #include -#include -#include -#include -#include -#include -#include -#include + using namespace Seele; -MeshLoader::MeshLoader(Gfx::PGraphics graphics) - : graphics(graphics) -{ -} +MeshLoader::MeshLoader(Gfx::PGraphics graphics) : graphics(graphics) {} -MeshLoader::~MeshLoader() -{ -} +MeshLoader::~MeshLoader() {} -void MeshLoader::importAsset(MeshImportArgs args) -{ +void MeshLoader::importAsset(MeshImportArgs args) { std::filesystem::path assetPath = args.filePath.filename(); assetPath.replace_extension("asset"); OMeshAsset asset = new MeshAsset(args.importPath, assetPath.stem().string()); @@ -41,43 +36,31 @@ void MeshLoader::importAsset(MeshImportArgs args) import(args, ref); } - -void MeshLoader::convertAssimpARGB(unsigned char* dst, aiTexel* src, uint32 numPixels) -{ - for (uint32 i = 0; i < numPixels; ++i) - { +void MeshLoader::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 MeshLoader::loadTextures(const aiScene* scene, const std::filesystem::path& meshDirectory, const std::string& importPath, Array& textures) -{ - for (uint32 i = 0; i < scene->mNumTextures; ++i) - { +void MeshLoader::loadTextures(const aiScene* scene, const std::filesystem::path& meshDirectory, const std::string& importPath, + Array& textures) { + for (uint32 i = 0; i < scene->mNumTextures; ++i) { aiTexture* tex = scene->mTextures[i]; auto texPath = std::filesystem::path(tex->mFilename.C_Str()); - if (std::filesystem::exists(texPath)) - { - } - else if (std::filesystem::exists(meshDirectory / texPath)) - { + if (std::filesystem::exists(texPath)) { + } else if (std::filesystem::exists(meshDirectory / texPath)) { texPath = meshDirectory / texPath; - } - else - { + } else { texPath = (meshDirectory / texPath).replace_extension("png"); - if (tex->mHeight == 0) - { + if (tex->mHeight == 0) { std::cout << "Dumping texture " << texPath << std::endl; // already compressed, just dump it to the disk std::ofstream file(texPath, std::ios::binary); file.write((const char*)tex->pcData, tex->mWidth); file.flush(); - } - else - { + } else { std::cout << "Writing extracted png " << texPath << std::endl; // recompress data so that the TextureLoader can read it unsigned char* texData = new unsigned char[tex->mWidth * tex->mHeight * 4]; @@ -90,7 +73,7 @@ void MeshLoader::loadTextures(const aiScene* scene, const std::filesystem::path& AssetImporter::importTexture(TextureImportArgs{ .filePath = texPath, .importPath = importPath, - }); + }); textures.add(AssetRegistry::findTexture(importPath, texPath.stem().string())); } } @@ -111,18 +94,23 @@ constexpr const char* KEY_ROUGHNESS_TEXTURE = "tex_r"; constexpr const char* KEY_METALLIC_TEXTURE = "tex_m"; constexpr const char* KEY_AMBIENT_OCCLUSION_TEXTURE = "tex_ao"; -void MeshLoader::loadMaterials(const aiScene* scene, const Array& textures, const std::string& baseName, const std::filesystem::path& meshDirectory, const std::string& importPath, Array& globalMaterials) -{ - for (uint32 m = 0; m < scene->mNumMaterials; ++m) - { +void MeshLoader::loadMaterials(const aiScene* scene, const Array& textures, const std::string& baseName, + const std::filesystem::path& meshDirectory, const std::string& importPath, + Array& globalMaterials) { + for (uint32 m = 0; m < scene->mNumMaterials; ++m) { aiMaterial* material = scene->mMaterials[m]; aiString texPath; std::string materialName = fmt::format("M{0}{1}{2}", baseName, material->GetName().C_Str(), m); - materialName.erase(std::remove(materialName.begin(), materialName.end(), '.'), materialName.end()); // dots break adding the .asset extension later - materialName.erase(std::remove(materialName.begin(), materialName.end(), '-'), materialName.end()); // dots break adding the .asset extension later - materialName.erase(std::remove(materialName.begin(), materialName.end(), ' '), materialName.end()); // dots break adding the .asset extension later - materialName.erase(std::remove(materialName.begin(), materialName.end(), '('), materialName.end()); // dots break adding the .asset extension later - materialName.erase(std::remove(materialName.begin(), materialName.end(), ')'), materialName.end()); // dots break adding the .asset extension later + materialName.erase(std::remove(materialName.begin(), materialName.end(), '.'), + materialName.end()); // dots break adding the .asset extension later + materialName.erase(std::remove(materialName.begin(), materialName.end(), '-'), + materialName.end()); // dots break adding the .asset extension later + materialName.erase(std::remove(materialName.begin(), materialName.end(), ' '), + materialName.end()); // dots break adding the .asset extension later + materialName.erase(std::remove(materialName.begin(), materialName.end(), '('), + materialName.end()); // dots break adding the .asset extension later + materialName.erase(std::remove(materialName.begin(), materialName.end(), ')'), + materialName.end()); // dots break adding the .asset extension later Gfx::ODescriptorLayout materialLayout = graphics->createDescriptorLayout("pMaterial"); Array expressions; Array parameters; @@ -131,200 +119,183 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array& .binding = 0, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .shaderStages = Gfx::SE_SHADER_STAGE_FRAGMENT_BIT, - }); + }); size_t uniformSize = 0; uint32 bindingCounter = 1; - auto addScalarParameter = [&](std::string paramKey, const char* matKey, int type, int index) - { - float scalar; - material->Get(matKey, type, index, scalar); - expressions.add(new FloatParameter(paramKey, scalar, uniformSize, 0)); - uniformSize += sizeof(float); - parameters.add(paramKey); - }; + auto addScalarParameter = [&](std::string paramKey, const char* matKey, int type, int index) { + float scalar; + material->Get(matKey, type, index, scalar); + expressions.add(new FloatParameter(paramKey, scalar, uniformSize, 0)); + uniformSize += sizeof(float); + parameters.add(paramKey); + }; - auto addVectorParameter = [&](std::string paramKey, const char* matKey, int type, int index) - { - aiColor3D color; - material->Get(matKey, type, index, color); - uniformSize = (uniformSize + sizeof(Vector4) - 1) / sizeof(Vector4) * sizeof(Vector4); - expressions.add(new VectorParameter(paramKey, Vector(color.r, color.g, color.b), uniformSize, 0)); - uniformSize += sizeof(Vector); - parameters.add(paramKey); - }; + auto addVectorParameter = [&](std::string paramKey, const char* matKey, int type, int index) { + aiColor3D color; + material->Get(matKey, type, index, color); + uniformSize = (uniformSize + sizeof(Vector4) - 1) / sizeof(Vector4) * sizeof(Vector4); + expressions.add(new VectorParameter(paramKey, Vector(color.r, color.g, color.b), uniformSize, 0)); + uniformSize += sizeof(Vector); + parameters.add(paramKey); + }; - auto addTextureParameter = [&](std::string paramKey, aiTextureType type, int index, std::string& result, StaticArray extractMask = { 0, 1, 2, -1 }) - { - aiString texPath; - aiTextureMapping mapping; - uint32 uvIndex = 0; - aiTextureMapMode mapMode = aiTextureMapMode_Clamp; - float blend = std::numeric_limits::max(); - aiTextureOp op; - if (material->GetTexture(type, index, &texPath, &mapping, &uvIndex, nullptr, nullptr, nullptr) != AI_SUCCESS) - { - std::cout << "fuck" << std::endl; - } + auto addTextureParameter = [&](std::string paramKey, aiTextureType type, int index, std::string& result, + StaticArray extractMask = {0, 1, 2, -1}) { + aiString texPath; + aiTextureMapping mapping; + uint32 uvIndex = 0; + aiTextureMapMode mapMode = aiTextureMapMode_Clamp; + float blend = std::numeric_limits::max(); + aiTextureOp op; + if (material->GetTexture(type, index, &texPath, &mapping, &uvIndex, nullptr, nullptr, nullptr) != AI_SUCCESS) { + std::cout << "fuck" << std::endl; + } - std::string textureKey = fmt::format("{0}Texture{1}", paramKey, index); - auto texFilename = std::filesystem::path(texPath.C_Str()); - PTextureAsset texture; + std::string textureKey = fmt::format("{0}Texture{1}", paramKey, index); + auto texFilename = std::filesystem::path(texPath.C_Str()); + PTextureAsset texture; - if (texFilename.string()[0] == '*') - { - texture = textures[atoi(texFilename.string().substr(1).c_str())]; - } - else if (std::filesystem::exists(texFilename)) - { - AssetImporter::importTexture(TextureImportArgs{ + if (texFilename.string()[0] == '*') { + texture = textures[atoi(texFilename.string().substr(1).c_str())]; + } else if (std::filesystem::exists(texFilename)) { + AssetImporter::importTexture(TextureImportArgs{ .filePath = texFilename, .importPath = importPath, - }); - texture = AssetRegistry::findTexture(importPath, texFilename.stem().string()); - } - else if (std::filesystem::exists(meshDirectory / texFilename)) - { - AssetImporter::importTexture(TextureImportArgs{ + }); + texture = AssetRegistry::findTexture(importPath, texFilename.stem().string()); + } else if (std::filesystem::exists(meshDirectory / texFilename)) { + AssetImporter::importTexture(TextureImportArgs{ .filePath = meshDirectory / texFilename, .importPath = importPath, .type = type == aiTextureType_NORMALS ? TextureImportType::TEXTURE_NORMAL : TextureImportType::TEXTURE_2D, - }); - texture = AssetRegistry::findTexture(importPath, texFilename.stem().string()); - } - else if (std::filesystem::exists(meshDirectory.parent_path() / "textures" / texFilename)) - { - AssetImporter::importTexture(TextureImportArgs{ + }); + texture = AssetRegistry::findTexture(importPath, texFilename.stem().string()); + } else if (std::filesystem::exists(meshDirectory.parent_path() / "textures" / texFilename)) { + AssetImporter::importTexture(TextureImportArgs{ .filePath = meshDirectory.parent_path() / "textures" / texFilename, .importPath = importPath, .type = type == aiTextureType_NORMALS ? TextureImportType::TEXTURE_NORMAL : TextureImportType::TEXTURE_2D, - }); - texture = AssetRegistry::findTexture(importPath, texFilename.stem().string()); - } - else - { - std::cout << "couldnt find " << texPath.C_Str() << std::endl; - return; - } - expressions.add(new TextureParameter(textureKey, texture, bindingCounter)); - materialLayout->addDescriptorBinding(Gfx::DescriptorBinding{ - .binding = bindingCounter, - .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, - .textureType = Gfx::SE_IMAGE_VIEW_TYPE_2D, - .shaderStages = Gfx::SE_SHADER_STAGE_FRAGMENT_BIT, - }); - parameters.add(textureKey); - bindingCounter++; + }); + texture = AssetRegistry::findTexture(importPath, texFilename.stem().string()); + } else { + std::cout << "couldnt find " << texPath.C_Str() << std::endl; + return; + } + expressions.add(new TextureParameter(textureKey, texture, bindingCounter)); + materialLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = bindingCounter, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, + .textureType = Gfx::SE_IMAGE_VIEW_TYPE_2D, + .shaderStages = Gfx::SE_SHADER_STAGE_FRAGMENT_BIT, + }); + parameters.add(textureKey); + bindingCounter++; - std::string samplerKey = fmt::format("{0}Sampler{1}", paramKey, index); - SamplerCreateInfo samplerInfo = {}; - switch (mapMode) - { - case aiTextureMapMode_Wrap: - samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT; - samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT; - samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT; - break; - case aiTextureMapMode_Clamp: - samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - break; - case aiTextureMapMode_Decal: - samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; - samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; - samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; - break; - case aiTextureMapMode_Mirror: - samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; - samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; - samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; - break; - } - expressions.add(new SamplerParameter(samplerKey, graphics->createSampler(samplerInfo), bindingCounter)); - materialLayout->addDescriptorBinding(Gfx::DescriptorBinding{ - .binding = bindingCounter, - .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER, - .shaderStages = Gfx::SE_SHADER_STAGE_FRAGMENT_BIT, - }); - parameters.add(samplerKey); - bindingCounter++; + std::string samplerKey = fmt::format("{0}Sampler{1}", paramKey, index); + SamplerCreateInfo samplerInfo = {}; + switch (mapMode) { + case aiTextureMapMode_Wrap: + samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT; + samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT; + samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT; + break; + case aiTextureMapMode_Clamp: + samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + break; + case aiTextureMapMode_Decal: + samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; + samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; + samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; + break; + case aiTextureMapMode_Mirror: + samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; + samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; + samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; + break; + } + expressions.add(new SamplerParameter(samplerKey, graphics->createSampler(samplerInfo), bindingCounter)); + materialLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = bindingCounter, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER, + .shaderStages = Gfx::SE_SHADER_STAGE_FRAGMENT_BIT, + }); + parameters.add(samplerKey); + bindingCounter++; - std::string sampleKey = fmt::format("{0}Sample{1}", paramKey, index); - expressions.add(new SampleExpression()); - expressions.back()->key = sampleKey; - expressions.back()->inputs["texture"].source = textureKey; - expressions.back()->inputs["sampler"].source = samplerKey; - expressions.back()->inputs["coords"].source = fmt::format("input.texCoords[{0}]", uvIndex); + std::string sampleKey = fmt::format("{0}Sample{1}", paramKey, index); + expressions.add(new SampleExpression()); + expressions.back()->key = sampleKey; + expressions.back()->inputs["texture"].source = textureKey; + expressions.back()->inputs["sampler"].source = samplerKey; + expressions.back()->inputs["coords"].source = fmt::format("input.texCoords[{0}]", uvIndex); - std::string colorExtract = fmt::format("{0}Extract{1}", paramKey, index); - expressions.add(new SwizzleExpression(extractMask)); - expressions.back()->key = colorExtract; - expressions.back()->inputs["target"].source = sampleKey; - //TODO: extract alpha, set opacity + std::string colorExtract = fmt::format("{0}Extract{1}", paramKey, index); + expressions.add(new SwizzleExpression(extractMask)); + expressions.back()->key = colorExtract; + expressions.back()->inputs["target"].source = sampleKey; + // TODO: extract alpha, set opacity - if (blend == std::numeric_limits::max()) - { - result = colorExtract; - return; - } - std::string blendFactorKey = fmt::format("{0}BlendFactor{1}", paramKey, index); - expressions.add(new FloatParameter(blendFactorKey, blend, uniformSize, 0)); - uniformSize += sizeof(float); - parameters.add(blendFactorKey); + if (blend == std::numeric_limits::max()) { + result = colorExtract; + return; + } + std::string blendFactorKey = fmt::format("{0}BlendFactor{1}", paramKey, index); + expressions.add(new FloatParameter(blendFactorKey, blend, uniformSize, 0)); + uniformSize += sizeof(float); + parameters.add(blendFactorKey); - std::string strengthKey = fmt::format("{0}Strength{1}", paramKey, index); + std::string strengthKey = fmt::format("{0}Strength{1}", paramKey, index); + expressions.add(new MulExpression()); + expressions.back()->key = strengthKey; + expressions.back()->inputs["lhs"].source = colorExtract; + expressions.back()->inputs["rhs"].source = blendFactorKey; + + std::string blendKey = fmt::format("{0}Blend{1}", paramKey, index); + switch (op) { + /** T = T1 * T2 */ + case aiTextureOp_Multiply: expressions.add(new MulExpression()); - expressions.back()->key = strengthKey; - expressions.back()->inputs["lhs"].source = colorExtract; - expressions.back()->inputs["rhs"].source = blendFactorKey; + break; - std::string blendKey = fmt::format("{0}Blend{1}", paramKey, index); - switch (op) { - /** T = T1 * T2 */ - case aiTextureOp_Multiply: - expressions.add(new MulExpression()); - break; + /** T = T1 - T2 */ + case aiTextureOp_Subtract: + expressions.add(new SubExpression()); + break; - /** T = T1 - T2 */ - case aiTextureOp_Subtract: - expressions.add(new SubExpression()); - break; + /** T = T1 / T2 */ + case aiTextureOp_Divide: + // expressions[blendKey] = new DivExpression(); + throw std::logic_error("Not implemented"); - /** T = T1 / T2 */ - case aiTextureOp_Divide: - //expressions[blendKey] = new DivExpression(); - throw std::logic_error("Not implemented"); + /** T = (T1 + T2) - (T1 * T2) */ + case aiTextureOp_SmoothAdd: + throw std::logic_error("Not implemented"); - /** T = (T1 + T2) - (T1 * T2) */ - case aiTextureOp_SmoothAdd: - throw std::logic_error("Not implemented"); + /** T = T1 + (T2-0.5) */ + case aiTextureOp_SignedAdd: + throw std::logic_error("Not implemented"); + /** T = T1 + T2 */ + case aiTextureOp_Add: + default: + expressions.add(new AddExpression()); + break; + } + expressions.back()->key = blendKey; + expressions.back()->inputs["lhs"].source = result; + expressions.back()->inputs["rhs"].source = strengthKey; - /** T = T1 + (T2-0.5) */ - case aiTextureOp_SignedAdd: - throw std::logic_error("Not implemented"); - - /** T = T1 + T2 */ - case aiTextureOp_Add: - default: - expressions.add(new AddExpression()); - break; - } - expressions.back()->key = blendKey; - expressions.back()->inputs["lhs"].source = result; - expressions.back()->inputs["rhs"].source = strengthKey; - - result = blendKey; - - }; + result = blendKey; + }; // Diffuse addVectorParameter(KEY_DIFFUSE_COLOR, AI_MATKEY_COLOR_DIFFUSE); std::string outputDiffuse = KEY_DIFFUSE_COLOR; uint32 numDiffuseTextures = material->GetTextureCount(aiTextureType_DIFFUSE); - for (uint32 i = 0; i < numDiffuseTextures; ++i) - { + for (uint32 i = 0; i < numDiffuseTextures; ++i) { addTextureParameter(KEY_DIFFUSE_TEXTURE, aiTextureType_DIFFUSE, i, outputDiffuse); } @@ -332,16 +303,14 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array& addVectorParameter(KEY_SPECULAR_COLOR, AI_MATKEY_COLOR_SPECULAR); std::string outputSpecular = KEY_SPECULAR_COLOR; uint32 numSpecular = material->GetTextureCount(aiTextureType_SPECULAR); - for (uint32 i = 0; i < numSpecular; ++i) - { + for (uint32 i = 0; i < numSpecular; ++i) { addTextureParameter(KEY_SPECULAR_TEXTURE, aiTextureType_SPECULAR, i, outputSpecular); } // Normal std::string outputNormal = ""; uint32 numNormal = material->GetTextureCount(aiTextureType_NORMALS); - for (uint32 i = 0; i < numNormal; ++i) - { + for (uint32 i = 0; i < numNormal; ++i) { addTextureParameter(KEY_NORMAL_TEXTURE, aiTextureType_NORMALS, i, outputNormal); } @@ -349,8 +318,7 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array& addVectorParameter(KEY_AMBIENT_COLOR, AI_MATKEY_COLOR_AMBIENT); std::string outputAmbient = KEY_AMBIENT_COLOR; uint32 numAmbient = material->GetTextureCount(aiTextureType_AMBIENT); - for (uint32 i = 0; i < numAmbient; ++i) - { + for (uint32 i = 0; i < numAmbient; ++i) { addTextureParameter(KEY_AMBIENT_TEXTURE, aiTextureType_AMBIENT, i, outputAmbient); } @@ -358,42 +326,36 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array& addScalarParameter(KEY_SHININESS, AI_MATKEY_SHININESS); std::string outputShininess = KEY_SHININESS; uint32 numShiny = material->GetTextureCount(aiTextureType_SHININESS); - for (uint32 i = 0; i < numShiny; ++i) - { - addTextureParameter(KEY_SHININESS_TEXTURE, aiTextureType_SHININESS, i, outputShininess, { 0, -1, -1, -1 }); + for (uint32 i = 0; i < numShiny; ++i) { + addTextureParameter(KEY_SHININESS_TEXTURE, aiTextureType_SHININESS, i, outputShininess, {0, -1, -1, -1}); } // Roughness addScalarParameter(KEY_ROUGHNESS, AI_MATKEY_ROUGHNESS_FACTOR); std::string outputRoughness = KEY_ROUGHNESS; uint32 numRoughness = material->GetTextureCount(aiTextureType_DIFFUSE_ROUGHNESS); - for (uint32 i = 0; i < numRoughness; ++i) - { - addTextureParameter(KEY_ROUGHNESS_TEXTURE, aiTextureType_DIFFUSE_ROUGHNESS, i, outputRoughness, { 0, -1, -1, -1 }); + for (uint32 i = 0; i < numRoughness; ++i) { + addTextureParameter(KEY_ROUGHNESS_TEXTURE, aiTextureType_DIFFUSE_ROUGHNESS, i, outputRoughness, {0, -1, -1, -1}); } // Metallic addScalarParameter(KEY_METALLIC, AI_MATKEY_METALLIC_FACTOR); std::string outputMetallic = KEY_METALLIC; uint32 numMetallic = material->GetTextureCount(aiTextureType_METALNESS); - for (uint32 i = 0; i < numMetallic; ++i) - { - addTextureParameter(KEY_METALLIC_TEXTURE, aiTextureType_METALNESS, i, outputMetallic, { 0, -1, -1, -1 }); + for (uint32 i = 0; i < numMetallic; ++i) { + addTextureParameter(KEY_METALLIC_TEXTURE, aiTextureType_METALNESS, i, outputMetallic, {0, -1, -1, -1}); } // Ambient Occlusion std::string outputAO = ""; uint32 numAO = material->GetTextureCount(aiTextureType_AMBIENT_OCCLUSION); - for (uint32 i = 0; i < numAO; ++i) - { - addTextureParameter(KEY_AMBIENT_OCCLUSION_TEXTURE, aiTextureType_AMBIENT_OCCLUSION, i, outputAO, { 0, -1, -1, -1 }); + for (uint32 i = 0; i < numAO; ++i) { + addTextureParameter(KEY_AMBIENT_OCCLUSION_TEXTURE, aiTextureType_AMBIENT_OCCLUSION, i, outputAO, {0, -1, -1, -1}); } - MaterialNode brdf; brdf.variables["baseColor"] = outputDiffuse; - if (!outputNormal.empty()) - { + if (!outputNormal.empty()) { expressions.add(new MulExpression()); expressions.back()->key = "NormalMul"; expressions.back()->inputs["lhs"].source = "2"; @@ -429,8 +391,7 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array& brdf.profile = "CookTorrance"; brdf.variables["roughness"] = outputRoughness; brdf.variables["metallic"] = outputMetallic; - if (!outputAO.empty()) - { + if (!outputAO.empty()) { brdf.variables["ambientOcclusion"] = outputAmbient; } break; @@ -439,41 +400,32 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array& materialLayout->create(); OMaterialAsset baseMat = new MaterialAsset(importPath, materialName); - baseMat->material = new Material(graphics, - std::move(materialLayout), - uniformSize, 0, materialName, - std::move(expressions), - std::move(parameters), - std::move(brdf) - ); + baseMat->material = new Material(graphics, std::move(materialLayout), uniformSize, 0, materialName, std::move(expressions), + std::move(parameters), std::move(brdf)); baseMat->material->compile(); graphics->getShaderCompiler()->registerMaterial(baseMat->material); globalMaterials[m] = baseMat->instantiate(InstantiationParameter{ .name = fmt::format("{0}_Inst_0", baseMat->getName()), .folderPath = baseMat->getFolderPath(), - }); + }); AssetRegistry::get().saveAsset(PMaterialAsset(baseMat), MaterialAsset::IDENTIFIER, baseMat->getFolderPath(), baseMat->getName()); AssetRegistry::get().registerMaterial(std::move(baseMat)); } } -void findMeshRoots(aiNode* node, List& meshNodes) -{ - if (node->mNumMeshes > 0) - { +void findMeshRoots(aiNode* node, List& meshNodes) { + if (node->mNumMeshes > 0) { meshNodes.add(node); return; } - for (uint32 i = 0; i < node->mNumChildren; ++i) - { + for (uint32 i = 0; i < node->mNumChildren; ++i) { findMeshRoots(node->mChildren[i], meshNodes); } } -void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array& materials, Array& globalMeshes, Component::Collider& collider) -{ - for (int32 meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex) - { +void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array& materials, Array& globalMeshes, + Component::Collider& collider) { + for (int32 meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex) { aiMesh* mesh = scene->mMeshes[meshIndex]; if (!(mesh->mPrimitiveTypes & aiPrimitiveType_TRIANGLE)) continue; @@ -483,8 +435,7 @@ void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array positions(mesh->mNumVertices); StaticArray, MAX_TEXCOORDS> texCoords; - for (size_t i = 0; i < MAX_TEXCOORDS; ++i) - { + for (size_t i = 0; i < MAX_TEXCOORDS; ++i) { texCoords[i].resize(mesh->mNumVertices); } Array normals(mesh->mNumVertices); @@ -493,45 +444,33 @@ void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array colors(mesh->mNumVertices); StaticMeshVertexData* vertexData = StaticMeshVertexData::getInstance(); - for (int32 i = 0; i < mesh->mNumVertices; ++i) - { + for (int32 i = 0; i < mesh->mNumVertices; ++i) { positions[i] = Vector(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z); - for (size_t j = 0; j < MAX_TEXCOORDS; ++j) - { - if (mesh->HasTextureCoords(j)) - { + for (size_t j = 0; j < MAX_TEXCOORDS; ++j) { + if (mesh->HasTextureCoords(j)) { texCoords[j][i] = Vector2(mesh->mTextureCoords[j][i].x, mesh->mTextureCoords[j][i].y); - } - else - { + } else { texCoords[j][i] = Vector2(0, 0); } } normals[i] = Vector(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z); - if (mesh->HasTangentsAndBitangents()) - { + 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 - { + } else { tangents[i] = Vector(0, 0, 1); biTangents[i] = Vector(1, 0, 0); } - if (mesh->HasVertexColors(0)) - { + if (mesh->HasVertexColors(0)) { colors[i] = Vector(mesh->mColors[0][i].r, mesh->mColors[0][i].g, mesh->mColors[0][i].b); - } - else - { + } else { colors[i] = Vector(1, 1, 1); } } MeshId id = vertexData->allocateVertexData(mesh->mNumVertices); vertexData->loadPositions(id, positions); - for (size_t i = 0; i < MAX_TEXCOORDS; ++i) - { + for (size_t i = 0; i < MAX_TEXCOORDS; ++i) { vertexData->loadTexCoords(id, i, texCoords[i]); } vertexData->loadNormals(id, normals); @@ -540,8 +479,7 @@ void MeshLoader::loadGlobalMeshes(const aiScene* scene, const ArrayloadColors(id, colors); Array indices(mesh->mNumFaces * 3); - for (int32 faceIndex = 0; faceIndex < mesh->mNumFaces; ++faceIndex) - { + for (int32 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]; @@ -552,7 +490,7 @@ void MeshLoader::loadGlobalMeshes(const aiScene* scene, const ArrayloadMesh(id, indices, meshlets); - //collider.physicsMesh.addCollider(positions, indices, Matrix4(1.0f)); + // collider.physicsMesh.addCollider(positions, indices, Matrix4(1.0f)); globalMeshes[meshIndex] = new Mesh(); globalMeshes[meshIndex]->vertexData = vertexData; @@ -564,42 +502,27 @@ void MeshLoader::loadGlobalMeshes(const aiScene* scene, const ArraymParent != nullptr) - { + if (node->mParent != nullptr) { parent = loadNodeTransform(node->mParent); } return node->mTransformation * parent; } -void MeshLoader::import(MeshImportArgs args, PMeshAsset meshAsset) -{ +void MeshLoader::import(MeshImportArgs args, PMeshAsset meshAsset) { std::cout << "Starting to import " << args.filePath << std::endl; meshAsset->setStatus(Asset::Status::Loading); Assimp::Importer importer; - importer.ReadFile(args.filePath.string().c_str(), (uint32)( - aiProcess_JoinIdenticalVertices | - aiProcess_FlipUVs | - aiProcess_Triangulate | - aiProcess_SortByPType | - aiProcess_GenBoundingBoxes | - aiProcess_GenSmoothNormals | - aiProcess_ImproveCacheLocality | - aiProcess_GenUVCoords | - aiProcess_FindDegenerates)); + importer.ReadFile(args.filePath.string().c_str(), + (uint32)(aiProcess_JoinIdenticalVertices | aiProcess_FlipUVs | aiProcess_Triangulate | aiProcess_SortByPType | + aiProcess_GenBoundingBoxes | aiProcess_GenSmoothNormals | aiProcess_ImproveCacheLocality | + aiProcess_GenUVCoords | aiProcess_FindDegenerates)); const aiScene* scene = importer.ApplyPostProcessing(aiProcess_CalcTangentSpace); std::cout << importer.GetErrorString() << std::endl; @@ -616,12 +539,9 @@ void MeshLoader::import(MeshImportArgs args, PMeshAsset meshAsset) findMeshRoots(scene->mRootNode, meshNodes); Array meshes; - for (auto meshNode : meshNodes) - { - for (uint32 i = 0; i < meshNode->mNumMeshes; ++i) - { - if (globalMeshes[meshNode->mMeshes[i]] == nullptr) - { + for (auto meshNode : meshNodes) { + for (uint32 i = 0; i < meshNode->mNumMeshes; ++i) { + if (globalMeshes[meshNode->mMeshes[i]] == nullptr) { continue; } meshes.add(std::move(globalMeshes[meshNode->mMeshes[i]])); @@ -631,7 +551,8 @@ void MeshLoader::import(MeshImportArgs args, PMeshAsset meshAsset) meshAsset->meshes = std::move(meshes); meshAsset->physicsMesh = std::move(collider); - auto stream = AssetRegistry::createWriteStream((std::filesystem::path(meshAsset->getFolderPath()) / meshAsset->getName()).replace_extension("asset").string(), std::ios::binary); + 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); diff --git a/src/Editor/Asset/MeshLoader.h b/src/Editor/Asset/MeshLoader.h index e1db7eb..c7bc5b7 100644 --- a/src/Editor/Asset/MeshLoader.h +++ b/src/Editor/Asset/MeshLoader.h @@ -1,35 +1,38 @@ #pragma once -#include "MinimalEngine.h" +#include "Component/Collider.h" #include "Containers/List.h" #include "Containers/Map.h" -#include "Component/Collider.h" +#include "MinimalEngine.h" #include + struct aiScene; struct aiTexel; struct aiNode; -namespace Seele -{ +namespace Seele { DECLARE_REF(Mesh) DECLARE_REF(MeshAsset) DECLARE_REF(MaterialInstanceAsset) DECLARE_REF(TextureAsset) DECLARE_NAME_REF(Gfx, Graphics) -struct MeshImportArgs -{ +struct MeshImportArgs { std::filesystem::path filePath; std::string importPath; }; -class MeshLoader -{ -public: +class MeshLoader { + public: MeshLoader(Gfx::PGraphics graphic); ~MeshLoader(); void importAsset(MeshImportArgs args); -private: - void loadTextures(const aiScene* scene, const std::filesystem::path& meshDirectory, const std::string& importPath, Array& textures); - void loadMaterials(const aiScene* scene, const Array& textures, const std::string& baseName, const std::filesystem::path& meshDirectory, const std::string& importPath, Array& globalMaterials); - void loadGlobalMeshes(const aiScene* scene, const Array& materials, Array& globalMeshes, Component::Collider& collider); + + private: + void loadTextures(const aiScene* scene, const std::filesystem::path& meshDirectory, const std::string& importPath, + Array& textures); + void loadMaterials(const aiScene* scene, const Array& textures, const std::string& baseName, + const std::filesystem::path& meshDirectory, const std::string& importPath, + Array& globalMaterials); + void loadGlobalMeshes(const aiScene* scene, const Array& materials, Array& globalMeshes, + Component::Collider& collider); void convertAssimpARGB(unsigned char* dst, aiTexel* src, uint32 numPixels); void import(MeshImportArgs args, PMeshAsset meshAsset); diff --git a/src/Editor/Asset/TextureLoader.cpp b/src/Editor/Asset/TextureLoader.cpp index 16d7801..76e42c5 100644 --- a/src/Editor/Asset/TextureLoader.cpp +++ b/src/Editor/Asset/TextureLoader.cpp @@ -1,8 +1,9 @@ #include "TextureLoader.h" +#include "Asset/AssetRegistry.h" #include "Asset/TextureAsset.h" #include "Graphics/Graphics.h" -#include "Asset/AssetRegistry.h" #include "Graphics/Vulkan/Enums.h" + #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-compare" #pragma GCC diagnostic ignored "-Wunused-but-set-variable" @@ -17,28 +18,25 @@ using namespace Seele; -TextureLoader::TextureLoader(Gfx::PGraphics graphics) - : graphics(graphics) -{ +TextureLoader::TextureLoader(Gfx::PGraphics graphics) : graphics(graphics) { OTextureAsset placeholder = new TextureAsset(); placeholderAsset = placeholder; - import(TextureImportArgs{ - .filePath = std::filesystem::absolute("textures/placeholder.png"), - .importPath = "", - }, placeholderAsset); + import( + TextureImportArgs{ + .filePath = std::filesystem::absolute("textures/placeholder.png"), + .importPath = "", + }, + placeholderAsset); AssetRegistry::get().assetRoot->textures[""] = std::move(placeholder); } -TextureLoader::~TextureLoader() -{ -} +TextureLoader::~TextureLoader() {} -void TextureLoader::importAsset(TextureImportArgs args) -{ +void TextureLoader::importAsset(TextureImportArgs args) { std::string str = args.filePath.filename().string(); auto pos = str.rfind("."); str.replace(str.begin() + pos, str.end(), ""); - + OTextureAsset asset = new TextureAsset(args.importPath, str); PTextureAsset ref = asset; asset->setStatus(Asset::Status::Loading); @@ -46,25 +44,26 @@ void TextureLoader::importAsset(TextureImportArgs args) import(args, ref); } -PTextureAsset TextureLoader::getPlaceholderTexture() -{ - return placeholderAsset; -} +PTextureAsset TextureLoader::getPlaceholderTexture() { return placeholderAsset; } -#define KTX_ASSERT(x) { auto error = x; if(error != KTX_SUCCESS) { std::cout << ktxErrorString(error) << std::endl; abort(); } } +#define KTX_ASSERT(x) \ + { \ + auto error = x; \ + if (error != KTX_SUCCESS) { \ + std::cout << ktxErrorString(error) << std::endl; \ + abort(); \ + } \ + } -void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset) -{ +void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset) { // manually transcode ktx textures using toktx - if (args.filePath.extension().compare("ktx") != 0) - { + if (args.filePath.extension().compare("ktx") != 0) { auto ktxFile = args.filePath; ktxFile.replace_extension("ktx"); std::stringstream ss; ss << "toktx --encode etc1s "; - if (args.type == TextureImportType::TEXTURE_NORMAL) - { - //ss << "--normal_mode "; + if (args.type == TextureImportType::TEXTURE_NORMAL) { + // ss << "--normal_mode "; } ss << ktxFile << " " << args.filePath; system(ss.str().c_str()); @@ -72,31 +71,30 @@ void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset) } ktxTexture2* ktxHandle; - KTX_ASSERT(ktxTexture_CreateFromNamedFile(args.filePath.string().c_str(), 0, (ktxTexture**) & ktxHandle)); + KTX_ASSERT(ktxTexture_CreateFromNamedFile(args.filePath.string().c_str(), 0, (ktxTexture**)&ktxHandle)); - - //int totalWidth = 0, totalHeight = 0, n = 0; - //unsigned char* data = stbi_load(args.filePath.string().c_str(), &totalWidth, &totalHeight, &n, 4); - //ktxTexture2* kTexture = nullptr; - //VkFormat format = VK_FORMAT_R8G8B8A8_UNORM; - //ktxTextureCreateInfo createInfo = { - // .vkFormat = (uint32)format, - // .baseDepth = 1, - // .numLevels = 1, - // .numLayers = 1, - // .isArray = false, - // .generateMipmaps = false, - //}; + // int totalWidth = 0, totalHeight = 0, n = 0; + // unsigned char* data = stbi_load(args.filePath.string().c_str(), &totalWidth, &totalHeight, &n, 4); + // ktxTexture2* kTexture = nullptr; + // VkFormat format = VK_FORMAT_R8G8B8A8_UNORM; + // ktxTextureCreateInfo createInfo = { + // .vkFormat = (uint32)format, + // .baseDepth = 1, + // .numLevels = 1, + // .numLayers = 1, + // .isArray = false, + // .generateMipmaps = false, + // }; // - //if (args.type == TextureImportType::TEXTURE_CUBEMAP) + // if (args.type == TextureImportType::TEXTURE_CUBEMAP) //{ - // uint32 faceWidth = totalWidth / 4; - // // uint32 faceHeight = totalHeight / 3; - // // Cube map - // createInfo.baseWidth = totalWidth / 4; - // createInfo.baseHeight = totalHeight / 3; - // createInfo.numFaces = 6; - // createInfo.numDimensions = 2; + // uint32 faceWidth = totalWidth / 4; + // // uint32 faceHeight = totalHeight / 3; + // // Cube map + // createInfo.baseWidth = totalWidth / 4; + // createInfo.baseHeight = totalHeight / 3; + // createInfo.numFaces = 6; + // createInfo.numDimensions = 2; // KTX_ASSERT(ktxTexture2_Create(&createInfo, // KTX_TEXTURE_CREATE_ALLOC_STORAGE, @@ -124,7 +122,7 @@ void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset) // loadCubeFace(1, 1, 4); // +Z // loadCubeFace(3, 1, 5); // -Z //} - //else + // else //{ // createInfo.baseWidth = totalWidth; // createInfo.baseHeight = totalHeight; @@ -138,34 +136,33 @@ void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset) // ktxTexture_SetImageFromMemory(ktxTexture(kTexture), // 0, 0, 0, data, totalWidth * totalHeight * n * sizeof(unsigned char)); //} - //ktxTexture_WriteToNamedFile(ktxTexture(kTexture), args.filePath.replace_extension(".ktx").string().c_str()); + // ktxTexture_WriteToNamedFile(ktxTexture(kTexture), args.filePath.replace_extension(".ktx").string().c_str()); - //ktxBasisParams basisParams = { - // .structSize = sizeof(ktxBasisParams), - // .uastc = true, - // .threadCount = std::thread::hardware_concurrency(), - // .normalMap = normalMap, - // .uastcFlags = KTX_PACK_UASTC_LEVEL_VERYSLOW, - // .uastcRDO = true, - // .uastcRDOQualityScalar = 1, - //}; - //KTX_ASSERT(ktxTexture2_CompressBasisEx(kTexture, &basisParams)); - //KTX_ASSERT(ktxTexture2_DeflateZstd(kTexture, 3)); + // ktxBasisParams basisParams = { + // .structSize = sizeof(ktxBasisParams), + // .uastc = true, + // .threadCount = std::thread::hardware_concurrency(), + // .normalMap = normalMap, + // .uastcFlags = KTX_PACK_UASTC_LEVEL_VERYSLOW, + // .uastcRDO = true, + // .uastcRDOQualityScalar = 1, + // }; + // KTX_ASSERT(ktxTexture2_CompressBasisEx(kTexture, &basisParams)); + // KTX_ASSERT(ktxTexture2_DeflateZstd(kTexture, 3)); - //char writer[100]; - //snprintf(writer, sizeof(writer), "%s version %s", "SeeleEngine", "0.0.1"); - //ktxHashList_AddKVPair(&kTexture->kvDataHead, KTX_WRITER_KEY, - // (ktx_uint32_t)strlen(writer) + 1, - // writer); + // char writer[100]; + // snprintf(writer, sizeof(writer), "%s version %s", "SeeleEngine", "0.0.1"); + // ktxHashList_AddKVPair(&kTexture->kvDataHead, KTX_WRITER_KEY, + // (ktx_uint32_t)strlen(writer) + 1, + // writer); - //uint8* texData; - //size_t texSize; - //KTX_ASSERT(ktxTexture_WriteToMemory(ktxTexture(kTexture), &texData, &texSize)); + // uint8* texData; + // size_t texSize; + // KTX_ASSERT(ktxTexture_WriteToMemory(ktxTexture(kTexture), &texData, &texSize)); // - //stbi_image_free(data); + // stbi_image_free(data); - if (textureAsset->getName().empty()) - { + if (textureAsset->getName().empty()) { return; } diff --git a/src/Editor/Asset/TextureLoader.h b/src/Editor/Asset/TextureLoader.h index 42bcec3..17f011e 100644 --- a/src/Editor/Asset/TextureLoader.h +++ b/src/Editor/Asset/TextureLoader.h @@ -1,36 +1,34 @@ #pragma once -#include "MinimalEngine.h" #include "Containers/List.h" #include "Graphics/Enums.h" +#include "MinimalEngine.h" #include -namespace Seele -{ + +namespace Seele { DECLARE_REF(TextureAsset) DECLARE_NAME_REF(Gfx, Graphics) DECLARE_NAME_REF(Gfx, Texture2D) -enum class TextureImportType -{ +enum class TextureImportType { TEXTURE_2D, TEXTURE_NORMAL, TEXTURE_CUBEMAP, }; -struct TextureImportArgs -{ +struct TextureImportArgs { std::filesystem::path filePath; std::string importPath; TextureImportType type = TextureImportType::TEXTURE_2D; Gfx::SeImageUsageFlagBits usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT; uint32 numChannels = 4; }; -class TextureLoader -{ -public: +class TextureLoader { + public: TextureLoader(Gfx::PGraphics graphic); ~TextureLoader(); void importAsset(TextureImportArgs args); PTextureAsset getPlaceholderTexture(); -private: + + private: void import(TextureImportArgs args, PTextureAsset asset); Gfx::PGraphics graphics; PTextureAsset placeholderAsset; diff --git a/src/Editor/Window/InspectorView.cpp b/src/Editor/Window/InspectorView.cpp index dd1e298..de73fdd 100644 --- a/src/Editor/Window/InspectorView.cpp +++ b/src/Editor/Window/InspectorView.cpp @@ -1,74 +1,49 @@ #include "InspectorView.h" -#include "Graphics/Graphics.h" #include "Actor/Actor.h" #include "Asset/AssetRegistry.h" #include "Asset/FontLoader.h" +#include "Graphics/Graphics.h" #include "UI/System.h" #include "Window/Window.h" + using namespace Seele; using namespace Seele::Editor; -InspectorView::InspectorView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo &createInfo) +InspectorView::InspectorView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo) : View(graphics, std::move(window), std::move(createInfo), "InspectorView") - //, renderGraph(RenderGraphBuilder::build( - // UIPass(graphics), - // TextPass(graphics) - //)) - , uiSystem(new UI::System()) -{ - //renderGraph.updateViewport(viewport); + //, renderGraph(RenderGraphBuilder::build( + // UIPass(graphics), + // TextPass(graphics) + //)) + , + uiSystem(new UI::System()) { + // renderGraph.updateViewport(viewport); uiSystem->updateViewport(viewport); } -InspectorView::~InspectorView() -{ +InspectorView::~InspectorView() {} + +void InspectorView::beginUpdate() { + // co_return; } -void InspectorView::beginUpdate() -{ - //co_return; +void InspectorView::update() { + // co_return; } -void InspectorView::update() -{ - //co_return; -} +void InspectorView::commitUpdate() {} -void InspectorView::commitUpdate() -{ -} +void InspectorView::prepareRender() {} -void InspectorView::prepareRender() -{ - -} +void InspectorView::render() {} -void InspectorView::render() -{ -} +void InspectorView::keyCallback(KeyCode, InputAction, KeyModifier) {} -void InspectorView::keyCallback(KeyCode, InputAction, KeyModifier) -{ - -} +void InspectorView::mouseMoveCallback(double, double) {} -void InspectorView::mouseMoveCallback(double, double) -{ - -} +void InspectorView::mouseButtonCallback(MouseButton, InputAction, KeyModifier) {} -void InspectorView::mouseButtonCallback(MouseButton, InputAction, KeyModifier) -{ - -} +void InspectorView::scrollCallback(double, double) {} -void InspectorView::scrollCallback(double, double) -{ - -} - -void InspectorView::fileCallback(int, const char**) -{ - -} +void InspectorView::fileCallback(int, const char**) {} diff --git a/src/Editor/Window/InspectorView.h b/src/Editor/Window/InspectorView.h index fa6ee8c..0c151f6 100644 --- a/src/Editor/Window/InspectorView.h +++ b/src/Editor/Window/InspectorView.h @@ -1,38 +1,36 @@ #pragma once -#include "Window/View.h" #include "Graphics/RenderPass/RenderGraph.h" -#include "Graphics/RenderPass/UIPass.h" #include "Graphics/RenderPass/TextPass.h" +#include "Graphics/RenderPass/UIPass.h" #include "UI/Elements/Panel.h" +#include "Window/View.h" -namespace Seele -{ + +namespace Seele { DECLARE_REF(Actor) -namespace Editor -{ -class InspectorView : public View -{ -public: - InspectorView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo &createInfo); +namespace Editor { +class InspectorView : public View { + public: + InspectorView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo); virtual ~InspectorView(); virtual void beginUpdate() override; - virtual void update() override; - virtual void commitUpdate() override; - + virtual void update() override; + virtual void commitUpdate() override; + virtual void prepareRender() override; virtual void render() override; void selectActor(); -protected: + protected: UI::PSystem uiSystem; PActor selectedActor; - - virtual void keyCallback(KeyCode code, InputAction action, KeyModifier modifier) override; - virtual void mouseMoveCallback(double xPos, double yPos) override; - virtual void mouseButtonCallback(MouseButton button, InputAction action, KeyModifier modifier) override; - virtual void scrollCallback(double xOffset, double yOffset) override; - virtual void fileCallback(int count, const char** paths) override; + + virtual void keyCallback(KeyCode code, InputAction action, KeyModifier modifier) override; + virtual void mouseMoveCallback(double xPos, double yPos) override; + virtual void mouseButtonCallback(MouseButton button, InputAction action, KeyModifier modifier) override; + virtual void scrollCallback(double xOffset, double yOffset) override; + virtual void fileCallback(int count, const char** paths) override; }; DEFINE_REF(InspectorView) } // namespace Editor diff --git a/src/Editor/Window/PlayView.cpp b/src/Editor/Window/PlayView.cpp index a9a6b35..12bff3d 100644 --- a/src/Editor/Window/PlayView.cpp +++ b/src/Editor/Window/PlayView.cpp @@ -5,35 +5,16 @@ using namespace Seele; using namespace Seele::Editor; PlayView::PlayView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::string dllPath) - : GameView(graphics, window, createInfo, dllPath) -{ -} + : GameView(graphics, window, createInfo, dllPath) {} -PlayView::~PlayView() -{ -} +PlayView::~PlayView() {} -void PlayView::beginUpdate() -{ - GameView::beginUpdate(); -} +void PlayView::beginUpdate() { GameView::beginUpdate(); } -void PlayView::update() -{ - GameView::update(); -} +void PlayView::update() { GameView::update(); } -void PlayView::commitUpdate() -{ - GameView::commitUpdate(); -} +void PlayView::commitUpdate() { GameView::commitUpdate(); } -void PlayView::prepareRender() -{ - GameView::prepareRender(); -} +void PlayView::prepareRender() { GameView::prepareRender(); } -void PlayView::render() -{ - GameView::render(); -} +void PlayView::render() { GameView::render(); } diff --git a/src/Editor/Window/PlayView.h b/src/Editor/Window/PlayView.h index 6c9cbf5..82ed110 100644 --- a/src/Editor/Window/PlayView.h +++ b/src/Editor/Window/PlayView.h @@ -1,22 +1,20 @@ #pragma once #include "Window/GameView.h" -namespace Seele -{ -namespace Editor -{ -class PlayView : public GameView -{ -public: +namespace Seele { +namespace Editor { +class PlayView : public GameView { + public: PlayView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::string dllPath); virtual ~PlayView(); - virtual void beginUpdate() override; - virtual void update() override; - virtual void commitUpdate() override; + virtual void beginUpdate() override; + virtual void update() override; + virtual void commitUpdate() override; - virtual void prepareRender() override; - virtual void render() override; -private: + virtual void prepareRender() override; + virtual void render() override; + + private: }; DECLARE_REF(PlayView) } // namespace Editor diff --git a/src/Editor/Window/SceneView.cpp b/src/Editor/Window/SceneView.cpp index 9c591ce..9d3cc26 100644 --- a/src/Editor/Window/SceneView.cpp +++ b/src/Editor/Window/SceneView.cpp @@ -1,22 +1,20 @@ #include "SceneView.h" -#include "Scene/Scene.h" -#include "Window/Window.h" -#include "Graphics/Mesh.h" -#include "Graphics/Graphics.h" -#include "Asset/MeshAsset.h" -#include "Asset/AssetRegistry.h" #include "Actor/CameraActor.h" +#include "Asset/AssetRegistry.h" +#include "Asset/MeshAsset.h" #include "Component/Camera.h" #include "Component/Mesh.h" +#include "Graphics/Graphics.h" +#include "Graphics/Mesh.h" +#include "Scene/Scene.h" +#include "Window/Window.h" + using namespace Seele; using namespace Seele::Editor; -SceneView::SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo &createInfo) - : View(graphics, owner, createInfo, "SceneView") - , scene(new Scene(graphics)) - , cameraSystem(createInfo.dimensions, Vector(0, 0, 10)) -{ +SceneView::SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo& createInfo) + : View(graphics, owner, createInfo, "SceneView"), scene(new Scene(graphics)), cameraSystem(createInfo.dimensions, Vector(0, 0, 10)) { cameraSystem.update(viewportCamera, static_cast(Gfx::getCurrentFrameDelta())); renderGraph.addPass(new DepthPrepass(graphics, scene)); renderGraph.addPass(new LightCullingPass(graphics, scene)); @@ -25,54 +23,31 @@ SceneView::SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreat renderGraph.createRenderPass(); } -SceneView::~SceneView() -{ +SceneView::~SceneView() {} + +void SceneView::beginUpdate() { + // co_return; } -void SceneView::beginUpdate() -{ - //co_return; -} - -void SceneView::update() -{ +void SceneView::update() { cameraSystem.update(viewportCamera, static_cast(Gfx::getCurrentFrameDelta())); - //co_return; + // co_return; } -void SceneView::commitUpdate() -{ -} +void SceneView::commitUpdate() {} -void SceneView::prepareRender() -{ -} +void SceneView::prepareRender() {} -void SceneView::render() -{ - renderGraph.render(viewportCamera); -} +void SceneView::render() { renderGraph.render(viewportCamera); } -void SceneView::keyCallback(KeyCode code, InputAction action, KeyModifier) -{ - cameraSystem.keyCallback(code, action); -} +void SceneView::keyCallback(KeyCode code, InputAction action, KeyModifier) { cameraSystem.keyCallback(code, action); } -void SceneView::mouseMoveCallback(double xPos, double yPos) -{ - cameraSystem.mouseMoveCallback(xPos, yPos); -} +void SceneView::mouseMoveCallback(double xPos, double yPos) { cameraSystem.mouseMoveCallback(xPos, yPos); } -void SceneView::mouseButtonCallback(MouseButton button, InputAction action, KeyModifier) -{ +void SceneView::mouseButtonCallback(MouseButton button, InputAction action, KeyModifier) { cameraSystem.mouseButtonCallback(button, action); } -void SceneView::scrollCallback(double, double) -{ -} +void SceneView::scrollCallback(double, double) {} -void SceneView::fileCallback(int, const char**) -{ - -} +void SceneView::fileCallback(int, const char**) {} diff --git a/src/Editor/Window/SceneView.h b/src/Editor/Window/SceneView.h index 1ec01eb..d43affe 100644 --- a/src/Editor/Window/SceneView.h +++ b/src/Editor/Window/SceneView.h @@ -1,43 +1,42 @@ #pragma once -#include "ThreadPool.h" -#include "Window/View.h" +#include "Graphics/RenderPass/BasePass.h" #include "Graphics/RenderPass/DepthPrepass.h" #include "Graphics/RenderPass/LightCullingPass.h" -#include "Graphics/RenderPass/BasePass.h" +#include "ThreadPool.h" #include "ViewportControl.h" +#include "Window/View.h" -namespace Seele -{ + +namespace Seele { DECLARE_REF(Scene) -namespace Editor -{ -class SceneView : public View -{ -public: - SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo &createInfo); - ~SceneView(); +namespace Editor { +class SceneView : public View { + public: + SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo& createInfo); + ~SceneView(); - virtual void beginUpdate() override; - virtual void update() override; - virtual void commitUpdate() override; + virtual void beginUpdate() override; + virtual void update() override; + virtual void commitUpdate() override; - virtual void prepareRender() override; - virtual void render() override; + virtual void prepareRender() override; + virtual void render() override; - PScene getScene() const { return scene; } -private: - OScene scene; - Component::Camera viewportCamera; - - RenderGraph renderGraph; + PScene getScene() const { return scene; } - ViewportControl cameraSystem; + private: + OScene scene; + Component::Camera viewportCamera; - virtual void keyCallback(KeyCode code, InputAction action, KeyModifier modifier) override; - virtual void mouseMoveCallback(double xPos, double yPos) override; - virtual void mouseButtonCallback(MouseButton button, InputAction action, KeyModifier modifier) override; - virtual void scrollCallback(double xOffset, double yOffset) override; - virtual void fileCallback(int count, const char** paths) override; + RenderGraph renderGraph; + + ViewportControl cameraSystem; + + virtual void keyCallback(KeyCode code, InputAction action, KeyModifier modifier) override; + virtual void mouseMoveCallback(double xPos, double yPos) override; + virtual void mouseButtonCallback(MouseButton button, InputAction action, KeyModifier modifier) override; + virtual void scrollCallback(double xOffset, double yOffset) override; + virtual void fileCallback(int count, const char** paths) override; }; DEFINE_REF(SceneView) } // namespace Editor diff --git a/src/Editor/Window/ViewportControl.cpp b/src/Editor/Window/ViewportControl.cpp index e672d13..1c5b22c 100644 --- a/src/Editor/Window/ViewportControl.cpp +++ b/src/Editor/Window/ViewportControl.cpp @@ -6,81 +6,56 @@ using namespace Seele; using namespace Seele::Editor; ViewportControl::ViewportControl(const URect& viewportDimensions, Vector initialPos) - : position(initialPos) - , fieldOfView(glm::radians(70.f)) - , aspectRatio(static_cast(viewportDimensions.size.x) / viewportDimensions.size.y) - , pitch(0) - , yaw(glm::pi()/-2.0f) -{ + : position(initialPos), fieldOfView(glm::radians(70.f)), + aspectRatio(static_cast(viewportDimensions.size.x) / viewportDimensions.size.y), pitch(0), yaw(glm::pi() / -2.0f) { std::cout << yaw << " " << pitch << std::endl; } -ViewportControl::~ViewportControl() -{ - -} +ViewportControl::~ViewportControl() {} -void ViewportControl::update(Component::Camera& camera, float deltaTime) -{ +void ViewportControl::update(Component::Camera& camera, float deltaTime) { float cameraMove = deltaTime * 20; - if(keys[KeyCode::KEY_LEFT_SHIFT]) - { + if (keys[KeyCode::KEY_LEFT_SHIFT]) { cameraMove *= 4; } Vector moveVector = Vector(); Vector forward = glm::normalize(springArm); Vector side = glm::cross(Vector(0, 1, 0), forward); - if(keys[KeyCode::KEY_W]) - { + if (keys[KeyCode::KEY_W]) { moveVector += forward * cameraMove; } - if(keys[KeyCode::KEY_S]) - { + if (keys[KeyCode::KEY_S]) { moveVector += forward * -cameraMove; } - if(keys[KeyCode::KEY_A]) - { + if (keys[KeyCode::KEY_A]) { moveVector += side * cameraMove; } - if(keys[KeyCode::KEY_D]) - { + if (keys[KeyCode::KEY_D]) { moveVector += side * -cameraMove; } - if(keys[KeyCode::KEY_E]) - { + if (keys[KeyCode::KEY_E]) { moveVector += glm::vec3(0, cameraMove, 0); - } - if(keys[KeyCode::KEY_Q]) - { + } + if (keys[KeyCode::KEY_Q]) { moveVector += glm::vec3(0, -cameraMove, 0); } throw std::logic_error("Not implemented"); } -void ViewportControl::keyCallback(KeyCode key, InputAction action) -{ - keys[static_cast(key)] = action != InputAction::RELEASE; -} +void ViewportControl::keyCallback(KeyCode key, InputAction action) { keys[static_cast(key)] = action != InputAction::RELEASE; } -void ViewportControl::mouseMoveCallback(double xPos, double yPos) -{ +void ViewportControl::mouseMoveCallback(double xPos, double yPos) { mouseX = static_cast(xPos); mouseY = static_cast(yPos); } -void ViewportControl::mouseButtonCallback(MouseButton button, InputAction action) -{ - if(button == MouseButton::MOUSE_BUTTON_1) - { +void ViewportControl::mouseButtonCallback(MouseButton button, InputAction action) { + if (button == MouseButton::MOUSE_BUTTON_1) { mouse1 = action != InputAction::RELEASE; } - if(button == MouseButton::MOUSE_BUTTON_2) - { + if (button == MouseButton::MOUSE_BUTTON_2) { mouse2 = action != InputAction::RELEASE; } } -void ViewportControl::viewportResize(URect dimensions) -{ - aspectRatio = static_cast(dimensions.size.x) / dimensions.size.y; -} +void ViewportControl::viewportResize(URect dimensions) { aspectRatio = static_cast(dimensions.size.x) / dimensions.size.y; } diff --git a/src/Editor/Window/ViewportControl.h b/src/Editor/Window/ViewportControl.h index d8704b6..ea6eada 100644 --- a/src/Editor/Window/ViewportControl.h +++ b/src/Editor/Window/ViewportControl.h @@ -1,37 +1,36 @@ #pragma once -#include "MinimalEngine.h" -#include "Math/Vector.h" #include "Component/Camera.h" -#include "Math/Math.h" -#include "Graphics/Enums.h" #include "Containers/Array.h" +#include "Graphics/Enums.h" +#include "Math/Math.h" +#include "Math/Vector.h" +#include "MinimalEngine.h" -namespace Seele -{ -namespace Editor -{ - class ViewportControl - { - public: - ViewportControl(const URect& viewportDimensions, Vector initialPos /*TODO: configurable initial rotations*/); - ~ViewportControl(); - void update(Component::Camera& camera, float deltaTime); - void keyCallback(KeyCode key, InputAction action); - void mouseMoveCallback(double xPos, double yPos); - void mouseButtonCallback(MouseButton button, InputAction action); - void viewportResize(URect dimensions); - private: - Vector position; - Vector springArm; - float fieldOfView; - float aspectRatio; - StaticArray(KeyCode::KEY_LAST)> keys; - bool mouse1 = false; - bool mouse2 = false; - float mouseX; - float mouseY; - float pitch; - float yaw; - }; + +namespace Seele { +namespace Editor { +class ViewportControl { + public: + ViewportControl(const URect& viewportDimensions, Vector initialPos /*TODO: configurable initial rotations*/); + ~ViewportControl(); + void update(Component::Camera& camera, float deltaTime); + void keyCallback(KeyCode key, InputAction action); + void mouseMoveCallback(double xPos, double yPos); + void mouseButtonCallback(MouseButton button, InputAction action); + void viewportResize(URect dimensions); + + private: + Vector position; + Vector springArm; + float fieldOfView; + float aspectRatio; + StaticArray(KeyCode::KEY_LAST)> keys; + bool mouse1 = false; + bool mouse2 = false; + float mouseX; + float mouseY; + float pitch; + float yaw; +}; } // namespace Editor } // namespace Seele diff --git a/src/Editor/main.cpp b/src/Editor/main.cpp index a50bfb7..210cb21 100644 --- a/src/Editor/main.cpp +++ b/src/Editor/main.cpp @@ -25,88 +25,86 @@ static Gfx::OGraphics graphics; int main() { std::string gameName = "MeshShadingDemo"; #ifdef WIN32 - std::filesystem::path outputPath = "C:/Users/Dynamitos/MeshShadingDemoGame"; - std::filesystem::path sourcePath = "C:/Users/Dynamitos/MeshShadingDemo"; - std::filesystem::path binaryPath = sourcePath / "bin" / "MeshShadingDemo.dll"; + std::filesystem::path outputPath = "C:/Users/Dynamitos/MeshShadingDemoGame"; + std::filesystem::path sourcePath = "C:/Users/Dynamitos/MeshShadingDemo"; + std::filesystem::path binaryPath = sourcePath / "bin" / "MeshShadingDemo.dll"; #elif __APPLE__ - std::filesystem::path outputPath = "/Users/dynamitos/MeshShadingDemoGame"; - std::filesystem::path sourcePath = "/Users/dynamitos/MeshShadingDemo"; - std::filesystem::path binaryPath = sourcePath / "cmake" / "libMeshShadingDemo.dylib"; + std::filesystem::path outputPath = "/Users/dynamitos/MeshShadingDemoGame"; + std::filesystem::path sourcePath = "/Users/dynamitos/MeshShadingDemo"; + std::filesystem::path binaryPath = sourcePath / "cmake" / "libMeshShadingDemo.dylib"; #else - std::filesystem::path outputPath = "/home/dynamitos/MeshShadingDemoGame"; - std::filesystem::path sourcePath = "/home/dynamitos/MeshShadingDemo"; - std::filesystem::path binaryPath = sourcePath / "cmake" / "libMeshShadingDemo.so"; + std::filesystem::path outputPath = "/home/dynamitos/MeshShadingDemoGame"; + std::filesystem::path sourcePath = "/home/dynamitos/MeshShadingDemo"; + std::filesystem::path binaryPath = sourcePath / "cmake" / "libMeshShadingDemo.so"; #endif - std::filesystem::path cmakePath = outputPath / "cmake"; + std::filesystem::path cmakePath = outputPath / "cmake"; #ifdef __APPLE__ - graphics = new Metal::Graphics(); + graphics = new Metal::Graphics(); #else - graphics = new Vulkan::Graphics(); + graphics = new Vulkan::Graphics(); #endif - GraphicsInitializer initializer; - graphics->init(initializer); - StaticMeshVertexData* vd = StaticMeshVertexData::getInstance(); - vd->init(graphics); + GraphicsInitializer initializer; + graphics->init(initializer); + StaticMeshVertexData* vd = StaticMeshVertexData::getInstance(); + vd->init(graphics); - OWindowManager windowManager = new WindowManager(); - AssetRegistry::init(sourcePath / "Assets", graphics); - AssetImporter::init(graphics); - AssetImporter::importFont(FontImportArgs{ - .filePath = "./fonts/Calibri.ttf", - }); - AssetImporter::importMesh(MeshImportArgs{ - .filePath = sourcePath / "import/models/cube.fbx", - }); - //AssetImporter::importMesh(MeshImportArgs{ - // .filePath = sourcePath / "import/models/greek-temple/source/greek-temple.fbx", - // .importPath = "temple" - // }); - AssetImporter::importMesh(MeshImportArgs{ - .filePath = sourcePath / "import/models/after-the-rain-vr-sound/source/Whitechapel.fbx", - .importPath = "Whitechapel" - }); - //AssetImporter::importMesh(MeshImportArgs{ - // .filePath = sourcePath / "import/models/nitra-castle-rawscan/source/Nitriansky.obj", - // .importPath = "Nitriansky" - // }); - WindowCreateInfo mainWindowInfo; - mainWindowInfo.title = "SeeleEngine"; - mainWindowInfo.width = 1920; - mainWindowInfo.height = 1080; - mainWindowInfo.preferredFormat = Gfx::SE_FORMAT_B8G8R8A8_SRGB; - auto window = windowManager->addWindow(graphics, mainWindowInfo); - ViewportCreateInfo sceneViewInfo; - sceneViewInfo.dimensions.size.x = 1920; - sceneViewInfo.dimensions.size.y = 1080; - sceneViewInfo.dimensions.offset.x = 0; - sceneViewInfo.dimensions.offset.y = 0; - sceneViewInfo.numSamples = Gfx::SE_SAMPLE_COUNT_1_BIT; - OGameView sceneView = new Editor::PlayView(graphics, window, sceneViewInfo, binaryPath.generic_string()); - sceneView->setFocused(); + OWindowManager windowManager = new WindowManager(); + AssetRegistry::init(sourcePath / "Assets", graphics); + AssetImporter::init(graphics); + AssetImporter::importFont(FontImportArgs{ + .filePath = "./fonts/Calibri.ttf", + }); + AssetImporter::importMesh(MeshImportArgs{ + .filePath = sourcePath / "import/models/cube.fbx", + }); + // AssetImporter::importMesh(MeshImportArgs{ + // .filePath = sourcePath / "import/models/greek-temple/source/greek-temple.fbx", + // .importPath = "temple" + // }); + AssetImporter::importMesh(MeshImportArgs{.filePath = sourcePath / "import/models/after-the-rain-vr-sound/source/Whitechapel.fbx", + .importPath = "Whitechapel"}); + // AssetImporter::importMesh(MeshImportArgs{ + // .filePath = sourcePath / "import/models/nitra-castle-rawscan/source/Nitriansky.obj", + // .importPath = "Nitriansky" + // }); + WindowCreateInfo mainWindowInfo; + mainWindowInfo.title = "SeeleEngine"; + mainWindowInfo.width = 1920; + mainWindowInfo.height = 1080; + mainWindowInfo.preferredFormat = Gfx::SE_FORMAT_B8G8R8A8_SRGB; + auto window = windowManager->addWindow(graphics, mainWindowInfo); + ViewportCreateInfo sceneViewInfo; + sceneViewInfo.dimensions.size.x = 1920; + sceneViewInfo.dimensions.size.y = 1080; + sceneViewInfo.dimensions.offset.x = 0; + sceneViewInfo.dimensions.offset.y = 0; + sceneViewInfo.numSamples = Gfx::SE_SAMPLE_COUNT_1_BIT; + OGameView sceneView = new Editor::PlayView(graphics, window, sceneViewInfo, binaryPath.generic_string()); + sceneView->setFocused(); - while (windowManager->isActive()) { - windowManager->render(); - } - vd->destroy(); - // export game - if (false) { - std::filesystem::create_directories(outputPath); - std::system(fmt::format("cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DGAME_TITLE=\"{}\" -DGAME_DESTINATION=\"{}\" " - "-DGAME_BINARY=\"{}\" -P ./cmake/ExportProject.cmake", - gameName, outputPath.generic_string(), binaryPath.generic_string()) - .c_str()); - std::system(fmt::format("cmake -S {} -B {}", cmakePath.generic_string(), cmakePath.generic_string()).c_str()); - std::system(fmt::format("cmake --build {}", cmakePath.generic_string()).c_str()); - std::filesystem::copy(sourcePath / "Assets", outputPath / "Assets", std::filesystem::copy_options::recursive); - std::filesystem::copy("shaders", outputPath / "shaders", std::filesystem::copy_options::recursive); - std::filesystem::copy("textures", outputPath / "textures", std::filesystem::copy_options::recursive); + while (windowManager->isActive()) { + windowManager->render(); + } + vd->destroy(); + // export game + if (false) { + std::filesystem::create_directories(outputPath); + std::system(fmt::format("cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DGAME_TITLE=\"{}\" -DGAME_DESTINATION=\"{}\" " + "-DGAME_BINARY=\"{}\" -P ./cmake/ExportProject.cmake", + gameName, outputPath.generic_string(), binaryPath.generic_string()) + .c_str()); + std::system(fmt::format("cmake -S {} -B {}", cmakePath.generic_string(), cmakePath.generic_string()).c_str()); + std::system(fmt::format("cmake --build {}", cmakePath.generic_string()).c_str()); + std::filesystem::copy(sourcePath / "Assets", outputPath / "Assets", std::filesystem::copy_options::recursive); + std::filesystem::copy("shaders", outputPath / "shaders", std::filesystem::copy_options::recursive); + std::filesystem::copy("textures", outputPath / "textures", std::filesystem::copy_options::recursive); #ifdef WIN32 - std::filesystem::copy_file("assimp-vc143-mt.dll", outputPath / "assimp-vc143-mt.dll"); - std::filesystem::copy_file("slang.dll", outputPath / "slang.dll"); - std::filesystem::copy_file("slang-glslang.dll", outputPath / "slang-glslang.dll"); - std::filesystem::copy_file("slang-llvm.dll", outputPath / "slang-llvm.dll"); + std::filesystem::copy_file("assimp-vc143-mt.dll", outputPath / "assimp-vc143-mt.dll"); + std::filesystem::copy_file("slang.dll", outputPath / "slang.dll"); + std::filesystem::copy_file("slang-glslang.dll", outputPath / "slang-glslang.dll"); + std::filesystem::copy_file("slang-llvm.dll", outputPath / "slang-llvm.dll"); #endif - } - return 0; + } + return 0; } diff --git a/src/Engine/Actor/Actor.cpp b/src/Engine/Actor/Actor.cpp index 9109046..a1f0776 100644 --- a/src/Engine/Actor/Actor.cpp +++ b/src/Engine/Actor/Actor.cpp @@ -3,38 +3,23 @@ using namespace Seele; -Actor::Actor(PScene scene) - : Entity(scene) -{ - attachComponent(); -} +Actor::Actor(PScene scene) : Entity(scene) { attachComponent(); } -Actor::~Actor() -{ +Actor::~Actor() {} -} - -void Actor::setParent(PActor newParent) -{ - if(parent != nullptr) - { +void Actor::setParent(PActor newParent) { + if (parent != nullptr) { parent->removeChild(this); } parent = newParent; } -void Actor::addChild(PActor child) -{ +void Actor::addChild(PActor child) { children.add(child); child->setParent(this); } -void Actor::removeChild(PActor child) -{ +void Actor::removeChild(PActor child) { children.remove(children.find(child), false); child->setParent(nullptr); } -Component::Transform& Actor::getTransform() -{ - return accessComponent(); -} - +Component::Transform& Actor::getTransform() { return accessComponent(); } diff --git a/src/Engine/Actor/Actor.h b/src/Engine/Actor/Actor.h index e13566a..f2e94a4 100644 --- a/src/Engine/Actor/Actor.h +++ b/src/Engine/Actor/Actor.h @@ -1,15 +1,14 @@ #pragma once -#include "Entity.h" #include "Component/Transform.h" +#include "Entity.h" -namespace Seele -{ + +namespace Seele { DECLARE_REF(Actor) // Actors are entities that are part of the scene hierarchy // In order for that hierarchy to make sense it requires at least a transform component -class Actor : public Entity -{ -public: +class Actor : public Entity { + public: Actor(PScene scene); virtual ~Actor(); @@ -17,11 +16,11 @@ public: void addChild(PActor child); void removeChild(PActor child); Array getChildren(); - + Component::Transform& getTransform(); -protected: - //Component::Transform& getTransform(); + protected: + // Component::Transform& getTransform(); void setParent(PActor parent); PActor parent; Array children; diff --git a/src/Engine/Actor/CameraActor.cpp b/src/Engine/Actor/CameraActor.cpp index 6ba8af5..3e39d3b 100644 --- a/src/Engine/Actor/CameraActor.cpp +++ b/src/Engine/Actor/CameraActor.cpp @@ -3,23 +3,13 @@ using namespace Seele; -CameraActor::CameraActor(PScene scene) - : Actor(scene) -{ +CameraActor::CameraActor(PScene scene) : Actor(scene) { attachComponent(); accessComponent().setPosition(Vector(10, 5, 14)); } -CameraActor::~CameraActor() -{ -} +CameraActor::~CameraActor() {} -Component::Camera& CameraActor::getCameraComponent() -{ - return accessComponent(); -} +Component::Camera& CameraActor::getCameraComponent() { return accessComponent(); } -const Component::Camera& CameraActor::getCameraComponent() const -{ - return accessComponent(); -} \ No newline at end of file +const Component::Camera& CameraActor::getCameraComponent() const { return accessComponent(); } \ No newline at end of file diff --git a/src/Engine/Actor/CameraActor.h b/src/Engine/Actor/CameraActor.h index fa51458..c430917 100644 --- a/src/Engine/Actor/CameraActor.h +++ b/src/Engine/Actor/CameraActor.h @@ -2,16 +2,15 @@ #include "Actor.h" #include "Component/Camera.h" -namespace Seele -{ -class CameraActor : public Actor -{ -public: +namespace Seele { +class CameraActor : public Actor { + public: CameraActor(PScene scene); virtual ~CameraActor(); Component::Camera& getCameraComponent(); const Component::Camera& getCameraComponent() const; -private: + + private: }; DEFINE_REF(CameraActor) } // namespace Seele diff --git a/src/Engine/Actor/DirectionalLightActor.cpp b/src/Engine/Actor/DirectionalLightActor.cpp index 9fd9360..27a88c9 100644 --- a/src/Engine/Actor/DirectionalLightActor.cpp +++ b/src/Engine/Actor/DirectionalLightActor.cpp @@ -2,29 +2,18 @@ using namespace Seele; -DirectionalLightActor::DirectionalLightActor(PScene scene) - : Actor(scene) -{ - attachComponent(); -} +DirectionalLightActor::DirectionalLightActor(PScene scene) : Actor(scene) { attachComponent(); } -DirectionalLightActor::DirectionalLightActor(PScene scene, Vector color, Vector direction) - : Actor(scene) -{ +DirectionalLightActor::DirectionalLightActor(PScene scene, Vector color, Vector direction) : Actor(scene) { attachComponent(Vector4(color, 0), Vector4(direction, 0)); } -DirectionalLightActor::~DirectionalLightActor() -{ - -} +DirectionalLightActor::~DirectionalLightActor() {} -Component::DirectionalLight& DirectionalLightActor::getDirectionalLightComponent() -{ +Component::DirectionalLight& DirectionalLightActor::getDirectionalLightComponent() { return accessComponent(); } -const Component::DirectionalLight& DirectionalLightActor::getDirectionalLightComponent() const -{ +const Component::DirectionalLight& DirectionalLightActor::getDirectionalLightComponent() const { return accessComponent(); } \ No newline at end of file diff --git a/src/Engine/Actor/DirectionalLightActor.h b/src/Engine/Actor/DirectionalLightActor.h index 20dc0eb..e09444e 100644 --- a/src/Engine/Actor/DirectionalLightActor.h +++ b/src/Engine/Actor/DirectionalLightActor.h @@ -2,17 +2,16 @@ #include "Actor.h" #include "Component/DirectionalLight.h" -namespace Seele -{ -class DirectionalLightActor : public Actor -{ -public: +namespace Seele { +class DirectionalLightActor : public Actor { + public: DirectionalLightActor(PScene scene); DirectionalLightActor(PScene scene, Vector color, Vector direction); virtual ~DirectionalLightActor(); Component::DirectionalLight& getDirectionalLightComponent(); const Component::DirectionalLight& getDirectionalLightComponent() const; -private: + + private: }; DEFINE_REF(DirectionalLightActor) } // namespace Seele diff --git a/src/Engine/Actor/Entity.cpp b/src/Engine/Actor/Entity.cpp index 3b8bb4f..7bb7549 100644 --- a/src/Engine/Actor/Entity.cpp +++ b/src/Engine/Actor/Entity.cpp @@ -2,14 +2,6 @@ using namespace Seele; -Entity::Entity(PScene scene) - : scene(scene) - , identifier(scene->createEntity()) -{ -} +Entity::Entity(PScene scene) : scene(scene), identifier(scene->createEntity()) {} - -Entity::~Entity() -{ - scene->destroyEntity(identifier); -} \ No newline at end of file +Entity::~Entity() { scene->destroyEntity(identifier); } \ No newline at end of file diff --git a/src/Engine/Actor/Entity.h b/src/Engine/Actor/Entity.h index 25de08d..a5acd72 100644 --- a/src/Engine/Actor/Entity.h +++ b/src/Engine/Actor/Entity.h @@ -1,33 +1,23 @@ #pragma once -#include #include "MinimalEngine.h" #include "Scene/Scene.h" -namespace Seele -{ +#include + +namespace Seele { // An entity describes a part of a scene // It is just a wrapper the ID of a registry -class Entity -{ -public: +class Entity { + public: Entity(PScene scene); virtual ~Entity(); - template - Component& attachComponent(Args&&... args) - { + template Component& attachComponent(Args&&... args) { return scene->attachComponent(identifier, std::forward(args)...); } - template - Component& accessComponent() - { - return scene->accessComponent(identifier); - } - template - const Component& accessComponent() const - { - return scene->accessComponent(identifier); - } -protected: + template Component& accessComponent() { return scene->accessComponent(identifier); } + template const Component& accessComponent() const { return scene->accessComponent(identifier); } + + protected: PScene scene; entt::entity identifier; }; diff --git a/src/Engine/Actor/PointLightActor.cpp b/src/Engine/Actor/PointLightActor.cpp index b35cf91..c873eac 100644 --- a/src/Engine/Actor/PointLightActor.cpp +++ b/src/Engine/Actor/PointLightActor.cpp @@ -2,29 +2,14 @@ using namespace Seele; -PointLightActor::PointLightActor(PScene scene) - : Actor(scene) -{ - attachComponent(); -} +PointLightActor::PointLightActor(PScene scene) : Actor(scene) { attachComponent(); } -PointLightActor::PointLightActor(PScene scene, Vector position, Vector color, float attenuation) - : Actor(scene) -{ +PointLightActor::PointLightActor(PScene scene, Vector position, Vector color, float attenuation) : Actor(scene) { attachComponent(Vector4(position, 1), Vector4(color, attenuation)); } -PointLightActor::~PointLightActor() -{ - -} +PointLightActor::~PointLightActor() {} -Component::PointLight& PointLightActor::getPointLightComponent() -{ - return accessComponent(); -} +Component::PointLight& PointLightActor::getPointLightComponent() { return accessComponent(); } -const Component::PointLight& PointLightActor::getPointLightComponent() const -{ - return accessComponent(); -} \ No newline at end of file +const Component::PointLight& PointLightActor::getPointLightComponent() const { return accessComponent(); } \ No newline at end of file diff --git a/src/Engine/Actor/PointLightActor.h b/src/Engine/Actor/PointLightActor.h index c6e9677..9e19a4a 100644 --- a/src/Engine/Actor/PointLightActor.h +++ b/src/Engine/Actor/PointLightActor.h @@ -2,17 +2,16 @@ #include "Actor.h" #include "Component/PointLight.h" -namespace Seele -{ -class PointLightActor : public Actor -{ -public: +namespace Seele { +class PointLightActor : public Actor { + public: PointLightActor(PScene scene); PointLightActor(PScene scene, Vector position, Vector color, float attenuation); virtual ~PointLightActor(); Component::PointLight& getPointLightComponent(); const Component::PointLight& getPointLightComponent() const; -private: + + private: }; DEFINE_REF(PointLightActor) } // namespace Seele diff --git a/src/Engine/Actor/StaticMeshActor.cpp b/src/Engine/Actor/StaticMeshActor.cpp index 46e0203..3736827 100644 --- a/src/Engine/Actor/StaticMeshActor.cpp +++ b/src/Engine/Actor/StaticMeshActor.cpp @@ -2,22 +2,10 @@ using namespace Seele; -StaticMeshActor::StaticMeshActor(PScene scene, PMeshAsset mesh) - : Actor(scene) -{ - attachComponent(mesh); -} +StaticMeshActor::StaticMeshActor(PScene scene, PMeshAsset mesh) : Actor(scene) { attachComponent(mesh); } -Seele::StaticMeshActor::~StaticMeshActor() -{ -} +Seele::StaticMeshActor::~StaticMeshActor() {} -Component::Mesh &Seele::StaticMeshActor::getMesh() -{ - return accessComponent(); -} +Component::Mesh& Seele::StaticMeshActor::getMesh() { return accessComponent(); } -const Component::Mesh &Seele::StaticMeshActor::getMesh() const -{ - return accessComponent(); -} +const Component::Mesh& Seele::StaticMeshActor::getMesh() const { return accessComponent(); } diff --git a/src/Engine/Actor/StaticMeshActor.h b/src/Engine/Actor/StaticMeshActor.h index 101441f..f07355b 100644 --- a/src/Engine/Actor/StaticMeshActor.h +++ b/src/Engine/Actor/StaticMeshActor.h @@ -2,16 +2,15 @@ #include "Actor.h" #include "Component/Mesh.h" -namespace Seele -{ -class StaticMeshActor : public Actor -{ -public: +namespace Seele { +class StaticMeshActor : public Actor { + public: StaticMeshActor(PScene scene, PMeshAsset mesh); virtual ~StaticMeshActor(); Component::Mesh& getMesh(); const Component::Mesh& getMesh() const; -private: + + private: }; DEFINE_REF(StaticMeshActor) } // namespace Seele diff --git a/src/Engine/Asset/Asset.cpp b/src/Engine/Asset/Asset.cpp index a7fdd3a..e89af0d 100644 --- a/src/Engine/Asset/Asset.cpp +++ b/src/Engine/Asset/Asset.cpp @@ -4,44 +4,19 @@ using namespace Seele; -Asset::Asset() - : folderPath("") - , name("") - , status(Status::Uninitialized) - , byteSize(0) -{ -} -Asset::Asset(std::string_view _folderPath, std::string_view _name) - : folderPath(_folderPath) - , name(_name) - , status(Status::Uninitialized) -{ - if (folderPath.empty()) - { +Asset::Asset() : folderPath(""), name(""), status(Status::Uninitialized), byteSize(0) {} +Asset::Asset(std::string_view _folderPath, std::string_view _name) : folderPath(_folderPath), name(_name), status(Status::Uninitialized) { + if (folderPath.empty()) { assetId = name; - } - else - { + } else { assetId = folderPath + "/" + name; } } +Asset::~Asset() {} -Asset::~Asset() -{ -} +std::string Asset::getFolderPath() const { return folderPath; } -std::string Asset::getFolderPath() const -{ - return folderPath; -} +std::string Asset::getName() const { return name; } -std::string Asset::getName() const -{ - return name; -} - -std::string Asset::getAssetIdentifier() const -{ - return assetId; -} +std::string Asset::getAssetIdentifier() const { return assetId; } diff --git a/src/Engine/Asset/Asset.h b/src/Engine/Asset/Asset.h index c2a7245..bfa2108 100644 --- a/src/Engine/Asset/Asset.h +++ b/src/Engine/Asset/Asset.h @@ -2,18 +2,11 @@ #include "MinimalEngine.h" #include "Serialization/ArchiveBuffer.h" -namespace Seele -{ +namespace Seele { DECLARE_NAME_REF(Gfx, Graphics) -class Asset -{ -public: - enum class Status - { - Uninitialized, - Loading, - Ready - }; +class Asset { + public: + enum class Status { Uninitialized, Loading, Ready }; Asset(); Asset(std::string_view folderPath, std::string_view name); virtual ~Asset(); @@ -22,7 +15,7 @@ public: virtual void save(ArchiveBuffer& buffer) const = 0; virtual void load(ArchiveBuffer& buffer) = 0; - + bool isModified() const; // returns the assets name std::string getName() const; @@ -31,15 +24,10 @@ public: // returns the identifier with which it can be found from the asset registry std::string getAssetIdentifier() const; - constexpr Status getStatus() - { - return status; - } - constexpr void setStatus(Status _status) - { - status = _status; - } -protected: + constexpr Status getStatus() { return status; } + constexpr void setStatus(Status _status) { status = _status; } + + protected: std::string folderPath; std::string name; std::string assetId; diff --git a/src/Engine/Asset/AssetRegistry.cpp b/src/Engine/Asset/AssetRegistry.cpp index c6c819e..2f204bf 100644 --- a/src/Engine/Asset/AssetRegistry.cpp +++ b/src/Engine/Asset/AssetRegistry.cpp @@ -1,134 +1,96 @@ #include "AssetRegistry.h" -#include "MeshAsset.h" #include "FontAsset.h" -#include "TextureAsset.h" +#include "Graphics/Graphics.h" +#include "Graphics/Mesh.h" #include "MaterialAsset.h" #include "MaterialInstanceAsset.h" -#include "Graphics/Mesh.h" -#include "Graphics/Graphics.h" -#include "Window/WindowManager.h" #include "MeshAsset.h" -#include -#include +#include "TextureAsset.h" +#include "Window/WindowManager.h" #include +#include +#include + using namespace Seele; AssetRegistry* _instance = new AssetRegistry(); -AssetRegistry::~AssetRegistry() -{ - delete assetRoot; -} +AssetRegistry::~AssetRegistry() { delete assetRoot; } -void AssetRegistry::init(std::filesystem::path rootFolder, Gfx::PGraphics graphics) -{ - get().initialize(rootFolder, graphics); -} +void AssetRegistry::init(std::filesystem::path rootFolder, Gfx::PGraphics graphics) { get().initialize(rootFolder, graphics); } -PMeshAsset AssetRegistry::findMesh(std::string_view folderPath, std::string_view filePath) -{ +PMeshAsset AssetRegistry::findMesh(std::string_view folderPath, std::string_view filePath) { AssetFolder* folder = get().assetRoot; - if (!folderPath.empty()) - { + if (!folderPath.empty()) { folder = get().getOrCreateFolder(folderPath); } return folder->meshes.at(std::string(filePath)); } -PTextureAsset AssetRegistry::findTexture(std::string_view folderPath, std::string_view filePath) -{ +PTextureAsset AssetRegistry::findTexture(std::string_view folderPath, std::string_view filePath) { AssetFolder* folder = get().assetRoot; - if (!folderPath.empty()) - { + if (!folderPath.empty()) { folder = get().getOrCreateFolder(folderPath); } return folder->textures.at(std::string(filePath)); } -PFontAsset AssetRegistry::findFont(std::string_view folderPath, std::string_view filePath) -{ +PFontAsset AssetRegistry::findFont(std::string_view folderPath, std::string_view filePath) { AssetFolder* folder = get().assetRoot; - if (!folderPath.empty()) - { + if (!folderPath.empty()) { folder = get().getOrCreateFolder(folderPath); } return folder->fonts.at(std::string(filePath)); } -PMaterialAsset AssetRegistry::findMaterial(std::string_view folderPath, std::string_view filePath) -{ +PMaterialAsset AssetRegistry::findMaterial(std::string_view folderPath, std::string_view filePath) { AssetFolder* folder = get().assetRoot; - if (!folderPath.empty()) - { + if (!folderPath.empty()) { folder = get().getOrCreateFolder(folderPath); } return folder->materials.at(std::string(filePath)); } -PMaterialInstanceAsset AssetRegistry::findMaterialInstance(std::string_view folderPath, std::string_view filePath) -{ +PMaterialInstanceAsset AssetRegistry::findMaterialInstance(std::string_view folderPath, std::string_view filePath) { AssetFolder* folder = get().assetRoot; - if (!folderPath.empty()) - { + if (!folderPath.empty()) { folder = get().getOrCreateFolder(folderPath); } return folder->instances.at(std::string(filePath)); } -std::ofstream AssetRegistry::createWriteStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode) -{ +std::ofstream AssetRegistry::createWriteStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode) { return get().internalCreateWriteStream(relativePath, openmode); } -std::ifstream AssetRegistry::createReadStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode) -{ +std::ifstream AssetRegistry::createReadStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode) { return get().internalCreateReadStream(relativePath, openmode); } -AssetRegistry &AssetRegistry::get() -{ - return *_instance; -} +AssetRegistry& AssetRegistry::get() { return *_instance; } -AssetRegistry::AssetRegistry() - : assetRoot(nullptr) -{ -} +AssetRegistry::AssetRegistry() : assetRoot(nullptr) {} -AssetRegistry* AssetRegistry::getInstance() -{ - return _instance; -} +AssetRegistry* AssetRegistry::getInstance() { return _instance; } -void AssetRegistry::loadRegistry() -{ - get().loadRegistryInternal(); -} +void AssetRegistry::loadRegistry() { get().loadRegistryInternal(); } -void AssetRegistry::saveRegistry() -{ - get().saveRegistryInternal(); -} +void AssetRegistry::saveRegistry() { get().saveRegistryInternal(); } -AssetRegistry::AssetFolder* AssetRegistry::getOrCreateFolder(std::string_view fullPath) -{ +AssetRegistry::AssetFolder* AssetRegistry::getOrCreateFolder(std::string_view fullPath) { AssetFolder* result = assetRoot; std::string temp = std::string(fullPath); - while (!temp.empty()) - { + while (!temp.empty()) { size_t slashLoc = temp.find("/"); - if (slashLoc == std::string::npos) - { - if (!result->children.contains(temp)) - { + if (slashLoc == std::string::npos) { + if (!result->children.contains(temp)) { result->children[temp] = new AssetFolder(temp); } return result->children[temp]; } std::string folderName = temp.substr(0, slashLoc); - if (!result->children.contains(folderName)) - { + if (!result->children.contains(folderName)) { result->children[folderName] = new AssetFolder(fullPath); } result = result->children[folderName]; @@ -137,40 +99,31 @@ AssetRegistry::AssetFolder* AssetRegistry::getOrCreateFolder(std::string_view fu return result; } -void AssetRegistry::initialize(const std::filesystem::path &_rootFolder, Gfx::PGraphics _graphics) -{ +void AssetRegistry::initialize(const std::filesystem::path& _rootFolder, Gfx::PGraphics _graphics) { this->graphics = _graphics; this->rootFolder = _rootFolder; this->assetRoot = new AssetFolder(""); loadRegistryInternal(); } -void AssetRegistry::loadRegistryInternal() -{ +void AssetRegistry::loadRegistryInternal() { peekFolder(assetRoot); loadFolder(assetRoot); } -void AssetRegistry::peekFolder(AssetFolder* folder) -{ - for (const auto& entry : std::filesystem::directory_iterator(rootFolder / folder->folderPath)) - { +void AssetRegistry::peekFolder(AssetFolder* folder) { + for (const auto& entry : std::filesystem::directory_iterator(rootFolder / folder->folderPath)) { const auto& stem = entry.path().stem().string(); - if (entry.is_directory()) - { - if (folder->folderPath.empty()) - { + if (entry.is_directory()) { + if (folder->folderPath.empty()) { folder->children[stem] = new AssetFolder(stem); - } - else - { + } else { folder->children[stem] = new AssetFolder(folder->folderPath + "/" + stem); } peekFolder(folder->children[stem]); continue; } - if(entry.path().filename().compare(".DS_Store") == 0) - { + if (entry.path().filename().compare(".DS_Store") == 0) { continue; } auto stream = std::ifstream(entry.path(), std::ios::binary); @@ -181,20 +134,16 @@ void AssetRegistry::peekFolder(AssetFolder* folder) } } -void AssetRegistry::loadFolder(AssetFolder* folder) -{ - for (const auto& entry : std::filesystem::directory_iterator(rootFolder / folder->folderPath)) - { +void AssetRegistry::loadFolder(AssetFolder* folder) { + for (const auto& entry : std::filesystem::directory_iterator(rootFolder / folder->folderPath)) { const auto& path = entry.path(); - if (entry.is_directory()) - { + if (entry.is_directory()) { auto relative = path.stem().string(); loadFolder(folder->children[relative]); continue; } - if(entry.path().filename().compare(".DS_Store") == 0) - { + if (entry.path().filename().compare(".DS_Store") == 0) { continue; } auto stream = std::ifstream(path, std::ios::binary); @@ -205,8 +154,7 @@ void AssetRegistry::loadFolder(AssetFolder* folder) } } -void AssetRegistry::peekAsset(ArchiveBuffer& buffer) -{ +void AssetRegistry::peekAsset(ArchiveBuffer& buffer) { // Read asset type uint64 identifier; Serialization::load(buffer, identifier); @@ -222,8 +170,7 @@ void AssetRegistry::peekAsset(ArchiveBuffer& buffer) AssetFolder* folder = getOrCreateFolder(folderPath); OAsset asset; - switch (identifier) - { + switch (identifier) { case TextureAsset::IDENTIFIER: asset = new TextureAsset(folderPath, name); folder->textures[name] = std::move(asset); @@ -249,8 +196,7 @@ void AssetRegistry::peekAsset(ArchiveBuffer& buffer) } } -void AssetRegistry::loadAsset(ArchiveBuffer& buffer) -{ +void AssetRegistry::loadAsset(ArchiveBuffer& buffer) { // Read asset type uint64 identifier; Serialization::load(buffer, identifier); @@ -264,10 +210,9 @@ void AssetRegistry::loadAsset(ArchiveBuffer& buffer) Serialization::load(buffer, folderPath); AssetFolder* folder = getOrCreateFolder(folderPath); - + PAsset asset; - switch (identifier) - { + switch (identifier) { case TextureAsset::IDENTIFIER: asset = PTextureAsset(folder->textures.at(name)); break; @@ -289,42 +234,31 @@ void AssetRegistry::loadAsset(ArchiveBuffer& buffer) asset->load(buffer); } -void AssetRegistry::saveRegistryInternal() -{ - saveFolder("", assetRoot); -} +void AssetRegistry::saveRegistryInternal() { saveFolder("", assetRoot); } -void AssetRegistry::saveFolder(const std::filesystem::path& folderPath, AssetFolder* folder) -{ +void AssetRegistry::saveFolder(const std::filesystem::path& folderPath, AssetFolder* folder) { std::filesystem::create_directory(rootFolder / folderPath); - for (const auto& [name, texture] : folder->textures) - { + for (const auto& [name, texture] : folder->textures) { saveAsset(PTextureAsset(texture), TextureAsset::IDENTIFIER, folderPath, name); } - for (const auto& [name, mesh] : folder->meshes) - { + for (const auto& [name, mesh] : folder->meshes) { saveAsset(PMeshAsset(mesh), MeshAsset::IDENTIFIER, folderPath, name); } - for (const auto& [name, material] : folder->materials) - { + for (const auto& [name, material] : folder->materials) { saveAsset(PMaterialAsset(material), MaterialAsset::IDENTIFIER, folderPath, name); } - for (const auto& [name, material] : folder->instances) - { + for (const auto& [name, material] : folder->instances) { saveAsset(PMaterialInstanceAsset(material), MaterialInstanceAsset::IDENTIFIER, folderPath, name); } - for (const auto& [name, font] : folder->fonts) - { + for (const auto& [name, font] : folder->fonts) { saveAsset(PFontAsset(font), FontAsset::IDENTIFIER, folderPath, name); } - for (auto& [name, child] : folder->children) - { + for (auto& [name, child] : folder->children) { saveFolder(folderPath / name, child); } } -void AssetRegistry::saveAsset(PAsset asset, uint64 identifier, const std::filesystem::path& folderPath, std::string name) -{ +void AssetRegistry::saveAsset(PAsset asset, uint64 identifier, const std::filesystem::path& folderPath, std::string name) { if (name.empty()) return; @@ -342,65 +276,49 @@ void AssetRegistry::saveAsset(PAsset asset, uint64 identifier, const std::filesy buffer.writeToStream(assetStream); } -std::filesystem::path AssetRegistry::getRootFolder() -{ - return get().rootFolder; -} +std::filesystem::path AssetRegistry::getRootFolder() { return get().rootFolder; } -void AssetRegistry::registerMesh(OMeshAsset mesh) -{ +void AssetRegistry::registerMesh(OMeshAsset mesh) { AssetFolder* folder = getOrCreateFolder(mesh->getFolderPath()); folder->meshes[mesh->getName()] = std::move(mesh); } -void AssetRegistry::registerTexture(OTextureAsset texture) -{ +void AssetRegistry::registerTexture(OTextureAsset texture) { AssetFolder* folder = getOrCreateFolder(texture->getFolderPath()); folder->textures[texture->getName()] = std::move(texture); } -void AssetRegistry::registerFont(OFontAsset font) -{ +void AssetRegistry::registerFont(OFontAsset font) { AssetFolder* folder = getOrCreateFolder(font->getFolderPath()); folder->fonts[font->getName()] = std::move(font); } -void AssetRegistry::registerMaterial(OMaterialAsset material) -{ +void AssetRegistry::registerMaterial(OMaterialAsset material) { AssetFolder* folder = getOrCreateFolder(material->getFolderPath()); folder->materials[material->getName()] = std::move(material); } -void AssetRegistry::registerMaterialInstance(OMaterialInstanceAsset material) -{ +void AssetRegistry::registerMaterialInstance(OMaterialInstanceAsset material) { AssetFolder* folder = getOrCreateFolder(material->getFolderPath()); folder->instances[material->getName()] = std::move(material); } - -std::ofstream AssetRegistry::internalCreateWriteStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode) -{ +std::ofstream AssetRegistry::internalCreateWriteStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode) { auto fullPath = rootFolder / relativePath; std::filesystem::create_directories(fullPath.parent_path()); return std::ofstream(fullPath.string(), openmode); } -std::ifstream AssetRegistry::internalCreateReadStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode) -{ +std::ifstream AssetRegistry::internalCreateReadStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode) { auto fullPath = rootFolder / relativePath; std::filesystem::create_directories(fullPath.parent_path()); return std::ifstream(fullPath.string(), openmode); } -AssetRegistry::AssetFolder::AssetFolder(std::string_view folderPath) - : folderPath(folderPath) -{} +AssetRegistry::AssetFolder::AssetFolder(std::string_view folderPath) : folderPath(folderPath) {} -AssetRegistry::AssetFolder::~AssetFolder() -{ - for (auto [_, child] : children) - { +AssetRegistry::AssetFolder::~AssetFolder() { + for (auto [_, child] : children) { delete child; } } - diff --git a/src/Engine/Asset/AssetRegistry.h b/src/Engine/Asset/AssetRegistry.h index 0005e1b..59bd09d 100644 --- a/src/Engine/Asset/AssetRegistry.h +++ b/src/Engine/Asset/AssetRegistry.h @@ -1,21 +1,20 @@ #pragma once -#include "MinimalEngine.h" #include "Asset.h" #include "Containers/Map.h" -#include +#include "MinimalEngine.h" #include +#include -namespace Seele -{ + +namespace Seele { DECLARE_REF(TextureAsset) DECLARE_REF(FontAsset) DECLARE_REF(MeshAsset) DECLARE_REF(MaterialAsset) DECLARE_REF(MaterialInstanceAsset) DECLARE_NAME_REF(Gfx, Graphics) -class AssetRegistry -{ -public: +class AssetRegistry { + public: ~AssetRegistry(); static void init(std::filesystem::path path, Gfx::PGraphics graphics); @@ -34,8 +33,7 @@ public: static void loadRegistry(); static void saveRegistry(); - struct AssetFolder - { + struct AssetFolder { std::string folderPath; Map children; Map textures; @@ -49,7 +47,8 @@ public: AssetFolder* getOrCreateFolder(std::string_view foldername); AssetRegistry(); static AssetRegistry* getInstance(); -private: + + private: static AssetRegistry& get(); void initialize(const std::filesystem::path& rootFolder, Gfx::PGraphics graphics); @@ -81,4 +80,4 @@ private: friend class MaterialLoader; friend class MeshLoader; }; -} \ No newline at end of file +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Asset/FontAsset.cpp b/src/Engine/Asset/FontAsset.cpp index 7856f91..3614d76 100644 --- a/src/Engine/Asset/FontAsset.cpp +++ b/src/Engine/Asset/FontAsset.cpp @@ -5,26 +5,16 @@ using namespace Seele; -FontAsset::FontAsset() -{ -} +FontAsset::FontAsset() {} -FontAsset::FontAsset(std::string_view folderPath, std::string_view name) - : Asset(folderPath, name) -{ -} +FontAsset::FontAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {} -FontAsset::~FontAsset() -{ - -} +FontAsset::~FontAsset() {} -void FontAsset::save(ArchiveBuffer& buffer) const -{ +void FontAsset::save(ArchiveBuffer& buffer) const { Serialization::save(buffer, glyphs); Serialization::save(buffer, usedTextures.size()); - for (uint32 x = 0; x < usedTextures.size(); ++x) - { + for (uint32 x = 0; x < usedTextures.size(); ++x) { Array textureData; ktxTexture2* kTexture; ktxTextureCreateInfo createInfo = { @@ -34,7 +24,9 @@ void FontAsset::save(ArchiveBuffer& buffer) const .baseWidth = usedTextures[x]->getWidth(), .baseHeight = usedTextures[x]->getHeight(), .baseDepth = usedTextures[x]->getDepth(), - .numDimensions = usedTextures[x]->getDepth() > 1 ? 3u : usedTextures[x]->getHeight() > 1 ? 2u : 1u, + .numDimensions = usedTextures[x]->getDepth() > 1 ? 3u + : usedTextures[x]->getHeight() > 1 ? 2u + : 1u, .numLevels = usedTextures[x]->getMipLevels(), .numLayers = usedTextures[x]->getDepth(), .numFaces = usedTextures[x]->getNumFaces(), @@ -43,10 +35,8 @@ void FontAsset::save(ArchiveBuffer& buffer) const }; ktxTexture2_Create(&createInfo, KTX_TEXTURE_CREATE_ALLOC_STORAGE, &kTexture); - for (uint32 depth = 0; depth < usedTextures[x]->getDepth(); ++depth) - { - for (uint32 face = 0; face < usedTextures[x]->getNumFaces(); ++face) - { + for (uint32 depth = 0; depth < usedTextures[x]->getDepth(); ++depth) { + for (uint32 face = 0; face < usedTextures[x]->getNumFaces(); ++face) { // technically, downloading cant be const, because we have to allocate temporary buffers and change layouts // but practically the texture stays the same const_cast(*(usedTextures[x]))->download(0, depth, face, textureData); @@ -55,9 +45,7 @@ void FontAsset::save(ArchiveBuffer& buffer) const } char writer[100]; snprintf(writer, sizeof(writer), "%s version %s", "SeeleEngine", "0.0.1"); - ktxHashList_AddKVPair(&kTexture->kvDataHead, KTX_WRITER_KEY, - (ktx_uint32_t)strlen(writer) + 1, - writer); + ktxHashList_AddKVPair(&kTexture->kvDataHead, KTX_WRITER_KEY, (ktx_uint32_t)strlen(writer) + 1, writer); ktxTexture2_TranscodeBasis(kTexture, KTX_TTF_ASTC_4x4_RGBA, 0); @@ -74,31 +62,26 @@ void FontAsset::save(ArchiveBuffer& buffer) const } } - -void FontAsset::load(ArchiveBuffer& buffer) -{ +void FontAsset::load(ArchiveBuffer& buffer) { Serialization::load(buffer, glyphs); size_t numTextures; Serialization::load(buffer, numTextures); - for (uint64 x = 0; x < numTextures; ++x) - { + for (uint64 x = 0; x < numTextures; ++x) { Array rawTex; Serialization::load(buffer, rawTex); ktxTexture2* kTexture; - ktxTexture2_CreateFromMemory(rawTex.data(), - rawTex.size(), - KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, - &kTexture); + ktxTexture2_CreateFromMemory(rawTex.data(), rawTex.size(), KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, &kTexture); ktxTexture2_TranscodeBasis(kTexture, KTX_TTF_BC7_RGBA, 0); TextureCreateInfo createInfo = { - .sourceData = { - .size = ktxTexture_GetDataSize(ktxTexture(kTexture)), - .data = ktxTexture_GetData(ktxTexture(kTexture)), - .owner = Gfx::QueueType::GRAPHICS, - }, + .sourceData = + { + .size = ktxTexture_GetDataSize(ktxTexture(kTexture)), + .data = ktxTexture_GetData(ktxTexture(kTexture)), + .owner = Gfx::QueueType::GRAPHICS, + }, .format = (Gfx::SeFormat)kTexture->vkFormat, .width = kTexture->baseWidth, .height = kTexture->baseHeight, @@ -116,21 +99,16 @@ void FontAsset::load(ArchiveBuffer& buffer) } } -void Seele::FontAsset::setUsedTextures(Array _usedTextures) -{ - usedTextures = std::move(_usedTextures); -} +void Seele::FontAsset::setUsedTextures(Array _usedTextures) { usedTextures = std::move(_usedTextures); } -void FontAsset::Glyph::save(ArchiveBuffer& buffer) const -{ +void FontAsset::Glyph::save(ArchiveBuffer& buffer) const { Serialization::save(buffer, textureIndex); Serialization::save(buffer, size); Serialization::save(buffer, bearing); Serialization::save(buffer, advance); } -void FontAsset::Glyph::load(ArchiveBuffer& buffer) -{ +void FontAsset::Glyph::load(ArchiveBuffer& buffer) { Serialization::load(buffer, textureIndex); Serialization::load(buffer, size); Serialization::load(buffer, bearing); diff --git a/src/Engine/Asset/FontAsset.h b/src/Engine/Asset/FontAsset.h index 12dce63..a17a6de 100644 --- a/src/Engine/Asset/FontAsset.h +++ b/src/Engine/Asset/FontAsset.h @@ -3,12 +3,10 @@ #include "Containers/Map.h" #include "Math/Math.h" -namespace Seele -{ +namespace Seele { DECLARE_NAME_REF(Gfx, Texture2D) -class FontAsset : public Asset -{ -public: +class FontAsset : public Asset { + public: static constexpr uint64 IDENTIFIER = 0x10; FontAsset(); FontAsset(std::string_view folderPath, std::string_view name); @@ -16,8 +14,7 @@ public: virtual void save(ArchiveBuffer& buffer) const override; virtual void load(ArchiveBuffer& buffer) override; - struct Glyph - { + struct Glyph { uint32 textureIndex; IVector2 size; IVector2 bearing; @@ -28,7 +25,8 @@ public: const Map getGlyphData() const { return glyphs; } Gfx::PTexture2D getTexture(uint32 index) { return usedTextures[index]; } void setUsedTextures(Array _usedTextures); -private: + + private: Array usedTextures; Map glyphs; friend class FontLoader; diff --git a/src/Engine/Asset/LevelAsset.cpp b/src/Engine/Asset/LevelAsset.cpp index 75073d0..173d424 100644 --- a/src/Engine/Asset/LevelAsset.cpp +++ b/src/Engine/Asset/LevelAsset.cpp @@ -2,28 +2,12 @@ using namespace Seele; -LevelAsset::LevelAsset() -{ - -} +LevelAsset::LevelAsset() {} -LevelAsset::LevelAsset(std::string_view folderPath, std::string_view name) - : Asset(folderPath, name) -{ - -} +LevelAsset::LevelAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {} -LevelAsset::~LevelAsset() -{ - -} +LevelAsset::~LevelAsset() {} -void LevelAsset::save(ArchiveBuffer&) const -{ - -} +void LevelAsset::save(ArchiveBuffer&) const {} -void LevelAsset::load(ArchiveBuffer&) -{ - -} +void LevelAsset::load(ArchiveBuffer&) {} diff --git a/src/Engine/Asset/LevelAsset.h b/src/Engine/Asset/LevelAsset.h index 0b0798e..2029ff3 100644 --- a/src/Engine/Asset/LevelAsset.h +++ b/src/Engine/Asset/LevelAsset.h @@ -1,18 +1,16 @@ #pragma once #include "Asset.h" -namespace Seele -{ -class LevelAsset : public Asset -{ -public: +namespace Seele { +class LevelAsset : public Asset { + public: static constexpr uint64 IDENTIFIER = 0x20; LevelAsset(); LevelAsset(std::string_view folderPath, std::string_view name); virtual ~LevelAsset(); virtual void save(ArchiveBuffer& buffer) const override; virtual void load(ArchiveBuffer& buffer) override; -private: + private: }; } // namespace Seele diff --git a/src/Engine/Asset/MaterialAsset.cpp b/src/Engine/Asset/MaterialAsset.cpp index 3107055..2c427e9 100644 --- a/src/Engine/Asset/MaterialAsset.cpp +++ b/src/Engine/Asset/MaterialAsset.cpp @@ -1,38 +1,27 @@ #include "MaterialAsset.h" -#include "Material/Material.h" -#include "Graphics/Graphics.h" -#include "MaterialInstanceAsset.h" #include "Asset/AssetRegistry.h" +#include "Graphics/Graphics.h" +#include "Material/Material.h" +#include "MaterialInstanceAsset.h" + using namespace Seele; -MaterialAsset::MaterialAsset() -{ -} +MaterialAsset::MaterialAsset() {} -MaterialAsset::MaterialAsset(std::string_view folderPath, std::string_view name) - : Asset(folderPath, name) -{ -} +MaterialAsset::MaterialAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {} -MaterialAsset::~MaterialAsset() -{ -} +MaterialAsset::~MaterialAsset() {} -void MaterialAsset::save(ArchiveBuffer& buffer) const -{ - material->save(buffer); -} +void MaterialAsset::save(ArchiveBuffer& buffer) const { material->save(buffer); } -void MaterialAsset::load(ArchiveBuffer& buffer) -{ +void MaterialAsset::load(ArchiveBuffer& buffer) { material = new Material(); material->load(buffer); material->compile(); } -PMaterialInstanceAsset MaterialAsset::instantiate(const InstantiationParameter& params) -{ +PMaterialInstanceAsset MaterialAsset::instantiate(const InstantiationParameter& params) { OMaterialInstance instance = material->instantiate(); instance->setBaseMaterial(this); OMaterialInstanceAsset asset = new MaterialInstanceAsset(params.folderPath, params.name); diff --git a/src/Engine/Asset/MaterialAsset.h b/src/Engine/Asset/MaterialAsset.h index 386deb4..444b534 100644 --- a/src/Engine/Asset/MaterialAsset.h +++ b/src/Engine/Asset/MaterialAsset.h @@ -1,18 +1,15 @@ #pragma once #include "Asset.h" -namespace Seele -{ +namespace Seele { DECLARE_REF(Material) DECLARE_REF(MaterialInstanceAsset) -struct InstantiationParameter -{ +struct InstantiationParameter { std::string name; std::string folderPath; }; -class MaterialAsset : public Asset -{ -public: +class MaterialAsset : public Asset { + public: static constexpr uint64 IDENTIFIER = 0x4; MaterialAsset(); MaterialAsset(std::string_view folderPath, std::string_view name); @@ -21,7 +18,8 @@ public: virtual void load(ArchiveBuffer& buffer) override; PMaterial getMaterial() const { return material; } PMaterialInstanceAsset instantiate(const InstantiationParameter& params); -private: + + private: OMaterial material; friend class MaterialLoader; friend class MeshLoader; diff --git a/src/Engine/Asset/MaterialInstanceAsset.cpp b/src/Engine/Asset/MaterialInstanceAsset.cpp index 4f4c0d2..4c95f87 100644 --- a/src/Engine/Asset/MaterialInstanceAsset.cpp +++ b/src/Engine/Asset/MaterialInstanceAsset.cpp @@ -1,34 +1,25 @@ #include "MaterialInstanceAsset.h" -#include "Material/MaterialInstance.h" -#include "Material/Material.h" -#include "Graphics/Graphics.h" #include "Asset/AssetRegistry.h" +#include "Graphics/Graphics.h" +#include "Material/Material.h" +#include "Material/MaterialInstance.h" + using namespace Seele; -MaterialInstanceAsset::MaterialInstanceAsset() -{ -} +MaterialInstanceAsset::MaterialInstanceAsset() {} -MaterialInstanceAsset::MaterialInstanceAsset(std::string_view folderPath, std::string_view name) - : Asset(folderPath, name) -{ -} +MaterialInstanceAsset::MaterialInstanceAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {} -MaterialInstanceAsset::~MaterialInstanceAsset() -{ -} +MaterialInstanceAsset::~MaterialInstanceAsset() {} - -void MaterialInstanceAsset::save(ArchiveBuffer& buffer) const -{ +void MaterialInstanceAsset::save(ArchiveBuffer& buffer) const { Serialization::save(buffer, baseMaterial->getFolderPath()); Serialization::save(buffer, baseMaterial->getName()); material->save(buffer); } -void MaterialInstanceAsset::load(ArchiveBuffer& buffer) -{ +void MaterialInstanceAsset::load(ArchiveBuffer& buffer) { std::string folder; Serialization::load(buffer, folder); std::string id; diff --git a/src/Engine/Asset/MaterialInstanceAsset.h b/src/Engine/Asset/MaterialInstanceAsset.h index 6995cbf..326bfe3 100644 --- a/src/Engine/Asset/MaterialInstanceAsset.h +++ b/src/Engine/Asset/MaterialInstanceAsset.h @@ -2,11 +2,9 @@ #include "Asset.h" #include "Material/MaterialInstance.h" -namespace Seele -{ -class MaterialInstanceAsset : public Asset -{ -public: +namespace Seele { +class MaterialInstanceAsset : public Asset { + public: static constexpr uint64 IDENTIFIER = 0x8; MaterialInstanceAsset(); MaterialInstanceAsset(std::string_view folderPath, std::string_view name); @@ -16,7 +14,8 @@ public: void setHandle(OMaterialInstance handle) { material = std::move(handle); } void setBase(PMaterialAsset base) { baseMaterial = base; } PMaterialInstance getHandle() const { return material; } -private: + + private: OMaterialInstance material; PMaterialAsset baseMaterial; }; diff --git a/src/Engine/Asset/MeshAsset.cpp b/src/Engine/Asset/MeshAsset.cpp index dff7038..d7a98e1 100644 --- a/src/Engine/Asset/MeshAsset.cpp +++ b/src/Engine/Asset/MeshAsset.cpp @@ -1,29 +1,17 @@ #include "MeshAsset.h" +#include "AssetRegistry.h" #include "Graphics/Graphics.h" #include "Graphics/Mesh.h" -#include "AssetRegistry.h" + using namespace Seele; -MeshAsset::MeshAsset() -{ -} +MeshAsset::MeshAsset() {} -MeshAsset::MeshAsset(std::string_view folderPath, std::string_view name) - : Asset(folderPath, name) -{ -} +MeshAsset::MeshAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {} -MeshAsset::~MeshAsset() -{ -} +MeshAsset::~MeshAsset() {} -void MeshAsset::save(ArchiveBuffer& buffer) const -{ - Serialization::save(buffer, meshes); -} +void MeshAsset::save(ArchiveBuffer& buffer) const { Serialization::save(buffer, meshes); } -void MeshAsset::load(ArchiveBuffer& buffer) -{ - Serialization::load(buffer, meshes); -} +void MeshAsset::load(ArchiveBuffer& buffer) { Serialization::load(buffer, meshes); } diff --git a/src/Engine/Asset/MeshAsset.h b/src/Engine/Asset/MeshAsset.h index 57091bf..12053ae 100644 --- a/src/Engine/Asset/MeshAsset.h +++ b/src/Engine/Asset/MeshAsset.h @@ -2,20 +2,18 @@ #include "Asset.h" #include "Component/Collider.h" -namespace Seele -{ +namespace Seele { DECLARE_REF(Mesh) DECLARE_REF(MaterialInterface) -class MeshAsset : public Asset -{ -public: +class MeshAsset : public Asset { + public: static constexpr uint64 IDENTIFIER = 0x2; MeshAsset(); MeshAsset(std::string_view folderPath, std::string_view name); virtual ~MeshAsset(); virtual void save(ArchiveBuffer& buffer) const override; virtual void load(ArchiveBuffer& buffer) override; - //Workaround while no editor + // Workaround while no editor Array meshes; Component::Collider physicsMesh; }; diff --git a/src/Engine/Asset/TextureAsset.cpp b/src/Engine/Asset/TextureAsset.cpp index 5ba213a..593b8dc 100644 --- a/src/Engine/Asset/TextureAsset.cpp +++ b/src/Engine/Asset/TextureAsset.cpp @@ -1,69 +1,67 @@ #include "TextureAsset.h" #include "Graphics/Graphics.h" -#include "Window/WindowManager.h" -#include "Graphics/Vulkan/Enums.h" #include "Graphics/Texture.h" +#include "Graphics/Vulkan/Enums.h" +#include "Window/WindowManager.h" #include "ktx.h" + using namespace Seele; -#define KTX_ASSERT(x) { auto error = x; if(error != KTX_SUCCESS) { std::cout << ktxErrorString(error) << std::endl; abort(); } } +#define KTX_ASSERT(x) \ + { \ + auto error = x; \ + if (error != KTX_SUCCESS) { \ + std::cout << ktxErrorString(error) << std::endl; \ + abort(); \ + } \ + } -TextureAsset::TextureAsset() -{ -} +TextureAsset::TextureAsset() {} -TextureAsset::TextureAsset(std::string_view folderPath, std::string_view name) - : Asset(folderPath, name) -{ -} +TextureAsset::TextureAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {} -TextureAsset::~TextureAsset() -{ -} +TextureAsset::~TextureAsset() {} -void TextureAsset::save(ArchiveBuffer& buffer) const -{ - //ktxBasisParams basisParams = { - // .structSize = sizeof(ktxBasisParams), - // .uastc = true, - // .threadCount = std::thread::hardware_concurrency(), - // .normalMap = normalMap, - // .uastcFlags = KTX_PACK_UASTC_LEVEL_VERYSLOW, - // .uastcRDO = true, - // .uastcRDOQualityScalar = 1, - //}; - //KTX_ASSERT(ktxTexture2_CompressBasisEx(ktxHandle, &basisParams)); - //KTX_ASSERT(ktxTexture2_DeflateZstd(ktxHandle, 20)); - //ktx_uint8_t* texData; - //ktx_size_t texSize; - //KTX_ASSERT(ktxTexture_WriteToMemory(ktxTexture(ktxHandle), &texData, &texSize)); +void TextureAsset::save(ArchiveBuffer& buffer) const { + // ktxBasisParams basisParams = { + // .structSize = sizeof(ktxBasisParams), + // .uastc = true, + // .threadCount = std::thread::hardware_concurrency(), + // .normalMap = normalMap, + // .uastcFlags = KTX_PACK_UASTC_LEVEL_VERYSLOW, + // .uastcRDO = true, + // .uastcRDOQualityScalar = 1, + // }; + // KTX_ASSERT(ktxTexture2_CompressBasisEx(ktxHandle, &basisParams)); + // KTX_ASSERT(ktxTexture2_DeflateZstd(ktxHandle, 20)); + // ktx_uint8_t* texData; + // ktx_size_t texSize; + // KTX_ASSERT(ktxTexture_WriteToMemory(ktxTexture(ktxHandle), &texData, &texSize)); // - //Array rawData(texSize); - //std::memcpy(rawData.data(), texData, texSize); - //Serialization::save(buffer, rawData); - //free(texData); + // Array rawData(texSize); + // std::memcpy(rawData.data(), texData, texSize); + // Serialization::save(buffer, rawData); + // free(texData); } -void TextureAsset::load(ArchiveBuffer& buffer) -{ +void TextureAsset::load(ArchiveBuffer& buffer) { std::string ktxPath; Serialization::load(buffer, ktxPath); ktxTexture2* ktxHandle; - - KTX_ASSERT(ktxTexture_CreateFromNamedFile(ktxPath.c_str(), - KTX_TEXTURE_CREATE_NO_FLAGS, - (ktxTexture**)&ktxHandle)); + + KTX_ASSERT(ktxTexture_CreateFromNamedFile(ktxPath.c_str(), KTX_TEXTURE_CREATE_NO_FLAGS, (ktxTexture**)&ktxHandle)); KTX_ASSERT(ktxTexture2_TranscodeBasis(ktxHandle, KTX_TTF_BC7_RGBA, 0)); Gfx::PGraphics graphics = buffer.getGraphics(); TextureCreateInfo createInfo = { - .sourceData = { - .size = ktxTexture_GetDataSize(ktxTexture(ktxHandle)), - .data = ktxTexture_GetData(ktxTexture(ktxHandle)), - .owner = Gfx::QueueType::TRANSFER, - }, + .sourceData = + { + .size = ktxTexture_GetDataSize(ktxTexture(ktxHandle)), + .data = ktxTexture_GetData(ktxTexture(ktxHandle)), + .owner = Gfx::QueueType::TRANSFER, + }, .format = (Gfx::SeFormat)ktxHandle->vkFormat, .width = ktxHandle->baseWidth, .height = ktxHandle->baseHeight, @@ -73,34 +71,20 @@ void TextureAsset::load(ArchiveBuffer& buffer) .elements = ktxHandle->numLayers, .usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT, }; - if (ktxHandle->isCubemap) - { + if (ktxHandle->isCubemap) { texture = graphics->createTextureCube(createInfo); - } - else if (ktxHandle->isArray) - { + } else if (ktxHandle->isArray) { texture = graphics->createTexture3D(createInfo); - } - else - { + } else { texture = graphics->createTexture2D(createInfo); } - + texture->transferOwnership(Gfx::QueueType::GRAPHICS); ktxTexture_Destroy(ktxTexture(ktxHandle)); } -void TextureAsset::setTexture(Gfx::OTexture _texture) -{ - texture = std::move(_texture); -} +void TextureAsset::setTexture(Gfx::OTexture _texture) { texture = std::move(_texture); } -uint32 TextureAsset::getWidth() -{ - return texture->getWidth(); -} +uint32 TextureAsset::getWidth() { return texture->getWidth(); } -uint32 TextureAsset::getHeight() -{ - return texture->getHeight(); -} +uint32 TextureAsset::getHeight() { return texture->getHeight(); } diff --git a/src/Engine/Asset/TextureAsset.h b/src/Engine/Asset/TextureAsset.h index e8b4a35..561ccc6 100644 --- a/src/Engine/Asset/TextureAsset.h +++ b/src/Engine/Asset/TextureAsset.h @@ -2,12 +2,10 @@ #include "Asset.h" struct ktxTexture2; -namespace Seele -{ +namespace Seele { DECLARE_NAME_REF(Gfx, Texture) -class TextureAsset : public Asset -{ -public: +class TextureAsset : public Asset { + public: static constexpr uint64 IDENTIFIER = 0x1; TextureAsset(); TextureAsset(std::string_view folderPath, std::string_view name); @@ -15,13 +13,11 @@ public: virtual void save(ArchiveBuffer& buffer) const override; virtual void load(ArchiveBuffer& buffer) override; void setTexture(Gfx::OTexture _texture); - Gfx::PTexture getTexture() - { - return texture; - } + Gfx::PTexture getTexture() { return texture; } uint32 getWidth(); uint32 getHeight(); -private: + + private: Gfx::OTexture texture; bool normalMap; friend class TextureLoader; diff --git a/src/Engine/Component/Camera.cpp b/src/Engine/Component/Camera.cpp index 6989aad..c6e7493 100644 --- a/src/Engine/Component/Camera.cpp +++ b/src/Engine/Component/Camera.cpp @@ -7,21 +7,14 @@ using namespace Seele; using namespace Seele::Component; using namespace Seele::Math; -Camera::Camera() - : viewMatrix(Matrix4()) - , cameraPos(Vector()) - , bNeedsViewBuild(false) -{ - yaw = -3.1415f/2; +Camera::Camera() : viewMatrix(Matrix4()), cameraPos(Vector()), bNeedsViewBuild(false) { + yaw = -3.1415f / 2; pitch = 0; } -Camera::~Camera() -{ -} +Camera::~Camera() {} -void Camera::mouseMove(float deltaYaw, float deltaPitch) -{ +void Camera::mouseMove(float deltaYaw, float deltaPitch) { yaw += deltaYaw / 500.f; pitch += deltaPitch / 500.f; Vector cameraDirection = glm::normalize(Vector(cos(yaw) * cos(pitch), sin(pitch), sin(yaw) * cos(pitch))); @@ -30,26 +23,22 @@ void Camera::mouseMove(float deltaYaw, float deltaPitch) bNeedsViewBuild = true; } -void Camera::mouseScroll(float x) -{ - getTransform().translate(getTransform().getForward()*x); +void Camera::mouseScroll(float x) { + getTransform().translate(getTransform().getForward() * x); bNeedsViewBuild = true; } -void Camera::moveX(float amount) -{ - getTransform().translate(getTransform().getForward()*amount); +void Camera::moveX(float amount) { + getTransform().translate(getTransform().getForward() * amount); bNeedsViewBuild = true; } -void Camera::moveY(float amount) -{ - getTransform().translate(getTransform().getRight()*amount); +void Camera::moveY(float amount) { + getTransform().translate(getTransform().getRight() * amount); bNeedsViewBuild = true; } -void Camera::buildViewMatrix() -{ +void Camera::buildViewMatrix() { Vector eyePos = getTransform().getPosition(); Vector lookAt = eyePos + getTransform().getForward(); viewMatrix = glm::lookAt(eyePos, lookAt, Vector(0, 1, 0)); diff --git a/src/Engine/Component/Camera.h b/src/Engine/Component/Camera.h index b8a31ed..cf169e6 100644 --- a/src/Engine/Component/Camera.h +++ b/src/Engine/Component/Camera.h @@ -3,34 +3,28 @@ #include "Math/Matrix.h" #include "Transform.h" -namespace Seele -{ -namespace Component -{ -struct Camera -{ +namespace Seele { +namespace Component { +struct Camera { REQUIRE_COMPONENT(Transform) - + Camera(); ~Camera(); - Matrix4 getViewMatrix() const - { - assert (!bNeedsViewBuild); + Matrix4 getViewMatrix() const { + assert(!bNeedsViewBuild); return viewMatrix; } - Vector getCameraPosition() const - { - return cameraPos; - } + Vector getCameraPosition() const { return cameraPos; } void mouseMove(float deltaX, float deltaY); void mouseScroll(float x); void moveX(float amount); void moveY(float amount); void buildViewMatrix(); - + bool mainCamera = false; -private: + + private: float yaw; float pitch; Matrix4 viewMatrix; diff --git a/src/Engine/Component/Collider.cpp b/src/Engine/Component/Collider.cpp index ad30e05..c7728e1 100644 --- a/src/Engine/Component/Collider.cpp +++ b/src/Engine/Component/Collider.cpp @@ -3,8 +3,7 @@ using namespace Seele; using namespace Seele::Component; -Collider Collider::transform(const Transform& transform) const -{ +Collider Collider::transform(const Transform& transform) const { return Collider{ .type = this->type, .boundingbox = this->boundingbox.getTransformedBox(transform.toMatrix()), diff --git a/src/Engine/Component/Collider.h b/src/Engine/Component/Collider.h index 3315947..ee328d5 100644 --- a/src/Engine/Component/Collider.h +++ b/src/Engine/Component/Collider.h @@ -2,17 +2,13 @@ #include "Math/AABB.h" #include "ShapeBase.h" -namespace Seele -{ -namespace Component -{ -enum class ColliderType -{ +namespace Seele { +namespace Component { +enum class ColliderType { STATIC, DYNAMIC, }; -struct Collider -{ +struct Collider { ColliderType type = ColliderType::STATIC; AABB boundingbox; ShapeBase physicsMesh; diff --git a/src/Engine/Component/Component.h b/src/Engine/Component/Component.h index d85dd50..995971d 100644 --- a/src/Engine/Component/Component.h +++ b/src/Engine/Component/Component.h @@ -2,58 +2,41 @@ #include #include -namespace Seele -{ -template -struct Dependencies; -template<> -struct Dependencies<> -{ +namespace Seele { +template struct Dependencies; +template <> struct Dependencies<> { int x; - template - Dependencies operator|(const Dependencies&) - { - return Dependencies(); - } + template Dependencies operator|(const Dependencies&) { return Dependencies(); } }; -template -struct Dependencies : public Dependencies -{ - template - Dependencies operator|(const Dependencies&) - { +template struct Dependencies : public Dependencies { + template Dependencies operator|(const Dependencies&) { return Dependencies(); } int x; }; -namespace Component -{ - template - Comp& getComponent(); +namespace Component { +template Comp& getComponent(); } -template +template concept has_dependencies = requires(Comp) { Comp::dependencies; }; -#define REQUIRE_COMPONENT(x) \ - private: \ - x& get##x() { return getComponent(); } \ - const x& get##x() const { return getComponent(); } \ - public: \ +#define REQUIRE_COMPONENT(x) \ + private: \ + x& get##x() { return getComponent(); } \ + const x& get##x() const { return getComponent(); } \ + \ + public: \ constexpr static Dependencies dependencies = {}; -#define DECLARE_COMPONENT(x) \ - void accessComponent(x& val); \ - template<> \ - x& getComponent(); - - -#define DEFINE_COMPONENT(x) \ - thread_local x* tl_##x = nullptr; \ - void Seele::Component::accessComponent(x& ref) { tl_##x = &ref; } \ - template<> \ - x& Seele::Component::getComponent() { return *tl_##x; } +#define DECLARE_COMPONENT(x) \ + void accessComponent(x& val); \ + template <> x& getComponent(); +#define DEFINE_COMPONENT(x) \ + thread_local x* tl_##x = nullptr; \ + void Seele::Component::accessComponent(x& ref) { tl_##x = &ref; } \ + template <> x& Seele::Component::getComponent() { return *tl_##x; } } // namespace Seele diff --git a/src/Engine/Component/DirectionalLight.h b/src/Engine/Component/DirectionalLight.h index fc89dbc..4cc40b4 100644 --- a/src/Engine/Component/DirectionalLight.h +++ b/src/Engine/Component/DirectionalLight.h @@ -1,11 +1,8 @@ #pragma once #include "Math/Vector.h" -namespace Seele -{ -namespace Component -{ -struct DirectionalLight -{ +namespace Seele { +namespace Component { +struct DirectionalLight { Vector4 color; Vector4 direction; }; diff --git a/src/Engine/Component/KeyboardInput.h b/src/Engine/Component/KeyboardInput.h index cbf83ff..9146c08 100644 --- a/src/Engine/Component/KeyboardInput.h +++ b/src/Engine/Component/KeyboardInput.h @@ -1,12 +1,9 @@ #pragma once #include "Graphics/Resources.h" -namespace Seele -{ -namespace Component -{ -struct KeyboardInput -{ +namespace Seele { +namespace Component { +struct KeyboardInput { Seele::StaticArray(Seele::KeyCode::KEY_LAST)> keys; bool mouse1; bool mouse2; @@ -16,6 +13,6 @@ struct KeyboardInput float deltaY; float scrollX; float scrollY; -}; +}; } // namespace Component } // namespace Seele \ No newline at end of file diff --git a/src/Engine/Component/Mesh.h b/src/Engine/Component/Mesh.h index 8e3c6f8..c8a57c5 100644 --- a/src/Engine/Component/Mesh.h +++ b/src/Engine/Component/Mesh.h @@ -1,12 +1,9 @@ #pragma once #include "Asset/MeshAsset.h" -namespace Seele -{ -namespace Component -{ -struct Mesh -{ +namespace Seele { +namespace Component { +struct Mesh { PMeshAsset asset; bool isStatic = true; }; diff --git a/src/Engine/Component/PointLight.h b/src/Engine/Component/PointLight.h index efbba1c..c43e087 100644 --- a/src/Engine/Component/PointLight.h +++ b/src/Engine/Component/PointLight.h @@ -1,14 +1,11 @@ #pragma once #include "Math/Vector.h" -namespace Seele -{ -namespace Component -{ -struct PointLight -{ +namespace Seele { +namespace Component { +struct PointLight { Vector4 positionWS; - //Vector4 positionVS; + // Vector4 positionVS; Vector4 colorRange; }; } // namespace Component diff --git a/src/Engine/Component/RigidBody.h b/src/Engine/Component/RigidBody.h index b9599ea..05b13b4 100644 --- a/src/Engine/Component/RigidBody.h +++ b/src/Engine/Component/RigidBody.h @@ -1,12 +1,9 @@ #pragma once #include "Math/AABB.h" -namespace Seele -{ -namespace Component -{ -struct RigidBody -{ +namespace Seele { +namespace Component { +struct RigidBody { float mass = 1.0f; Vector force; Vector torque; diff --git a/src/Engine/Component/ShapeBase.cpp b/src/Engine/Component/ShapeBase.cpp index 229eefd..c9aa51d 100644 --- a/src/Engine/Component/ShapeBase.cpp +++ b/src/Engine/Component/ShapeBase.cpp @@ -4,14 +4,12 @@ using namespace Seele; using namespace Seele::Component; - -//https://people.eecs.berkeley.edu/~jfc/mirtich/massProps.html -struct ComputationState -{ +// https://people.eecs.berkeley.edu/~jfc/mirtich/massProps.html +struct ComputationState { // compute physics properties - int A; /* alpha */ - int B; /* beta */ - int C; /* gamma */ + int A; /* alpha */ + int B; /* beta */ + int C; /* gamma */ /* projection integrals */ float P1, Pa, Pb, Paa, Pab, Pbb, Paaa, Paab, Pabb, Pbbb; @@ -24,28 +22,25 @@ struct ComputationState Vector T1, T2, TP; }; -struct Face -{ +struct Face { StaticArray vertices; Vector normal; float w; }; -void computeProjectionIntegrals(Face& f, ComputationState& state) -{ +void computeProjectionIntegrals(Face& f, ComputationState& state) { state.P1 = state.Pa = state.Pb = state.Paa = state.Pab = state.Pbb = state.Paaa = state.Paab = state.Pabb = state.Pbbb = 0.0; - for(uint32_t i = 0; i < 3; ++i) - { + for (uint32_t i = 0; i < 3; ++i) { float a0 = f.vertices[i][state.A]; float b0 = f.vertices[i][state.B]; - float a1 = f.vertices[(i+1)%3][state.A]; - float b1 = f.vertices[(i+1)%3][state.B]; + float a1 = f.vertices[(i + 1) % 3][state.A]; + float b1 = f.vertices[(i + 1) % 3][state.B]; float da = a1 - a0; float db = b1 - b0; float a0_2 = a0 * a0, a0_3 = a0_2 * a0, a0_4 = a0_3 * a0; - float b0_2 = b0 * b0, b0_3 = b0_2 * b0, b0_4 = b0_3 * b0; + float b0_2 = b0 * b0, b0_3 = b0_2 * b0, b0_4 = b0_3 * b0; float a1_2 = a1 * a1, a1_3 = a1_2 * a1; float b1_2 = b1 * b1, b1_3 = b1_2 * b1; @@ -87,10 +82,9 @@ void computeProjectionIntegrals(Face& f, ComputationState& state) state.Pabb /= -60.0; } -void computeFaceIntegrals(Face& f, ComputationState& state) -{ +void computeFaceIntegrals(Face& f, ComputationState& state) { computeProjectionIntegrals(f, state); - float k1 = 1.0f/f.normal[state.C]; + float k1 = 1.0f / f.normal[state.C]; float k2 = k1 * k1; float k3 = k2 * k1; float k4 = k3 * k1; @@ -104,53 +98,46 @@ void computeFaceIntegrals(Face& f, ComputationState& state) state.Faa = k1 * state.Paa; state.Fbb = k1 * state.Pbb; - state.Fcc = k3 * (n[state.A] * n[state.A] * state.Paa - + 2 * n[state.A] * n[state.B] * state.Pab - + n[state.B] * n[state.B] * state.Pbb - + w * (2 * (n[state.A] * state.Pa + n[state.B] * state.Pb) + w * state.P1)); - + state.Fcc = k3 * (n[state.A] * n[state.A] * state.Paa + 2 * n[state.A] * n[state.B] * state.Pab + n[state.B] * n[state.B] * state.Pbb + + w * (2 * (n[state.A] * state.Pa + n[state.B] * state.Pb) + w * state.P1)); + state.Faaa = k1 * state.Paaa; state.Fbbb = k1 * state.Pbbb; - state.Fccc = -k4 * (n[state.A] * n[state.A] * n[state.A] * state.Paaa - + 3 * n[state.A] * n[state.A] * n[state.B] * state.Paab - + 3 * n[state.A] * n[state.B] * n[state.B] * state.Pabb - + 3 * n[state.B] * n[state.B] * n[state.B] * state.Pbbb - + 3 * w * (n[state.A] * n[state.A] * state.Paa - + 2 * n[state.A] * n[state.B] * state.Pa - + n[state.B] * n[state.B] * state.Pbb) - + w * w *(3 * (n[state.A]*state.Pa + n[state.B]*state.Pb) + w * state.P1) - ); - + state.Fccc = + -k4 * + (n[state.A] * n[state.A] * n[state.A] * state.Paaa + 3 * n[state.A] * n[state.A] * n[state.B] * state.Paab + + 3 * n[state.A] * n[state.B] * n[state.B] * state.Pabb + 3 * n[state.B] * n[state.B] * n[state.B] * state.Pbbb + + 3 * w * (n[state.A] * n[state.A] * state.Paa + 2 * n[state.A] * n[state.B] * state.Pa + n[state.B] * n[state.B] * state.Pbb) + + w * w * (3 * (n[state.A] * state.Pa + n[state.B] * state.Pb) + w * state.P1)); + state.Faab = k1 * state.Paab; state.Fbbc = -k2 * (n[state.A] * state.Paab + n[state.B] * state.Pbbb + w * state.Pbb); - state.Fcca = k3 * (n[state.A] * n[state.A] * state.Paa + 2 * n[state.A] * n[state.B] * state.Paab + n[state.B] * n[state.B] * state.Pabb - + w * (2 * (n[state.A] * state.Paa + n[state.B] * state.Pab) + w * state.Pa)); + state.Fcca = k3 * (n[state.A] * n[state.A] * state.Paa + 2 * n[state.A] * n[state.B] * state.Paab + + n[state.B] * n[state.B] * state.Pabb + w * (2 * (n[state.A] * state.Paa + n[state.B] * state.Pab) + w * state.Pa)); } -void computeVolumeIntegrals(const Array vertices, const Array& indices, ComputationState& state) -{ +void computeVolumeIntegrals(const Array vertices, const Array& indices, ComputationState& state) { std::memset(&state, 0, sizeof(ComputationState)); - for (size_t i = 0; i < indices.size(); i+=3) - { + for (size_t i = 0; i < indices.size(); i += 3) { Face f; f.vertices = { vertices[indices[i]], - vertices[indices[i+1]], - vertices[indices[i+2]], + vertices[indices[i + 1]], + vertices[indices[i + 2]], }; - + Vector e1 = f.vertices[2] - f.vertices[0]; Vector e2 = f.vertices[1] - f.vertices[0]; f.normal = glm::normalize(glm::cross(e1, e2)); - f.w = - f.normal.x * f.vertices[0].x - - f.normal.y * f.vertices[0].y - - f.normal.z * f.vertices[0].z; - + f.w = -f.normal.x * f.vertices[0].x - f.normal.y * f.vertices[0].y - f.normal.z * f.vertices[0].z; + float nx = std::abs(f.normal.x); float ny = std::abs(f.normal.y); float nz = std::abs(f.normal.z); - if (nx > ny && nx > nz) state.C = 0; - else state.C = (ny > nz) ? 1 : 2; + if (nx > ny && nx > nz) + state.C = 0; + else + state.C = (ny > nz) ? 1 : 2; state.A = (state.C + 1) % 3; state.B = (state.A + 1) % 3; @@ -172,8 +159,8 @@ void computeVolumeIntegrals(const Array vertices, const Array& i state.TP /= 2.0f; } -void computePhysicsParamsForMesh(Array& vertices, const Array& indices, Matrix3& bodyInertia, Vector& centerOfMass, float& mass) -{ +void computePhysicsParamsForMesh(Array& vertices, const Array& indices, Matrix3& bodyInertia, Vector& centerOfMass, + float& mass) { ComputationState state; computeVolumeIntegrals(vertices, indices, state); float density = 1; @@ -183,9 +170,9 @@ void computePhysicsParamsForMesh(Array& vertices, const Array& i bodyInertia[0][0] = density * (state.T2.y + state.T2.z); bodyInertia[1][1] = density * (state.T2.z + state.T2.x); bodyInertia[2][2] = density * (state.T2.x + state.T2.y); - bodyInertia[0][1] = bodyInertia[1][0] = - density * state.TP.x; - bodyInertia[1][2] = bodyInertia[2][1] = - density * state.TP.y; - bodyInertia[2][1] = bodyInertia[1][2] = - density * state.TP.z; + bodyInertia[0][1] = bodyInertia[1][0] = -density * state.TP.x; + bodyInertia[1][2] = bodyInertia[2][1] = -density * state.TP.y; + bodyInertia[2][1] = bodyInertia[1][2] = -density * state.TP.z; bodyInertia[0][0] -= mass * (r.y * r.y + r.z * r.z); bodyInertia[1][1] -= mass * (r.z * r.z + r.x * r.x); @@ -195,74 +182,61 @@ void computePhysicsParamsForMesh(Array& vertices, const Array& i bodyInertia[2][1] = bodyInertia[1][2] += mass * r.z * r.x; } -ShapeBase::ShapeBase() -{ - -} +ShapeBase::ShapeBase() {} -ShapeBase::ShapeBase(Array vertices, Array indices) - : vertices(vertices) - , indices(indices) -{ +ShapeBase::ShapeBase(Array vertices, Array indices) : vertices(vertices), indices(indices) { computePhysicsParamsForMesh(vertices, indices, bodyInertia, centerOfMass, mass); } -ShapeBase ShapeBase::transform(const Component::Transform& transform) const -{ +ShapeBase ShapeBase::transform(const Component::Transform& transform) const { ShapeBase result = *this; - for(auto& vert : result.vertices) - { + for (auto& vert : result.vertices) { vert = transform.toMatrix() * Vector4(vert, 1.0f); } return result; } -void ShapeBase::addCollider(Array verts, Array inds, Matrix4 matrix) -{ +void ShapeBase::addCollider(Array verts, Array inds, Matrix4 matrix) { size_t indOffset = vertices.size(); - for(auto vert : verts) - { + for (auto vert : verts) { vertices.add(Vector(matrix * Vector4(vert, 1.0f))); } - for(auto ind : inds) - { + for (auto ind : inds) { indices.add(ind + static_cast(indOffset)); } computePhysicsParamsForMesh(vertices, indices, bodyInertia, centerOfMass, mass); } -void ShapeBase::visualize() const -{ +void ShapeBase::visualize() const { Array verts; - for(uint32 i = 0; i < indices.size(); i+=3) - { + for (uint32 i = 0; i < indices.size(); i += 3) { verts.add(DebugVertex{ - .position = Vector(vertices[indices[i+0]]), - .color = Vector(1, 0, 0), - }); - - verts.add(DebugVertex{ - .position = Vector(vertices[indices[i+1]]), + .position = Vector(vertices[indices[i + 0]]), .color = Vector(1, 0, 0), }); verts.add(DebugVertex{ - .position = Vector(vertices[indices[i+1]]), + .position = Vector(vertices[indices[i + 1]]), .color = Vector(1, 0, 0), }); verts.add(DebugVertex{ - .position = Vector(vertices[indices[i+2]]), + .position = Vector(vertices[indices[i + 1]]), .color = Vector(1, 0, 0), }); verts.add(DebugVertex{ - .position = Vector(vertices[indices[i+2]]), + .position = Vector(vertices[indices[i + 2]]), .color = Vector(1, 0, 0), }); verts.add(DebugVertex{ - .position = Vector(vertices[indices[i+0]]), + .position = Vector(vertices[indices[i + 2]]), + .color = Vector(1, 0, 0), + }); + + verts.add(DebugVertex{ + .position = Vector(vertices[indices[i + 0]]), .color = Vector(1, 0, 0), }); } diff --git a/src/Engine/Component/ShapeBase.h b/src/Engine/Component/ShapeBase.h index a036c2a..fb78615 100644 --- a/src/Engine/Component/ShapeBase.h +++ b/src/Engine/Component/ShapeBase.h @@ -1,14 +1,12 @@ #pragma once #include "Containers/Array.h" -#include "Transform.h" #include "Graphics/DebugVertex.h" +#include "Transform.h" -namespace Seele -{ -namespace Component -{ -struct ShapeBase -{ + +namespace Seele { +namespace Component { +struct ShapeBase { ShapeBase(); ShapeBase(Array vertices, Array indices); ShapeBase transform(const Component::Transform& transform) const; diff --git a/src/Engine/Component/Skybox.h b/src/Engine/Component/Skybox.h index 77cf477..c1348fd 100644 --- a/src/Engine/Component/Skybox.h +++ b/src/Engine/Component/Skybox.h @@ -1,12 +1,9 @@ #pragma once #include "Graphics/Texture.h" -namespace Seele -{ -namespace Component -{ -struct Skybox -{ +namespace Seele { +namespace Component { +struct Skybox { Gfx::PTextureCube day; Gfx::PTextureCube night; Vector fogColor; diff --git a/src/Engine/Component/Transform.cpp b/src/Engine/Component/Transform.cpp index 71dc320..e67162e 100644 --- a/src/Engine/Component/Transform.cpp +++ b/src/Engine/Component/Transform.cpp @@ -4,29 +4,11 @@ using namespace Seele::Component; DEFINE_COMPONENT(Transform); -void Transform::setPosition(Vector pos) -{ - transform.setPosition(pos); -} +void Transform::setPosition(Vector pos) { transform.setPosition(pos); } -void Transform::setRotation(Quaternion quat) -{ - transform.setRotation(quat); -} +void Transform::setRotation(Quaternion quat) { transform.setRotation(quat); } -void Transform::setScale(Vector scale) -{ - transform.setScale(scale); -} -void Transform::translate(Vector direction) -{ - transform.setPosition(transform.getPosition() + direction); -} -void Transform::rotate(Quaternion quat) -{ - transform.setRotation(transform.getRotation() * quat); -} -void Transform::scale(Vector scale) -{ - transform.setScale(transform.getScale() + scale); -} \ No newline at end of file +void Transform::setScale(Vector scale) { transform.setScale(scale); } +void Transform::translate(Vector direction) { transform.setPosition(transform.getPosition() + direction); } +void Transform::rotate(Quaternion quat) { transform.setRotation(transform.getRotation() * quat); } +void Transform::scale(Vector scale) { transform.setScale(transform.getScale() + scale); } \ No newline at end of file diff --git a/src/Engine/Component/Transform.h b/src/Engine/Component/Transform.h index 5a31693..c60fa8c 100644 --- a/src/Engine/Component/Transform.h +++ b/src/Engine/Component/Transform.h @@ -1,13 +1,11 @@ #pragma once -#include "Math/Transform.h" #include "Component.h" +#include "Math/Transform.h" -namespace Seele -{ -namespace Component -{ -struct Transform -{ + +namespace Seele { +namespace Component { +struct Transform { Vector getPosition() const { return transform.getPosition(); } Quaternion getRotation() const { return transform.getRotation(); } Vector getScale() const { return transform.getScale(); } @@ -24,7 +22,8 @@ struct Transform void translate(Vector direction); void rotate(Quaternion quat); void scale(Vector scale); -private: + + private: Math::Transform transform; }; DECLARE_COMPONENT(Transform) diff --git a/src/Engine/Concepts.h b/src/Engine/Concepts.h index 657c337..8dc870a 100644 --- a/src/Engine/Concepts.h +++ b/src/Engine/Concepts.h @@ -1,19 +1,12 @@ #pragma once #include -namespace Seele -{ -template +namespace Seele { +template concept invocable = std::invocable; -template -concept serializable = requires(const T& t, Archive& a) -{ - t.save(a); -} && requires(T& t, Archive& a) -{ - t.load(a); -}; -template +template +concept serializable = requires(const T& t, Archive& a) { t.save(a); } && requires(T& t, Archive& a) { t.load(a); }; +template concept enumeration = std::is_enum_v; -} \ No newline at end of file +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Containers/Array.h b/src/Engine/Containers/Array.h index 06aff60..d8cceb9 100644 --- a/src/Engine/Containers/Array.h +++ b/src/Engine/Containers/Array.h @@ -1,105 +1,71 @@ #pragma once #include "EngineTypes.h" +#include +#include #include #include -#include #include -#include + #ifndef DEFAULT_ALLOC_SIZE #define DEFAULT_ALLOC_SIZE 16 #endif -namespace Seele -{ -template > -struct Array -{ -public: - template - class IteratorBase - { - public: +namespace Seele { +template > struct Array { + public: + template class IteratorBase { + public: using iterator_category = std::random_access_iterator_tag; using value_type = X; using difference_type = std::ptrdiff_t; using reference = X&; using pointer = X*; - constexpr IteratorBase(X *x = nullptr) - : p(x) - { - } - constexpr reference operator*() const - { - return *p; - } - constexpr pointer operator->() const - { - return p; - } - constexpr bool operator==(const IteratorBase &other) const - { - return p == other.p; - } - constexpr bool operator!=(const IteratorBase &other) const - { - return p != other.p; - } - constexpr std::strong_ordering operator<=>(const IteratorBase &other) const - { - return p <=> other.p; - } - constexpr IteratorBase operator+(size_t other) const - { + constexpr IteratorBase(X* x = nullptr) : p(x) {} + constexpr reference operator*() const { return *p; } + constexpr pointer operator->() const { return p; } + constexpr bool operator==(const IteratorBase& other) const { return p == other.p; } + constexpr bool operator!=(const IteratorBase& other) const { return p != other.p; } + constexpr std::strong_ordering operator<=>(const IteratorBase& other) const { return p <=> other.p; } + constexpr IteratorBase operator+(size_t other) const { IteratorBase tmp(*this); tmp.p += other; return tmp; } - constexpr int operator-(const IteratorBase &other) const - { - return (int)(p - other.p); - } - constexpr IteratorBase& operator-=(difference_type other) - { - p-=other; + constexpr int operator-(const IteratorBase& other) const { return (int)(p - other.p); } + constexpr IteratorBase& operator-=(difference_type other) { + p -= other; return *this; } - constexpr IteratorBase& operator+=(difference_type other) - { - p+=other; + constexpr IteratorBase& operator+=(difference_type other) { + p += other; return *this; } - constexpr IteratorBase operator-(difference_type diff) const - { - return IteratorBase(p - diff); - } - constexpr IteratorBase &operator++() - { + constexpr IteratorBase operator-(difference_type diff) const { return IteratorBase(p - diff); } + constexpr IteratorBase& operator++() { p++; return *this; } - constexpr IteratorBase &operator--() - { + constexpr IteratorBase& operator--() { p--; return *this; } - constexpr IteratorBase operator++(int) - { + constexpr IteratorBase operator++(int) { IteratorBase tmp(*this); ++*this; return tmp; } - constexpr IteratorBase operator--(int) - { + constexpr IteratorBase operator--(int) { IteratorBase tmp(*this); --*this; return tmp; } - private: - X *p; + + private: + X* p; }; - + using value_type = T; using allocator_type = Allocator; using size_type = std::size_t; @@ -116,97 +82,63 @@ public: using reverse_iterator = std::reverse_iterator; using const_reverse_iterator = std::reverse_iterator; - constexpr Array() noexcept(noexcept(Allocator())) - : arraySize(0) - , allocated(DEFAULT_ALLOC_SIZE) - , allocator(Allocator()) - { + constexpr Array() noexcept(noexcept(Allocator())) : arraySize(0), allocated(DEFAULT_ALLOC_SIZE), allocator(Allocator()) { _data = allocateArray(DEFAULT_ALLOC_SIZE); assert(_data != nullptr); } - constexpr explicit Array(const allocator_type& alloc) noexcept - : arraySize(0) - , allocated(DEFAULT_ALLOC_SIZE) - , allocator(alloc) - { + constexpr explicit Array(const allocator_type& alloc) noexcept : arraySize(0), allocated(DEFAULT_ALLOC_SIZE), allocator(alloc) { _data = allocateArray(DEFAULT_ALLOC_SIZE); assert(_data != nullptr); } constexpr Array(size_type size, const value_type& value, const allocator_type& alloc = allocator_type()) - : arraySize(size) - , allocated(size) - , allocator(alloc) - { + : arraySize(size), allocated(size), allocator(alloc) { _data = allocateArray(size); assert(_data != nullptr); - for (size_type i = 0; i < size; ++i) - { + for (size_type i = 0; i < size; ++i) { std::allocator_traits::construct(allocator, &_data[i], value); } } constexpr explicit Array(size_type size, const allocator_type& alloc = allocator_type()) - : arraySize(size) - , allocated(size) - , allocator(alloc) - { + : arraySize(size), allocated(size), allocator(alloc) { _data = allocateArray(size); assert(_data != nullptr); - if constexpr (std::is_integral_v || std::is_floating_point_v) - { + if constexpr (std::is_integral_v || std::is_floating_point_v) { std::memset(_data, 0, size * sizeof(T)); - } - else - { - for (size_type i = 0; i < size; ++i) - { + } else { + for (size_type i = 0; i < size; ++i) { std::allocator_traits::construct(allocator, &_data[i]); } } } constexpr Array(std::initializer_list init, const allocator_type& alloc = allocator_type()) - : arraySize(init.size()) - , allocated(init.size()) - , allocator(alloc) - { + : arraySize(init.size()), allocated(init.size()), allocator(alloc) { _data = allocateArray(init.size()); assert(_data != nullptr); std::uninitialized_move(init.begin(), init.end(), begin()); } - - constexpr Array(const Array &other) - : arraySize(other.arraySize) - , allocated(other.allocated) - , allocator(std::allocator_traits::select_on_container_copy_construction(other.allocator)) - { + + constexpr Array(const Array& other) + : arraySize(other.arraySize), allocated(other.allocated), + allocator(std::allocator_traits::select_on_container_copy_construction(other.allocator)) { _data = allocateArray(other.allocated); assert(_data != nullptr); std::uninitialized_copy(other.begin(), other.end(), begin()); } - constexpr Array(const Array& other, const Allocator& alloc) - : arraySize(other.arraySize) - , allocated(other.allocated) - , allocator(alloc) - { + constexpr Array(const Array& other, const Allocator& alloc) : arraySize(other.arraySize), allocated(other.allocated), allocator(alloc) { _data = allocateArray(other.allocated); assert(_data != nullptr); std::uninitialized_copy(other.begin(), other.end(), begin()); } - constexpr Array(Array &&other) noexcept - : arraySize(std::move(other.arraySize)) - , allocated(std::move(other.allocated)) - , allocator(std::move(other.allocator)) - { + constexpr Array(Array&& other) noexcept + : arraySize(std::move(other.arraySize)), allocated(std::move(other.allocated)), allocator(std::move(other.allocator)) { _data = other._data; other._data = nullptr; other.allocated = 0; other.arraySize = 0; } - constexpr Array(Array &&other, const Allocator& alloc) noexcept - : arraySize(std::move(other.arraySize)) - , allocated(std::move(other.allocated)) - , allocator(alloc) - { + constexpr Array(Array&& other, const Allocator& alloc) noexcept + : arraySize(std::move(other.arraySize)), allocated(std::move(other.allocated)), allocator(alloc) { _data = allocateArray(other.allocated); std::uninitialized_move(other.begin(), other.end(), begin()); other.deallocateArray(other._data, other.allocated); @@ -214,25 +146,18 @@ public: other.allocated = 0; other.arraySize = 0; } - Array &operator=(const Array &other) - { - if (this != &other) - { - if (other.arraySize > allocated) - { + Array& operator=(const Array& other) { + if (this != &other) { + if (other.arraySize > allocated) { clear(); } - if constexpr (std::allocator_traits::propagate_on_container_copy_assignment::value ) - { - if (!std::allocator_traits::is_always_equal::value - && allocator != other.allocator) - { + if constexpr (std::allocator_traits::propagate_on_container_copy_assignment::value) { + if (!std::allocator_traits::is_always_equal::value && allocator != other.allocator) { clear(); } allocator = other.allocator; } - if(_data == nullptr) - { + if (_data == nullptr) { _data = allocateArray(other.allocated); allocated = other.allocated; } @@ -241,17 +166,13 @@ public: } return *this; } - Array &operator=(Array &&other) noexcept(std::allocator_traits::propagate_on_container_move_assignment::value - || std::allocator_traits::is_always_equal::value) - { - if (this != &other) - { - if (_data != nullptr) - { + Array& operator=(Array&& other) noexcept(std::allocator_traits::propagate_on_container_move_assignment::value || + std::allocator_traits::is_always_equal::value) { + if (this != &other) { + if (_data != nullptr) { clear(); } - if constexpr (std::allocator_traits::propagate_on_container_move_assignment::value) - { + if constexpr (std::allocator_traits::propagate_on_container_move_assignment::value) { allocator = std::move(other.allocator); } allocated = std::move(other.allocated); @@ -261,155 +182,98 @@ public: } return *this; } - constexpr ~Array() - { - clear(); - } - + constexpr ~Array() { clear(); } + [[nodiscard]] - constexpr iterator find(const value_type &item) noexcept - { - for (size_type i = 0; i < arraySize; ++i) - { - if (_data[i] == item) - { + constexpr iterator find(const value_type& item) noexcept { + for (size_type i = 0; i < arraySize; ++i) { + if (_data[i] == item) { return iterator(&_data[i]); } } return end(); } [[nodiscard]] - constexpr iterator find(value_type&& item) noexcept - { - for (size_type i = 0; i < arraySize; ++i) - { - if (_data[i] == item) - { + constexpr iterator find(value_type&& item) noexcept { + for (size_type i = 0; i < arraySize; ++i) { + if (_data[i] == item) { return iterator(&_data[i]); } } - return end(); + return end(); } [[nodiscard]] - constexpr const_iterator find(const value_type &item) const noexcept - { - for (size_type i = 0; i < arraySize; ++i) - { - if (_data[i] == item) - { + constexpr const_iterator find(const value_type& item) const noexcept { + for (size_type i = 0; i < arraySize; ++i) { + if (_data[i] == item) { return const_iterator(&_data[i]); } } return end(); } [[nodiscard]] - constexpr const_iterator find(value_type&& item) const noexcept - { - for (size_type i = 0; i < arraySize; ++i) - { - if (_data[i] == item) - { + constexpr const_iterator find(value_type&& item) const noexcept { + for (size_type i = 0; i < arraySize; ++i) { + if (_data[i] == item) { return const_iterator(&_data[i]); } } - return end(); + return end(); } - template - requires std::predicate - constexpr const_iterator find(Pred pred) const noexcept - { - for (size_type i = 0; i < arraySize; ++i) - { - if(pred(_data[i])) - { + template + requires std::predicate + constexpr const_iterator find(Pred pred) const noexcept { + for (size_type i = 0; i < arraySize; ++i) { + if (pred(_data[i])) { return const_iterator(&_data[i]); } } return end(); } - template - requires std::predicate - constexpr iterator find(Pred pred) noexcept - { - for (size_type i = 0; i < arraySize; ++i) - { - if (pred(_data[i])) - { + template + requires std::predicate + constexpr iterator find(Pred pred) noexcept { + for (size_type i = 0; i < arraySize; ++i) { + if (pred(_data[i])) { return iterator(&_data[i]); } } return end(); } - constexpr allocator_type get_allocator() const noexcept - { - return allocator; - } - constexpr iterator begin() noexcept - { - return iterator(_data); - } - constexpr iterator end() noexcept - { - return iterator(_data + arraySize); - } - constexpr const_iterator begin() const noexcept - { - return const_iterator(_data); - } - constexpr const_iterator end() const noexcept - { - return const_iterator(_data + arraySize); - } - constexpr const_iterator cbegin() const noexcept - { - return const_iterator(_data); - } - constexpr const_iterator cend() const noexcept - { - return const_iterator(_data + arraySize); - } - constexpr reference add(const value_type &item = value_type()) - { - return addInternal(item); - } - constexpr reference add(value_type&& item) - { - return addInternal(std::forward(item)); - } - constexpr void addAll(const Array& other) - { - for(const auto& value : other) - { + constexpr allocator_type get_allocator() const noexcept { return allocator; } + constexpr iterator begin() noexcept { return iterator(_data); } + constexpr iterator end() noexcept { return iterator(_data + arraySize); } + constexpr const_iterator begin() const noexcept { return const_iterator(_data); } + constexpr const_iterator end() const noexcept { return const_iterator(_data + arraySize); } + constexpr const_iterator cbegin() const noexcept { return const_iterator(_data); } + constexpr const_iterator cend() const noexcept { return const_iterator(_data + arraySize); } + constexpr reference add(const value_type& item = value_type()) { return addInternal(item); } + constexpr reference add(value_type&& item) { return addInternal(std::forward(item)); } + constexpr void addAll(const Array& other) { + for (const auto& value : other) { addInternal(value); } } - constexpr void addAll(Array&& other) - { - for(auto&& value : other) - { - addInternal(value); - } + constexpr void addAll(Array&& other) { + for (auto&& value : other) { + addInternal(value); + } } - constexpr reference addUnique(const value_type &item = value_type()) - { + constexpr reference addUnique(const value_type& item = value_type()) { iterator it; - if((it = std::move(find(item))) != end()) - { + if ((it = std::move(find(item))) != end()) { return *it; } return addInternal(item); } - template - constexpr reference emplace(args... arguments) - { - if (arraySize == allocated) - { + template constexpr reference emplace(args... arguments) { + if (arraySize == allocated) { size_type newSize = arraySize + 1; allocated = calculateGrowth(newSize); - T *tempArray = allocateArray(allocated); + T* tempArray = allocateArray(allocated); assert(tempArray != nullptr); - + std::uninitialized_move(begin(), end(), Iterator(tempArray)); deallocateArray(_data, arraySize); _data = tempArray; @@ -417,61 +281,33 @@ public: std::allocator_traits::construct(allocator, &_data[arraySize++], arguments...); return _data[arraySize - 1]; } - template - requires std::predicate - constexpr void remove_if(Pred pred, bool keepOrder = true) - { + template + requires std::predicate + constexpr void remove_if(Pred pred, bool keepOrder = true) { remove(find(pred), keepOrder); } - constexpr void remove(const value_type& element, bool keepOrder = true) - { - remove(find(element), keepOrder); - } - constexpr void remove(value_type&& element, bool keepOrder = true) - { - remove(find(element), keepOrder); - } - constexpr void remove(iterator it, bool keepOrder = true) - { - removeAt(it - begin(), keepOrder); - } - constexpr void remove(const_iterator it, bool keepOrder = true) - { - removeAt(it - cbegin(), keepOrder); - } - constexpr void removeAt(size_type index, bool keepOrder = true) - { - if (keepOrder) - { - for(size_type i = index; i < arraySize-1; ++i) - { - _data[i] = std::move(_data[i+1]); + constexpr void remove(const value_type& element, bool keepOrder = true) { remove(find(element), keepOrder); } + constexpr void remove(value_type&& element, bool keepOrder = true) { remove(find(element), keepOrder); } + constexpr void remove(iterator it, bool keepOrder = true) { removeAt(it - begin(), keepOrder); } + constexpr void remove(const_iterator it, bool keepOrder = true) { removeAt(it - cbegin(), keepOrder); } + constexpr void removeAt(size_type index, bool keepOrder = true) { + if (keepOrder) { + for (size_type i = index; i < arraySize - 1; ++i) { + _data[i] = std::move(_data[i + 1]); } - } - else - { + } else { _data[index] = std::move(_data[arraySize - 1]); } std::allocator_traits::destroy(allocator, &_data[--arraySize]); } - constexpr void resize(size_type newSize) - { - resizeInternal(newSize, T()); - } - constexpr void resize(size_type newSize, const value_type& value) - { - resizeInternal(newSize, value); - } - constexpr void clear() noexcept - { - if(_data == nullptr) - { + constexpr void resize(size_type newSize) { resizeInternal(newSize, T()); } + constexpr void resize(size_type newSize, const value_type& value) { resizeInternal(newSize, value); } + constexpr void clear() noexcept { + if (_data == nullptr) { return; } - if constexpr (!std::is_trivially_destructible_v) - { - for (size_type i = 0; i < arraySize; ++i) - { + if constexpr (!std::is_trivially_destructible_v) { + for (size_type i = 0; i < arraySize; ++i) { std::allocator_traits::destroy(allocator, &_data[i]); } } @@ -480,42 +316,21 @@ public: arraySize = 0; allocated = 0; } - constexpr size_type indexOf(iterator iterator) - { - return iterator - begin(); - } - constexpr size_type indexOf(const_iterator iterator) const - { - return iterator.p - begin().p; - } - constexpr size_type indexOf(T& t) - { - return indexOf(find(t)); - } - constexpr size_type indexOf(const T& t) const - { - return indexOf(find(t)); - } - constexpr size_type size() const noexcept - { - return arraySize; - } + constexpr size_type indexOf(iterator iterator) { return iterator - begin(); } + constexpr size_type indexOf(const_iterator iterator) const { return iterator.p - begin().p; } + constexpr size_type indexOf(T& t) { return indexOf(find(t)); } + constexpr size_type indexOf(const T& t) const { return indexOf(find(t)); } + constexpr size_type size() const noexcept { return arraySize; } [[nodiscard]] - constexpr bool empty() const noexcept - { + constexpr bool empty() const noexcept { return arraySize == 0; } - constexpr void reserve(size_type new_cap) - { - if(new_cap > allocated) - { + constexpr void reserve(size_type new_cap) { + if (new_cap > allocated) { T* temp = allocateArray(new_cap); - if constexpr (std::is_trivially_copyable_v) - { + if constexpr (std::is_trivially_copyable_v) { std::memcpy(temp, _data, sizeof(T) * arraySize); - } - else - { + } else { std::uninitialized_move_n(begin(), arraySize, temp); } deallocateArray(_data, allocated); @@ -523,78 +338,55 @@ public: } allocated = new_cap; } - constexpr size_type capacity() const noexcept - { - return allocated; - } - constexpr pointer data() const noexcept - { - return _data; - } - constexpr reference front() const - { + constexpr size_type capacity() const noexcept { return allocated; } + constexpr pointer data() const noexcept { return _data; } + constexpr reference front() const { assert(arraySize > 0); return _data[0]; } - constexpr reference back() const - { + constexpr reference back() const { assert(arraySize > 0); return _data[arraySize - 1]; } - constexpr void pop() - { - std::allocator_traits::destroy(allocator, &_data[--arraySize]); - } - constexpr reference operator[](size_type index) - { + constexpr void pop() { std::allocator_traits::destroy(allocator, &_data[--arraySize]); } + constexpr reference operator[](size_type index) { assert(index < arraySize); return _data[index]; } - constexpr const_reference operator[](size_type index) const - { + constexpr const_reference operator[](size_type index) const { assert(index < arraySize); return _data[index]; } -private: - size_type calculateGrowth(size_type newSize) const - { + + private: + size_type calculateGrowth(size_type newSize) const { const size_type oldCapacity = capacity(); - if (oldCapacity > SIZE_MAX - oldCapacity) - { + if (oldCapacity > SIZE_MAX - oldCapacity) { return newSize; // geometric growth would overflow } const size_type geometric = oldCapacity + oldCapacity; - if (geometric < newSize) - { + if (geometric < newSize) { return newSize; // geometric growth would be insufficient } return geometric; // geometric growth is sufficient } [[nodiscard]] - T* allocateArray(size_type size) - { + T* allocateArray(size_type size) { T* result = allocator.allocate(size); assert(result != nullptr); return result; } - void deallocateArray(T* ptr, size_type size) - { - allocator.deallocate(ptr, size); - } - template - T& addInternal(Type&& t) noexcept - { - if (arraySize == allocated) - { + void deallocateArray(T* ptr, size_type size) { allocator.deallocate(ptr, size); } + template T& addInternal(Type&& t) noexcept { + if (arraySize == allocated) { size_type newSize = arraySize + 1; allocated = calculateGrowth(newSize); - T *tempArray = allocateArray(allocated); - for (size_type i = 0; i < arraySize; ++i) - { + T* tempArray = allocateArray(allocated); + for (size_type i = 0; i < arraySize; ++i) { std::allocator_traits::construct(allocator, &tempArray[i], std::forward(_data[i])); } deallocateArray(_data, arraySize); @@ -603,52 +395,37 @@ private: std::allocator_traits::construct(allocator, &_data[arraySize], std::forward(t)); return _data[arraySize++]; } - template - void resizeInternal(size_type newSize, const Type& value) noexcept - { - if (newSize <= allocated) - { + template void resizeInternal(size_type newSize, const Type& value) noexcept { + if (newSize <= allocated) { // The array is already big enough - if(newSize < arraySize) - { + if (newSize < arraySize) { // But since we are sizing down we destruct some of them - if constexpr (!std::is_trivially_destructible_v) - { - for (size_type i = newSize; i < arraySize; ++i) - { + if constexpr (!std::is_trivially_destructible_v) { + for (size_type i = newSize; i < arraySize; ++i) { std::allocator_traits::destroy(allocator, &_data[i]); } } - } - else - { + } else { // Or construct the new elements by default - for(size_type i = arraySize; i < newSize; ++i) - { + for (size_type i = arraySize; i < newSize; ++i) { std::allocator_traits::construct(allocator, &_data[i], value); } } arraySize = newSize; - } - else - { + } else { allocated = calculateGrowth(newSize); // The array is not big enough, so we make a new one - T *newData = allocateArray(allocated); + T* newData = allocateArray(allocated); - if constexpr (std::is_integral_v || std::is_floating_point_v) - { + if constexpr (std::is_integral_v || std::is_floating_point_v) { std::memcpy(newData, _data, sizeof(T) * arraySize); std::memset(&newData[arraySize], 0, sizeof(T) * (allocated - arraySize)); - } - else - { + } else { // And move the current elements into that one std::uninitialized_move(begin(), end(), Iterator(newData)); // As well as default initialize the others - for (size_type i = arraySize; i < allocated; ++i) - { + for (size_type i = arraySize; i < allocated; ++i) { std::allocator_traits::construct(allocator, &newData[i], value); } } @@ -659,94 +436,62 @@ private: } size_type arraySize = 0; size_type allocated = 0; - T *_data = nullptr; + T* _data = nullptr; allocator_type allocator; }; - -template -constexpr bool operator==(const Array &lhs, const Array& rhs) -{ - if(lhs.size() != rhs.size()) - { +template constexpr bool operator==(const Array& lhs, const Array& rhs) { + if (lhs.size() != rhs.size()) { return false; } - for(auto it1 = lhs.begin(), it2 = rhs.begin(); it1 != lhs.end() && it2 != rhs.end(); ++it1, ++it2) - { - if(*it1 != *it2) - { + for (auto it1 = lhs.begin(), it2 = rhs.begin(); it1 != lhs.end() && it2 != rhs.end(); ++it1, ++it2) { + if (*it1 != *it2) { return false; } } return true; } -template -constexpr auto operator<=>(const Array& lhs, const Array& rhs) -{ +template constexpr auto operator<=>(const Array& lhs, const Array& rhs) { return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); } -template -struct StaticArray -{ -public: - template - class IteratorBase - { - public: +template struct StaticArray { + public: + template class IteratorBase { + public: using iterator_category = std::random_access_iterator_tag; using value_type = X; using difference_type = std::ptrdiff_t; using reference = X&; using pointer = X*; - IteratorBase(X *x = nullptr) - : p(x) - { - } - reference operator*() const - { - return *p; - } - pointer operator->() const - { - return p; - } - inline bool operator!=(const IteratorBase &other) - { - return p != other.p; - } - inline bool operator==(const IteratorBase &other) - { - return p == other.p; - } - IteratorBase &operator++() - { + IteratorBase(X* x = nullptr) : p(x) {} + reference operator*() const { return *p; } + pointer operator->() const { return p; } + inline bool operator!=(const IteratorBase& other) { return p != other.p; } + inline bool operator==(const IteratorBase& other) { return p == other.p; } + IteratorBase& operator++() { p++; return *this; } - IteratorBase operator++(int) - { + IteratorBase operator++(int) { IteratorBase tmp(*this); ++*this; return tmp; } - IteratorBase &operator--() - { + IteratorBase& operator--() { p--; return *this; } - IteratorBase operator--(int) - { + IteratorBase operator--(int) { IteratorBase tmp(*this); --*this; return tmp; } - - private: - X *p; + private: + X* p; }; using value_type = T; using size_type = size_t; @@ -762,85 +507,47 @@ public: using reverse_iterator = std::reverse_iterator; using const_reverse_iterator = std::reverse_iterator; - StaticArray() - { + StaticArray() { beginIt = iterator(_data); endIt = iterator(_data + N); } - StaticArray(T value) - { - for (size_t i = 0; i < N; ++i) - { + StaticArray(T value) { + for (size_t i = 0; i < N; ++i) { _data[i] = value; } beginIt = iterator(_data); endIt = iterator(_data + N); } - StaticArray(std::initializer_list init) - { + StaticArray(std::initializer_list init) { auto beg = init.begin(); - for (size_t i = 0; i < N; ++i) - { + for (size_t i = 0; i < N; ++i) { _data[i] = *beg; - if (init.size() == N) - { + if (init.size() == N) { beg++; } } } - ~StaticArray() - { - } - - inline size_type size() const - { - return N; - } - inline pointer data() - { - return _data; - } - inline const_pointer data() const - { - return _data; - } - template - constexpr reference operator[](I index) noexcept - { - return operator[](static_cast(index)); - } - template - constexpr const_reference operator[](I index) const noexcept - { - return operator[](static_cast(index)); - } - constexpr reference operator[](size_type index) noexcept - { + ~StaticArray() {} + + inline size_type size() const { return N; } + inline pointer data() { return _data; } + inline const_pointer data() const { return _data; } + template constexpr reference operator[](I index) noexcept { return operator[](static_cast(index)); } + template constexpr const_reference operator[](I index) const noexcept { return operator[](static_cast(index)); } + constexpr reference operator[](size_type index) noexcept { assert(index < N); return _data[index]; } - constexpr const_reference operator[](size_type index) const noexcept - { + constexpr const_reference operator[](size_type index) const noexcept { assert(index < N); return _data[index]; } - iterator begin() - { - return beginIt; - } - iterator end() - { - return endIt; - } - const_iterator begin() const - { - return beginIt; - } - const_iterator end() const - { - return beginIt; - } -private: + iterator begin() { return beginIt; } + iterator end() { return endIt; } + const_iterator begin() const { return beginIt; } + const_iterator end() const { return beginIt; } + + private: T _data[N]; iterator beginIt; iterator endIt; diff --git a/src/Engine/Containers/List.h b/src/Engine/Containers/List.h index d2c7cd8..2bb908d 100644 --- a/src/Engine/Containers/List.h +++ b/src/Engine/Containers/List.h @@ -1,124 +1,77 @@ #pragma once -#include #include +#include -namespace Seele -{ -template > -class List -{ -private: - struct Node - { - Node(Node* prev, Node* next, const T& data) - : prev(prev) - , next(next) - , data(data) - {} - Node(Node* prev, Node* next, T&& data) - : prev(prev) - , next(next) - , data(std::move(data)) - {} - Node *prev; - Node *next; + +namespace Seele { +template > class List { + private: + struct Node { + Node(Node* prev, Node* next, const T& data) : prev(prev), next(next), data(data) {} + Node(Node* prev, Node* next, T&& data) : prev(prev), next(next), data(std::move(data)) {} + Node* prev; + Node* next; T data; }; using NodeAllocator = std::allocator_traits::template rebind_alloc; -public: - template - class IteratorBase - { - public: + public: + template class IteratorBase { + public: using iterator_category = std::forward_iterator_tag; using value_type = X; using difference_type = std::ptrdiff_t; using reference = X&; using pointer = X*; - IteratorBase(Node *x = nullptr) - : node(x) - { - } - IteratorBase(const IteratorBase &i) - : node(i.node) - { - } - IteratorBase(IteratorBase&& i) noexcept - : node(std::move(i.node)) - { - } - ~IteratorBase() - { - } - IteratorBase& operator=(const IteratorBase& other) - { - if(this != &other) - { + IteratorBase(Node* x = nullptr) : node(x) {} + IteratorBase(const IteratorBase& i) : node(i.node) {} + IteratorBase(IteratorBase&& i) noexcept : node(std::move(i.node)) {} + ~IteratorBase() {} + IteratorBase& operator=(const IteratorBase& other) { + if (this != &other) { node = other.node; } return *this; } - IteratorBase& operator=(IteratorBase&& other) noexcept - { - if(this != &other) - { + IteratorBase& operator=(IteratorBase&& other) noexcept { + if (this != &other) { node = std::move(other.node); } return *this; } - constexpr reference operator*() const - { - return node->data; - } - constexpr pointer operator->() const - { - return &node->data; - } - constexpr bool operator!=(const IteratorBase &other) - { - return node != other.node; - } - constexpr bool operator==(const IteratorBase &other) - { - return node == other.node; - } - constexpr std::strong_ordering operator<=>(const IteratorBase& other) - { - return node <=> other.node; - } - constexpr IteratorBase &operator--() - { + constexpr reference operator*() const { return node->data; } + constexpr pointer operator->() const { return &node->data; } + constexpr bool operator!=(const IteratorBase& other) { return node != other.node; } + constexpr bool operator==(const IteratorBase& other) { return node == other.node; } + constexpr std::strong_ordering operator<=>(const IteratorBase& other) { return node <=> other.node; } + constexpr IteratorBase& operator--() { node = node->prev; return *this; } - constexpr IteratorBase operator--(int) - { + constexpr IteratorBase operator--(int) { IteratorBase tmp(*this); --*this; return tmp; } - constexpr IteratorBase &operator++() - { + constexpr IteratorBase& operator++() { node = node->next; return *this; } - constexpr IteratorBase operator++(int) - { + constexpr IteratorBase operator++(int) { IteratorBase tmp(*this); ++*this; return tmp; } - private: - Node *node; + private: + Node* node; friend class List; }; - + using Iterator = IteratorBase; using ConstIterator = IteratorBase; - + using value_type = T; using allocator_type = Allocator; using size_type = std::size_t; @@ -132,118 +85,72 @@ public: using const_iterator = ConstIterator; using reverse_iterator = std::reverse_iterator; using const_reverse_iterator = std::reverse_iterator; - - constexpr List() - : allocator(Allocator()) - , root(allocateNode()) - , tail(root) - , beginIt(Iterator(root)) - , endIt(Iterator(tail)) - , _size(0) - { - } + + constexpr List() : allocator(Allocator()), root(allocateNode()), tail(root), beginIt(Iterator(root)), endIt(Iterator(tail)), _size(0) {} constexpr explicit List(const Allocator& alloc) - : allocator(alloc) - , root(allocateNode()) - , tail(root) - , beginIt(Iterator(root)) - , endIt(Iterator(tail)) - , _size(0) - { - } - constexpr List(size_type count, const T& value = T(), const Allocator& alloc = Allocator()) - : List(alloc) - { - for(size_type i = 0; i < count; ++i) - { + : allocator(alloc), root(allocateNode()), tail(root), beginIt(Iterator(root)), endIt(Iterator(tail)), _size(0) {} + constexpr List(size_type count, const T& value = T(), const Allocator& alloc = Allocator()) : List(alloc) { + for (size_type i = 0; i < count; ++i) { add(value); } } - constexpr List(size_type count, const Allocator& alloc = Allocator()) - : List(alloc) - { - for(size_type i = 0; i < count; ++i) - { + constexpr List(size_type count, const Allocator& alloc = Allocator()) : List(alloc) { + for (size_type i = 0; i < count; ++i) { add(T()); } } constexpr List(const List& other) - : List(std::allocator_traits::select_on_container_copy_construction(other.allocator)) - { - //TODO: improve - for(const auto& it : other) - { + : List(std::allocator_traits::select_on_container_copy_construction(other.allocator)) { + // TODO: improve + for (const auto& it : other) { add(it); } } - - constexpr List(const List& other, const Allocator& alloc) - : List(alloc) - { - //TODO: improve - for(const auto& it : other) - { + + constexpr List(const List& other, const Allocator& alloc) : List(alloc) { + // TODO: improve + for (const auto& it : other) { add(it); } } constexpr List(List&& other) - : allocator(std::move(other.allocator)) - , root(std::move(other.root)) - , tail(std::move(other.tail)) - , beginIt(std::move(other.beginIt)) - , endIt(std::move(other.endIt)) - , _size(std::move(other._size)) - { + : allocator(std::move(other.allocator)), root(std::move(other.root)), tail(std::move(other.tail)), + beginIt(std::move(other.beginIt)), endIt(std::move(other.endIt)), _size(std::move(other._size)) { other.root = nullptr; other.tail = nullptr; other._size = 0; } constexpr List(List&& other, const Allocator& alloc) - : allocator(alloc) - , root(std::move(other.root)) - , tail(std::move(other.tail)) - , beginIt(std::move(other.beginIt)) - , endIt(std::move(other.endIt)) - , _size(std::move(other._size)) - { + : allocator(alloc), root(std::move(other.root)), tail(std::move(other.tail)), beginIt(std::move(other.beginIt)), + endIt(std::move(other.endIt)), _size(std::move(other._size)) { other.root = nullptr; other.tail = nullptr; other._size = 0; } - constexpr ~List() - { + constexpr ~List() { clear(); deallocateNode(tail); } - constexpr List& operator=(const List& other) - { - if(this != &other) - { + constexpr List& operator=(const List& other) { + if (this != &other) { clear(); - if constexpr (std::allocator_traits::propagate_on_container_copy_assignment::value ) - { - if (!std::allocator_traits::is_always_equal::value - && allocator != other.allocator) - { + if constexpr (std::allocator_traits::propagate_on_container_copy_assignment::value) { + if (!std::allocator_traits::is_always_equal::value && allocator != other.allocator) { clear(); } allocator = other.allocator; } - for(const auto& it : other) - { + for (const auto& it : other) { add(it); } markIteratorDirty(); } return *this; } - constexpr List& operator=(List&& other) - { - if(this != &other) - { + constexpr List& operator=(List&& other) { + if (this != &other) { clear(); - if constexpr (std::allocator_traits::propagate_on_container_move_assignment::value) - { + if constexpr (std::allocator_traits::propagate_on_container_move_assignment::value) { allocator = std::move(other.allocator); } root = other.root; @@ -258,23 +165,14 @@ public: } return *this; } - - constexpr reference front() - { - return root->data; - } - constexpr reference back() - { - return tail->prev->data; - } - constexpr void clear() - { - if (empty()) - { + + constexpr reference front() { return root->data; } + constexpr reference back() { return tail->prev->data; } + constexpr void clear() { + if (empty()) { return; } - for (Node *tmp = root; tmp != tail;) - { + for (Node* tmp = root; tmp != tail;) { tmp = tmp->next; destroyNode(tmp->prev); deallocateNode(tmp->prev); @@ -283,24 +181,12 @@ public: markIteratorDirty(); _size = 0; } - //Insert at the end - constexpr iterator add(const T &value) - { - return addInternal(value); - } - constexpr iterator add(T&& value) - { - return addInternal(std::move(value)); - } - template - constexpr reference emplace(args... arguments) - { - std::allocator_traits::construct(allocator, - tail, - tail->prev, - tail->next, - arguments...); - Node *newTail = allocateNode(); + // Insert at the end + constexpr iterator add(const T& value) { return addInternal(value); } + constexpr iterator add(T&& value) { return addInternal(std::move(value)); } + template constexpr reference emplace(args... arguments) { + std::allocator_traits::construct(allocator, tail, tail->prev, tail->next, arguments...); + Node* newTail = allocateNode(); newTail->prev = tail; newTail->next = nullptr; tail->next = newTail; @@ -311,31 +197,23 @@ public: return insertedElement; } // front + popFront - constexpr value_type retrieve() - { + constexpr value_type retrieve() { value_type temp = std::move(root->data); popFront(); return temp; } - constexpr iterator remove(iterator pos) - { + constexpr iterator remove(iterator pos) { _size--; - Node *prev = pos.node->prev; - Node *next = pos.node->next; - if (prev == nullptr) - { + Node* prev = pos.node->prev; + Node* next = pos.node->next; + if (prev == nullptr) { root = next; - } - else - { + } else { prev->next = next; } - if(next == nullptr) - { + if (next == nullptr) { tail = prev; - } - else - { + } else { next->prev = prev; } destroyNode(pos.node); @@ -343,111 +221,67 @@ public: markIteratorDirty(); return Iterator(next); } - constexpr void popBack() - { + constexpr void popBack() { assert(_size > 0); remove(Iterator(tail->prev)); } - constexpr void pop_back() - { + constexpr void pop_back() { assert(_size > 0); remove(Iterator(tail->prev)); } - constexpr void popFront() - { + constexpr void popFront() { assert(_size > 0); remove(Iterator(root)); } - constexpr void pop_front() - { + constexpr void pop_front() { assert(_size > 0); remove(Iterator(root)); } - constexpr iterator insert(iterator pos, const T &value) - { + constexpr iterator insert(iterator pos, const T& value) { _size++; - Node *newNode = allocateNode(); + Node* newNode = allocateNode(); initializeNode(newNode, value); newNode->next = pos.node; pos.node->prev = newNode; - Node *tmp = pos.node->prev; - if (tmp != nullptr) - { + Node* tmp = pos.node->prev; + if (tmp != nullptr) { tmp->next = newNode; newNode->prev = tmp; - } - else - { + } else { root = newNode; } markIteratorDirty(); return Iterator(newNode); } - constexpr iterator find(const T &value) - { - for (Node *i = root; i != tail; i = i->next) - { - if (!(i->data < value) && !(value < i->data)) - { + constexpr iterator find(const T& value) { + for (Node* i = root; i != tail; i = i->next) { + if (!(i->data < value) && !(value < i->data)) { return iterator(i); } } return endIt; } - constexpr bool empty() const - { - return _size == 0; - } - constexpr size_type size() const - { - return _size; - } - constexpr iterator begin() - { - return beginIt; - } - constexpr const_iterator begin() const - { - return cbeginIt; - } - constexpr iterator end() - { - return endIt; - } - constexpr const_iterator end() const - { - return cendIt; - } + constexpr bool empty() const { return _size == 0; } + constexpr size_type size() const { return _size; } + constexpr iterator begin() { return beginIt; } + constexpr const_iterator begin() const { return cbeginIt; } + constexpr iterator end() { return endIt; } + constexpr const_iterator end() const { return cendIt; } -private: - constexpr Node* allocateNode() - { + private: + constexpr Node* allocateNode() { Node* node = allocator.allocate(1); assert(node != nullptr); node->prev = nullptr; node->next = nullptr; return node; } - template - constexpr void initializeNode(Node* node, Type&& data) - { - std::allocator_traits::construct(allocator, - node, - node->prev, - node->next, - std::forward(data)); + template constexpr void initializeNode(Node* node, Type&& data) { + std::allocator_traits::construct(allocator, node, node->prev, node->next, std::forward(data)); } - constexpr void destroyNode(Node* node) - { - std::allocator_traits::destroy(allocator, node); - } - constexpr void deallocateNode(Node* node) - { - allocator.deallocate(node, 1); - } - template - constexpr iterator addInternal(ValueType&& value) - { + constexpr void destroyNode(Node* node) { std::allocator_traits::destroy(allocator, node); } + constexpr void deallocateNode(Node* node) { allocator.deallocate(node, 1); } + template constexpr iterator addInternal(ValueType&& value) { initializeNode(tail, std::forward(value)); Node* newTail = allocateNode(); newTail->prev = tail; @@ -459,16 +293,15 @@ private: _size++; return insertedElement; } - constexpr void markIteratorDirty() - { + constexpr void markIteratorDirty() { beginIt = Iterator(root); endIt = Iterator(tail); cbeginIt = ConstIterator(root); cendIt = ConstIterator(tail); } NodeAllocator allocator; - Node *root; - Node *tail; + Node* root; + Node* tail; iterator beginIt; iterator endIt; const_iterator cbeginIt; diff --git a/src/Engine/Containers/Map.h b/src/Engine/Containers/Map.h index 9ef90b6..77583a6 100644 --- a/src/Engine/Containers/Map.h +++ b/src/Engine/Containers/Map.h @@ -1,26 +1,17 @@ #pragma once -#include #include "Array.h" #include "Pair.h" -#include "Tree.h" #include "Serialization/Serialization.h" +#include "Tree.h" +#include -namespace Seele -{ -template -struct _KeyFun -{ - const KeyType& operator()(const PairType& pair) const - { - return pair.key; - } + +namespace Seele { +template struct _KeyFun { + const KeyType& operator()(const PairType& pair) const { return pair.key; } }; -template , - typename Allocator = std::pmr::polymorphic_allocator>> -struct Map : public Tree, _KeyFun>, Compare, Allocator> -{ +template , typename Allocator = std::pmr::polymorphic_allocator>> +struct Map : public Tree, _KeyFun>, Compare, Allocator> { using Super = Tree, _KeyFun>, Compare, Allocator>; using key_type = Super::key_type; using mapped_type = V; @@ -39,84 +30,42 @@ struct Map : public Tree, _KeyFun>, Compare, Allocat using reverse_iterator = Super::reverse_iterator; using const_reverse_iterator = Super::const_reverse_iterator; - constexpr Map() noexcept - : Super() - { - } + constexpr Map() noexcept : Super() {} constexpr explicit Map(const Compare& comp, const Allocator& alloc = Allocator()) noexcept(noexcept(Allocator())) - : Super(comp, alloc) - { - } - constexpr explicit Map(const Allocator& alloc) noexcept(noexcept(Compare())) - : Super(alloc) - { - } - constexpr mapped_type& operator[](const key_type& key) - { + : Super(comp, alloc) {} + constexpr explicit Map(const Allocator& alloc) noexcept(noexcept(Compare())) : Super(alloc) {} + constexpr mapped_type& operator[](const key_type& key) { auto [it, inserted] = Super::insert(Pair(key, V())); return it->value; } - constexpr const mapped_type& operator[](const key_type& key) const - { - return Super::find(key)->value; - } - constexpr mapped_type& at(const key_type& key) - { + constexpr const mapped_type& operator[](const key_type& key) const { return Super::find(key)->value; } + constexpr mapped_type& at(const key_type& key) { iterator elem = Super::find(key); - if (elem == Super::end()) - { + if (elem == Super::end()) { throw std::logic_error("Key not found"); } return elem->value; } - constexpr const mapped_type& at(const key_type& key) const - { - return Super::find(key)->value; - } - constexpr iterator find(const key_type& key) - { - return Super::find(key); - } - constexpr iterator erase(const key_type& key) - { - return Super::remove(key); - } - constexpr bool exists(const key_type& key) const - { - return Super::find(key) != Super::end(); - } - constexpr bool exists(const key_type& key) - { - return Super::find(key) != Super::end(); - } - constexpr bool contains(const key_type& key) const - { - return exists(key); - } - constexpr bool contains(const key_type& key) - { - return exists(key); - } - constexpr Pair insert(const value_type& val) - { - return Super::insert(val); - } - void save(ArchiveBuffer& buffer) const - { + constexpr const mapped_type& at(const key_type& key) const { return Super::find(key)->value; } + constexpr iterator find(const key_type& key) { return Super::find(key); } + constexpr iterator erase(const key_type& key) { return Super::remove(key); } + constexpr bool exists(const key_type& key) const { return Super::find(key) != Super::end(); } + constexpr bool exists(const key_type& key) { return Super::find(key) != Super::end(); } + constexpr bool contains(const key_type& key) const { return exists(key); } + constexpr bool contains(const key_type& key) { return exists(key); } + constexpr Pair insert(const value_type& val) { return Super::insert(val); } + void save(ArchiveBuffer& buffer) const { size_t s = Super::size(); buffer.writeBytes(&s, sizeof(uint64)); - for(const auto& [k, v] : *this) - { + for (const auto& [k, v] : *this) { Serialization::save(buffer, k); Serialization::save(buffer, v); } } - void load(ArchiveBuffer& buffer) - { + void load(ArchiveBuffer& buffer) { uint64 len = 0; buffer.readBytes(&len, sizeof(uint64)); - for(uint64 i = 0; i < len; ++i) - { + for (uint64 i = 0; i < len; ++i) { K k = K(); V v = V(); Serialization::load(buffer, k); diff --git a/src/Engine/Containers/Pair.h b/src/Engine/Containers/Pair.h index c804c11..45cb210 100644 --- a/src/Engine/Containers/Pair.h +++ b/src/Engine/Containers/Pair.h @@ -1,30 +1,17 @@ #pragma once -namespace Seele -{ -template -struct Pair -{ -public: - constexpr Pair() - : key(K()), value(V()) - {} - constexpr Pair(const K & key, const V & value) - : key(key), value(value) - {} - template - constexpr Pair(U1&& x, U2&& y) - : key(std::forward(x)) - , value(std::forward(y)) - { - } +namespace Seele { +template struct Pair { + public: + constexpr Pair() : key(K()), value(V()) {} + constexpr Pair(const K& key, const V& value) : key(key), value(value) {} + template constexpr Pair(U1&& x, U2&& y) : key(std::forward(x)), value(std::forward(y)) {} Pair(const Pair& other) = default; Pair(Pair&& other) = default; - ~Pair(){} + ~Pair() {} Pair& operator=(const Pair& other) = default; Pair& operator=(Pair&& other) = default; - constexpr friend bool operator<(const Pair& left, const Pair& right) - { + constexpr friend bool operator<(const Pair& left, const Pair& right) { return left.key < right.key || (!(right.key < left.key) && left.value < right.value); } K key; diff --git a/src/Engine/Containers/Set.h b/src/Engine/Containers/Set.h index 7031b88..4105e41 100644 --- a/src/Engine/Containers/Set.h +++ b/src/Engine/Containers/Set.h @@ -1,14 +1,13 @@ #pragma once -#include #include "Array.h" #include "Tree.h" +#include -namespace Seele -{ -template, class Allocator = std::pmr::polymorphic_allocator> -class Set : public Tree -{ -public: + +namespace Seele { +template , class Allocator = std::pmr::polymorphic_allocator> +class Set : public Tree { + public: using Super = Tree; using key_type = Key; using value_type = Key; @@ -26,21 +25,9 @@ public: using reverse_iterator = Super::reverse_iterator; using const_reverse_iterator = Super::const_reverse_iterator; - Set() - : Set(Compare()) - { - } - explicit Set(const Compare& comp, const Allocator alloc = Allocator()) - : Super(comp, alloc) - { - } - explicit Set(const Allocator alloc) - : Super(alloc) - { - } - constexpr Pair insert(const value_type& value) - { - return Super::insert(value); - } + Set() : Set(Compare()) {} + explicit Set(const Compare& comp, const Allocator alloc = Allocator()) : Super(comp, alloc) {} + explicit Set(const Allocator alloc) : Super(alloc) {} + constexpr Pair insert(const value_type& value) { return Super::insert(value); } }; } // namespace Seele \ No newline at end of file diff --git a/src/Engine/Containers/Tree.h b/src/Engine/Containers/Tree.h index f7b70e6..b9e8a1c 100644 --- a/src/Engine/Containers/Tree.h +++ b/src/Engine/Containers/Tree.h @@ -1,147 +1,88 @@ #pragma once -#include #include "Pair.h" +#include -namespace Seele -{ -template < - typename KeyType, - typename NodeData, - typename KeyFun, - typename Compare, - typename Allocator> -struct Tree -{ -protected: - struct Node - { - Node(Node* left, Node* right, const NodeData& nodeData) - : leftChild(left) - , rightChild(right) - , data(nodeData) - {} - Node(Node* left, Node* right, NodeData&& nodeData) - : leftChild(left) - , rightChild(right) - , data(std::move(nodeData)) - {} + +namespace Seele { +template struct Tree { + protected: + struct Node { + Node(Node* left, Node* right, const NodeData& nodeData) : leftChild(left), rightChild(right), data(nodeData) {} + Node(Node* left, Node* right, NodeData&& nodeData) : leftChild(left), rightChild(right), data(std::move(nodeData)) {} Node* leftChild; Node* rightChild; NodeData data; }; using NodeAlloc = std::allocator_traits::template rebind_alloc; -public: - template - class IteratorBase - { - public: + + public: + template class IteratorBase { + public: using iterator_category = std::bidirectional_iterator_tag; using value_type = IterType; using difference_type = std::ptrdiff_t; using reference = IterType&; using pointer = IterType*; - constexpr IteratorBase(Node* x = nullptr, Array&& beginIt = Array()) - : node(x), traversal(std::move(beginIt)) - { - } - constexpr IteratorBase(const IteratorBase& i) - : node(i.node), traversal(i.traversal) - { - } - constexpr IteratorBase(IteratorBase&& i) noexcept - : node(std::move(i.node)), traversal(std::move(i.traversal)) - { - } - constexpr IteratorBase& operator=(const IteratorBase& other) - { - if (this != &other) - { + constexpr IteratorBase(Node* x = nullptr, Array&& beginIt = Array()) : node(x), traversal(std::move(beginIt)) {} + constexpr IteratorBase(const IteratorBase& i) : node(i.node), traversal(i.traversal) {} + constexpr IteratorBase(IteratorBase&& i) noexcept : node(std::move(i.node)), traversal(std::move(i.traversal)) {} + constexpr IteratorBase& operator=(const IteratorBase& other) { + if (this != &other) { node = other.node; traversal = other.traversal; } return *this; } - constexpr IteratorBase& operator=(IteratorBase&& other) noexcept - { - if (this != &other) - { + constexpr IteratorBase& operator=(IteratorBase&& other) noexcept { + if (this != &other) { node = std::move(other.node); traversal = std::move(other.traversal); } return *this; } - constexpr reference operator*() const - { - return node->data; - } - constexpr pointer operator->() const - { - return &(node->data); - } - constexpr bool operator!=(const IteratorBase& other) - { - return node != other.node; - } - constexpr bool operator==(const IteratorBase& other) - { - return node == other.node; - } - constexpr std::strong_ordering operator<=>(const IteratorBase& other) - { - return node <=> other.node; - } - constexpr IteratorBase& operator++() - { + constexpr reference operator*() const { return node->data; } + constexpr pointer operator->() const { return &(node->data); } + constexpr bool operator!=(const IteratorBase& other) { return node != other.node; } + constexpr bool operator==(const IteratorBase& other) { return node == other.node; } + constexpr std::strong_ordering operator<=>(const IteratorBase& other) { return node <=> other.node; } + constexpr IteratorBase& operator++() { node = node->rightChild; - while (node != nullptr - && node->leftChild != nullptr) - { + while (node != nullptr && node->leftChild != nullptr) { traversal.add(node); node = node->leftChild; } - if (node == nullptr - && traversal.size() > 0) - { + if (node == nullptr && traversal.size() > 0) { node = traversal.back(); traversal.pop(); } return *this; } - constexpr IteratorBase& operator--() - { + constexpr IteratorBase& operator--() { node = node->leftChild; - while (node != nullptr - && node->rightChild != nullptr) - { + while (node != nullptr && node->rightChild != nullptr) { traversal.add(node); node = node->rightchild; } - if (node == nullptr - && traversal.size() > 0) - { + if (node == nullptr && traversal.size() > 0) { node = traversal.back(); traversal.pop(); } return *this; } - constexpr IteratorBase operator--(int) - { + constexpr IteratorBase operator--(int) { IteratorBase tmp(*this); --*this; return tmp; } - constexpr IteratorBase operator++(int) - { + constexpr IteratorBase operator++(int) { IteratorBase tmp(*this); ++*this; return tmp; } - Node* getNode() - { - return node; - } - private: + Node* getNode() { return node; } + + private: Node* node; Array traversal; }; @@ -164,84 +105,39 @@ public: using const_reverse_iterator = std::reverse_iterator; constexpr Tree() noexcept - : alloc(NodeAlloc()) - , root(nullptr) - , beginIt(nullptr) - , endIt(nullptr) - , iteratorsDirty(true) - , _size(0) - , comp(Compare()) - { - } + : alloc(NodeAlloc()), root(nullptr), beginIt(nullptr), endIt(nullptr), iteratorsDirty(true), _size(0), comp(Compare()) {} constexpr explicit Tree(const Compare& comp, const Allocator& alloc = Allocator()) noexcept(noexcept(Allocator())) - : alloc(alloc) - , root(nullptr) - , beginIt(nullptr) - , endIt(nullptr) - , iteratorsDirty(true) - , _size(0) - , comp(comp) - { - } + : alloc(alloc), root(nullptr), beginIt(nullptr), endIt(nullptr), iteratorsDirty(true), _size(0), comp(comp) {} constexpr explicit Tree(const Allocator& alloc) noexcept(noexcept(Compare())) - : alloc(alloc) - , root(nullptr) - , beginIt(nullptr) - , endIt(nullptr) - , iteratorsDirty(true) - , _size(0) - , comp(Compare()) - { - } - constexpr Tree(const Tree& other) - : alloc(other.alloc) - , root(nullptr) - , iteratorsDirty(true) - , _size() - , comp(other.comp) - { - for (const auto& elem : other) - { + : alloc(alloc), root(nullptr), beginIt(nullptr), endIt(nullptr), iteratorsDirty(true), _size(0), comp(Compare()) {} + constexpr Tree(const Tree& other) : alloc(other.alloc), root(nullptr), iteratorsDirty(true), _size(), comp(other.comp) { + for (const auto& elem : other) { insert(elem); } } constexpr Tree(Tree&& other) noexcept - : alloc(std::move(other.alloc)) - , root(std::move(other.root)) - , iteratorsDirty(true) - , _size(std::move(other._size)) - , comp(std::move(other.comp)) - { + : alloc(std::move(other.alloc)), root(std::move(other.root)), iteratorsDirty(true), _size(std::move(other._size)), + comp(std::move(other.comp)) { other._size = 0; } - constexpr ~Tree() noexcept - { - clear(); - } - constexpr Tree& operator=(const Tree& other) - { - if (this != &other) - { + constexpr ~Tree() noexcept { clear(); } + constexpr Tree& operator=(const Tree& other) { + if (this != &other) { clear(); - if constexpr (std::allocator_traits::propagate_on_container_copy_assignment::value) - { + if constexpr (std::allocator_traits::propagate_on_container_copy_assignment::value) { alloc = other.alloc; } - for (const auto& elem : other) - { + for (const auto& elem : other) { insert(elem); } markIteratorsDirty(); } return *this; } - constexpr Tree& operator=(Tree&& other) noexcept - { - if (this != &other) - { + constexpr Tree& operator=(Tree&& other) noexcept { + if (this != &other) { clear(); - if constexpr (std::allocator_traits::propagate_on_container_move_assignment::value) - { + if constexpr (std::allocator_traits::propagate_on_container_move_assignment::value) { alloc = std::move(other.alloc); } root = std::move(other.root); @@ -252,144 +148,108 @@ public: } return *this; } - constexpr void clear() - { - while (_size > 0) - { + constexpr void clear() { + while (_size > 0) { root = _remove(root, keyFun(root->data)); } root = nullptr; markIteratorsDirty(); } - constexpr iterator begin() - { - if (iteratorsDirty) - { + constexpr iterator begin() { + if (iteratorsDirty) { refreshIterators(); } return beginIt; } - constexpr iterator end() - { - if (iteratorsDirty) - { + constexpr iterator end() { + if (iteratorsDirty) { refreshIterators(); } return endIt; } - constexpr iterator begin() const - { - if (iteratorsDirty) - { + constexpr iterator begin() const { + if (iteratorsDirty) { return calcBeginIterator(); } return beginIt; } - constexpr iterator end() const - { - if (iteratorsDirty) - { + constexpr iterator end() const { + if (iteratorsDirty) { return calcEndIterator(); } return endIt; } - constexpr bool empty() const - { - return _size == 0; - } - constexpr size_type size() const - { - return _size; - } -protected: - constexpr iterator find(const key_type& key) - { + constexpr bool empty() const { return _size == 0; } + constexpr size_type size() const { return _size; } + + protected: + constexpr iterator find(const key_type& key) { root = _splay(root, key); - if (root == nullptr || !equal(root->data, key)) - { + if (root == nullptr || !equal(root->data, key)) { return end(); } return iterator(root); } - constexpr iterator find(const key_type& key) const - { + constexpr iterator find(const key_type& key) const { Node* it = root; - while (it != nullptr && !equal(it->data, key)) - { - if (comp(key, keyFun(it->data))) - { + while (it != nullptr && !equal(it->data, key)) { + if (comp(key, keyFun(it->data))) { it = it->leftChild; - } - else - { + } else { it = it->rightChild; } } - if (it == nullptr) - { + if (it == nullptr) { return end(); } return iterator(it); } - constexpr Pair insert(const NodeData& data) - { + constexpr Pair insert(const NodeData& data) { auto [r, inserted] = _insert(root, data); root = r; return Pair(iterator(root), inserted); } - constexpr Pair insert(NodeData&& data) - { + constexpr Pair insert(NodeData&& data) { auto [r, inserted] = _insert(root, std::move(data)); root = r; return Pair(iterator(root), inserted); } - constexpr iterator remove(const key_type& key) - { + constexpr iterator remove(const key_type& key) { root = _remove(root, key); return iterator(root); } -private: - void verifyTree() - { + + private: + void verifyTree() { size_t numElems = 0; - for (const auto& it : *this) - { + for (const auto& it : *this) { numElems++; } assert(numElems == _size); } - void markIteratorsDirty() - { - iteratorsDirty = true; - } - void refreshIterators() - { + void markIteratorsDirty() { iteratorsDirty = true; } + void refreshIterators() { beginIt = calcBeginIterator(); endIt = calcEndIterator(); iteratorsDirty = false; } - constexpr Iterator calcBeginIterator() const - { + constexpr Iterator calcBeginIterator() const { Node* begin = root; Array beginTraversal; - while (begin != nullptr) - { + while (begin != nullptr) { beginTraversal.add(begin); begin = begin->leftChild; } - if (!beginTraversal.empty()) - { + if (!beginTraversal.empty()) { begin = beginTraversal.back(); beginTraversal.pop(); } return Iterator(begin, std::move(beginTraversal)); } - constexpr Iterator calcEndIterator() const - { + constexpr Iterator calcEndIterator() const { Node* endIndex = root; Array endTraversal; - while (endIndex != nullptr) - { + while (endIndex != nullptr) { endTraversal.add(endIndex); endIndex = endIndex->rightChild; } @@ -403,26 +263,21 @@ private: size_type _size; Compare comp; KeyFun keyFun = KeyFun(); - Node* rotateLeft(Node* x) - { + Node* rotateLeft(Node* x) { Node* y = x->rightChild; x->rightChild = y->leftChild; y->leftChild = x; return y; } - Node* rotateRight(Node* x) - { + Node* rotateRight(Node* x) { Node* y = x->leftChild; x->leftChild = y->rightChild; y->rightChild = x; return y; } - template - Pair _insert(Node* r, NodeDataType&& data) - { + template Pair _insert(Node* r, NodeDataType&& data) { markIteratorsDirty(); - if (r == nullptr) - { + if (r == nullptr) { root = alloc.allocate(1); std::allocator_traits::construct(alloc, root, nullptr, nullptr, std::forward(data)); _size++; @@ -436,14 +291,11 @@ private: Node* newNode = alloc.allocate(1); std::allocator_traits::construct(alloc, newNode, nullptr, nullptr, std::forward(data)); - if (comp(keyFun(newNode->data), keyFun(r->data))) - { + if (comp(keyFun(newNode->data), keyFun(r->data))) { newNode->rightChild = r; newNode->leftChild = r->leftChild; r->leftChild = nullptr; - } - else - { + } else { newNode->leftChild = r; newNode->rightChild = r->rightChild; r->rightChild = nullptr; @@ -451,9 +303,7 @@ private: _size++; return Pair(newNode, true); } - template - Node* _remove(Node* r, K&& key) - { + template Node* _remove(Node* r, K&& key) { markIteratorsDirty(); Node* temp; if (r == nullptr) @@ -464,13 +314,10 @@ private: if (!equal(r->data, key)) return r; - if (r->leftChild == nullptr) - { + if (r->leftChild == nullptr) { temp = r; r = r->rightChild; - } - else - { + } else { temp = r; r = _splay(r->leftChild, key); @@ -481,52 +328,38 @@ private: _size--; return r; } - template - Node* _splay(Node* r, K&& key) - { + template Node* _splay(Node* r, K&& key) { markIteratorsDirty(); - if (r == nullptr || equal(r->data, key)) - { + if (r == nullptr || equal(r->data, key)) { return r; } - if (comp(key, keyFun(r->data))) - { + if (comp(key, keyFun(r->data))) { if (r->leftChild == nullptr) return r; - if (comp(key, keyFun(r->leftChild->data))) - { + if (comp(key, keyFun(r->leftChild->data))) { r->leftChild->leftChild = _splay(r->leftChild->leftChild, key); r = rotateRight(r); - } - else if (comp(keyFun(r->leftChild->data), key)) - { + } else if (comp(keyFun(r->leftChild->data), key)) { r->leftChild->rightChild = _splay(r->leftChild->rightChild, key); - if (r->leftChild->rightChild != nullptr) - { + if (r->leftChild->rightChild != nullptr) { r->leftChild = rotateLeft(r->leftChild); } } return (r->leftChild == nullptr) ? r : rotateRight(r); - } - else - { + } else { if (r->rightChild == nullptr) return r; - if (comp(key, keyFun(r->rightChild->data))) - { + if (comp(key, keyFun(r->rightChild->data))) { r->rightChild->leftChild = _splay(r->rightChild->leftChild, key); - if (r->rightChild->leftChild != nullptr) - { + if (r->rightChild->leftChild != nullptr) { r->rightChild = rotateRight(r->rightChild); } - } - else if (comp(keyFun(r->rightChild->data), key)) - { + } else if (comp(keyFun(r->rightChild->data), key)) { r->rightChild->rightChild = _splay(r->rightChild->rightChild, key); r = rotateLeft(r); @@ -534,10 +367,6 @@ private: return (r->rightChild == nullptr) ? r : rotateLeft(r); } } - template - bool equal(const NodeData& a, K&& b) const - { - return !comp(keyFun(a), b) && !comp(b, keyFun(a)); - } + template bool equal(const NodeData& a, K&& b) const { return !comp(keyFun(a), b) && !comp(b, keyFun(a)); } }; } // namespace Seele \ No newline at end of file diff --git a/src/Engine/Game.h b/src/Engine/Game.h index f7e567f..acbcd53 100644 --- a/src/Engine/Game.h +++ b/src/Engine/Game.h @@ -2,11 +2,9 @@ #include "Scene/Scene.h" #include "System/SystemGraph.h" -namespace Seele -{ -class Game -{ -public: +namespace Seele { +class Game { + public: Game() {} virtual ~Game() {} virtual void setupScene(PScene scene, PSystemGraph graph) = 0; diff --git a/src/Engine/Graphics/Buffer.cpp b/src/Engine/Graphics/Buffer.cpp index e0fec8e..85b0a16 100644 --- a/src/Engine/Graphics/Buffer.cpp +++ b/src/Engine/Graphics/Buffer.cpp @@ -3,60 +3,34 @@ using namespace Seele; using namespace Seele::Gfx; -Buffer::Buffer(QueueFamilyMapping mapping, QueueType startQueue) - : QueueOwnedResource(mapping, startQueue) -{ -} +Buffer::Buffer(QueueFamilyMapping mapping, QueueType startQueue) : QueueOwnedResource(mapping, startQueue) {} -Buffer::~Buffer() -{ -} +Buffer::~Buffer() {} VertexBuffer::VertexBuffer(QueueFamilyMapping mapping, uint32 numVertices, uint32 vertexSize, QueueType startQueueType) - : Buffer(mapping, startQueueType) - , numVertices(numVertices) - , vertexSize(vertexSize) -{ -} -VertexBuffer::~VertexBuffer() -{ -} + : Buffer(mapping, startQueueType), numVertices(numVertices), vertexSize(vertexSize) {} +VertexBuffer::~VertexBuffer() {} IndexBuffer::IndexBuffer(QueueFamilyMapping mapping, uint64 size, Gfx::SeIndexType indexType, QueueType startQueueType) - : Buffer(mapping, startQueueType) - , indexType(indexType) -{ - switch (indexType) - { - case SE_INDEX_TYPE_UINT16: - numIndices = size / sizeof(uint16); - break; - case SE_INDEX_TYPE_UINT32: - numIndices = size / sizeof(uint32); - break; - default: - break; - } -} -IndexBuffer::~IndexBuffer() -{ + : Buffer(mapping, startQueueType), indexType(indexType) { + switch (indexType) { + case SE_INDEX_TYPE_UINT16: + numIndices = size / sizeof(uint16); + break; + case SE_INDEX_TYPE_UINT32: + numIndices = size / sizeof(uint32); + break; + default: + break; + } } +IndexBuffer::~IndexBuffer() {} -UniformBuffer::UniformBuffer(QueueFamilyMapping mapping, const DataSource& sourceData) - : Buffer(mapping, sourceData.owner) -{} +UniformBuffer::UniformBuffer(QueueFamilyMapping mapping, const DataSource& sourceData) : Buffer(mapping, sourceData.owner) {} -UniformBuffer::~UniformBuffer() -{ -} +UniformBuffer::~UniformBuffer() {} ShaderBuffer::ShaderBuffer(QueueFamilyMapping mapping, uint32 numElements, const DataSource& sourceData) - : Buffer(mapping, sourceData.owner) - , numElements(numElements) -{ -} - -ShaderBuffer::~ShaderBuffer() -{ -} + : Buffer(mapping, sourceData.owner), numElements(numElements) {} +ShaderBuffer::~ShaderBuffer() {} diff --git a/src/Engine/Graphics/Buffer.h b/src/Engine/Graphics/Buffer.h index 245ae54..eae9395 100644 --- a/src/Engine/Graphics/Buffer.h +++ b/src/Engine/Graphics/Buffer.h @@ -1,106 +1,95 @@ #pragma once -#include "Resources.h" #include "Initializer.h" +#include "Resources.h" + namespace Seele { namespace Gfx { class Buffer : public QueueOwnedResource { -public: - Buffer(QueueFamilyMapping mapping, QueueType startQueueType); - virtual ~Buffer(); + public: + Buffer(QueueFamilyMapping mapping, QueueType startQueueType); + virtual ~Buffer(); -protected: - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(QueueType newOwner) = 0; + protected: + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(QueueType newOwner) = 0; }; class VertexBuffer : public Buffer { -public: - VertexBuffer(QueueFamilyMapping mapping, uint32 numVertices, - uint32 vertexSize, QueueType startQueueType); - virtual ~VertexBuffer(); - constexpr uint32 getNumVertices() const { return numVertices; } - // Size of one vertex in bytes - constexpr uint32 getVertexSize() const { return vertexSize; } + public: + VertexBuffer(QueueFamilyMapping mapping, uint32 numVertices, uint32 vertexSize, QueueType startQueueType); + virtual ~VertexBuffer(); + constexpr uint32 getNumVertices() const { return numVertices; } + // Size of one vertex in bytes + constexpr uint32 getVertexSize() const { return vertexSize; } - virtual void updateRegion(DataSource update) = 0; - virtual void download(Array &buffer) = 0; + virtual void updateRegion(DataSource update) = 0; + virtual void download(Array& buffer) = 0; -protected: - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, - SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, - SePipelineStageFlags dstStage) = 0; - uint32 numVertices; - uint32 vertexSize; + protected: + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(QueueType newOwner) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, + SePipelineStageFlags dstStage) = 0; + uint32 numVertices; + uint32 vertexSize; }; DEFINE_REF(VertexBuffer) class IndexBuffer : public Buffer { -public: - IndexBuffer(QueueFamilyMapping mapping, uint64 size, Gfx::SeIndexType index, - QueueType startQueueType); - virtual ~IndexBuffer(); - constexpr uint64 getNumIndices() const { return numIndices; } - constexpr Gfx::SeIndexType getIndexType() const { return indexType; } + public: + IndexBuffer(QueueFamilyMapping mapping, uint64 size, Gfx::SeIndexType index, QueueType startQueueType); + virtual ~IndexBuffer(); + constexpr uint64 getNumIndices() const { return numIndices; } + constexpr Gfx::SeIndexType getIndexType() const { return indexType; } - virtual void download(Array &buffer) = 0; + virtual void download(Array& buffer) = 0; -protected: - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, - SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, - SePipelineStageFlags dstStage) = 0; - Gfx::SeIndexType indexType; - uint64 numIndices; + protected: + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(QueueType newOwner) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, + SePipelineStageFlags dstStage) = 0; + Gfx::SeIndexType indexType; + uint64 numIndices; }; DEFINE_REF(IndexBuffer) DECLARE_REF(UniformBuffer) class UniformBuffer : public Buffer { -public: - UniformBuffer(QueueFamilyMapping mapping, const DataSource &sourceData); - virtual ~UniformBuffer(); + public: + UniformBuffer(QueueFamilyMapping mapping, const DataSource& sourceData); + virtual ~UniformBuffer(); - virtual void rotateBuffer(uint64 size) = 0; - virtual void updateContents(const DataSource &sourceData) = 0; + virtual void rotateBuffer(uint64 size) = 0; + virtual void updateContents(const DataSource& sourceData) = 0; -protected: - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, - SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, - SePipelineStageFlags dstStage) = 0; + protected: + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(QueueType newOwner) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, + SePipelineStageFlags dstStage) = 0; }; DEFINE_REF(UniformBuffer) class ShaderBuffer : public Buffer { -public: - ShaderBuffer(QueueFamilyMapping mapping, uint32 numElements, - const DataSource &bulkResourceData); - virtual ~ShaderBuffer(); - virtual void rotateBuffer(uint64 size, bool preserveContents = false) = 0; - virtual void updateContents(const ShaderBufferCreateInfo &sourceData) = 0; - constexpr uint32 getNumElements() const { return numElements; } - virtual void *mapRegion(uint64 offset = 0, uint64 size = -1, - bool writeOnly = true) = 0; - virtual void unmap() = 0; + public: + ShaderBuffer(QueueFamilyMapping mapping, uint32 numElements, const DataSource& bulkResourceData); + virtual ~ShaderBuffer(); + virtual void rotateBuffer(uint64 size, bool preserveContents = false) = 0; + virtual void updateContents(const ShaderBufferCreateInfo& sourceData) = 0; + constexpr uint32 getNumElements() const { return numElements; } + virtual void* mapRegion(uint64 offset = 0, uint64 size = -1, bool writeOnly = true) = 0; + virtual void unmap() = 0; - virtual void clear() = 0; + virtual void clear() = 0; -protected: - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, - SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, - SePipelineStageFlags dstStage) = 0; + protected: + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(QueueType newOwner) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, + SePipelineStageFlags dstStage) = 0; - uint32 numElements; + uint32 numElements; }; DEFINE_REF(ShaderBuffer) } // namespace Gfx diff --git a/src/Engine/Graphics/Command.cpp b/src/Engine/Graphics/Command.cpp index 5e4203b..c0002b8 100644 --- a/src/Engine/Graphics/Command.cpp +++ b/src/Engine/Graphics/Command.cpp @@ -3,19 +3,10 @@ using namespace Seele; using namespace Seele::Gfx; +RenderCommand::RenderCommand() {} -RenderCommand::RenderCommand() -{ -} +RenderCommand::~RenderCommand() {} -RenderCommand::~RenderCommand() -{ -} +ComputeCommand::ComputeCommand() {} -ComputeCommand::ComputeCommand() -{ -} - -ComputeCommand::~ComputeCommand() -{ -} +ComputeCommand::~ComputeCommand() {} diff --git a/src/Engine/Graphics/Command.h b/src/Engine/Graphics/Command.h index b18b690..996a196 100644 --- a/src/Engine/Graphics/Command.h +++ b/src/Engine/Graphics/Command.h @@ -1,15 +1,13 @@ #pragma once -#include "Enums.h" #include "Descriptor.h" +#include "Enums.h" -namespace Seele -{ -namespace Gfx -{ + +namespace Seele { +namespace Gfx { DECLARE_REF(Viewport) -class RenderCommand -{ -public: +class RenderCommand { + public: RenderCommand(); virtual ~RenderCommand(); virtual void setViewport(Gfx::PViewport viewport) = 0; @@ -26,9 +24,8 @@ public: std::string name; }; DEFINE_REF(RenderCommand) - class ComputeCommand -{ -public: +class ComputeCommand { + public: ComputeCommand(); virtual ~ComputeCommand(); virtual void bindPipeline(Gfx::PComputePipeline pipeline) = 0; @@ -40,5 +37,5 @@ public: }; DEFINE_REF(ComputeCommand) -} -} \ No newline at end of file +} // namespace Gfx +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/DebugVertex.h b/src/Engine/Graphics/DebugVertex.h index 4f82006..494770b 100644 --- a/src/Engine/Graphics/DebugVertex.h +++ b/src/Engine/Graphics/DebugVertex.h @@ -1,11 +1,10 @@ #pragma once -#include "Math/Vector.h" #include "Containers/Array.h" +#include "Math/Vector.h" -namespace Seele -{ -struct DebugVertex -{ + +namespace Seele { +struct DebugVertex { Vector position; Vector color; }; diff --git a/src/Engine/Graphics/Descriptor.cpp b/src/Engine/Graphics/Descriptor.cpp index 1d32d32..09cfbbe 100644 --- a/src/Engine/Graphics/Descriptor.cpp +++ b/src/Engine/Graphics/Descriptor.cpp @@ -6,28 +6,28 @@ using namespace Seele::Gfx; DescriptorLayout::DescriptorLayout(const std::string& name) : name(name) {} DescriptorLayout::DescriptorLayout(const DescriptorLayout& other) { - descriptorBindings.resize(other.descriptorBindings.size()); - for (uint32 i = 0; i < descriptorBindings.size(); ++i) { - descriptorBindings[i] = other.descriptorBindings[i]; - } + descriptorBindings.resize(other.descriptorBindings.size()); + for (uint32 i = 0; i < descriptorBindings.size(); ++i) { + descriptorBindings[i] = other.descriptorBindings[i]; + } } DescriptorLayout& DescriptorLayout::operator=(const DescriptorLayout& other) { - if (this != &other) { - descriptorBindings.resize(other.descriptorBindings.size()); - for (uint32 i = 0; i < descriptorBindings.size(); ++i) { - descriptorBindings[i] = other.descriptorBindings[i]; + if (this != &other) { + descriptorBindings.resize(other.descriptorBindings.size()); + for (uint32 i = 0; i < descriptorBindings.size(); ++i) { + descriptorBindings[i] = other.descriptorBindings[i]; + } } - } - return *this; + return *this; } DescriptorLayout::~DescriptorLayout() {} void DescriptorLayout::addDescriptorBinding(DescriptorBinding binding) { - if (descriptorBindings.size() <= binding.binding) { - descriptorBindings.resize(binding.binding + 1); - } + if (descriptorBindings.size() <= binding.binding) { + descriptorBindings.resize(binding.binding + 1); + } descriptorBindings[binding.binding] = binding; } @@ -45,27 +45,22 @@ DescriptorSet::~DescriptorSet() {} PipelineLayout::PipelineLayout(const std::string& name) : name(name) {} -PipelineLayout::PipelineLayout(const std::string& name, PPipelineLayout baseLayout) : name(name){ - if (baseLayout != nullptr) { - descriptorSetLayouts = baseLayout->descriptorSetLayouts; - pushConstants = baseLayout->pushConstants; - } +PipelineLayout::PipelineLayout(const std::string& name, PPipelineLayout baseLayout) : name(name) { + if (baseLayout != nullptr) { + descriptorSetLayouts = baseLayout->descriptorSetLayouts; + pushConstants = baseLayout->pushConstants; + } } PipelineLayout::~PipelineLayout() {} -void PipelineLayout::addDescriptorLayout(PDescriptorLayout layout) { - descriptorSetLayouts[layout->getName()] = layout; -} +void PipelineLayout::addDescriptorLayout(PDescriptorLayout layout) { descriptorSetLayouts[layout->getName()] = layout; } void PipelineLayout::addPushConstants(const SePushConstantRange& pushConstant) { pushConstants.add(pushConstant); } -void PipelineLayout::addMapping(Map mapping) -{ - for(const auto& [name, index] : mapping) - { - if(parameterMapping.contains(name)) - { +void PipelineLayout::addMapping(Map mapping) { + for (const auto& [name, index] : mapping) { + if (parameterMapping.contains(name)) { assert(parameterMapping[name] == index); } parameterMapping[name] = index; diff --git a/src/Engine/Graphics/Descriptor.h b/src/Engine/Graphics/Descriptor.h index 5b4ae49..ae46c30 100644 --- a/src/Engine/Graphics/Descriptor.h +++ b/src/Engine/Graphics/Descriptor.h @@ -1,55 +1,54 @@ #pragma once #include "Enums.h" -#include "Resources.h" #include "Initializer.h" +#include "Resources.h" + namespace Seele { namespace Gfx { struct DescriptorBinding { - uint32 binding = 0; - SeDescriptorType descriptorType = SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER; - SeImageViewType textureType = SE_IMAGE_VIEW_TYPE_2D; - uint32 descriptorCount = 1; - SeDescriptorBindingFlags bindingFlags = 0; - SeShaderStageFlags shaderStages = SE_SHADER_STAGE_ALL; - Gfx::SeDescriptorAccessTypeFlags access = SE_DESCRIPTOR_ACCESS_READ_ONLY_BIT; + uint32 binding = 0; + SeDescriptorType descriptorType = SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + SeImageViewType textureType = SE_IMAGE_VIEW_TYPE_2D; + uint32 descriptorCount = 1; + SeDescriptorBindingFlags bindingFlags = 0; + SeShaderStageFlags shaderStages = SE_SHADER_STAGE_ALL; + Gfx::SeDescriptorAccessTypeFlags access = SE_DESCRIPTOR_ACCESS_READ_ONLY_BIT; }; DECLARE_REF(DescriptorPool) DECLARE_REF(DescriptorSet) class DescriptorLayout { -public: - DescriptorLayout(const std::string &name); - DescriptorLayout(const DescriptorLayout &other); - DescriptorLayout &operator=(const DescriptorLayout &other); - virtual ~DescriptorLayout(); - void addDescriptorBinding(DescriptorBinding binding); - void reset(); - PDescriptorSet allocateDescriptorSet(); - virtual void create() = 0; - constexpr const Array &getBindings() const { - return descriptorBindings; - } - constexpr uint32 getHash() const { return hash; } - constexpr const std::string &getName() const { return name; } + public: + DescriptorLayout(const std::string& name); + DescriptorLayout(const DescriptorLayout& other); + DescriptorLayout& operator=(const DescriptorLayout& other); + virtual ~DescriptorLayout(); + void addDescriptorBinding(DescriptorBinding binding); + void reset(); + PDescriptorSet allocateDescriptorSet(); + virtual void create() = 0; + constexpr const Array& getBindings() const { return descriptorBindings; } + constexpr uint32 getHash() const { return hash; } + constexpr const std::string& getName() const { return name; } -protected: - Array descriptorBindings; - ODescriptorPool pool; - std::string name; - uint32 hash = 0; - friend class PipelineLayout; - friend class DescriptorPool; + protected: + Array descriptorBindings; + ODescriptorPool pool; + std::string name; + uint32 hash = 0; + friend class PipelineLayout; + friend class DescriptorPool; }; DEFINE_REF(DescriptorLayout) DECLARE_REF(DescriptorSet) class DescriptorPool { -public: - DescriptorPool(); - virtual ~DescriptorPool(); - virtual PDescriptorSet allocateDescriptorSet() = 0; - virtual void reset() = 0; + public: + DescriptorPool(); + virtual ~DescriptorPool(); + virtual PDescriptorSet allocateDescriptorSet() = 0; + virtual void reset() = 0; }; DEFINE_REF(DescriptorPool) DECLARE_REF(UniformBuffer) @@ -57,54 +56,47 @@ DECLARE_REF(ShaderBuffer) DECLARE_REF(Texture) DECLARE_REF(Sampler) class DescriptorSet { -public: - DescriptorSet(PDescriptorLayout layout); - virtual ~DescriptorSet(); - virtual void writeChanges() = 0; - virtual void updateBuffer(uint32 binding, PUniformBuffer uniformBuffer) = 0; - virtual void updateBuffer(uint32 binding, PShaderBuffer ShaderBuffer) = 0; - virtual void updateBuffer(uint32_t binding, uint32 index, - Gfx::PShaderBuffer uniformBuffer) = 0; - virtual void updateSampler(uint32 binding, PSampler sampler) = 0; - virtual void updateTexture(uint32 binding, PTexture texture, - PSampler samplerState = nullptr) = 0; - virtual void updateTextureArray(uint32_t binding, - Array texture) = 0; - bool operator<(PDescriptorSet other); + public: + DescriptorSet(PDescriptorLayout layout); + virtual ~DescriptorSet(); + virtual void writeChanges() = 0; + virtual void updateBuffer(uint32 binding, PUniformBuffer uniformBuffer) = 0; + virtual void updateBuffer(uint32 binding, PShaderBuffer ShaderBuffer) = 0; + virtual void updateBuffer(uint32_t binding, uint32 index, Gfx::PShaderBuffer uniformBuffer) = 0; + virtual void updateSampler(uint32 binding, PSampler sampler) = 0; + virtual void updateTexture(uint32 binding, PTexture texture, PSampler samplerState = nullptr) = 0; + virtual void updateTextureArray(uint32_t binding, Array texture) = 0; + bool operator<(PDescriptorSet other); - constexpr PDescriptorLayout getLayout() const { return layout; } - constexpr const std::string &getName() const { return layout->getName(); } + constexpr PDescriptorLayout getLayout() const { return layout; } + constexpr const std::string& getName() const { return layout->getName(); } -protected: - PDescriptorLayout layout; + protected: + PDescriptorLayout layout; }; DEFINE_REF(DescriptorSet) DECLARE_REF(PipelineLayout) class PipelineLayout { -public: - PipelineLayout(const std::string &name); - PipelineLayout(const std::string &name, PPipelineLayout baseLayout); - virtual ~PipelineLayout(); - virtual void create() = 0; - void addDescriptorLayout(PDescriptorLayout layout); - void addPushConstants(const SePushConstantRange &pushConstants); - constexpr uint32 getHash() const { return layoutHash; } - constexpr const Map &getLayouts() const { - return descriptorSetLayouts; - } - constexpr uint32 findParameter(const std::string ¶m) const { - return parameterMapping[param]; - } - void addMapping(Map mapping); - constexpr std::string getName() const { return name; }; + public: + PipelineLayout(const std::string& name); + PipelineLayout(const std::string& name, PPipelineLayout baseLayout); + virtual ~PipelineLayout(); + virtual void create() = 0; + void addDescriptorLayout(PDescriptorLayout layout); + void addPushConstants(const SePushConstantRange& pushConstants); + constexpr uint32 getHash() const { return layoutHash; } + constexpr const Map& getLayouts() const { return descriptorSetLayouts; } + constexpr uint32 findParameter(const std::string& param) const { return parameterMapping[param]; } + void addMapping(Map mapping); + constexpr std::string getName() const { return name; }; -protected: - uint32 layoutHash = 0; - Map descriptorSetLayouts; - Map parameterMapping; - Array pushConstants; - std::string name; + protected: + uint32 layoutHash = 0; + Map descriptorSetLayouts; + Map parameterMapping; + Array pushConstants; + std::string name; }; DEFINE_REF(PipelineLayout) } // namespace Gfx diff --git a/src/Engine/Graphics/Enums.cpp b/src/Engine/Graphics/Enums.cpp index 171d834..10b4f5b 100644 --- a/src/Engine/Graphics/Enums.cpp +++ b/src/Engine/Graphics/Enums.cpp @@ -4,113 +4,112 @@ using namespace Seele; using namespace Seele::Gfx; -FormatCompatibilityInfo Gfx::getFormatInfo(SeFormat format) -{ - switch(format) { - case SE_FORMAT_R4G4_UNORM_PACK8: - case SE_FORMAT_R8_UNORM: - case SE_FORMAT_R8_SNORM: - case SE_FORMAT_R8_USCALED: - case SE_FORMAT_R8_SSCALED: - case SE_FORMAT_R8_UINT: - case SE_FORMAT_R8_SINT: - case SE_FORMAT_R8_SRGB: - return FormatCompatibilityInfo { - .blockSize = 1, - .blockExtent = UVector(1, 1, 1), - .texelsPerBlock = 1, - }; - case SE_FORMAT_R10X6_UNORM_PACK16: - case SE_FORMAT_R12X4_UNORM_PACK16: - //case SE_FORMAT_A4R4G4B4_UNORM_PACK16: - //case SE_FORMAT_A4B4G4R4_UNORM_PACK16: - case SE_FORMAT_R4G4B4A4_UNORM_PACK16: - case SE_FORMAT_B4G4R4A4_UNORM_PACK16: - case SE_FORMAT_R5G6B5_UNORM_PACK16: - case SE_FORMAT_B5G6R5_UNORM_PACK16: - case SE_FORMAT_R5G5B5A1_UNORM_PACK16: - case SE_FORMAT_B5G5R5A1_UNORM_PACK16: - case SE_FORMAT_A1R5G5B5_UNORM_PACK16: - case SE_FORMAT_R8G8_UNORM: - case SE_FORMAT_R8G8_SNORM: - case SE_FORMAT_R8G8_USCALED: - case SE_FORMAT_R8G8_SSCALED: - case SE_FORMAT_R8G8_UINT: - case SE_FORMAT_R8G8_SINT: - case SE_FORMAT_R8G8_SRGB: - case SE_FORMAT_R16_UNORM: - case SE_FORMAT_R16_SNORM: - case SE_FORMAT_R16_USCALED: - case SE_FORMAT_R16_SSCALED: - case SE_FORMAT_R16_UINT: - case SE_FORMAT_R16_SINT: - case SE_FORMAT_R16_SFLOAT: - return FormatCompatibilityInfo { - .blockSize = 2, - .blockExtent = UVector(1, 1, 1), - .texelsPerBlock = 1, - }; - case SE_FORMAT_BC7_UNORM_BLOCK: - case SE_FORMAT_BC7_SRGB_BLOCK: - return FormatCompatibilityInfo { - .blockSize = 16, - .blockExtent = UVector(4, 4, 1), - .texelsPerBlock = 16, - }; - case SE_FORMAT_R10X6G10X6_UNORM_2PACK16: - case SE_FORMAT_R12X4G12X4_UNORM_2PACK16: - //case SE_FORMAT_R16G16_S10_5_NV: - case SE_FORMAT_R8G8B8A8_UNORM: - case SE_FORMAT_R8G8B8A8_SNORM: - case SE_FORMAT_R8G8B8A8_USCALED: - case SE_FORMAT_R8G8B8A8_SSCALED: - case SE_FORMAT_R8G8B8A8_UINT: - case SE_FORMAT_R8G8B8A8_SINT: - case SE_FORMAT_R8G8B8A8_SRGB: - case SE_FORMAT_B8G8R8A8_UNORM: - case SE_FORMAT_B8G8R8A8_SNORM: - case SE_FORMAT_B8G8R8A8_USCALED: - case SE_FORMAT_B8G8R8A8_SSCALED: - case SE_FORMAT_B8G8R8A8_UINT: - case SE_FORMAT_B8G8R8A8_SINT: - case SE_FORMAT_B8G8R8A8_SRGB: - case SE_FORMAT_A8B8G8R8_UNORM_PACK32: - case SE_FORMAT_A8B8G8R8_SNORM_PACK32: - case SE_FORMAT_A8B8G8R8_USCALED_PACK32: - case SE_FORMAT_A8B8G8R8_SSCALED_PACK32: - case SE_FORMAT_A8B8G8R8_UINT_PACK32: - case SE_FORMAT_A8B8G8R8_SINT_PACK32: - case SE_FORMAT_A8B8G8R8_SRGB_PACK32: - case SE_FORMAT_A2R10G10B10_UNORM_PACK32: - case SE_FORMAT_A2R10G10B10_SNORM_PACK32: - case SE_FORMAT_A2R10G10B10_USCALED_PACK32: - case SE_FORMAT_A2R10G10B10_SSCALED_PACK32: - case SE_FORMAT_A2R10G10B10_UINT_PACK32: - case SE_FORMAT_A2R10G10B10_SINT_PACK32: - case SE_FORMAT_A2B10G10R10_UNORM_PACK32: - case SE_FORMAT_A2B10G10R10_SNORM_PACK32: - case SE_FORMAT_A2B10G10R10_USCALED_PACK32: - case SE_FORMAT_A2B10G10R10_SSCALED_PACK32: - case SE_FORMAT_A2B10G10R10_UINT_PACK32: - case SE_FORMAT_A2B10G10R10_SINT_PACK32: - case SE_FORMAT_R16G16_UNORM: - case SE_FORMAT_R16G16_SNORM: - case SE_FORMAT_R16G16_USCALED: - case SE_FORMAT_R16G16_SSCALED: - case SE_FORMAT_R16G16_UINT: - case SE_FORMAT_R16G16_SINT: - case SE_FORMAT_R16G16_SFLOAT: - case SE_FORMAT_R32_UINT: - case SE_FORMAT_R32_SINT: - case SE_FORMAT_R32_SFLOAT: - case SE_FORMAT_B10G11R11_UFLOAT_PACK32: - case SE_FORMAT_E5B9G9R9_UFLOAT_PACK32: - return FormatCompatibilityInfo{ - .blockSize = 4, - .blockExtent = Vector(1, 1, 1), - .texelsPerBlock = 1, - }; - default: - throw new std::logic_error("not yet implemented"); +FormatCompatibilityInfo Gfx::getFormatInfo(SeFormat format) { + switch (format) { + case SE_FORMAT_R4G4_UNORM_PACK8: + case SE_FORMAT_R8_UNORM: + case SE_FORMAT_R8_SNORM: + case SE_FORMAT_R8_USCALED: + case SE_FORMAT_R8_SSCALED: + case SE_FORMAT_R8_UINT: + case SE_FORMAT_R8_SINT: + case SE_FORMAT_R8_SRGB: + return FormatCompatibilityInfo{ + .blockSize = 1, + .blockExtent = UVector(1, 1, 1), + .texelsPerBlock = 1, + }; + case SE_FORMAT_R10X6_UNORM_PACK16: + case SE_FORMAT_R12X4_UNORM_PACK16: + // case SE_FORMAT_A4R4G4B4_UNORM_PACK16: + // case SE_FORMAT_A4B4G4R4_UNORM_PACK16: + case SE_FORMAT_R4G4B4A4_UNORM_PACK16: + case SE_FORMAT_B4G4R4A4_UNORM_PACK16: + case SE_FORMAT_R5G6B5_UNORM_PACK16: + case SE_FORMAT_B5G6R5_UNORM_PACK16: + case SE_FORMAT_R5G5B5A1_UNORM_PACK16: + case SE_FORMAT_B5G5R5A1_UNORM_PACK16: + case SE_FORMAT_A1R5G5B5_UNORM_PACK16: + case SE_FORMAT_R8G8_UNORM: + case SE_FORMAT_R8G8_SNORM: + case SE_FORMAT_R8G8_USCALED: + case SE_FORMAT_R8G8_SSCALED: + case SE_FORMAT_R8G8_UINT: + case SE_FORMAT_R8G8_SINT: + case SE_FORMAT_R8G8_SRGB: + case SE_FORMAT_R16_UNORM: + case SE_FORMAT_R16_SNORM: + case SE_FORMAT_R16_USCALED: + case SE_FORMAT_R16_SSCALED: + case SE_FORMAT_R16_UINT: + case SE_FORMAT_R16_SINT: + case SE_FORMAT_R16_SFLOAT: + return FormatCompatibilityInfo{ + .blockSize = 2, + .blockExtent = UVector(1, 1, 1), + .texelsPerBlock = 1, + }; + case SE_FORMAT_BC7_UNORM_BLOCK: + case SE_FORMAT_BC7_SRGB_BLOCK: + return FormatCompatibilityInfo{ + .blockSize = 16, + .blockExtent = UVector(4, 4, 1), + .texelsPerBlock = 16, + }; + case SE_FORMAT_R10X6G10X6_UNORM_2PACK16: + case SE_FORMAT_R12X4G12X4_UNORM_2PACK16: + // case SE_FORMAT_R16G16_S10_5_NV: + case SE_FORMAT_R8G8B8A8_UNORM: + case SE_FORMAT_R8G8B8A8_SNORM: + case SE_FORMAT_R8G8B8A8_USCALED: + case SE_FORMAT_R8G8B8A8_SSCALED: + case SE_FORMAT_R8G8B8A8_UINT: + case SE_FORMAT_R8G8B8A8_SINT: + case SE_FORMAT_R8G8B8A8_SRGB: + case SE_FORMAT_B8G8R8A8_UNORM: + case SE_FORMAT_B8G8R8A8_SNORM: + case SE_FORMAT_B8G8R8A8_USCALED: + case SE_FORMAT_B8G8R8A8_SSCALED: + case SE_FORMAT_B8G8R8A8_UINT: + case SE_FORMAT_B8G8R8A8_SINT: + case SE_FORMAT_B8G8R8A8_SRGB: + case SE_FORMAT_A8B8G8R8_UNORM_PACK32: + case SE_FORMAT_A8B8G8R8_SNORM_PACK32: + case SE_FORMAT_A8B8G8R8_USCALED_PACK32: + case SE_FORMAT_A8B8G8R8_SSCALED_PACK32: + case SE_FORMAT_A8B8G8R8_UINT_PACK32: + case SE_FORMAT_A8B8G8R8_SINT_PACK32: + case SE_FORMAT_A8B8G8R8_SRGB_PACK32: + case SE_FORMAT_A2R10G10B10_UNORM_PACK32: + case SE_FORMAT_A2R10G10B10_SNORM_PACK32: + case SE_FORMAT_A2R10G10B10_USCALED_PACK32: + case SE_FORMAT_A2R10G10B10_SSCALED_PACK32: + case SE_FORMAT_A2R10G10B10_UINT_PACK32: + case SE_FORMAT_A2R10G10B10_SINT_PACK32: + case SE_FORMAT_A2B10G10R10_UNORM_PACK32: + case SE_FORMAT_A2B10G10R10_SNORM_PACK32: + case SE_FORMAT_A2B10G10R10_USCALED_PACK32: + case SE_FORMAT_A2B10G10R10_SSCALED_PACK32: + case SE_FORMAT_A2B10G10R10_UINT_PACK32: + case SE_FORMAT_A2B10G10R10_SINT_PACK32: + case SE_FORMAT_R16G16_UNORM: + case SE_FORMAT_R16G16_SNORM: + case SE_FORMAT_R16G16_USCALED: + case SE_FORMAT_R16G16_SSCALED: + case SE_FORMAT_R16G16_UINT: + case SE_FORMAT_R16G16_SINT: + case SE_FORMAT_R16G16_SFLOAT: + case SE_FORMAT_R32_UINT: + case SE_FORMAT_R32_SINT: + case SE_FORMAT_R32_SFLOAT: + case SE_FORMAT_B10G11R11_UFLOAT_PACK32: + case SE_FORMAT_E5B9G9R9_UFLOAT_PACK32: + return FormatCompatibilityInfo{ + .blockSize = 4, + .blockExtent = Vector(1, 1, 1), + .texelsPerBlock = 1, + }; + default: + throw new std::logic_error("not yet implemented"); } } diff --git a/src/Engine/Graphics/Enums.h b/src/Engine/Graphics/Enums.h index afa5bde..2797726 100644 --- a/src/Engine/Graphics/Enums.h +++ b/src/Engine/Graphics/Enums.h @@ -1,169 +1,160 @@ #pragma once -#include "MinimalEngine.h" #include "Math/Vector.h" +#include "MinimalEngine.h" -namespace Seele -{ + +namespace Seele { // Input codes matching GLFW for convenience, since its the primary windowing system -enum class KeyCode : size_t -{ +enum class KeyCode : size_t { /* Printable keys */ - KEY_SPACE = 32, - KEY_APOSTROPHE = 39 /* ' */, - KEY_COMMA = 44 /* , */, - KEY_MINUS = 45 /* - */, - KEY_PERIOD = 46 /* . */, - KEY_SLASH = 47 /* / */, - KEY_0 = 48, - KEY_1 = 49, - KEY_2 = 50, - KEY_3 = 51, - KEY_4 = 52, - KEY_5 = 53, - KEY_6 = 54, - KEY_7 = 55, - KEY_8 = 56, - KEY_9 = 57, - KEY_SEMICOLON = 59 /* ; */, - KEY_EQUAL = 61 /* = */, - KEY_A = 65, - KEY_B = 66, - KEY_C = 67, - KEY_D = 68, - KEY_E = 69, - KEY_F = 70, - KEY_G = 71, - KEY_H = 72, - KEY_I = 73, - KEY_J = 74, - KEY_K = 75, - KEY_L = 76, - KEY_M = 77, - KEY_N = 78, - KEY_O = 79, - KEY_P = 80, - KEY_Q = 81, - KEY_R = 82, - KEY_S = 83, - KEY_T = 84, - KEY_U = 85, - KEY_V = 86, - KEY_W = 87, - KEY_X = 88, - KEY_Y = 89, - KEY_Z = 90, - KEY_LEFT_BRACKET = 91 /* [ */, - KEY_BACKSLASH = 92 /* \ */, - KEY_RIGHT_BRACKET = 93 /* ] */, - KEY_GRAVE_ACCENT = 96 /* ` */, - KEY_WORLD_1 = 161 /* non-US #1 */, - KEY_WORLD_2 = 162 /* non-US #2 */, + KEY_SPACE = 32, + KEY_APOSTROPHE = 39 /* ' */, + KEY_COMMA = 44 /* , */, + KEY_MINUS = 45 /* - */, + KEY_PERIOD = 46 /* . */, + KEY_SLASH = 47 /* / */, + KEY_0 = 48, + KEY_1 = 49, + KEY_2 = 50, + KEY_3 = 51, + KEY_4 = 52, + KEY_5 = 53, + KEY_6 = 54, + KEY_7 = 55, + KEY_8 = 56, + KEY_9 = 57, + KEY_SEMICOLON = 59 /* ; */, + KEY_EQUAL = 61 /* = */, + KEY_A = 65, + KEY_B = 66, + KEY_C = 67, + KEY_D = 68, + KEY_E = 69, + KEY_F = 70, + KEY_G = 71, + KEY_H = 72, + KEY_I = 73, + KEY_J = 74, + KEY_K = 75, + KEY_L = 76, + KEY_M = 77, + KEY_N = 78, + KEY_O = 79, + KEY_P = 80, + KEY_Q = 81, + KEY_R = 82, + KEY_S = 83, + KEY_T = 84, + KEY_U = 85, + KEY_V = 86, + KEY_W = 87, + KEY_X = 88, + KEY_Y = 89, + KEY_Z = 90, + KEY_LEFT_BRACKET = 91 /* [ */, + KEY_BACKSLASH = 92 /* \ */, + KEY_RIGHT_BRACKET = 93 /* ] */, + KEY_GRAVE_ACCENT = 96 /* ` */, + KEY_WORLD_1 = 161 /* non-US #1 */, + KEY_WORLD_2 = 162 /* non-US #2 */, /* Function keys */ - KEY_ESCAPE = 256, - KEY_ENTER = 257, - KEY_TAB = 258, - KEY_BACKSPACE = 259, - KEY_INSERT = 260, - KEY_DELETE = 261, - KEY_RIGHT = 262, - KEY_LEFT = 263, - KEY_DOWN = 264, - KEY_UP = 265, - KEY_PAGE_UP = 266, - KEY_PAGE_DOWN = 267, - KEY_HOME = 268, - KEY_END = 269, - KEY_CAPS_LOCK = 280, - KEY_SCROLL_LOCK = 281, - KEY_NUM_LOCK = 282, - KEY_PRINT_SCREEN = 283, - KEY_PAUSE = 284, - KEY_F1 = 290, - KEY_F2 = 291, - KEY_F3 = 292, - KEY_F4 = 293, - KEY_F5 = 294, - KEY_F6 = 295, - KEY_F7 = 296, - KEY_F8 = 297, - KEY_F9 = 298, - KEY_F10 = 299, - KEY_F11 = 300, - KEY_F12 = 301, - KEY_F13 = 302, - KEY_F14 = 303, - KEY_F15 = 304, - KEY_F16 = 305, - KEY_F17 = 306, - KEY_F18 = 307, - KEY_F19 = 308, - KEY_F20 = 309, - KEY_F21 = 310, - KEY_F22 = 311, - KEY_F23 = 312, - KEY_F24 = 313, - KEY_F25 = 314, - KEY_KP_0 = 320, - KEY_KP_1 = 321, - KEY_KP_2 = 322, - KEY_KP_3 = 323, - KEY_KP_4 = 324, - KEY_KP_5 = 325, - KEY_KP_6 = 326, - KEY_KP_7 = 327, - KEY_KP_8 = 328, - KEY_KP_9 = 329, - KEY_KP_DECIMAL = 330, - KEY_KP_DIVIDE = 331, - KEY_KP_MULTIPLY = 332, - KEY_KP_SUBTRACT = 333, - KEY_KP_ADD = 334, - KEY_KP_ENTER = 335, - KEY_KP_EQUAL = 336, - KEY_LEFT_SHIFT = 340, - KEY_LEFT_CONTROL = 341, - KEY_LEFT_ALT = 342, - KEY_LEFT_SUPER = 343, - KEY_RIGHT_SHIFT = 344, - KEY_RIGHT_CONTROL = 345, - KEY_RIGHT_ALT = 346, - KEY_RIGHT_SUPER = 347, - KEY_MENU = 348, - KEY_LAST = KEY_MENU + KEY_ESCAPE = 256, + KEY_ENTER = 257, + KEY_TAB = 258, + KEY_BACKSPACE = 259, + KEY_INSERT = 260, + KEY_DELETE = 261, + KEY_RIGHT = 262, + KEY_LEFT = 263, + KEY_DOWN = 264, + KEY_UP = 265, + KEY_PAGE_UP = 266, + KEY_PAGE_DOWN = 267, + KEY_HOME = 268, + KEY_END = 269, + KEY_CAPS_LOCK = 280, + KEY_SCROLL_LOCK = 281, + KEY_NUM_LOCK = 282, + KEY_PRINT_SCREEN = 283, + KEY_PAUSE = 284, + KEY_F1 = 290, + KEY_F2 = 291, + KEY_F3 = 292, + KEY_F4 = 293, + KEY_F5 = 294, + KEY_F6 = 295, + KEY_F7 = 296, + KEY_F8 = 297, + KEY_F9 = 298, + KEY_F10 = 299, + KEY_F11 = 300, + KEY_F12 = 301, + KEY_F13 = 302, + KEY_F14 = 303, + KEY_F15 = 304, + KEY_F16 = 305, + KEY_F17 = 306, + KEY_F18 = 307, + KEY_F19 = 308, + KEY_F20 = 309, + KEY_F21 = 310, + KEY_F22 = 311, + KEY_F23 = 312, + KEY_F24 = 313, + KEY_F25 = 314, + KEY_KP_0 = 320, + KEY_KP_1 = 321, + KEY_KP_2 = 322, + KEY_KP_3 = 323, + KEY_KP_4 = 324, + KEY_KP_5 = 325, + KEY_KP_6 = 326, + KEY_KP_7 = 327, + KEY_KP_8 = 328, + KEY_KP_9 = 329, + KEY_KP_DECIMAL = 330, + KEY_KP_DIVIDE = 331, + KEY_KP_MULTIPLY = 332, + KEY_KP_SUBTRACT = 333, + KEY_KP_ADD = 334, + KEY_KP_ENTER = 335, + KEY_KP_EQUAL = 336, + KEY_LEFT_SHIFT = 340, + KEY_LEFT_CONTROL = 341, + KEY_LEFT_ALT = 342, + KEY_LEFT_SUPER = 343, + KEY_RIGHT_SHIFT = 344, + KEY_RIGHT_CONTROL = 345, + KEY_RIGHT_ALT = 346, + KEY_RIGHT_SUPER = 347, + KEY_MENU = 348, + KEY_LAST = KEY_MENU }; -enum class MouseButton -{ - MOUSE_BUTTON_1 = 0, - MOUSE_BUTTON_2 = 1, - MOUSE_BUTTON_3 = 2, - MOUSE_BUTTON_4 = 3, - MOUSE_BUTTON_5 = 4, - MOUSE_BUTTON_6 = 5, - MOUSE_BUTTON_7 = 6, - MOUSE_BUTTON_8 = 7, +enum class MouseButton { + MOUSE_BUTTON_1 = 0, + MOUSE_BUTTON_2 = 1, + MOUSE_BUTTON_3 = 2, + MOUSE_BUTTON_4 = 3, + MOUSE_BUTTON_5 = 4, + MOUSE_BUTTON_6 = 5, + MOUSE_BUTTON_7 = 6, + MOUSE_BUTTON_8 = 7, }; -enum class InputAction -{ - RELEASE = 0, - PRESS = 1, - REPEAT = 2 -}; +enum class InputAction { RELEASE = 0, PRESS = 1, REPEAT = 2 }; -enum class KeyModifier : uint32 -{ - MOD_SHIFT = 0x0001, - MOD_CONTROL = 0x0002, - MOD_ALT = 0x0004, - MOD_SUPER = 0x0008, - MOD_CAPS_LOCK = 0x0010, - MOD_NUM_LOCK = 0x0020 +enum class KeyModifier : uint32 { + MOD_SHIFT = 0x0001, + MOD_CONTROL = 0x0002, + MOD_ALT = 0x0004, + MOD_SUPER = 0x0008, + MOD_CAPS_LOCK = 0x0010, + MOD_NUM_LOCK = 0x0020 }; typedef uint32 KeyModifierFlags; -namespace Gfx -{ +namespace Gfx { static constexpr bool useAsyncCompute = false; static constexpr bool useMeshShading = true; static constexpr uint32 numFramesBuffered = 3; @@ -174,8 +165,7 @@ static constexpr uint32 numPrimitivesPerMeshlet = 256; double getCurrentFrameDelta(); uint32 getCurrentFrameIndex(); -enum class QueueType -{ +enum class QueueType { GRAPHICS = 1, COMPUTE = 2, TRANSFER = 3, @@ -185,8 +175,7 @@ typedef uint32_t SeFlags; typedef uint32_t SeBool32; typedef uint64_t SeDeviceSize; typedef uint32_t SeSampleMask; -typedef enum SeResult -{ +typedef enum SeResult { SE_SUCCESS = 0, SE_NOT_READY = 1, SE_TIMEOUT = 2, @@ -221,8 +210,7 @@ typedef enum SeResult SE_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT = -1000255000, } SeResult; -typedef enum SeStructureType -{ +typedef enum SeStructureType { SE_STRUCTURE_TYPE_APPLICATION_INFO = 0, SE_STRUCTURE_TYPE_INSTANCE_CREATE_INFO = 1, SE_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO = 2, @@ -598,8 +586,7 @@ typedef enum SeStructureType SE_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_PROPERTIES_EXT = 1000281001, } SeStructureType; -typedef enum SeSystemAllocationScope -{ +typedef enum SeSystemAllocationScope { SE_SYSTEM_ALLOCATION_SCOPE_COMMAND = 0, SE_SYSTEM_ALLOCATION_SCOPE_OBJECT = 1, SE_SYSTEM_ALLOCATION_SCOPE_CACHE = 2, @@ -607,13 +594,11 @@ typedef enum SeSystemAllocationScope SE_SYSTEM_ALLOCATION_SCOPE_INSTANCE = 4, } SeSystemAllocationScope; -typedef enum SeInternalAllocationType -{ +typedef enum SeInternalAllocationType { SE_INTERNAL_ALLOCATION_TYPE_EXECUTABLE = 0, } SeInternalAllocationType; -typedef enum SeFormat -{ +typedef enum SeFormat { SE_FORMAT_UNDEFINED = 0, SE_FORMAT_R4G4_UNORM_PACK8 = 1, SE_FORMAT_R4G4B4A4_UNORM_PACK16 = 2, @@ -857,8 +842,7 @@ typedef enum SeFormat SE_FORMAT_ASTC_12x12_SFLOAT_BLOCK = 1000066013, } SeFormat; -struct FormatCompatibilityInfo -{ +struct FormatCompatibilityInfo { // std::string class uint32 blockSize; UVector blockExtent; @@ -867,21 +851,18 @@ struct FormatCompatibilityInfo FormatCompatibilityInfo getFormatInfo(SeFormat format); -typedef enum SeImageType -{ +typedef enum SeImageType { SE_IMAGE_TYPE_1D = 0, SE_IMAGE_TYPE_2D = 1, SE_IMAGE_TYPE_3D = 2, } SeImageType; -typedef enum SeImageTiling -{ +typedef enum SeImageTiling { SE_IMAGE_TILING_OPTIMAL = 0, SE_IMAGE_TILING_LINEAR = 1, } SeImageTiling; -typedef enum SePhysicalDeviceType -{ +typedef enum SePhysicalDeviceType { SE_PHYSICAL_DEVICE_TYPE_OTHER = 0, SE_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU = 1, SE_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU = 2, @@ -889,8 +870,7 @@ typedef enum SePhysicalDeviceType SE_PHYSICAL_DEVICE_TYPE_CPU = 4, } SePhysicalDeviceType; -typedef enum SeQueryType -{ +typedef enum SeQueryType { SE_QUERY_TYPE_OCCLUSION = 0, SE_QUERY_TYPE_PIPELINE_STATISTICS = 1, SE_QUERY_TYPE_TIMESTAMP = 2, @@ -899,14 +879,12 @@ typedef enum SeQueryType SE_QUERY_TYPE_PERFORMANCE_QUERY_INTEL = 1000210000, } SeQueryType; -typedef enum SeSharingMode -{ +typedef enum SeSharingMode { SE_SHARING_MODE_EXCLUSIVE = 0, SE_SHARING_MODE_CONCURRENT = 1, } SeSharingMode; -typedef enum SeImageLayout -{ +typedef enum SeImageLayout { SE_IMAGE_LAYOUT_UNDEFINED = 0, SE_IMAGE_LAYOUT_GENERAL = 1, SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL = 2, @@ -924,8 +902,7 @@ typedef enum SeImageLayout SE_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT = 1000218000, } SeImageLayout; -typedef enum SeImageViewType -{ +typedef enum SeImageViewType { SE_IMAGE_VIEW_TYPE_1D = 0, SE_IMAGE_VIEW_TYPE_2D = 1, SE_IMAGE_VIEW_TYPE_3D = 2, @@ -935,8 +912,7 @@ typedef enum SeImageViewType SE_IMAGE_VIEW_TYPE_CUBE_ARRAY = 6, } SeImageViewType; -typedef enum SeComponentSwizzle -{ +typedef enum SeComponentSwizzle { SE_COMPONENT_SWIZZLE_IDENTITY = 0, SE_COMPONENT_SWIZZLE_ZERO = 1, SE_COMPONENT_SWIZZLE_ONE = 2, @@ -946,14 +922,12 @@ typedef enum SeComponentSwizzle SE_COMPONENT_SWIZZLE_A = 6, } SeComponentSwizzle; -typedef enum SeVertexInputRate -{ +typedef enum SeVertexInputRate { SE_VERTEX_INPUT_RATE_VERTEX = 0, SE_VERTEX_INPUT_RATE_INSTANCE = 1, } SeVertexInputRate; -typedef enum SePrimitiveTopology -{ +typedef enum SePrimitiveTopology { SE_PRIMITIVE_TOPOLOGY_POINT_LIST = 0, SE_PRIMITIVE_TOPOLOGY_LINE_LIST = 1, SE_PRIMITIVE_TOPOLOGY_LINE_STRIP = 2, @@ -967,22 +941,19 @@ typedef enum SePrimitiveTopology SE_PRIMITIVE_TOPOLOGY_PATCH_LIST = 10, } SePrimitiveTopology; -typedef enum SePolygonMode -{ +typedef enum SePolygonMode { SE_POLYGON_MODE_FILL = 0, SE_POLYGON_MODE_LINE = 1, SE_POLYGON_MODE_POINT = 2, SE_POLYGON_MODE_FILL_RECTANGLE_NV = 1000153000, } SePolygonMode; -typedef enum SeFrontFace -{ +typedef enum SeFrontFace { SE_FRONT_FACE_COUNTER_CLOCKWISE = 0, SE_FRONT_FACE_CLOCKWISE = 1, } SeFrontFace; -typedef enum SeCompareOp -{ +typedef enum SeCompareOp { SE_COMPARE_OP_NEVER = 0, SE_COMPARE_OP_LESS = 1, SE_COMPARE_OP_EQUAL = 2, @@ -993,8 +964,7 @@ typedef enum SeCompareOp SE_COMPARE_OP_ALWAYS = 7, } SeCompareOp; -typedef enum SeStencilOp -{ +typedef enum SeStencilOp { SE_STENCIL_OP_KEEP = 0, SE_STENCIL_OP_ZERO = 1, SE_STENCIL_OP_REPLACE = 2, @@ -1005,8 +975,7 @@ typedef enum SeStencilOp SE_STENCIL_OP_DECREMENT_AND_WRAP = 7, } SeStencilOp; -typedef enum SeLogicOp -{ +typedef enum SeLogicOp { SE_LOGIC_OP_CLEAR = 0, SE_LOGIC_OP_AND = 1, SE_LOGIC_OP_AND_REVERSE = 2, @@ -1025,8 +994,7 @@ typedef enum SeLogicOp SE_LOGIC_OP_SET = 15, } SeLogicOp; -typedef enum SeBlendFactor -{ +typedef enum SeBlendFactor { SE_BLEND_FACTOR_ZERO = 0, SE_BLEND_FACTOR_ONE = 1, SE_BLEND_FACTOR_SRC_COLOR = 2, @@ -1048,8 +1016,7 @@ typedef enum SeBlendFactor SE_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA = 18, } SeBlendFactor; -typedef enum SeBlendOp -{ +typedef enum SeBlendOp { SE_BLEND_OP_ADD = 0, SE_BLEND_OP_SUBTRACT = 1, SE_BLEND_OP_REVERSE_SUBTRACT = 2, @@ -1103,8 +1070,7 @@ typedef enum SeBlendOp SE_BLEND_OP_BLUE_EXT = 1000148045, } SeBlendOp; -typedef enum SeDynamicState -{ +typedef enum SeDynamicState { SE_DYNAMIC_STATE_VIEWPORT = 0, SE_DYNAMIC_STATE_SCISSOR = 1, SE_DYNAMIC_STATE_LINE_WIDTH = 2, @@ -1123,21 +1089,18 @@ typedef enum SeDynamicState SE_DYNAMIC_STATE_LINE_STIPPLE_EXT = 1000259000, } SeDynamicState; -typedef enum SeFilter -{ +typedef enum SeFilter { SE_FILTER_NEAREST = 0, SE_FILTER_LINEAR = 1, SE_FILTER_CUBIC_IMG = 1000015000, } SeFilter; -typedef enum SeSamplerMipmapMode -{ +typedef enum SeSamplerMipmapMode { SE_SAMPLER_MIPMAP_MODE_NEAREST = 0, SE_SAMPLER_MIPMAP_MODE_LINEAR = 1, } SeSamplerMipmapMode; -typedef enum SeSamplerAddressMode -{ +typedef enum SeSamplerAddressMode { SE_SAMPLER_ADDRESS_MODE_REPEAT = 0, SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT = 1, SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE = 2, @@ -1145,8 +1108,7 @@ typedef enum SeSamplerAddressMode SE_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE = 4, } SeSamplerAddressMode; -typedef enum SeBorderColor -{ +typedef enum SeBorderColor { SE_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK = 0, SE_BORDER_COLOR_INT_TRANSPARENT_BLACK = 1, SE_BORDER_COLOR_FLOAT_OPAQUE_BLACK = 2, @@ -1155,8 +1117,7 @@ typedef enum SeBorderColor SE_BORDER_COLOR_INT_OPAQUE_WHITE = 5, } SeBorderColor; -typedef enum SeDescriptorType -{ +typedef enum SeDescriptorType { SE_DESCRIPTOR_TYPE_SAMPLER = 0, SE_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER = 1, SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE = 2, @@ -1180,47 +1141,40 @@ typedef enum SeDescriptorBindingFlagBits { } SeDescriptorBindingFlagBits; typedef SeFlags SeDescriptorBindingFlags; -typedef enum SeAttachmentLoadOp -{ +typedef enum SeAttachmentLoadOp { SE_ATTACHMENT_LOAD_OP_LOAD = 0, SE_ATTACHMENT_LOAD_OP_CLEAR = 1, SE_ATTACHMENT_LOAD_OP_DONT_CARE = 2, } SeAttachmentLoadOp; -typedef enum SeAttachmentStoreOp -{ +typedef enum SeAttachmentStoreOp { SE_ATTACHMENT_STORE_OP_STORE = 0, SE_ATTACHMENT_STORE_OP_DONT_CARE = 1, } SeAttachmentStoreOp; -typedef enum SePipelineBindPoint -{ +typedef enum SePipelineBindPoint { SE_PIPELINE_BIND_POINT_GRAPHICS = 0, SE_PIPELINE_BIND_POINT_COMPUTE = 1, SE_PIPELINE_BIND_POINT_RAY_TRACING_NV = 1000165000, } SePipelineBindPoint; -typedef enum SeCommandBufferLevel -{ +typedef enum SeCommandBufferLevel { SE_COMMAND_BUFFER_LEVEL_PRIMARY = 0, SE_COMMAND_BUFFER_LEVEL_SECONDARY = 1, } SeCommandBufferLevel; -typedef enum SeIndexType -{ +typedef enum SeIndexType { SE_INDEX_TYPE_UINT16 = 0, SE_INDEX_TYPE_UINT32 = 1, SE_INDEX_TYPE_NONE_NV = 1000165000, SE_INDEX_TYPE_UINT8_EXT = 1000265000, } SeIndexType; -typedef enum SeSubpassContents -{ +typedef enum SeSubpassContents { SE_SUBPASS_CONTENTS_INLINE = 0, } SeSubpassContents; -typedef enum SeObjectType -{ +typedef enum SeObjectType { SE_OBJECT_TYPE_UNKNOWN = 0, SE_OBJECT_TYPE_INSTANCE = 1, SE_OBJECT_TYPE_PHYSICAL_DEVICE = 2, @@ -1262,16 +1216,14 @@ typedef enum SeObjectType SE_OBJECT_TYPE_PERFORMANCE_CONFIGURATION_INTEL = 1000210000, } SeObjectType; -typedef enum SeVendorId -{ +typedef enum SeVendorId { SE_VENDOR_ID_VIV = 0x10001, SE_VENDOR_ID_VSI = 0x10002, SE_VENDOR_ID_KAZAN = 0x10003, } SeVendorId; typedef SeFlags SeInstanceCreateFlags; -typedef enum SeFormatFeatureFlagBits -{ +typedef enum SeFormatFeatureFlagBits { SE_FORMAT_FEATURE_SAMPLED_IMAGE_BIT = 0x00000001, SE_FORMAT_FEATURE_STORAGE_IMAGE_BIT = 0x00000002, SE_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT = 0x00000004, @@ -1300,10 +1252,14 @@ typedef enum SeFormatFeatureFlagBits SE_FORMAT_FEATURE_TRANSFER_SRC_BIT_KHR = SE_FORMAT_FEATURE_TRANSFER_SRC_BIT, SE_FORMAT_FEATURE_TRANSFER_DST_BIT_KHR = SE_FORMAT_FEATURE_TRANSFER_DST_BIT, SE_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT_KHR = SE_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT, - SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT_KHR = SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT, - SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT_KHR = SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT, - SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT_KHR = SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT, - SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT_KHR = SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT, + SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT_KHR = + SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT, + SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT_KHR = + SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT, + SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT_KHR = + SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT, + SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT_KHR = + SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT, SE_FORMAT_FEATURE_DISJOINT_BIT_KHR = SE_FORMAT_FEATURE_DISJOINT_BIT, SE_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT_KHR = SE_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT, SE_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_EXT = SE_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG, @@ -1311,8 +1267,7 @@ typedef enum SeFormatFeatureFlagBits } SeFormatFeatureFlagBits; typedef SeFlags SeFormatFeatureFlags; -typedef enum SeImageUsageFlagBits -{ +typedef enum SeImageUsageFlagBits { SE_IMAGE_USAGE_TRANSFER_SRC_BIT = 0x00000001, SE_IMAGE_USAGE_TRANSFER_DST_BIT = 0x00000002, SE_IMAGE_USAGE_SAMPLED_BIT = 0x00000004, @@ -1327,8 +1282,7 @@ typedef enum SeImageUsageFlagBits } SeImageUsageFlagBits; typedef SeFlags SeImageUsageFlags; -typedef enum SeImageCreateFlagBits -{ +typedef enum SeImageCreateFlagBits { SE_IMAGE_CREATE_SPARSE_BINDING_BIT = 0x00000001, SE_IMAGE_CREATE_SPARSE_RESIDENCY_BIT = 0x00000002, SE_IMAGE_CREATE_SPARSE_ALIASED_BIT = 0x00000004, @@ -1354,8 +1308,7 @@ typedef enum SeImageCreateFlagBits } SeImageCreateFlagBits; typedef SeFlags SeImageCreateFlags; -typedef enum SeSampleCountFlagBits -{ +typedef enum SeSampleCountFlagBits { SE_SAMPLE_COUNT_1_BIT = 0x00000001, SE_SAMPLE_COUNT_2_BIT = 0x00000002, SE_SAMPLE_COUNT_4_BIT = 0x00000004, @@ -1367,8 +1320,7 @@ typedef enum SeSampleCountFlagBits } SeSampleCountFlagBits; typedef SeFlags SeSampleCountFlags; -typedef enum SeQueueFlagBits -{ +typedef enum SeQueueFlagBits { SE_QUEUE_GRAPHICS_BIT = 0x00000001, SE_QUEUE_COMPUTE_BIT = 0x00000002, SE_QUEUE_TRANSFER_BIT = 0x00000004, @@ -1378,8 +1330,7 @@ typedef enum SeQueueFlagBits } SeQueueFlagBits; typedef SeFlags SeQueueFlags; -typedef enum SeMemoryPropertyFlagBits -{ +typedef enum SeMemoryPropertyFlagBits { SE_MEMORY_PROPERTY_DEVICE_LOCAL_BIT = 0x00000001, SE_MEMORY_PROPERTY_HOST_VISIBLE_BIT = 0x00000002, SE_MEMORY_PROPERTY_HOST_COHERENT_BIT = 0x00000004, @@ -1392,8 +1343,7 @@ typedef enum SeMemoryPropertyFlagBits } SeMemoryPropertyFlagBits; typedef SeFlags SeMemoryPropertyFlags; -typedef enum SeMemoryHeapFlagBits -{ +typedef enum SeMemoryHeapFlagBits { SE_MEMORY_HEAP_DEVICE_LOCAL_BIT = 0x00000001, SE_MEMORY_HEAP_MULTI_INSTANCE_BIT = 0x00000002, SE_MEMORY_HEAP_MULTI_INSTANCE_BIT_KHR = SE_MEMORY_HEAP_MULTI_INSTANCE_BIT, @@ -1402,15 +1352,13 @@ typedef enum SeMemoryHeapFlagBits typedef SeFlags SeMemoryHeapFlags; typedef SeFlags SeDeviceCreateFlags; -typedef enum SeDeviceQueueCreateFlagBits -{ +typedef enum SeDeviceQueueCreateFlagBits { SE_DEVICE_QUEUE_CREATE_PROTECTED_BIT = 0x00000001, SE_DEVICE_QUEUE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeDeviceQueueCreateFlagBits; typedef SeFlags SeDeviceQueueCreateFlags; -typedef enum SePipelineStageFlagBits -{ +typedef enum SePipelineStageFlagBits { SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT = 0x00000001, SE_PIPELINE_STAGE_DRAW_INDIRECT_BIT = 0x00000002, SE_PIPELINE_STAGE_VERTEX_INPUT_BIT = 0x00000004, @@ -1443,8 +1391,7 @@ typedef enum SePipelineStageFlagBits typedef SeFlags SePipelineStageFlags; typedef SeFlags SeMemoryMapFlags; -typedef enum SeImageAspectFlagBits -{ +typedef enum SeImageAspectFlagBits { SE_IMAGE_ASPECT_COLOR_BIT = 0x00000001, SE_IMAGE_ASPECT_DEPTH_BIT = 0x00000002, SE_IMAGE_ASPECT_STENCIL_BIT = 0x00000004, @@ -1463,8 +1410,7 @@ typedef enum SeImageAspectFlagBits } SeImageAspectFlagBits; typedef SeFlags SeImageAspectFlags; -typedef enum SeSparseImageFormatFlagBits -{ +typedef enum SeSparseImageFormatFlagBits { SE_SPARSE_IMAGE_FORMAT_SINGLE_MIPTAIL_BIT = 0x00000001, SE_SPARSE_IMAGE_FORMAT_ALIGNED_MIP_SIZE_BIT = 0x00000002, SE_SPARSE_IMAGE_FORMAT_NONSTANDARD_BLOCK_SIZE_BIT = 0x00000004, @@ -1472,15 +1418,13 @@ typedef enum SeSparseImageFormatFlagBits } SeSparseImageFormatFlagBits; typedef SeFlags SeSparseImageFormatFlags; -typedef enum SeSparseMemoryBindFlagBits -{ +typedef enum SeSparseMemoryBindFlagBits { SE_SPARSE_MEMORY_BIND_METADATA_BIT = 0x00000001, SE_SPARSE_MEMORY_BIND_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeSparseMemoryBindFlagBits; typedef SeFlags SeSparseMemoryBindFlags; -typedef enum SeFenceCreateFlagBits -{ +typedef enum SeFenceCreateFlagBits { SE_FENCE_CREATE_SIGNALED_BIT = 0x00000001, SE_FENCE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeFenceCreateFlagBits; @@ -1489,8 +1433,7 @@ typedef SeFlags SeSemaphoreCreateFlags; typedef SeFlags SeEventCreateFlags; typedef SeFlags SeQueryPoolCreateFlags; -typedef enum SeQueryPipelineStatisticFlagBits -{ +typedef enum SeQueryPipelineStatisticFlagBits { SE_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT = 0x00000001, SE_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT = 0x00000002, SE_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT = 0x00000004, @@ -1506,8 +1449,7 @@ typedef enum SeQueryPipelineStatisticFlagBits } SeQueryPipelineStatisticFlagBits; typedef SeFlags SeQueryPipelineStatisticFlags; -typedef enum SeQueryResultFlagBits -{ +typedef enum SeQueryResultFlagBits { SE_QUERY_RESULT_64_BIT = 0x00000001, SE_QUERY_RESULT_WAIT_BIT = 0x00000002, SE_QUERY_RESULT_WITH_AVAILABILITY_BIT = 0x00000004, @@ -1516,8 +1458,7 @@ typedef enum SeQueryResultFlagBits } SeQueryResultFlagBits; typedef SeFlags SeQueryResultFlags; -typedef enum SeBufferCreateFlagBits -{ +typedef enum SeBufferCreateFlagBits { SE_BUFFER_CREATE_SPARSE_BINDING_BIT = 0x00000001, SE_BUFFER_CREATE_SPARSE_RESIDENCY_BIT = 0x00000002, SE_BUFFER_CREATE_SPARSE_ALIASED_BIT = 0x00000004, @@ -1527,8 +1468,7 @@ typedef enum SeBufferCreateFlagBits } SeBufferCreateFlagBits; typedef SeFlags SeBufferCreateFlags; -typedef enum SeBufferUsageFlagBits -{ +typedef enum SeBufferUsageFlagBits { SE_BUFFER_USAGE_TRANSFER_SRC_BIT = 0x00000001, SE_BUFFER_USAGE_TRANSFER_DST_BIT = 0x00000002, SE_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT = 0x00000004, @@ -1548,22 +1488,17 @@ typedef enum SeBufferUsageFlagBits typedef SeFlags SeBufferUsageFlags; typedef SeFlags SeBufferViewCreateFlags; -typedef enum SeImageViewCreateFlagBits -{ +typedef enum SeImageViewCreateFlagBits { SE_IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DYNAMIC_BIT_EXT = 0x00000001, SE_IMAGE_VIEW_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeImageViewCreateFlagBits; typedef SeFlags SeImageViewCreateFlags; -typedef enum SeShaderModuleCreateFlagBits -{ - SE_SHADER_MODULE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} SeShaderModuleCreateFlagBits; +typedef enum SeShaderModuleCreateFlagBits { SE_SHADER_MODULE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeShaderModuleCreateFlagBits; typedef SeFlags SeShaderModuleCreateFlags; typedef SeFlags SePipelineCacheCreateFlags; -typedef enum SePipelineCreateFlagBits -{ +typedef enum SePipelineCreateFlagBits { SE_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT = 0x00000001, SE_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT = 0x00000002, SE_PIPELINE_CREATE_DERIVATIVE_BIT = 0x00000004, @@ -1578,16 +1513,14 @@ typedef enum SePipelineCreateFlagBits } SePipelineCreateFlagBits; typedef SeFlags SePipelineCreateFlags; -typedef enum SePipelineShaderStageCreateFlagBits -{ +typedef enum SePipelineShaderStageCreateFlagBits { SE_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT = 0x00000001, SE_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT_EXT = 0x00000002, SE_PIPELINE_SHADER_STAGE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SePipelineShaderStageCreateFlagBits; typedef SeFlags SePipelineShaderStageCreateFlags; -typedef enum SeShaderStageFlagBits -{ +typedef enum SeShaderStageFlagBits { SE_SHADER_STAGE_VERTEX_BIT = 0x00000001, SE_SHADER_STAGE_TESSELLATION_CONTROL_BIT = 0x00000002, SE_SHADER_STAGE_TESSELLATION_EVALUATION_BIT = 0x00000004, @@ -1613,8 +1546,7 @@ typedef SeFlags SePipelineTessellationStateCreateFlags; typedef SeFlags SePipelineViewportStateCreateFlags; typedef SeFlags SePipelineRasterizationStateCreateFlags; -typedef enum SeCullModeFlagBits -{ +typedef enum SeCullModeFlagBits { SE_CULL_MODE_NONE = 0, SE_CULL_MODE_FRONT_BIT = 0x00000001, SE_CULL_MODE_BACK_BIT = 0x00000002, @@ -1626,8 +1558,7 @@ typedef SeFlags SePipelineMultisampleStateCreateFlags; typedef SeFlags SePipelineDepthStencilStateCreateFlags; typedef SeFlags SePipelineColorBlendStateCreateFlags; -typedef enum SeColorComponentFlagBits -{ +typedef enum SeColorComponentFlagBits { SE_COLOR_COMPONENT_R_BIT = 0x00000001, SE_COLOR_COMPONENT_G_BIT = 0x00000002, SE_COLOR_COMPONENT_B_BIT = 0x00000004, @@ -1639,24 +1570,21 @@ typedef SeFlags SePipelineDynamicStateCreateFlags; typedef SeFlags SePipelineLayoutCreateFlags; typedef SeFlags SeShaderStageFlags; -typedef enum SeSamplerCreateFlagBits -{ +typedef enum SeSamplerCreateFlagBits { SE_SAMPLER_CREATE_SUBSAMPLED_BIT_EXT = 0x00000001, SE_SAMPLER_CREATE_SUBSAMPLED_COARSE_RECONSTRUCTION_BIT_EXT = 0x00000002, SE_SAMPLER_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeSamplerCreateFlagBits; typedef SeFlags SeSamplerCreateFlags; -typedef enum SeDescriptorSetLayoutCreateFlagBits -{ +typedef enum SeDescriptorSetLayoutCreateFlagBits { SE_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR = 0x00000001, SE_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT = 0x00000002, SE_DESCRIPTOR_SET_LAYOUT_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeDescriptorSetLayoutCreateFlagBits; typedef SeFlags SeDescriptorSetLayoutCreateFlags; -typedef enum SeDescriptorPoolCreateFlagBits -{ +typedef enum SeDescriptorPoolCreateFlagBits { SE_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT = 0x00000001, SE_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT = 0x00000002, SE_DESCRIPTOR_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF @@ -1664,36 +1592,29 @@ typedef enum SeDescriptorPoolCreateFlagBits typedef SeFlags SeDescriptorPoolCreateFlags; typedef SeFlags SeDescriptorPoolResetFlags; -typedef enum SeFramebufferCreateFlagBits -{ +typedef enum SeFramebufferCreateFlagBits { SE_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR = 0x00000001, SE_FRAMEBUFFER_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeFramebufferCreateFlagBits; typedef SeFlags SeFramebufferCreateFlags; -typedef enum SeRenderPassCreateFlagBits -{ - SE_RENDER_PASS_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} SeRenderPassCreateFlagBits; +typedef enum SeRenderPassCreateFlagBits { SE_RENDER_PASS_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeRenderPassCreateFlagBits; typedef SeFlags SeRenderPassCreateFlags; -typedef enum SeAttachmentDescriptionFlagBits -{ +typedef enum SeAttachmentDescriptionFlagBits { SE_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT = 0x00000001, SE_ATTACHMENT_DESCRIPTION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeAttachmentDescriptionFlagBits; typedef SeFlags SeAttachmentDescriptionFlags; -typedef enum SeSubpassDescriptionFlagBits -{ +typedef enum SeSubpassDescriptionFlagBits { SE_SUBPASS_DESCRIPTION_PER_VIEW_ATTRIBUTES_BIT_NVX = 0x00000001, SE_SUBPASS_DESCRIPTION_PER_VIEW_POSITION_X_ONLY_BIT_NVX = 0x00000002, SE_SUBPASS_DESCRIPTION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeSubpassDescriptionFlagBits; typedef SeFlags SeSubpassDescriptionFlags; -typedef enum SeAccessFlagBits -{ +typedef enum SeAccessFlagBits { SE_ACCESS_INDIRECT_COMMAND_READ_BIT = 0x00000001, SE_ACCESS_INDEX_READ_BIT = 0x00000002, SE_ACCESS_VERTEX_ATTRIBUTE_READ_BIT = 0x00000004, @@ -1727,8 +1648,7 @@ typedef enum SeAccessFlagBits } SeAccessFlagBits; typedef SeFlags SeAccessFlags; -typedef enum SeDependencyFlagBits -{ +typedef enum SeDependencyFlagBits { SE_DEPENDENCY_BY_REGION_BIT = 0x00000001, SE_DEPENDENCY_DEVICE_GROUP_BIT = 0x00000004, SE_DEPENDENCY_VIEW_LOCAL_BIT = 0x00000002, @@ -1738,8 +1658,7 @@ typedef enum SeDependencyFlagBits } SeDependencyFlagBits; typedef SeFlags SeDependencyFlags; -typedef enum SeCommandPoolCreateFlagBits -{ +typedef enum SeCommandPoolCreateFlagBits { SE_COMMAND_POOL_CREATE_TRANSIENT_BIT = 0x00000001, SE_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT = 0x00000002, SE_COMMAND_POOL_CREATE_PROTECTED_BIT = 0x00000004, @@ -1747,15 +1666,13 @@ typedef enum SeCommandPoolCreateFlagBits } SeCommandPoolCreateFlagBits; typedef SeFlags SeCommandPoolCreateFlags; -typedef enum SeCommandPoolResetFlagBits -{ +typedef enum SeCommandPoolResetFlagBits { SE_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT = 0x00000001, SE_COMMAND_POOL_RESET_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeCommandPoolResetFlagBits; typedef SeFlags SeCommandPoolResetFlags; -typedef enum SeCommandBufferUsageFlagBits -{ +typedef enum SeCommandBufferUsageFlagBits { SE_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT = 0x00000001, SE_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT = 0x00000002, SE_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT = 0x00000004, @@ -1763,22 +1680,19 @@ typedef enum SeCommandBufferUsageFlagBits } SeCommandBufferUsageFlagBits; typedef SeFlags SeCommandBufferUsageFlags; -typedef enum SeQueryControlFlagBits -{ +typedef enum SeQueryControlFlagBits { SE_QUERY_CONTROL_PRECISE_BIT = 0x00000001, SE_QUERY_CONTROL_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeQueryControlFlagBits; typedef SeFlags SeQueryControlFlags; -typedef enum SeCommandBufferResetFlagBits -{ +typedef enum SeCommandBufferResetFlagBits { SE_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT = 0x00000001, SE_COMMAND_BUFFER_RESET_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeCommandBufferResetFlagBits; typedef SeFlags SeCommandBufferResetFlags; -typedef enum SeStencilFaceFlagBits -{ +typedef enum SeStencilFaceFlagBits { SE_STENCIL_FACE_FRONT_BIT = 0x00000001, SE_STENCIL_FACE_BACK_BIT = 0x00000002, SE_STENCIL_FACE_FRONT_AND_BACK = 0x00000003, @@ -1788,30 +1702,27 @@ typedef enum SeStencilFaceFlagBits typedef SeFlags SeStencilFaceFlags; typedef union SeClearColorValue { - float float32[4]; - int32_t int32[4]; - uint32_t uint32[4]; + float float32[4]; + int32_t int32[4]; + uint32_t uint32[4]; } SeClearColorValue; typedef struct SeClearDepthStencilValue { - float depth; - uint32_t stencil; + float depth; + uint32_t stencil; } SeClearDepthStencilValue; typedef union SeClearValue { - SeClearColorValue color; - SeClearDepthStencilValue depthStencil; + SeClearColorValue color; + SeClearDepthStencilValue depthStencil; } SeClearValue; - typedef enum SeDescriptorAccessTypeFlagBits { - SE_DESCRIPTOR_ACCESS_READ_ONLY_BIT = 0x00000001, - SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT = 0x00000002, - SE_DESCRIPTOR_ACCESS_WRITE_ONLY_BIT = 0x00000004, + SE_DESCRIPTOR_ACCESS_READ_ONLY_BIT = 0x00000001, + SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT = 0x00000002, + SE_DESCRIPTOR_ACCESS_WRITE_ONLY_BIT = 0x00000004, } SeDescriptorAccessTypeFlagBits; typedef SeFlags SeDescriptorAccessTypeFlags; - - } // namespace Gfx } // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/Graphics.cpp b/src/Engine/Graphics/Graphics.cpp index d3e23c7..6157e15 100644 --- a/src/Engine/Graphics/Graphics.cpp +++ b/src/Engine/Graphics/Graphics.cpp @@ -1,14 +1,9 @@ #include "Graphics.h" #include "Shader.h" -#include "Graphics.h" + using namespace Seele::Gfx; -Graphics::Graphics() -{ - shaderCompiler = new ShaderCompiler(this); -} +Graphics::Graphics() { shaderCompiler = new ShaderCompiler(this); } -Graphics::~Graphics() -{ -} +Graphics::~Graphics() {} diff --git a/src/Engine/Graphics/Graphics.h b/src/Engine/Graphics/Graphics.h index 94bfc13..1c4af25 100644 --- a/src/Engine/Graphics/Graphics.h +++ b/src/Engine/Graphics/Graphics.h @@ -1,14 +1,13 @@ #pragma once -#include "MinimalEngine.h" -#include "Initializer.h" -#include "Resources.h" -#include "RenderTarget.h" #include "Containers/Array.h" +#include "Initializer.h" +#include "MinimalEngine.h" +#include "RenderTarget.h" +#include "Resources.h" -namespace Seele -{ -namespace Gfx -{ + +namespace Seele { +namespace Gfx { DECLARE_REF(Window) DECLARE_REF(Viewport) DECLARE_REF(ShaderCompiler) @@ -33,25 +32,18 @@ DECLARE_REF(RenderCommand) DECLARE_REF(ComputeCommand) DECLARE_REF(BottomLevelAS) DECLARE_REF(TopLevelAS) -class Graphics -{ -public: +class Graphics { + public: Graphics(); virtual ~Graphics(); virtual void init(GraphicsInitializer initializer) = 0; - - const QueueFamilyMapping getFamilyMapping() const - { - return queueMapping; - } - PShaderCompiler getShaderCompiler() - { - return shaderCompiler; - } - - virtual OWindow createWindow(const WindowCreateInfo &createInfo) = 0; - virtual OViewport createViewport(PWindow owner, const ViewportCreateInfo &createInfo) = 0; + const QueueFamilyMapping getFamilyMapping() const { return queueMapping; } + + PShaderCompiler getShaderCompiler() { return shaderCompiler; } + + virtual OWindow createWindow(const WindowCreateInfo& createInfo) = 0; + virtual OViewport createViewport(PWindow owner, const ViewportCreateInfo& createInfo) = 0; virtual ORenderPass createRenderPass(RenderTargetLayout layout, Array dependencies, PViewport renderArea) = 0; virtual void beginRenderPass(PRenderPass renderPass) = 0; @@ -61,17 +53,17 @@ public: virtual void executeCommands(Array commands) = 0; virtual void executeCommands(Array commands) = 0; - virtual OTexture2D createTexture2D(const TextureCreateInfo &createInfo) = 0; - virtual OTexture3D createTexture3D(const TextureCreateInfo &createInfo) = 0; - virtual OTextureCube createTextureCube(const TextureCreateInfo &createInfo) = 0; - virtual OUniformBuffer createUniformBuffer(const UniformBufferCreateInfo &bulkData) = 0; - virtual OShaderBuffer createShaderBuffer(const ShaderBufferCreateInfo &bulkData) = 0; - virtual OVertexBuffer createVertexBuffer(const VertexBufferCreateInfo &bulkData) = 0; - virtual OIndexBuffer createIndexBuffer(const IndexBufferCreateInfo &bulkData) = 0; - + virtual OTexture2D createTexture2D(const TextureCreateInfo& createInfo) = 0; + virtual OTexture3D createTexture3D(const TextureCreateInfo& createInfo) = 0; + virtual OTextureCube createTextureCube(const TextureCreateInfo& createInfo) = 0; + virtual OUniformBuffer createUniformBuffer(const UniformBufferCreateInfo& bulkData) = 0; + virtual OShaderBuffer createShaderBuffer(const ShaderBufferCreateInfo& bulkData) = 0; + virtual OVertexBuffer createVertexBuffer(const VertexBufferCreateInfo& bulkData) = 0; + virtual OIndexBuffer createIndexBuffer(const IndexBufferCreateInfo& bulkData) = 0; + virtual ORenderCommand createRenderCommand(const std::string& name = "") = 0; virtual OComputeCommand createComputeCommand(const std::string& name = "") = 0; - + virtual OVertexShader createVertexShader(const ShaderCreateInfo& createInfo) = 0; virtual OFragmentShader createFragmentShader(const ShaderCreateInfo& createInfo) = 0; virtual OComputeShader createComputeShader(const ShaderCreateInfo& createInfo) = 0; @@ -82,8 +74,8 @@ public: virtual PComputePipeline createComputePipeline(ComputePipelineCreateInfo createInfo) = 0; virtual OSampler createSampler(const SamplerCreateInfo& createInfo) = 0; - virtual ODescriptorLayout createDescriptorLayout(const std::string& name = "") = 0; - virtual OPipelineLayout createPipelineLayout(const std::string& name = "", PPipelineLayout baseLayout = nullptr) = 0; + virtual ODescriptorLayout createDescriptorLayout(const std::string& name = "") = 0; + virtual OPipelineLayout createPipelineLayout(const std::string& name = "", PPipelineLayout baseLayout = nullptr) = 0; virtual OVertexInput createVertexInput(VertexInputStateCreateInfo createInfo) = 0; @@ -94,7 +86,8 @@ public: // Ray Tracing virtual OBottomLevelAS createBottomLevelAccelerationStructure(const BottomLevelASCreateInfo& createInfo) = 0; virtual OTopLevelAS createTopLevelAccelerationStructure(const TopLevelASCreateInfo& createInfo) = 0; -protected: + + protected: QueueFamilyMapping queueMapping; OShaderCompiler shaderCompiler; bool meshShadingEnabled = false; diff --git a/src/Engine/Graphics/Initializer.h b/src/Engine/Graphics/Initializer.h index 2d61e4e..ec5d21b 100644 --- a/src/Engine/Graphics/Initializer.h +++ b/src/Engine/Graphics/Initializer.h @@ -1,266 +1,233 @@ #pragma once -#include "Enums.h" #include "Containers/Map.h" +#include "Enums.h" #include "Math/Math.h" -#include "MinimalEngine.h" #include "MeshData.h" +#include "MinimalEngine.h" -namespace Seele -{ - struct GraphicsInitializer - { - const char* applicationName; - const char* engineName; - const char* windowLayoutFile; - /** - * layers defines the enabled Vulkan layers used in the instance, - * if ENABLE_VALIDATION is defined, standard validation is already enabled - * not yet implemented - */ - Array layers; - Array instanceExtensions; - Array deviceExtensions; - void* windowHandle; - GraphicsInitializer() - : applicationName("SeeleEngine") - , engineName("SeeleEngine") - , windowLayoutFile(nullptr) - , layers{ "VK_LAYER_LUNARG_monitor" } - , instanceExtensions{} - , deviceExtensions{ "VK_KHR_swapchain" } - , windowHandle(nullptr) - { - } - }; - struct WindowCreateInfo - { - int32 width; - int32 height; - const char* title; - Gfx::SeFormat preferredFormat = Gfx::SE_FORMAT_B8G8R8A8_UNORM; - void* windowHandle; - }; - struct ViewportCreateInfo - { - URect dimensions; - float fieldOfView = 1.222f; // 70 deg - Gfx::SeSampleCountFlags numSamples; - }; - // doesnt own the data, only proxy it - struct DataSource - { - uint64 size = 0; - uint64 offset = 0; - uint8* data = nullptr; - Gfx::QueueType owner = Gfx::QueueType::GRAPHICS; - }; - struct TextureCreateInfo - { - DataSource sourceData = DataSource(); - Gfx::SeFormat format = Gfx::SE_FORMAT_R32G32B32A32_SFLOAT; - uint32 width = 1; - uint32 height = 1; - uint32 depth = 1; - uint32 mipLevels = 1; - uint32 layers = 1; - uint32 elements = 1; - uint32 samples = 1; - Gfx::SeImageUsageFlags usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT; - Gfx::SeMemoryPropertyFlags memoryProps = Gfx::SE_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; - std::string name; - }; - struct SamplerCreateInfo - { - Gfx::SeSamplerCreateFlags flags; - Gfx::SeFilter magFilter = Gfx::SE_FILTER_LINEAR; - Gfx::SeFilter minFilter = Gfx::SE_FILTER_LINEAR; - Gfx::SeSamplerMipmapMode mipmapMode = Gfx::SE_SAMPLER_MIPMAP_MODE_LINEAR; - Gfx::SeSamplerAddressMode addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT; - Gfx::SeSamplerAddressMode addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT; - Gfx::SeSamplerAddressMode addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT; - float mipLodBias = 0.0f; - uint32 anisotropyEnable = 0; - float maxAnisotropy = 0.0f; - uint32 compareEnable = 0; - Gfx::SeCompareOp compareOp = Gfx::SE_COMPARE_OP_NEVER; - float minLod = 0.0f; - float maxLod = 0.0f; - Gfx::SeBorderColor borderColor = Gfx::SE_BORDER_COLOR_FLOAT_OPAQUE_BLACK; - uint32 unnormalizedCoordinates = 0; - std::string name; - }; - struct VertexBufferCreateInfo - { - DataSource sourceData = DataSource(); - // bytes per vertex - uint32 vertexSize = 0; - uint32 numVertices = 0; - std::string name = "Unnamed"; - }; - struct IndexBufferCreateInfo - { - DataSource sourceData = DataSource(); - Gfx::SeIndexType indexType = Gfx::SeIndexType::SE_INDEX_TYPE_UINT16; - std::string name = "Unnamed"; - }; - struct UniformBufferCreateInfo - { - DataSource sourceData = DataSource(); - uint8 dynamic = 0; - std::string name = "Unnamed"; - }; - struct ShaderBufferCreateInfo - { - DataSource sourceData = DataSource(); - uint64 numElements = 1; - uint8 dynamic = 0; - uint8 vertexBuffer = 0; - std::string name = "Unnamed"; - }; - DECLARE_NAME_REF(Gfx, PipelineLayout) - struct ShaderCreateInfo - { - std::string name; // Debug info - std::string mainModule; - Array additionalModules; - std::string entryPoint; - Array> typeParameter; - Map defines; - Gfx::PPipelineLayout rootSignature; - }; - struct VertexInputBinding - { - uint32 binding; - uint32 stride; - Gfx::SeVertexInputRate inputRate; - }; - struct VertexInputAttribute - { - uint32 location; - uint32 binding; - Gfx::SeFormat format; - uint32 offset; - }; - struct VertexInputStateCreateInfo - { - Array bindings; - Array attributes; - }; - DECLARE_REF(MaterialInstance) - namespace Gfx - { - struct SePushConstantRange - { - SeShaderStageFlags stageFlags; - uint32 offset; - uint32 size; - }; - struct RasterizationState - { - uint32 depthClampEnable = 0; - uint32 rasterizerDiscardEnable = 0; - SePolygonMode polygonMode = Gfx::SE_POLYGON_MODE_FILL; - SeCullModeFlags cullMode = Gfx::SE_CULL_MODE_BACK_BIT; - SeFrontFace frontFace = Gfx::SE_FRONT_FACE_COUNTER_CLOCKWISE; - uint32 depthBiasEnable = 0; - float depthBiasConstantFactor = 0; - float depthBiasClamp = 0; - float depthBiasSlopeFactor = 0; - float lineWidth = 1.0; - }; - struct MultisampleState - { - SeSampleCountFlags samples = 1; - uint32 sampleShadingEnable = 0; - float minSampleShading = 1; - uint8 alphaCoverageEnable = 0; - uint8 alphaToOneEnable = 0; - }; - struct DepthStencilState - { - uint32 depthTestEnable = 1; - uint32 depthWriteEnable = 1; - SeCompareOp depthCompareOp = Gfx::SE_COMPARE_OP_GREATER; - uint32 depthBoundsTestEnable = 0; - uint32 stencilTestEnable = 0; - SeStencilOp front = Gfx::SE_STENCIL_OP_ZERO; - SeStencilOp back = Gfx::SE_STENCIL_OP_ZERO; - float minDepthBounds = 0.0f; - float maxDepthBounds = 1.0f; - }; - struct ColorBlendState - { - struct BlendAttachment - { - uint32 blendEnable = 0; - SeBlendFactor srcColorBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA; - SeBlendFactor dstColorBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA; - SeBlendOp colorBlendOp = Gfx::SE_BLEND_OP_ADD; - SeBlendFactor srcAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA; - SeBlendFactor dstAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA; - SeBlendOp alphaBlendOp = Gfx::SE_BLEND_OP_ADD; - SeColorComponentFlags colorWriteMask = Gfx::SE_COLOR_COMPONENT_R_BIT | Gfx::SE_COLOR_COMPONENT_G_BIT | Gfx::SE_COLOR_COMPONENT_B_BIT | Gfx::SE_COLOR_COMPONENT_A_BIT; - }; - uint32 logicOpEnable = 0; - SeLogicOp logicOp = Gfx::SE_LOGIC_OP_OR; - uint32 attachmentCount = 0; - StaticArray blendAttachments; - StaticArray blendConstants = { 1.0f, 1.0f, 1.0f, 1.0f, }; - }; +namespace Seele { +struct GraphicsInitializer { + const char* applicationName; + const char* engineName; + const char* windowLayoutFile; + /** + * layers defines the enabled Vulkan layers used in the instance, + * if ENABLE_VALIDATION is defined, standard validation is already enabled + * not yet implemented + */ + Array layers; + Array instanceExtensions; + Array deviceExtensions; - DECLARE_REF(VertexInput) - DECLARE_REF(VertexShader) - DECLARE_REF(TaskShader) - DECLARE_REF(MeshShader) - DECLARE_REF(FragmentShader) - DECLARE_REF(ComputeShader) - DECLARE_REF(RenderPass) - DECLARE_REF(PipelineLayout) - struct LegacyPipelineCreateInfo - { - SePrimitiveTopology topology = Gfx::SE_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - PVertexInput vertexInput = nullptr; - PVertexShader vertexShader = nullptr; - PFragmentShader fragmentShader = nullptr; - PRenderPass renderPass = nullptr; - PPipelineLayout pipelineLayout = nullptr; - MultisampleState multisampleState; - RasterizationState rasterizationState; - DepthStencilState depthStencilState; - ColorBlendState colorBlend; - }; + void* windowHandle; + GraphicsInitializer() + : applicationName("SeeleEngine"), engineName("SeeleEngine"), windowLayoutFile(nullptr), layers{"VK_LAYER_LUNARG_monitor"}, + instanceExtensions{}, deviceExtensions{"VK_KHR_swapchain"}, windowHandle(nullptr) {} +}; +struct WindowCreateInfo { + int32 width; + int32 height; + const char* title; + Gfx::SeFormat preferredFormat = Gfx::SE_FORMAT_B8G8R8A8_UNORM; + void* windowHandle; +}; +struct ViewportCreateInfo { + URect dimensions; + float fieldOfView = 1.222f; // 70 deg + Gfx::SeSampleCountFlags numSamples; +}; +// doesnt own the data, only proxy it +struct DataSource { + uint64 size = 0; + uint64 offset = 0; + uint8* data = nullptr; + Gfx::QueueType owner = Gfx::QueueType::GRAPHICS; +}; +struct TextureCreateInfo { + DataSource sourceData = DataSource(); + Gfx::SeFormat format = Gfx::SE_FORMAT_R32G32B32A32_SFLOAT; + uint32 width = 1; + uint32 height = 1; + uint32 depth = 1; + uint32 mipLevels = 1; + uint32 layers = 1; + uint32 elements = 1; + uint32 samples = 1; + Gfx::SeImageUsageFlags usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT; + Gfx::SeMemoryPropertyFlags memoryProps = Gfx::SE_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + std::string name; +}; +struct SamplerCreateInfo { + Gfx::SeSamplerCreateFlags flags; + Gfx::SeFilter magFilter = Gfx::SE_FILTER_LINEAR; + Gfx::SeFilter minFilter = Gfx::SE_FILTER_LINEAR; + Gfx::SeSamplerMipmapMode mipmapMode = Gfx::SE_SAMPLER_MIPMAP_MODE_LINEAR; + Gfx::SeSamplerAddressMode addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT; + Gfx::SeSamplerAddressMode addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT; + Gfx::SeSamplerAddressMode addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT; + float mipLodBias = 0.0f; + uint32 anisotropyEnable = 0; + float maxAnisotropy = 0.0f; + uint32 compareEnable = 0; + Gfx::SeCompareOp compareOp = Gfx::SE_COMPARE_OP_NEVER; + float minLod = 0.0f; + float maxLod = 0.0f; + Gfx::SeBorderColor borderColor = Gfx::SE_BORDER_COLOR_FLOAT_OPAQUE_BLACK; + uint32 unnormalizedCoordinates = 0; + std::string name; +}; +struct VertexBufferCreateInfo { + DataSource sourceData = DataSource(); + // bytes per vertex + uint32 vertexSize = 0; + uint32 numVertices = 0; + std::string name = "Unnamed"; +}; +struct IndexBufferCreateInfo { + DataSource sourceData = DataSource(); + Gfx::SeIndexType indexType = Gfx::SeIndexType::SE_INDEX_TYPE_UINT16; + std::string name = "Unnamed"; +}; +struct UniformBufferCreateInfo { + DataSource sourceData = DataSource(); + uint8 dynamic = 0; + std::string name = "Unnamed"; +}; +struct ShaderBufferCreateInfo { + DataSource sourceData = DataSource(); + uint64 numElements = 1; + uint8 dynamic = 0; + uint8 vertexBuffer = 0; + std::string name = "Unnamed"; +}; +DECLARE_NAME_REF(Gfx, PipelineLayout) +struct ShaderCreateInfo { + std::string name; // Debug info + std::string mainModule; + Array additionalModules; + std::string entryPoint; + Array> typeParameter; + Map defines; + Gfx::PPipelineLayout rootSignature; +}; +struct VertexInputBinding { + uint32 binding; + uint32 stride; + Gfx::SeVertexInputRate inputRate; +}; +struct VertexInputAttribute { + uint32 location; + uint32 binding; + Gfx::SeFormat format; + uint32 offset; +}; +struct VertexInputStateCreateInfo { + Array bindings; + Array attributes; +}; +DECLARE_REF(MaterialInstance) +DECLARE_REF(Mesh) +namespace Gfx { +struct SePushConstantRange { + SeShaderStageFlags stageFlags; + uint32 offset; + uint32 size; +}; +struct RasterizationState { + uint32 depthClampEnable = 0; + uint32 rasterizerDiscardEnable = 0; + SePolygonMode polygonMode = Gfx::SE_POLYGON_MODE_FILL; + SeCullModeFlags cullMode = Gfx::SE_CULL_MODE_BACK_BIT; + SeFrontFace frontFace = Gfx::SE_FRONT_FACE_COUNTER_CLOCKWISE; + uint32 depthBiasEnable = 0; + float depthBiasConstantFactor = 0; + float depthBiasClamp = 0; + float depthBiasSlopeFactor = 0; + float lineWidth = 1.0; +}; +struct MultisampleState { + SeSampleCountFlags samples = 1; + uint32 sampleShadingEnable = 0; + float minSampleShading = 1; + uint8 alphaCoverageEnable = 0; + uint8 alphaToOneEnable = 0; +}; +struct DepthStencilState { + uint32 depthTestEnable = 1; + uint32 depthWriteEnable = 1; + SeCompareOp depthCompareOp = Gfx::SE_COMPARE_OP_GREATER; + uint32 depthBoundsTestEnable = 0; + uint32 stencilTestEnable = 0; + SeStencilOp front = Gfx::SE_STENCIL_OP_ZERO; + SeStencilOp back = Gfx::SE_STENCIL_OP_ZERO; + float minDepthBounds = 0.0f; + float maxDepthBounds = 1.0f; +}; +struct ColorBlendState { + struct BlendAttachment { + uint32 blendEnable = 0; + SeBlendFactor srcColorBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA; + SeBlendFactor dstColorBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA; + SeBlendOp colorBlendOp = Gfx::SE_BLEND_OP_ADD; + SeBlendFactor srcAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA; + SeBlendFactor dstAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA; + SeBlendOp alphaBlendOp = Gfx::SE_BLEND_OP_ADD; + SeColorComponentFlags colorWriteMask = + Gfx::SE_COLOR_COMPONENT_R_BIT | Gfx::SE_COLOR_COMPONENT_G_BIT | Gfx::SE_COLOR_COMPONENT_B_BIT | Gfx::SE_COLOR_COMPONENT_A_BIT; + }; + uint32 logicOpEnable = 0; + SeLogicOp logicOp = Gfx::SE_LOGIC_OP_OR; + uint32 attachmentCount = 0; + StaticArray blendAttachments; + StaticArray blendConstants = { + 1.0f, + 1.0f, + 1.0f, + 1.0f, + }; +}; - struct MeshPipelineCreateInfo - { - PTaskShader taskShader = nullptr; - PMeshShader meshShader = nullptr; - PFragmentShader fragmentShader = nullptr; - PRenderPass renderPass = nullptr; - PPipelineLayout pipelineLayout = nullptr; - MultisampleState multisampleState; - RasterizationState rasterizationState; - DepthStencilState depthStencilState; - ColorBlendState colorBlend; - }; - struct ComputePipelineCreateInfo - { - Gfx::PComputeShader computeShader = nullptr; - Gfx::PPipelineLayout pipelineLayout = nullptr; - }; - DECLARE_REF(ShaderBuffer) - struct BottomLevelASCreateInfo - { - PShaderBuffer positionBuffer; - PShaderBuffer indexBuffer; - MeshData meshData; - PMaterialInstance material; - uint64 verticesOffset; - uint64 indicesOffset; - }; - struct TopLevelASCreateInfo - { +DECLARE_REF(VertexInput) +DECLARE_REF(VertexShader) +DECLARE_REF(TaskShader) +DECLARE_REF(MeshShader) +DECLARE_REF(FragmentShader) +DECLARE_REF(ComputeShader) +DECLARE_REF(RenderPass) +DECLARE_REF(PipelineLayout) +struct LegacyPipelineCreateInfo { + SePrimitiveTopology topology = Gfx::SE_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + PVertexInput vertexInput = nullptr; + PVertexShader vertexShader = nullptr; + PFragmentShader fragmentShader = nullptr; + PRenderPass renderPass = nullptr; + PPipelineLayout pipelineLayout = nullptr; + MultisampleState multisampleState; + RasterizationState rasterizationState; + DepthStencilState depthStencilState; + ColorBlendState colorBlend; +}; - }; - } // namespace Gfx +struct MeshPipelineCreateInfo { + PTaskShader taskShader = nullptr; + PMeshShader meshShader = nullptr; + PFragmentShader fragmentShader = nullptr; + PRenderPass renderPass = nullptr; + PPipelineLayout pipelineLayout = nullptr; + MultisampleState multisampleState; + RasterizationState rasterizationState; + DepthStencilState depthStencilState; + ColorBlendState colorBlend; +}; +struct ComputePipelineCreateInfo { + Gfx::PComputeShader computeShader = nullptr; + Gfx::PPipelineLayout pipelineLayout = nullptr; +}; +DECLARE_REF(ShaderBuffer) +struct BottomLevelASCreateInfo { + PMesh mesh; +}; +struct TopLevelASCreateInfo {}; +} // namespace Gfx } // namespace Seele diff --git a/src/Engine/Graphics/Mesh.cpp b/src/Engine/Graphics/Mesh.cpp index 63d6904..65fd70b 100644 --- a/src/Engine/Graphics/Mesh.cpp +++ b/src/Engine/Graphics/Mesh.cpp @@ -1,19 +1,15 @@ #include "Mesh.h" -#include "Graphics/Graphics.h" #include "Asset/AssetRegistry.h" +#include "Graphics/Graphics.h" + using namespace Seele; -Mesh::Mesh() -{ -} +Mesh::Mesh() {} -Mesh::~Mesh() -{ -} +Mesh::~Mesh() {} -void Mesh::save(ArchiveBuffer& buffer) const -{ +void Mesh::save(ArchiveBuffer& buffer) const { Serialization::save(buffer, transform); Serialization::save(buffer, vertexData->getTypeName()); Serialization::save(buffer, vertexCount); @@ -24,8 +20,7 @@ void Mesh::save(ArchiveBuffer& buffer) const vertexData->serializeMesh(id, vertexCount, buffer); } -void Mesh::load(ArchiveBuffer& buffer) -{ +void Mesh::load(ArchiveBuffer& buffer) { std::string typeName; Serialization::load(buffer, transform); Serialization::load(buffer, typeName); diff --git a/src/Engine/Graphics/Mesh.h b/src/Engine/Graphics/Mesh.h index 6354b11..6e47b7c 100644 --- a/src/Engine/Graphics/Mesh.h +++ b/src/Engine/Graphics/Mesh.h @@ -1,13 +1,12 @@ #pragma once #include "Asset/MaterialInstanceAsset.h" -#include "VertexData.h" #include "Graphics/Buffer.h" +#include "VertexData.h" -namespace Seele -{ -class Mesh -{ -public: + +namespace Seele { +class Mesh { + public: Mesh(); ~Mesh(); @@ -21,21 +20,15 @@ public: Array meshlets; void save(ArchiveBuffer& buffer) const; void load(ArchiveBuffer& buffer); -private: + + private: }; DEFINE_REF(Mesh) -namespace Serialization -{ - template<> - void save(ArchiveBuffer& buffer, const OMesh& ptr) - { - ptr->save(buffer); - } - template<> - void load(ArchiveBuffer& buffer, OMesh& ptr) - { - ptr = new Mesh(); - ptr->load(buffer); - } +namespace Serialization { +template <> void save(ArchiveBuffer& buffer, const OMesh& ptr) { ptr->save(buffer); } +template <> void load(ArchiveBuffer& buffer, OMesh& ptr) { + ptr = new Mesh(); + ptr->load(buffer); +} } // namespace Serialization } // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/MeshData.h b/src/Engine/Graphics/MeshData.h index 7181e1d..ea73a67 100644 --- a/src/Engine/Graphics/MeshData.h +++ b/src/Engine/Graphics/MeshData.h @@ -1,18 +1,15 @@ #pragma once #include "Math/AABB.h" -namespace Seele -{ -struct MeshData -{ +namespace Seele { +struct MeshData { AABB bounding; uint32 numMeshlets = 0; uint32 meshletOffset = 0; uint32 firstIndex = 0; uint32 numIndices = 0; }; -struct InstanceData -{ +struct InstanceData { Matrix4 transformMatrix; Matrix4 inverseTransformMatrix; }; -} \ No newline at end of file +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/Meshlet.cpp b/src/Engine/Graphics/Meshlet.cpp index 7b7bf6a..dc5e43e 100644 --- a/src/Engine/Graphics/Meshlet.cpp +++ b/src/Engine/Graphics/Meshlet.cpp @@ -1,29 +1,26 @@ #include "Meshlet.h" -#include "Containers/Map.h" #include "Containers/List.h" +#include "Containers/Map.h" #include "Containers/Set.h" #include + using namespace Seele; -struct AdjacencyInfo -{ +struct AdjacencyInfo { Array trianglesPerVertex; Array indexBufferOffset; Array triangleData; }; -void buildAdjacency(const uint32 numVerts, const Array& indices, AdjacencyInfo& info) -{ +void buildAdjacency(const uint32 numVerts, const Array& indices, AdjacencyInfo& info) { info.trianglesPerVertex.resize(numVerts, 0); - for (size_t i = 0; i < indices.size(); ++i) - { + for (size_t i = 0; i < indices.size(); ++i) { info.trianglesPerVertex[indices[i]]++; } uint32 triangleOffset = 0; info.indexBufferOffset.resize(numVerts, 0); - for (size_t j = 0; j < numVerts; ++j) - { + for (size_t j = 0; j < numVerts; ++j) { info.indexBufferOffset[j] = triangleOffset; triangleOffset += info.trianglesPerVertex[j]; } @@ -31,8 +28,7 @@ void buildAdjacency(const uint32 numVerts, const Array& indices, Adjacen uint32 numTriangles = indices.size() / 3; info.triangleData.resize(triangleOffset); Array offsets = info.indexBufferOffset; - for (uint32 k = 0; k < numTriangles; ++k) - { + for (uint32 k = 0; k < numTriangles; ++k) { int a = indices[k * 3]; int b = indices[k * 3 + 1]; int c = indices[k * 3 + 2]; @@ -43,21 +39,16 @@ void buildAdjacency(const uint32 numVerts, const Array& indices, Adjacen } } -int32 skipDeadEnd(const Array& liveTriCount, List& deadEndStack, uint32& cursor) -{ - while (!deadEndStack.empty()) - { +int32 skipDeadEnd(const Array& liveTriCount, List& deadEndStack, uint32& cursor) { + while (!deadEndStack.empty()) { uint32 vertIdx = deadEndStack.front(); deadEndStack.popFront(); - if (liveTriCount[vertIdx] > 0) - { + if (liveTriCount[vertIdx] > 0) { return vertIdx; } } - while (cursor < liveTriCount.size()) - { - if (liveTriCount[cursor] > 0) - { + while (cursor < liveTriCount.size()) { + if (liveTriCount[cursor] > 0) { return cursor; } ++cursor; @@ -65,35 +56,29 @@ int32 skipDeadEnd(const Array& liveTriCount, List& deadEndStack, return -1; } -int32 getNextVertex(const uint32 cacheSize, const Array& oneRing, const Array& cacheTimeStamps, const uint32 timeStamp, const Array& liveTriCount, List& deadEndStack, uint32& cursor) -{ +int32 getNextVertex(const uint32 cacheSize, const Array& oneRing, const Array& cacheTimeStamps, const uint32 timeStamp, + const Array& liveTriCount, List& deadEndStack, uint32& cursor) { uint32 bestCandidate = std::numeric_limits::max(); int highestPriority = -1; - for (const uint32& vertIdx : oneRing) - { - if (liveTriCount[vertIdx] > 0) - { + for (const uint32& vertIdx : oneRing) { + if (liveTriCount[vertIdx] > 0) { int priority = 0; - if (timeStamp - cacheTimeStamps[vertIdx] + 2 * liveTriCount[vertIdx] <= cacheSize) - { + if (timeStamp - cacheTimeStamps[vertIdx] + 2 * liveTriCount[vertIdx] <= cacheSize) { priority = timeStamp - cacheTimeStamps[vertIdx]; } - if (priority > highestPriority) - { + if (priority > highestPriority) { highestPriority = priority; bestCandidate = vertIdx; } } } - if(bestCandidate == std::numeric_limits::max()) - { + if (bestCandidate == std::numeric_limits::max()) { bestCandidate = skipDeadEnd(liveTriCount, deadEndStack, cursor); } return bestCandidate; } -void tipsifyIndexBuffer(const Array& indices, const uint32 numVerts, const uint32 cacheSize, Array& outIndices) -{ +void tipsifyIndexBuffer(const Array& indices, const uint32 numVerts, const uint32 cacheSize, Array& outIndices) { AdjacencyInfo adjacencyStruct; buildAdjacency(numVerts, indices, adjacencyStruct); @@ -108,14 +93,12 @@ void tipsifyIndexBuffer(const Array& indices, const uint32 numVerts, con int32 curVert = 0; uint32 timeStamp = cacheSize + 1; uint32 cursor = 1; - while (curVert != -1) - { + while (curVert != -1) { Array oneRing; const uint32* startTriPointer = &adjacencyStruct.triangleData[0] + adjacencyStruct.indexBufferOffset[curVert]; const uint32* endTriPointer = startTriPointer + adjacencyStruct.trianglesPerVertex[curVert]; - for (const uint32* it = startTriPointer; it != endTriPointer; ++it) - { + for (const uint32* it = startTriPointer; it != endTriPointer; ++it) { uint32 triangle = *it; if (emittedTriangles[triangle]) @@ -156,22 +139,17 @@ void tipsifyIndexBuffer(const Array& indices, const uint32 numVerts, con } } -struct Triangle -{ +struct Triangle { StaticArray indices; }; -int findIndex(Meshlet ¤t, uint32 index) -{ - for (uint32 i = 0; i < current.numVertices; ++i) - { - if (current.uniqueVertices[i] == index) - { +int findIndex(Meshlet& current, uint32 index) { + for (uint32 i = 0; i < current.numVertices; ++i) { + if (current.uniqueVertices[i] == index) { return i; } } - if (current.numVertices == Gfx::numVerticesPerMeshlet) - { + if (current.numVertices == Gfx::numVerticesPerMeshlet) { return -1; } current.uniqueVertices[current.numVertices] = index; @@ -179,8 +157,7 @@ int findIndex(Meshlet ¤t, uint32 index) return current.numVertices++; } -void completeMeshlet(Array &meshlets, Meshlet ¤t) -{ +void completeMeshlet(Array& meshlets, Meshlet& current) { meshlets.add(current); current = { .boundingBox = AABB(), @@ -189,14 +166,12 @@ void completeMeshlet(Array &meshlets, Meshlet ¤t) }; } -bool addTriangle(const Array& positions, Meshlet ¤t, Triangle& tri) -{ +bool addTriangle(const Array& positions, Meshlet& current, Triangle& tri) { int f1 = findIndex(current, tri.indices[0]); int f2 = findIndex(current, tri.indices[1]); int f3 = findIndex(current, tri.indices[2]); - if (f1 == -1 || f2 == -1 || f3 == -1 || current.numPrimitives == Gfx::numPrimitivesPerMeshlet) - { + if (f1 == -1 || f2 == -1 || f3 == -1 || current.numPrimitives == Gfx::numPrimitivesPerMeshlet) { return false; } current.boundingBox.adjust(positions[tri.indices[0]]); @@ -209,36 +184,32 @@ bool addTriangle(const Array& positions, Meshlet ¤t, Triangle& tri return true; } -void Meshlet::build(const Array &positions, const Array &indices, Array &meshlets) -{ +void Meshlet::build(const Array& positions, const Array& indices, Array& meshlets) { Meshlet current = { .numVertices = 0, .numPrimitives = 0, }; - //Array optimizedIndices = indices; - //tipsifyIndexBuffer(indices, positions.size(), 25, optimizedIndices); + // Array optimizedIndices = indices; + // tipsifyIndexBuffer(indices, positions.size(), 25, optimizedIndices); Array triangles(indices.size() / 3); - for (size_t i = 0; i < triangles.size(); ++i) - { + for (size_t i = 0; i < triangles.size(); ++i) { triangles[i] = Triangle{ - .indices = { - indices[i * 3 + 0], - indices[i * 3 + 1], - indices[i * 3 + 2], - }, + .indices = + { + indices[i * 3 + 0], + indices[i * 3 + 1], + indices[i * 3 + 2], + }, }; } - while(!triangles.empty()) - { - if (!addTriangle(positions, current, triangles.back())) - { + while (!triangles.empty()) { + if (!addTriangle(positions, current, triangles.back())) { completeMeshlet(meshlets, current); addTriangle(positions, current, triangles.back()); } triangles.pop(); } - if (current.numVertices > 0) - { + if (current.numVertices > 0) { completeMeshlet(meshlets, current); } } diff --git a/src/Engine/Graphics/Meshlet.h b/src/Engine/Graphics/Meshlet.h index 88afea2..304bd75 100644 --- a/src/Engine/Graphics/Meshlet.h +++ b/src/Engine/Graphics/Meshlet.h @@ -1,13 +1,12 @@ #pragma once -#include "Math/AABB.h" #include "Graphics/Enums.h" +#include "Math/AABB.h" -namespace Seele -{ -struct Meshlet -{ + +namespace Seele { +struct Meshlet { AABB boundingBox; - uint32 uniqueVertices[Gfx::numVerticesPerMeshlet]; // unique vertiex indices in the vertex data + uint32 uniqueVertices[Gfx::numVerticesPerMeshlet]; // unique vertiex indices in the vertex data uint8 primitiveLayout[Gfx::numPrimitivesPerMeshlet * 3]; // indices into the uniqueVertices array, only uint8 needed uint32 numVertices; uint32 numPrimitives; diff --git a/src/Engine/Graphics/Metal/Buffer.h b/src/Engine/Graphics/Metal/Buffer.h index 4887fc2..6744b05 100644 --- a/src/Engine/Graphics/Metal/Buffer.h +++ b/src/Engine/Graphics/Metal/Buffer.h @@ -9,93 +9,93 @@ namespace Seele { namespace Metal { DECLARE_REF(Graphics) -class BufferAllocation : public CommandBoundResource -{ -public: - BufferAllocation(PGraphics graphics); - virtual ~BufferAllocation(); - MTL::Buffer* buffer = nullptr; - uint64 size = 0; +class BufferAllocation : public CommandBoundResource { + public: + BufferAllocation(PGraphics graphics); + virtual ~BufferAllocation(); + MTL::Buffer* buffer = nullptr; + uint64 size = 0; }; DECLARE_REF(BufferAllocation) class Buffer { -public: - Buffer(PGraphics graphics, uint64 size, void *data, bool dynamic, const std::string& name); - virtual ~Buffer(); - MTL::Buffer *getHandle() const { return buffers[currentBuffer]->buffer; } - PBufferAllocation getAlloc() const { return buffers[currentBuffer]; } - uint64 getSize() const { return buffers[currentBuffer]->size; } - void *map(bool writeOnly = true); - void *mapRegion(uint64 regionOffset, uint64 regionSize, bool writeOnly); - void unmap(); + public: + Buffer(PGraphics graphics, uint64 size, void* data, bool dynamic, const std::string& name); + virtual ~Buffer(); + MTL::Buffer* getHandle() const { return buffers[currentBuffer]->buffer; } + PBufferAllocation getAlloc() const { return buffers[currentBuffer]; } + uint64 getSize() const { return buffers[currentBuffer]->size; } + void* map(bool writeOnly = true); + void* mapRegion(uint64 regionOffset, uint64 regionSize, bool writeOnly); + void unmap(); -protected: - PGraphics graphics; - uint32 currentBuffer = 0; - Array buffers; - bool dynamic; - std::string name; - void rotateBuffer(uint64 size); - void createBuffer(uint64 size, void* data); + protected: + PGraphics graphics; + uint32 currentBuffer = 0; + Array buffers; + bool dynamic; + std::string name; + void rotateBuffer(uint64 size); + void createBuffer(uint64 size, void* data); }; DEFINE_REF(Buffer) class VertexBuffer : public Gfx::VertexBuffer, public Buffer { -public: - VertexBuffer(PGraphics graphics, const VertexBufferCreateInfo &createInfo); - virtual ~VertexBuffer(); - virtual void updateRegion(DataSource update) override; - virtual void download(Array &buffer) override; + public: + VertexBuffer(PGraphics graphics, const VertexBufferCreateInfo& createInfo); + virtual ~VertexBuffer(); + virtual void updateRegion(DataSource update) override; + virtual void download(Array& buffer) override; -protected: - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; - virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; + protected: + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; + virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) override; }; DEFINE_REF(VertexBuffer) class IndexBuffer : public Gfx::IndexBuffer, public Buffer { -public: - IndexBuffer(PGraphics graphics, const IndexBufferCreateInfo &createInfo); - virtual ~IndexBuffer(); + public: + IndexBuffer(PGraphics graphics, const IndexBufferCreateInfo& createInfo); + virtual ~IndexBuffer(); - virtual void download(Array &buffer) override; -protected: - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; - virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; + virtual void download(Array& buffer) override; + + protected: + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; + virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) override; }; DEFINE_REF(IndexBuffer) DEFINE_REF(IndexBuffer) class UniformBuffer : public Gfx::UniformBuffer, public Buffer { -public: - UniformBuffer(PGraphics graphics, const UniformBufferCreateInfo &createInfo); - virtual ~UniformBuffer(); + public: + UniformBuffer(PGraphics graphics, const UniformBufferCreateInfo& createInfo); + virtual ~UniformBuffer(); - virtual bool updateContents(const DataSource &sourceData) override; + virtual bool updateContents(const DataSource& sourceData) override; -protected: - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; - virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; + protected: + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; + virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) override; }; DEFINE_REF(UniformBuffer) class ShaderBuffer : public Gfx::ShaderBuffer, public Buffer { -public: - ShaderBuffer(PGraphics graphics, const ShaderBufferCreateInfo &createInfo); - virtual ~ShaderBuffer(); - virtual void rotateBuffer(uint64 size) override; - virtual void updateContents(const ShaderBufferCreateInfo &sourceData) override; - virtual void *mapRegion(uint64 offset, uint64 size, bool writeOnly) override; - virtual void unmap() override; + public: + ShaderBuffer(PGraphics graphics, const ShaderBufferCreateInfo& createInfo); + virtual ~ShaderBuffer(); + virtual void rotateBuffer(uint64 size) override; + virtual void updateContents(const ShaderBufferCreateInfo& sourceData) override; + virtual void* mapRegion(uint64 offset, uint64 size, bool writeOnly) override; + virtual void unmap() override; -protected: - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; - virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; + protected: + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; + virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) override; }; DEFINE_REF(ShaderBuffer) } // namespace Metal diff --git a/src/Engine/Graphics/Metal/Buffer.mm b/src/Engine/Graphics/Metal/Buffer.mm index ecd6d7b..e0c7c8c 100644 --- a/src/Engine/Graphics/Metal/Buffer.mm +++ b/src/Engine/Graphics/Metal/Buffer.mm @@ -11,49 +11,44 @@ using namespace Seele; using namespace Seele::Metal; BufferAllocation::BufferAllocation(PGraphics graphics) - : CommandBoundResource(graphics) -{} + : CommandBoundResource(graphics) {} -BufferAllocation::~BufferAllocation() -{ - if(buffer != nullptr) - { +BufferAllocation::~BufferAllocation() { + if (buffer != nullptr) { buffer->release(); } } -Buffer::Buffer(PGraphics graphics, uint64 size, void* data, bool dynamic, const std::string& name) - : graphics(graphics) - , dynamic(dynamic) - , name(name) { +Buffer::Buffer(PGraphics graphics, uint64 size, void *data, bool dynamic, + const std::string &name) + : graphics(graphics), dynamic(dynamic), name(name) { createBuffer(size, data); } Buffer::~Buffer() { for (size_t i = 0; i < buffers.size(); ++i) { - //TODO + // TODO } } -void* Buffer::map(bool) { return getHandle()->contents(); } +void *Buffer::map(bool) { return getHandle()->contents(); } -void* Buffer::mapRegion(uint64 regionOffset, uint64, bool) { return (char*)getHandle()->contents() + regionOffset; } +void *Buffer::mapRegion(uint64 regionOffset, uint64, bool) { + return (char *)getHandle()->contents() + regionOffset; +} void Buffer::unmap() {} -void Buffer::rotateBuffer(uint64 size) -{ +void Buffer::rotateBuffer(uint64 size) { size = std::max(getSize(), size); - for(size_t i = 0; i < buffers.size(); ++i) - { - if(buffers[i]->isCurrentlyBound()) - { + for (size_t i = 0; i < buffers.size(); ++i) { + if (buffers[i]->isCurrentlyBound()) { continue; } - if(buffers[i]->size < size) - { + if (buffers[i]->size < size) { buffers[i]->buffer->release(); - buffers[i]->buffer = graphics->getDevice()->newBuffer(size, MTL::StorageModeShared); + buffers[i]->buffer = + graphics->getDevice()->newBuffer(size, MTL::StorageModeShared); buffers[i]->size = size; } currentBuffer = i; @@ -63,79 +58,106 @@ void Buffer::rotateBuffer(uint64 size) currentBuffer = buffers.size() - 1; } -void Buffer::createBuffer(uint64 size, void* data) -{ +void Buffer::createBuffer(uint64 size, void *data) { buffers.add(new BufferAllocation(graphics)); if (data != nullptr) { - buffers.back()->buffer = graphics->getDevice()->newBuffer(data, size, MTL::StorageModeShared); + buffers.back()->buffer = + graphics->getDevice()->newBuffer(data, size, MTL::StorageModeShared); } else { - buffers.back()->buffer = graphics->getDevice()->newBuffer(size, MTL::StorageModeShared); + buffers.back()->buffer = + graphics->getDevice()->newBuffer(size, MTL::StorageModeShared); } - buffers.back()->buffer->setLabel(NS::String::string(name.c_str(), NS::ASCIIStringEncoding)); + buffers.back()->buffer->setLabel( + NS::String::string(name.c_str(), NS::ASCIIStringEncoding)); } -VertexBuffer::VertexBuffer(PGraphics graphics, const VertexBufferCreateInfo& createInfo) - : Gfx::VertexBuffer(graphics->getFamilyMapping(), createInfo.numVertices, createInfo.vertexSize, - createInfo.sourceData.owner), - Seele::Metal::Buffer(graphics, createInfo.sourceData.size, createInfo.sourceData.data, false, createInfo.name) {} +VertexBuffer::VertexBuffer(PGraphics graphics, + const VertexBufferCreateInfo &createInfo) + : Gfx::VertexBuffer(graphics->getFamilyMapping(), createInfo.numVertices, + createInfo.vertexSize, createInfo.sourceData.owner), + Seele::Metal::Buffer(graphics, createInfo.sourceData.size, + createInfo.sourceData.data, false, createInfo.name) { +} VertexBuffer::~VertexBuffer() {} void VertexBuffer::updateRegion(DataSource update) { - void* data = getHandle()->contents(); - std::memcpy((char*)data + update.offset, update.data, update.size); + void *data = getHandle()->contents(); + std::memcpy((char *)data + update.offset, update.data, update.size); } -void VertexBuffer::download(Array& buffer) { - void* data = getHandle()->contents(); +void VertexBuffer::download(Array &buffer) { + void *data = getHandle()->contents(); buffer.resize(getSize()); std::memcpy(buffer.data(), data, getSize()); } -void VertexBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { currentOwner = newOwner; } - -void VertexBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) { - +void VertexBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { + currentOwner = newOwner; } -IndexBuffer::IndexBuffer(PGraphics graphics, const IndexBufferCreateInfo& createInfo) - : Gfx::IndexBuffer(graphics->getFamilyMapping(), createInfo.sourceData.size, createInfo.indexType, - createInfo.sourceData.owner), - Seele::Metal::Buffer(graphics, createInfo.sourceData.size, createInfo.sourceData.data, false, createInfo.name) {} +void VertexBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, + Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) {} + +IndexBuffer::IndexBuffer(PGraphics graphics, + const IndexBufferCreateInfo &createInfo) + : Gfx::IndexBuffer(graphics->getFamilyMapping(), createInfo.sourceData.size, + createInfo.indexType, createInfo.sourceData.owner), + Seele::Metal::Buffer(graphics, createInfo.sourceData.size, + createInfo.sourceData.data, false, createInfo.name) { +} IndexBuffer::~IndexBuffer() {} -void IndexBuffer::download(Array& buffer) { - void* data = getHandle()->contents(); +void IndexBuffer::download(Array &buffer) { + void *data = getHandle()->contents(); buffer.resize(getSize()); std::memcpy(buffer.data(), data, getSize()); } -void IndexBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { currentOwner = newOwner; } +void IndexBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { + currentOwner = newOwner; +} -void IndexBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) {} +void IndexBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, + Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) {} -UniformBuffer::UniformBuffer(PGraphics graphics, const UniformBufferCreateInfo& createInfo) +UniformBuffer::UniformBuffer(PGraphics graphics, + const UniformBufferCreateInfo &createInfo) : Gfx::UniformBuffer(graphics->getFamilyMapping(), createInfo.sourceData), - Seele::Metal::Buffer(graphics, createInfo.sourceData.size, createInfo.sourceData.data, createInfo.dynamic, createInfo.name) {} + Seele::Metal::Buffer(graphics, createInfo.sourceData.size, + createInfo.sourceData.data, createInfo.dynamic, + createInfo.name) {} UniformBuffer::~UniformBuffer() {} -bool UniformBuffer::updateContents(const DataSource& sourceData) { - void* data = getHandle()->contents(); - std::memcpy((char*)data + sourceData.offset, sourceData.data, sourceData.size); +bool UniformBuffer::updateContents(const DataSource &sourceData) { + void *data = getHandle()->contents(); + std::memcpy((char *)data + sourceData.offset, sourceData.data, + sourceData.size); return true; } -void UniformBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { currentOwner = newOwner; } +void UniformBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { + currentOwner = newOwner; +} -void UniformBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) {} +void UniformBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, + Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) { +} -ShaderBuffer::ShaderBuffer(PGraphics graphics, const ShaderBufferCreateInfo& createInfo) - : Gfx::ShaderBuffer(graphics->getFamilyMapping(), createInfo.numElements, createInfo.sourceData), - Seele::Metal::Buffer(graphics, createInfo.sourceData.size, createInfo.sourceData.data, createInfo.dynamic, createInfo.name) {} +ShaderBuffer::ShaderBuffer(PGraphics graphics, + const ShaderBufferCreateInfo &createInfo) + : Gfx::ShaderBuffer(graphics->getFamilyMapping(), createInfo.numElements, + createInfo.sourceData), + Seele::Metal::Buffer(graphics, createInfo.sourceData.size, + createInfo.sourceData.data, createInfo.dynamic, + createInfo.name) {} ShaderBuffer::~ShaderBuffer() {} @@ -143,29 +165,28 @@ void ShaderBuffer::rotateBuffer(uint64 size) { Metal::Buffer::rotateBuffer(size); } -void ShaderBuffer::updateContents(const ShaderBufferCreateInfo& createInfo) { +void ShaderBuffer::updateContents(const ShaderBufferCreateInfo &createInfo) { Gfx::ShaderBuffer::updateContents(createInfo); - if(createInfo.sourceData.data == nullptr) - { + if (createInfo.sourceData.data == nullptr) { return; } - void* data = map(); - std::memcpy((char*)data + createInfo.sourceData.offset, createInfo.sourceData.data, createInfo.sourceData.size); + void *data = map(); + std::memcpy((char *)data + createInfo.sourceData.offset, + createInfo.sourceData.data, createInfo.sourceData.size); unmap(); } -void* ShaderBuffer::mapRegion(uint64 offset, uint64 size, bool writeOnly) -{ +void *ShaderBuffer::mapRegion(uint64 offset, uint64 size, bool writeOnly) { return Metal::Buffer::mapRegion(offset, size, writeOnly); } -void ShaderBuffer::unmap() -{ - Metal::Buffer::unmap(); +void ShaderBuffer::unmap() { Metal::Buffer::unmap(); } + +void ShaderBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { + currentOwner = newOwner; } -void ShaderBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { currentOwner = newOwner; } - - -void ShaderBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) {} +void ShaderBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, + Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) {} diff --git a/src/Engine/Graphics/Metal/Command.h b/src/Engine/Graphics/Metal/Command.h index fe1d00b..9508704 100644 --- a/src/Engine/Graphics/Metal/Command.h +++ b/src/Engine/Graphics/Metal/Command.h @@ -19,113 +19,109 @@ DECLARE_REF(IndexBuffer) DECLARE_REF(GraphicsPipeline) DECLARE_REF(ComputePipeline) class Command { -public: - Command(PGraphics graphics, MTL::CommandBuffer* cmdBuffer); - ~Command(); - void beginRenderPass(PRenderPass renderPass); - void endRenderPass(); - void present(MTL::Drawable* drawable); - void end(PEvent signal); - void waitDeviceIdle(); - void signalEvent(PEvent event); - void waitForEvent(PEvent event); - MTL::RenderCommandEncoder* createRenderEncoder() { return parallelEncoder->renderCommandEncoder(); } - MTL::BlitCommandEncoder* getBlitEncoder() { - assert(!parallelEncoder); - if(blitEncoder == nullptr) - { - blitEncoder = cmdBuffer->blitCommandEncoder(); + public: + Command(PGraphics graphics, MTL::CommandBuffer* cmdBuffer); + ~Command(); + void beginRenderPass(PRenderPass renderPass); + void endRenderPass(); + void present(MTL::Drawable* drawable); + void end(PEvent signal); + void waitDeviceIdle(); + void signalEvent(PEvent event); + void waitForEvent(PEvent event); + MTL::RenderCommandEncoder* createRenderEncoder() { return parallelEncoder->renderCommandEncoder(); } + MTL::BlitCommandEncoder* getBlitEncoder() { + assert(!parallelEncoder); + if (blitEncoder == nullptr) { + blitEncoder = cmdBuffer->blitCommandEncoder(); + } + return blitEncoder; } - return blitEncoder; - } - PEvent getCompletedEvent() const { return completed; } - constexpr MTL::CommandBuffer* getHandle() const { return cmdBuffer; } + PEvent getCompletedEvent() const { return completed; } + constexpr MTL::CommandBuffer* getHandle() const { return cmdBuffer; } -private: - PGraphics graphics; - OEvent completed; - MTL::CommandBuffer* cmdBuffer; - MTL::ParallelRenderCommandEncoder* parallelEncoder = nullptr; - MTL::BlitCommandEncoder* blitEncoder = nullptr; + private: + PGraphics graphics; + OEvent completed; + MTL::CommandBuffer* cmdBuffer; + MTL::ParallelRenderCommandEncoder* parallelEncoder = nullptr; + MTL::BlitCommandEncoder* blitEncoder = nullptr; }; DEFINE_REF(Command) class RenderCommand : public Gfx::RenderCommand { -public: - RenderCommand(MTL::RenderCommandEncoder* encode, const std::string& name); - virtual ~RenderCommand(); - void end(); - virtual void setViewport(Gfx::PViewport viewport) override; - virtual void bindPipeline(Gfx::PGraphicsPipeline pipeline) override; - virtual void bindDescriptor(Gfx::PDescriptorSet descriptorSet, Array dynamicOffsets) override; - virtual void bindDescriptor(const Array& descriptorSets, Array dynamicOffsets) override; - virtual void bindVertexBuffer(const Array& buffers) override; - virtual void bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) override; - virtual void pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, - const void* data) override; - virtual void draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) override; - virtual void drawIndexed(uint32 indexCount, uint32 instanceCount, int32 firstIndex, uint32 vertexOffset, - uint32 firstInstance) override; - virtual void drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) override; - virtual void drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) override; + public: + RenderCommand(MTL::RenderCommandEncoder* encode, const std::string& name); + virtual ~RenderCommand(); + void end(); + virtual void setViewport(Gfx::PViewport viewport) override; + virtual void bindPipeline(Gfx::PGraphicsPipeline pipeline) override; + virtual void bindDescriptor(Gfx::PDescriptorSet descriptorSet, Array dynamicOffsets) override; + virtual void bindDescriptor(const Array& descriptorSets, Array dynamicOffsets) override; + virtual void bindVertexBuffer(const Array& buffers) override; + virtual void bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) override; + virtual void pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, const void* data) override; + virtual void draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) override; + virtual void drawIndexed(uint32 indexCount, uint32 instanceCount, int32 firstIndex, uint32 vertexOffset, uint32 firstInstance) override; + virtual void drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) override; + virtual void drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) override; -private: + private: PGraphicsPipeline boundPipeline; PIndexBuffer boundIndexBuffer; MTL::Buffer* argumentBuffer; - MTL::RenderCommandEncoder* encoder; - std::string name; + MTL::RenderCommandEncoder* encoder; + std::string name; }; DEFINE_REF(RenderCommand) class ComputeCommand : public Gfx::ComputeCommand { -public: - ComputeCommand(MTL::CommandBuffer* cmdBuffer, const std::string& name); - virtual ~ComputeCommand(); - void end(); - virtual void bindPipeline(Gfx::PComputePipeline pipeline) override; - virtual void bindDescriptor(Gfx::PDescriptorSet set, Array dynamicOffsets) override; - virtual void bindDescriptor(const Array& sets, Array dynamicOffsets) override; - virtual void pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, - const void* data) override; - virtual void dispatch(uint32 threadX, uint32 threadY, uint32 threadZ) override; + public: + ComputeCommand(MTL::CommandBuffer* cmdBuffer, const std::string& name); + virtual ~ComputeCommand(); + void end(); + virtual void bindPipeline(Gfx::PComputePipeline pipeline) override; + virtual void bindDescriptor(Gfx::PDescriptorSet set, Array dynamicOffsets) override; + virtual void bindDescriptor(const Array& sets, Array dynamicOffsets) override; + virtual void pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, const void* data) override; + virtual void dispatch(uint32 threadX, uint32 threadY, uint32 threadZ) override; -private: - PComputePipeline boundPipeline; - MTL::CommandBuffer* commandBuffer; - MTL::ComputeCommandEncoder* encoder; + private: + PComputePipeline boundPipeline; + MTL::CommandBuffer* commandBuffer; + MTL::ComputeCommandEncoder* encoder; MTL::Buffer* argumentBuffer; - std::string name; + std::string name; }; DEFINE_REF(ComputeCommand) class CommandQueue { -public: - CommandQueue(PGraphics graphics); - ~CommandQueue(); - constexpr MTL::CommandQueue* getHandle() { return queue; } - PCommand getCommands() { return activeCommand; } - ORenderCommand getRenderCommand(const std::string& name); - OComputeCommand getComputeCommand(const std::string& name); - void executeCommands(Array commands); - void executeCommands(Array commands); - void submitCommands(PEvent signal = nullptr); + public: + CommandQueue(PGraphics graphics); + ~CommandQueue(); + constexpr MTL::CommandQueue* getHandle() { return queue; } + PCommand getCommands() { return activeCommand; } + ORenderCommand getRenderCommand(const std::string& name); + OComputeCommand getComputeCommand(const std::string& name); + void executeCommands(Array commands); + void executeCommands(Array commands); + void submitCommands(PEvent signal = nullptr); -private: - PGraphics graphics; - MTL::CommandQueue* queue; - OCommand activeCommand; - Array pendingCommands; + private: + PGraphics graphics; + MTL::CommandQueue* queue; + OCommand activeCommand; + Array pendingCommands; }; class IOCommandQueue { -public: - IOCommandQueue(PGraphics graphics); - ~IOCommandQueue(); - constexpr MTL::IOCommandQueue* getHandle() { return queue; } - PCommand getCommands() { return activeCommand; } // TODO - void submitCommands(PEvent signal = nullptr); + public: + IOCommandQueue(PGraphics graphics); + ~IOCommandQueue(); + constexpr MTL::IOCommandQueue* getHandle() { return queue; } + PCommand getCommands() { return activeCommand; } // TODO + void submitCommands(PEvent signal = nullptr); -private: - PGraphics graphics; - MTL::IOCommandQueue* queue; - OCommand activeCommand; + private: + PGraphics graphics; + MTL::IOCommandQueue* queue; + OCommand activeCommand; }; DEFINE_REF(IOCommandQueue) } // namespace Metal diff --git a/src/Engine/Graphics/Metal/Command.mm b/src/Engine/Graphics/Metal/Command.mm index 7213709..81be2e1 100644 --- a/src/Engine/Graphics/Metal/Command.mm +++ b/src/Engine/Graphics/Metal/Command.mm @@ -16,8 +16,9 @@ using namespace Seele; using namespace Seele::Metal; -Command::Command(PGraphics graphics, MTL::CommandBuffer* cmdBuffer) - : graphics(graphics), completed(new Event(graphics)), cmdBuffer(cmdBuffer) {} +Command::Command(PGraphics graphics, MTL::CommandBuffer *cmdBuffer) + : graphics(graphics), completed(new Event(graphics)), cmdBuffer(cmdBuffer) { +} Command::~Command() {} @@ -27,7 +28,8 @@ void Command::beginRenderPass(PRenderPass renderPass) { blitEncoder = nullptr; } renderPass->updateRenderPass(); - parallelEncoder = cmdBuffer->parallelRenderCommandEncoder(renderPass->getDescriptor()); + parallelEncoder = + cmdBuffer->parallelRenderCommandEncoder(renderPass->getDescriptor()); } void Command::endRenderPass() { @@ -35,7 +37,9 @@ void Command::endRenderPass() { parallelEncoder = nullptr; } -void Command::present(MTL::Drawable* drawable) { cmdBuffer->presentDrawable(drawable); } +void Command::present(MTL::Drawable *drawable) { + cmdBuffer->presentDrawable(drawable); +} void Command::end(PEvent signal) { assert(!parallelEncoder); @@ -49,11 +53,16 @@ void Command::end(PEvent signal) { void Command::waitDeviceIdle() { cmdBuffer->waitUntilCompleted(); } -void Command::signalEvent(PEvent event) { cmdBuffer->encodeSignalEvent(event->getHandle(), 1); } +void Command::signalEvent(PEvent event) { + cmdBuffer->encodeSignalEvent(event->getHandle(), 1); +} -void Command::waitForEvent(PEvent event) { cmdBuffer->encodeWait(event->getHandle(), 1); } +void Command::waitForEvent(PEvent event) { + cmdBuffer->encodeWait(event->getHandle(), 1); +} -RenderCommand::RenderCommand(MTL::RenderCommandEncoder* encoder, const std::string& name) +RenderCommand::RenderCommand(MTL::RenderCommandEncoder *encoder, + const std::string &name) : encoder(encoder), name(name) {} RenderCommand::~RenderCommand() {} @@ -79,15 +88,19 @@ void RenderCommand::bindPipeline(Gfx::PGraphicsPipeline pipeline) { for (auto [_, layout] : boundPipeline->getPipelineLayout()->getLayouts()) { argBufferSize += 3 * sizeof(uint64) * layout->getBindings().size(); } - argumentBuffer = boundPipeline->graphics->getDevice()->newBuffer(argBufferSize, MTL::ResourceStorageModeShared); + argumentBuffer = boundPipeline->graphics->getDevice()->newBuffer( + argBufferSize, MTL::ResourceStorageModeShared); argumentBuffer->setLabel( - NS::String::string(boundPipeline->getPipelineLayout()->getName().c_str(), NS::ASCIIStringEncoding)); + NS::String::string(boundPipeline->getPipelineLayout()->getName().c_str(), + NS::ASCIIStringEncoding)); } -void RenderCommand::bindDescriptor(Gfx::PDescriptorSet descriptorSet, Array offsets) { +void RenderCommand::bindDescriptor(Gfx::PDescriptorSet descriptorSet, + Array offsets) { auto metalSet = descriptorSet.cast(); - uint32 parameterIndex = boundPipeline->getPipelineLayout()->findParameter(descriptorSet->getLayout()->getName()); - uint64* topLevelTable = (uint64*)argumentBuffer->contents(); + uint32 parameterIndex = boundPipeline->getPipelineLayout()->findParameter( + descriptorSet->getLayout()->getName()); + uint64 *topLevelTable = (uint64 *)argumentBuffer->contents(); topLevelTable[parameterIndex] = metalSet->getBuffer()->gpuAddress(); auto bindings = metalSet->getLayout()->getBindings(); encoder->useResource(metalSet->getBuffer(), MTL::ResourceUsageRead); @@ -117,15 +130,17 @@ void RenderCommand::bindDescriptor(Gfx::PDescriptorSet descriptorSet, Array& descriptorSets, Array offsets) { +void RenderCommand::bindDescriptor( + const Array &descriptorSets, Array offsets) { for (auto set : descriptorSets) { bindDescriptor(set, offsets); } } -void RenderCommand::bindVertexBuffer(const Array& buffers) { +void RenderCommand::bindVertexBuffer(const Array &buffers) { uint32 i = 0; for (auto buffer : buffers) { - encoder->setVertexBuffer(buffer.cast()->getHandle(), 0, METAL_VERTEXBUFFER_OFFSET + i++); + encoder->setVertexBuffer(buffer.cast()->getHandle(), 0, + METAL_VERTEXBUFFER_OFFSET + i++); } } @@ -133,24 +148,29 @@ void RenderCommand::bindIndexBuffer(Gfx::PIndexBuffer gfxIndexBuffer) { boundIndexBuffer = gfxIndexBuffer.cast(); } -void RenderCommand::pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, - const void* data) { +void RenderCommand::pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, + uint32 size, const void *data) { if (stage & Gfx::SE_SHADER_STAGE_VERTEX_BIT) { - encoder->setVertexBytes((char*)data + offset, size, 0); + encoder->setVertexBytes((char *)data + offset, size, 0); } if (stage & Gfx::SE_SHADER_STAGE_FRAGMENT_BIT) { - encoder->setFragmentBytes((char*)data + offset, size, 0); + encoder->setFragmentBytes((char *)data + offset, size, 0); } } -void RenderCommand::draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) { - encoder->drawPrimitives(boundPipeline->getPrimitive(), firstVertex, vertexCount, instanceCount, firstInstance); +void RenderCommand::draw(uint32 vertexCount, uint32 instanceCount, + int32 firstVertex, uint32 firstInstance) { + encoder->drawPrimitives(boundPipeline->getPrimitive(), firstVertex, + vertexCount, instanceCount, firstInstance); } -void RenderCommand::drawIndexed(uint32 indexCount, uint32 instanceCount, int32 firstIndex, uint32 vertexOffset, +void RenderCommand::drawIndexed(uint32 indexCount, uint32 instanceCount, + int32 firstIndex, uint32 vertexOffset, uint32 firstInstance) { - encoder->drawIndexedPrimitives(boundPipeline->getPrimitive(), indexCount, cast(boundIndexBuffer->getIndexType()), - boundIndexBuffer->getHandle(), firstIndex, instanceCount, vertexOffset, firstInstance); + encoder->drawIndexedPrimitives(boundPipeline->getPrimitive(), indexCount, + cast(boundIndexBuffer->getIndexType()), + boundIndexBuffer->getHandle(), firstIndex, + instanceCount, vertexOffset, firstInstance); } void RenderCommand::drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) { @@ -159,15 +179,19 @@ void RenderCommand::drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) { encoder->setFragmentBuffer(argumentBuffer, 0, 2); encoder->setMeshBuffer(argumentBuffer, 0, 2); encoder->setObjectBuffer(argumentBuffer, 0, 2); - encoder->drawMeshThreadgroups(MTL::Size(groupX, groupY, groupZ), MTL::Size(128, 1, 1), MTL::Size(32, 1, 1)); + encoder->drawMeshThreadgroups(MTL::Size(groupX, groupY, groupZ), + MTL::Size(128, 1, 1), MTL::Size(32, 1, 1)); } -void RenderCommand::drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) { - //encoder->drawMeshThreadgroups() +void RenderCommand::drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset, + uint32 drawCount, uint32 stride) { + // encoder->drawMeshThreadgroups() } -ComputeCommand::ComputeCommand(MTL::CommandBuffer* cmdBuffer, const std::string& name) - : commandBuffer(cmdBuffer), encoder(cmdBuffer->computeCommandEncoder()), name(name) {} +ComputeCommand::ComputeCommand(MTL::CommandBuffer *cmdBuffer, + const std::string &name) + : commandBuffer(cmdBuffer), encoder(cmdBuffer->computeCommandEncoder()), + name(name) {} ComputeCommand::~ComputeCommand() {} @@ -180,16 +204,21 @@ void ComputeCommand::bindPipeline(Gfx::PComputePipeline pipeline) { boundPipeline = pipeline.cast(); encoder->setComputePipelineState(boundPipeline->getHandle()); argumentBuffer = boundPipeline->graphics->getDevice()->newBuffer( - sizeof(uint64) * (boundPipeline->getPipelineLayout()->getLayouts().size() + 1), MTL::ResourceStorageModeShared); + sizeof(uint64) * + (boundPipeline->getPipelineLayout()->getLayouts().size() + 1), + MTL::ResourceStorageModeShared); argumentBuffer->setLabel( - NS::String::string(pipeline->getPipelineLayout()->getName().c_str(), NS::ASCIIStringEncoding)); + NS::String::string(pipeline->getPipelineLayout()->getName().c_str(), + NS::ASCIIStringEncoding)); } -void ComputeCommand::bindDescriptor(Gfx::PDescriptorSet set, Array offsets) { +void ComputeCommand::bindDescriptor(Gfx::PDescriptorSet set, + Array offsets) { auto metalSet = set.cast(); metalSet->bind(); - uint32 parameterIndex = boundPipeline->getPipelineLayout()->findParameter(set->getLayout()->getName()); - uint64* topLevelTable = (uint64*)argumentBuffer->contents(); + uint32 parameterIndex = boundPipeline->getPipelineLayout()->findParameter( + set->getLayout()->getName()); + uint64 *topLevelTable = (uint64 *)argumentBuffer->contents(); topLevelTable[parameterIndex] = metalSet->getBuffer()->gpuAddress(); auto bindings = metalSet->getLayout()->getBindings(); encoder->useResource(metalSet->getBuffer(), MTL::ResourceUsageRead); @@ -219,42 +248,45 @@ void ComputeCommand::bindDescriptor(Gfx::PDescriptorSet set, Array offse } } -void ComputeCommand::bindDescriptor(const Array& sets, Array offsets) { - for (auto& set : sets) { +void ComputeCommand::bindDescriptor(const Array &sets, + Array offsets) { + for (auto &set : sets) { bindDescriptor(set, offsets); } } -void ComputeCommand::pushConstants(Gfx::SeShaderStageFlags, uint32 offset, uint32 size, - const void* data) { - encoder->setBytes((char*)data + offset, size, 0); +void ComputeCommand::pushConstants(Gfx::SeShaderStageFlags, uint32 offset, + uint32 size, const void *data) { + encoder->setBytes((char *)data + offset, size, 0); } void ComputeCommand::dispatch(uint32 threadX, uint32 threadY, uint32 threadZ) { // TODO encoder->setBuffer(argumentBuffer, 0, 2); - encoder->dispatchThreadgroups(MTL::Size(threadX, threadY, threadZ), MTL::Size(32, 32, 1)); + encoder->dispatchThreadgroups(MTL::Size(threadX, threadY, threadZ), + MTL::Size(32, 32, 1)); } CommandQueue::CommandQueue(PGraphics graphics) : graphics(graphics) { queue = graphics->getDevice()->newCommandQueue(); - MTL::CommandBufferDescriptor* descriptor = MTL::CommandBufferDescriptor::alloc()->init(); + MTL::CommandBufferDescriptor *descriptor = + MTL::CommandBufferDescriptor::alloc()->init(); activeCommand = new Command(graphics, queue->commandBuffer(descriptor)); descriptor->release(); } CommandQueue::~CommandQueue() { queue->release(); } -ORenderCommand CommandQueue::getRenderCommand(const std::string& name) { +ORenderCommand CommandQueue::getRenderCommand(const std::string &name) { return new RenderCommand(activeCommand->createRenderEncoder(), name); } -OComputeCommand CommandQueue::getComputeCommand(const std::string& name) { +OComputeCommand CommandQueue::getComputeCommand(const std::string &name) { return new ComputeCommand(queue->commandBuffer(), name); } void CommandQueue::executeCommands(Array commands) { - for (auto& command : commands) { + for (auto &command : commands) { auto metalCmd = Gfx::PRenderCommand(command).cast(); metalCmd->end(); } @@ -262,33 +294,38 @@ void CommandQueue::executeCommands(Array commands) { void CommandQueue::executeCommands(Array commands) { submitCommands(); - for (auto& command : commands) { + for (auto &command : commands) { auto metalCmd = Gfx::PComputeCommand(command).cast(); metalCmd->end(); } } void CommandQueue::submitCommands(PEvent signalSemaphore) { - activeCommand->getHandle()->addCompletedHandler(MTL::CommandBufferHandler([&](MTL::CommandBuffer* cmdBuffer) { - for (auto it = pendingCommands.begin(); it != pendingCommands.end(); it++) { - if ((*it)->getHandle() == cmdBuffer) { - pendingCommands.remove(it); - return; - } - } - })); + activeCommand->getHandle()->addCompletedHandler( + MTL::CommandBufferHandler([&](MTL::CommandBuffer *cmdBuffer) { + for (auto it = pendingCommands.begin(); it != pendingCommands.end(); + it++) { + if ((*it)->getHandle() == cmdBuffer) { + pendingCommands.remove(it); + return; + } + } + })); activeCommand->end(signalSemaphore); activeCommand->waitDeviceIdle(); PEvent prevCmdEvent = activeCommand->getCompletedEvent(); pendingCommands.add(std::move(activeCommand)); - MTL::CommandBufferDescriptor* descriptor = MTL::CommandBufferDescriptor::alloc()->init(); - descriptor->setErrorOptions(MTL::CommandBufferErrorOptionEncoderExecutionStatus); + MTL::CommandBufferDescriptor *descriptor = + MTL::CommandBufferDescriptor::alloc()->init(); + descriptor->setErrorOptions( + MTL::CommandBufferErrorOptionEncoderExecutionStatus); activeCommand = new Command(graphics, queue->commandBuffer(descriptor)); activeCommand->waitForEvent(prevCmdEvent); } IOCommandQueue::IOCommandQueue(PGraphics graphics) : graphics(graphics) { - MTL::IOCommandQueueDescriptor* desc = MTL::IOCommandQueueDescriptor::alloc()->init(); + MTL::IOCommandQueueDescriptor *desc = + MTL::IOCommandQueueDescriptor::alloc()->init(); desc->setType(MTL::IOCommandQueueTypeConcurrent); desc->setPriority(MTL::IOPriorityNormal); queue = graphics->getDevice()->newIOCommandQueue(desc, nullptr); diff --git a/src/Engine/Graphics/Metal/Descriptor.h b/src/Engine/Graphics/Metal/Descriptor.h index 59de66a..e3fe088 100644 --- a/src/Engine/Graphics/Metal/Descriptor.h +++ b/src/Engine/Graphics/Metal/Descriptor.h @@ -9,75 +9,69 @@ namespace Seele { namespace Metal { DECLARE_REF(Graphics) class DescriptorLayout : public Gfx::DescriptorLayout { -public: - DescriptorLayout(PGraphics graphics, const std::string &name); - virtual ~DescriptorLayout(); - virtual void create() override; + public: + DescriptorLayout(PGraphics graphics, const std::string& name); + virtual ~DescriptorLayout(); + virtual void create() override; -private: - PGraphics graphics; + private: + PGraphics graphics; }; DEFINE_REF(DescriptorLayout) DECLARE_REF(DescriptorSet) class DescriptorPool : public Gfx::DescriptorPool { -public: - DescriptorPool(PGraphics graphics, PDescriptorLayout layout); - virtual ~DescriptorPool(); - virtual Gfx::PDescriptorSet allocateDescriptorSet() override; - virtual void reset() override; - constexpr PDescriptorLayout getLayout() const { return layout; } + public: + DescriptorPool(PGraphics graphics, PDescriptorLayout layout); + virtual ~DescriptorPool(); + virtual Gfx::PDescriptorSet allocateDescriptorSet() override; + virtual void reset() override; + constexpr PDescriptorLayout getLayout() const { return layout; } -private: - PGraphics graphics; - PDescriptorLayout layout; - Array allocatedSets; + private: + PGraphics graphics; + PDescriptorLayout layout; + Array allocatedSets; }; DEFINE_REF(DescriptorPool) class DescriptorSet : public Gfx::DescriptorSet, public CommandBoundResource { -public: - DescriptorSet(PGraphics graphics, PDescriptorPool owner); - virtual ~DescriptorSet(); - virtual void writeChanges() override; - virtual void updateBuffer(uint32_t binding, - Gfx::PUniformBuffer uniformBuffer) override; - virtual void updateBuffer(uint32_t binding, Gfx::PShaderBuffer uniformBuffer) override; - virtual void updateBuffer(uint32_t binding, uint32 index, Gfx::PShaderBuffer uniformBuffer) override; - virtual void updateSampler(uint32_t binding, Gfx::PSampler samplerState) override; - virtual void updateTexture(uint32_t binding, Gfx::PTexture texture, - Gfx::PSampler sampler = nullptr) override; - virtual void updateTextureArray(uint32_t binding, - Array texture) override; + public: + DescriptorSet(PGraphics graphics, PDescriptorPool owner); + virtual ~DescriptorSet(); + virtual void writeChanges() override; + virtual void updateBuffer(uint32_t binding, Gfx::PUniformBuffer uniformBuffer) override; + virtual void updateBuffer(uint32_t binding, Gfx::PShaderBuffer uniformBuffer) override; + virtual void updateBuffer(uint32_t binding, uint32 index, Gfx::PShaderBuffer uniformBuffer) override; + virtual void updateSampler(uint32_t binding, Gfx::PSampler samplerState) override; + virtual void updateTexture(uint32_t binding, Gfx::PTexture texture, Gfx::PSampler sampler = nullptr) override; + virtual void updateTextureArray(uint32_t binding, Array texture) override; - constexpr bool isCurrentlyInUse() const { return currentlyInUse; } - constexpr void allocate() { currentlyInUse = true; } - constexpr void free() { currentlyInUse = false; } + constexpr bool isCurrentlyInUse() const { return currentlyInUse; } + constexpr void allocate() { currentlyInUse = true; } + constexpr void free() { currentlyInUse = false; } - constexpr MTL::Buffer *getBuffer() const { return buffer; } - constexpr const Array &getBoundResources() const { - return boundResources; - } + constexpr MTL::Buffer* getBuffer() const { return buffer; } + constexpr const Array& getBoundResources() const { return boundResources; } -private: - PGraphics graphics; - PDescriptorPool owner; - MTL::Buffer *buffer = nullptr; - uint64 *argumentBuffer = nullptr; - Array boundResources; - bool currentlyInUse; + private: + PGraphics graphics; + PDescriptorPool owner; + MTL::Buffer* buffer = nullptr; + uint64* argumentBuffer = nullptr; + Array boundResources; + bool currentlyInUse; }; DEFINE_REF(DescriptorSet) class PipelineLayout : public Gfx::PipelineLayout { -public: - PipelineLayout(PGraphics graphics, const std::string &name, - Gfx::PPipelineLayout baseLayout); - virtual ~PipelineLayout(); - virtual void create() override; + public: + PipelineLayout(PGraphics graphics, const std::string& name, Gfx::PPipelineLayout baseLayout); + virtual ~PipelineLayout(); + virtual void create() override; -private: - PGraphics graphics; + private: + PGraphics graphics; }; DEFINE_REF(PipelineLayout) } // namespace Metal diff --git a/src/Engine/Graphics/Metal/Descriptor.mm b/src/Engine/Graphics/Metal/Descriptor.mm index f1cb43b..a8f3714 100644 --- a/src/Engine/Graphics/Metal/Descriptor.mm +++ b/src/Engine/Graphics/Metal/Descriptor.mm @@ -94,11 +94,8 @@ void DescriptorSet::updateBuffer(uint32_t binding, boundResources[binding] = metalBuffer->getHandle(); } -void DescriptorSet::updateBuffer(uint32_t binding, uint32 index, Gfx::PShaderBuffer uniformBuffer) -{ - -} - +void DescriptorSet::updateBuffer(uint32_t binding, uint32 index, + Gfx::PShaderBuffer uniformBuffer) {} void DescriptorSet::updateSampler(uint32_t binding, Gfx::PSampler samplerState) { diff --git a/src/Engine/Graphics/Metal/Enums.h b/src/Engine/Graphics/Metal/Enums.h index d601a48..c9a8610 100644 --- a/src/Engine/Graphics/Metal/Enums.h +++ b/src/Engine/Graphics/Metal/Enums.h @@ -3,11 +3,9 @@ #include "Metal/MTLStageInputOutputDescriptor.hpp" #include "Resources.h" -namespace Seele -{ -namespace Metal -{ -constexpr uint64 METAL_VERTEXBUFFER_OFFSET = 6;// something about metal vertex fetch +namespace Seele { +namespace Metal { +constexpr uint64 METAL_VERTEXBUFFER_OFFSET = 6; // something about metal vertex fetch constexpr uint64 METAL_VERTEXATTRIBUTE_OFFSET = 11; MTL::PixelFormat cast(Gfx::SeFormat format); @@ -32,5 +30,5 @@ MTL::PrimitiveTopologyClass cast(Gfx::SePrimitiveTopology topology); Gfx::SePrimitiveTopology cast(MTL::PrimitiveTopologyClass topology); MTL::IndexType cast(Gfx::SeIndexType indexType); Gfx::SeIndexType cast(MTL::IndexType indexType); -} -} \ No newline at end of file +} // namespace Metal +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/Metal/Enums.mm b/src/Engine/Graphics/Metal/Enums.mm index 4abc893..b78f5bd 100644 --- a/src/Engine/Graphics/Metal/Enums.mm +++ b/src/Engine/Graphics/Metal/Enums.mm @@ -767,7 +767,8 @@ Gfx::SeSamplerAddressMode Seele::Metal::cast(MTL::SamplerAddressMode mode) { } } -MTL::PrimitiveTopologyClass Seele::Metal::cast(Gfx::SePrimitiveTopology topology) { +MTL::PrimitiveTopologyClass +Seele::Metal::cast(Gfx::SePrimitiveTopology topology) { switch (topology) { case Gfx::SE_PRIMITIVE_TOPOLOGY_POINT_LIST: return MTL::PrimitiveTopologyClassPoint; diff --git a/src/Engine/Graphics/Metal/Graphics.h b/src/Engine/Graphics/Metal/Graphics.h index aaa30ad..9e723ef 100644 --- a/src/Engine/Graphics/Metal/Graphics.h +++ b/src/Engine/Graphics/Metal/Graphics.h @@ -1,25 +1,24 @@ #pragma once -#include "Metal/Metal.hpp" #include "Graphics/Graphics.h" +#include "Metal/Metal.hpp" -namespace Seele -{ -namespace Metal -{ + +namespace Seele { +namespace Metal { DECLARE_REF(CommandQueue) DECLARE_REF(IOCommandQueue) DECLARE_REF(PipelineCache) -class Graphics : public Gfx::Graphics -{ -public: +class Graphics : public Gfx::Graphics { + public: Graphics(); virtual ~Graphics(); virtual void init(GraphicsInitializer initializer) override; - - virtual Gfx::OWindow createWindow(const WindowCreateInfo &createInfo) override; - virtual Gfx::OViewport createViewport(Gfx::PWindow owner, const ViewportCreateInfo &createInfo) override; - virtual Gfx::ORenderPass createRenderPass(Gfx::RenderTargetLayout layout, Array dependencies, Gfx::PViewport renderArea) override; + virtual Gfx::OWindow createWindow(const WindowCreateInfo& createInfo) override; + virtual Gfx::OViewport createViewport(Gfx::PWindow owner, const ViewportCreateInfo& createInfo) override; + + virtual Gfx::ORenderPass createRenderPass(Gfx::RenderTargetLayout layout, Array dependencies, + Gfx::PViewport renderArea) override; virtual void beginRenderPass(Gfx::PRenderPass renderPass) override; virtual void endRenderPass() override; virtual void waitDeviceIdle() override; @@ -27,17 +26,17 @@ public: virtual void executeCommands(Array commands) override; virtual void executeCommands(Array commands) override; - virtual Gfx::OTexture2D createTexture2D(const TextureCreateInfo &createInfo) override; - virtual Gfx::OTexture3D createTexture3D(const TextureCreateInfo &createInfo) override; - virtual Gfx::OTextureCube createTextureCube(const TextureCreateInfo &createInfo) override; - virtual Gfx::OUniformBuffer createUniformBuffer(const UniformBufferCreateInfo &bulkData) override; - virtual Gfx::OShaderBuffer createShaderBuffer(const ShaderBufferCreateInfo &bulkData) override; - virtual Gfx::OVertexBuffer createVertexBuffer(const VertexBufferCreateInfo &bulkData) override; - virtual Gfx::OIndexBuffer createIndexBuffer(const IndexBufferCreateInfo &bulkData) override; - + virtual Gfx::OTexture2D createTexture2D(const TextureCreateInfo& createInfo) override; + virtual Gfx::OTexture3D createTexture3D(const TextureCreateInfo& createInfo) override; + virtual Gfx::OTextureCube createTextureCube(const TextureCreateInfo& createInfo) override; + virtual Gfx::OUniformBuffer createUniformBuffer(const UniformBufferCreateInfo& bulkData) override; + virtual Gfx::OShaderBuffer createShaderBuffer(const ShaderBufferCreateInfo& bulkData) override; + virtual Gfx::OVertexBuffer createVertexBuffer(const VertexBufferCreateInfo& bulkData) override; + virtual Gfx::OIndexBuffer createIndexBuffer(const IndexBufferCreateInfo& bulkData) override; + virtual Gfx::ORenderCommand createRenderCommand(const std::string& name = "") override; virtual Gfx::OComputeCommand createComputeCommand(const std::string& name = "") override; - + virtual Gfx::OVertexShader createVertexShader(const ShaderCreateInfo& createInfo) override; virtual Gfx::OFragmentShader createFragmentShader(const ShaderCreateInfo& createInfo) override; virtual Gfx::OComputeShader createComputeShader(const ShaderCreateInfo& createInfo) override; @@ -48,22 +47,23 @@ public: virtual Gfx::PComputePipeline createComputePipeline(Gfx::ComputePipelineCreateInfo createInfo) override; virtual Gfx::OSampler createSampler(const SamplerCreateInfo& createInfo) override; - virtual Gfx::ODescriptorLayout createDescriptorLayout(const std::string& name = "") override; - virtual Gfx::OPipelineLayout createPipelineLayout(const std::string& name = "", Gfx::PPipelineLayout baseLayout = nullptr) override; + virtual Gfx::ODescriptorLayout createDescriptorLayout(const std::string& name = "") override; + virtual Gfx::OPipelineLayout createPipelineLayout(const std::string& name = "", Gfx::PPipelineLayout baseLayout = nullptr) override; virtual Gfx::OVertexInput createVertexInput(VertexInputStateCreateInfo createInfo) override; virtual void resolveTexture(Gfx::PTexture source, Gfx::PTexture destination) override; - + MTL::Device* getDevice() const { return device; } PCommandQueue getQueue() const { return queue; } PIOCommandQueue getIOQueue() const { return ioQueue; } -protected: + + protected: MTL::Device* device; OCommandQueue queue; OIOCommandQueue ioQueue; OPipelineCache cache; }; DEFINE_REF(Graphics) -} // namespace Metal +} // namespace Metal } // namespace Seele diff --git a/src/Engine/Graphics/Metal/Graphics.mm b/src/Engine/Graphics/Metal/Graphics.mm index c14b02d..b5bfac6 100644 --- a/src/Engine/Graphics/Metal/Graphics.mm +++ b/src/Engine/Graphics/Metal/Graphics.mm @@ -1,31 +1,25 @@ #include "Graphics.h" +#include "Buffer.h" +#include "Command.h" #include "Graphics/Initializer.h" #include "Graphics/Metal/Descriptor.h" #include "Graphics/Metal/Pipeline.h" #include "Graphics/Metal/PipelineCache.h" #include "Graphics/Metal/Resources.h" -#include "Shader.h" #include "RenderPass.h" #include "Resources.h" -#include "Command.h" +#include "Shader.h" #include "Window.h" -#include "Buffer.h" + using namespace Seele; using namespace Seele::Metal; -Graphics::Graphics() -{ - -} +Graphics::Graphics() {} -Graphics::~Graphics() -{ - -} +Graphics::~Graphics() {} -void Graphics::init(GraphicsInitializer) -{ +void Graphics::init(GraphicsInitializer) { glfwInit(); device = MTL::CreateSystemDefaultDevice(); queue = new CommandQueue(this); @@ -34,164 +28,149 @@ void Graphics::init(GraphicsInitializer) meshShadingEnabled = false; } -Gfx::OWindow Graphics::createWindow(const WindowCreateInfo &createInfo) -{ +Gfx::OWindow Graphics::createWindow(const WindowCreateInfo &createInfo) { return new Window(this, createInfo); } -Gfx::OViewport Graphics::createViewport(Gfx::PWindow owner, const ViewportCreateInfo &createInfo) -{ +Gfx::OViewport Graphics::createViewport(Gfx::PWindow owner, + const ViewportCreateInfo &createInfo) { return new Viewport(owner, createInfo); } -Gfx::ORenderPass Graphics::createRenderPass(Gfx::RenderTargetLayout layout, Array dependencies, Gfx::PViewport renderArea) -{ +Gfx::ORenderPass +Graphics::createRenderPass(Gfx::RenderTargetLayout layout, + Array dependencies, + Gfx::PViewport renderArea) { return new RenderPass(this, layout, dependencies, renderArea); } -void Graphics::beginRenderPass(Gfx::PRenderPass renderPass) -{ +void Graphics::beginRenderPass(Gfx::PRenderPass renderPass) { queue->getCommands()->beginRenderPass(renderPass.cast()); } -void Graphics::endRenderPass() -{ - queue->getCommands()->endRenderPass(); -} +void Graphics::endRenderPass() { queue->getCommands()->endRenderPass(); } -void Graphics::waitDeviceIdle() -{ - queue->getCommands()->waitDeviceIdle(); -} +void Graphics::waitDeviceIdle() { queue->getCommands()->waitDeviceIdle(); } -void Graphics::executeCommands(Array commands) -{ - queue->executeCommands(std::move(commands)); -} - -void Graphics::executeCommands(Array commands) -{ +void Graphics::executeCommands(Array commands) { queue->executeCommands(std::move(commands)); } -Gfx::OTexture2D Graphics::createTexture2D(const TextureCreateInfo &createInfo) -{ +void Graphics::executeCommands(Array commands) { + queue->executeCommands(std::move(commands)); +} + +Gfx::OTexture2D Graphics::createTexture2D(const TextureCreateInfo &createInfo) { return new Texture2D(this, createInfo); } -Gfx::OTexture3D Graphics::createTexture3D(const TextureCreateInfo &createInfo) -{ - +Gfx::OTexture3D Graphics::createTexture3D(const TextureCreateInfo &createInfo) { + return new Texture3D(this, createInfo); } -Gfx::OTextureCube Graphics::createTextureCube(const TextureCreateInfo &createInfo) -{ +Gfx::OTextureCube +Graphics::createTextureCube(const TextureCreateInfo &createInfo) { return new TextureCube(this, createInfo); } -Gfx::OUniformBuffer Graphics::createUniformBuffer(const UniformBufferCreateInfo &bulkData) -{ +Gfx::OUniformBuffer +Graphics::createUniformBuffer(const UniformBufferCreateInfo &bulkData) { return new UniformBuffer(this, bulkData); } -Gfx::OShaderBuffer Graphics::createShaderBuffer(const ShaderBufferCreateInfo &bulkData) -{ +Gfx::OShaderBuffer +Graphics::createShaderBuffer(const ShaderBufferCreateInfo &bulkData) { return new ShaderBuffer(this, bulkData); } -Gfx::OVertexBuffer Graphics::createVertexBuffer(const VertexBufferCreateInfo &bulkData) -{ +Gfx::OVertexBuffer +Graphics::createVertexBuffer(const VertexBufferCreateInfo &bulkData) { return new VertexBuffer(this, bulkData); } -Gfx::OIndexBuffer Graphics::createIndexBuffer(const IndexBufferCreateInfo &bulkData) -{ +Gfx::OIndexBuffer +Graphics::createIndexBuffer(const IndexBufferCreateInfo &bulkData) { return new IndexBuffer(this, bulkData); } -Gfx::ORenderCommand Graphics::createRenderCommand(const std::string& name) -{ +Gfx::ORenderCommand Graphics::createRenderCommand(const std::string &name) { return queue->getRenderCommand(name); } -Gfx::OComputeCommand Graphics::createComputeCommand(const std::string& name) -{ +Gfx::OComputeCommand Graphics::createComputeCommand(const std::string &name) { return queue->getComputeCommand(name); } -Gfx::OVertexShader Graphics::createVertexShader(const ShaderCreateInfo& createInfo) -{ +Gfx::OVertexShader +Graphics::createVertexShader(const ShaderCreateInfo &createInfo) { OVertexShader result = new VertexShader(this); result->create(createInfo); return result; } -Gfx::OFragmentShader Graphics::createFragmentShader(const ShaderCreateInfo& createInfo) -{ +Gfx::OFragmentShader +Graphics::createFragmentShader(const ShaderCreateInfo &createInfo) { OFragmentShader result = new FragmentShader(this); result->create(createInfo); return result; } -Gfx::OComputeShader Graphics::createComputeShader(const ShaderCreateInfo& createInfo) -{ +Gfx::OComputeShader +Graphics::createComputeShader(const ShaderCreateInfo &createInfo) { OComputeShader result = new ComputeShader(this); result->create(createInfo); return result; } -Gfx::OMeshShader Graphics::createMeshShader(const ShaderCreateInfo& createInfo) -{ +Gfx::OMeshShader +Graphics::createMeshShader(const ShaderCreateInfo &createInfo) { OMeshShader result = new MeshShader(this); result->create(createInfo); return result; } -Gfx::OTaskShader Graphics::createTaskShader(const ShaderCreateInfo& createInfo) -{ +Gfx::OTaskShader +Graphics::createTaskShader(const ShaderCreateInfo &createInfo) { OTaskShader result = new TaskShader(this); result->create(createInfo); return result; } -Gfx::PGraphicsPipeline Graphics::createGraphicsPipeline(Gfx::LegacyPipelineCreateInfo createInfo) -{ +Gfx::PGraphicsPipeline +Graphics::createGraphicsPipeline(Gfx::LegacyPipelineCreateInfo createInfo) { return cache->createPipeline(std::move(createInfo)); } -Gfx::PGraphicsPipeline Graphics::createGraphicsPipeline(Gfx::MeshPipelineCreateInfo createInfo) -{ +Gfx::PGraphicsPipeline +Graphics::createGraphicsPipeline(Gfx::MeshPipelineCreateInfo createInfo) { return cache->createPipeline(std::move(createInfo)); } -Gfx::PComputePipeline Graphics::createComputePipeline(Gfx::ComputePipelineCreateInfo createInfo) -{ +Gfx::PComputePipeline +Graphics::createComputePipeline(Gfx::ComputePipelineCreateInfo createInfo) { return cache->createPipeline(std::move(createInfo)); } -Gfx::OSampler Graphics::createSampler(const SamplerCreateInfo& createInfo) -{ +Gfx::OSampler Graphics::createSampler(const SamplerCreateInfo &createInfo) { return new Sampler(this, createInfo); } -Gfx::ODescriptorLayout Graphics::createDescriptorLayout(const std::string& name) -{ +Gfx::ODescriptorLayout +Graphics::createDescriptorLayout(const std::string &name) { return new DescriptorLayout(this, name); } -Gfx::OPipelineLayout Graphics::createPipelineLayout(const std::string& name, Gfx::PPipelineLayout baseLayout) -{ +Gfx::OPipelineLayout +Graphics::createPipelineLayout(const std::string &name, + Gfx::PPipelineLayout baseLayout) { return new PipelineLayout(this, name, baseLayout); } -Gfx::OVertexInput Graphics::createVertexInput(VertexInputStateCreateInfo createInfo) -{ +Gfx::OVertexInput +Graphics::createVertexInput(VertexInputStateCreateInfo createInfo) { return new VertexInput(createInfo); } -void Graphics::resolveTexture(Gfx::PTexture source, Gfx::PTexture destination) -{ +void Graphics::resolveTexture(Gfx::PTexture source, Gfx::PTexture destination) { } - - diff --git a/src/Engine/Graphics/Metal/Pipeline.h b/src/Engine/Graphics/Metal/Pipeline.h index 94daa92..b778a36 100644 --- a/src/Engine/Graphics/Metal/Pipeline.h +++ b/src/Engine/Graphics/Metal/Pipeline.h @@ -7,33 +7,35 @@ namespace Seele { namespace Metal { class VertexInput : public Gfx::VertexInput { -public: - VertexInput(VertexInputStateCreateInfo createInfo); - virtual ~VertexInput(); + public: + VertexInput(VertexInputStateCreateInfo createInfo); + virtual ~VertexInput(); }; DECLARE_REF(PipelineLayout) DECLARE_REF(Graphics) class GraphicsPipeline : public Gfx::GraphicsPipeline { -public: - GraphicsPipeline(PGraphics graphics, MTL::PrimitiveType primitive, MTL::RenderPipelineState* pipeline, Gfx::PPipelineLayout createInfo); - virtual ~GraphicsPipeline(); - constexpr MTL::RenderPipelineState* getHandle() const { return state; } - constexpr MTL::PrimitiveType getPrimitive() const { return primitiveType; } - PGraphics graphics; - MTL::RenderPipelineState* state; - MTL::PrimitiveType primitiveType; -private: + public: + GraphicsPipeline(PGraphics graphics, MTL::PrimitiveType primitive, MTL::RenderPipelineState* pipeline, Gfx::PPipelineLayout createInfo); + virtual ~GraphicsPipeline(); + constexpr MTL::RenderPipelineState* getHandle() const { return state; } + constexpr MTL::PrimitiveType getPrimitive() const { return primitiveType; } + PGraphics graphics; + MTL::RenderPipelineState* state; + MTL::PrimitiveType primitiveType; + + private: }; DEFINE_REF(GraphicsPipeline) class ComputePipeline : public Gfx::ComputePipeline { -public: - ComputePipeline(PGraphics graphics, MTL::ComputePipelineState* pipeline, Gfx::PPipelineLayout); - virtual ~ComputePipeline(); - constexpr MTL::ComputePipelineState* getHandle() const { return state; } + public: + ComputePipeline(PGraphics graphics, MTL::ComputePipelineState* pipeline, Gfx::PPipelineLayout); + virtual ~ComputePipeline(); + constexpr MTL::ComputePipelineState* getHandle() const { return state; } - PGraphics graphics; -private: - MTL::ComputePipelineState* state; + PGraphics graphics; + + private: + MTL::ComputePipelineState* state; }; DEFINE_REF(ComputePipeline) } // namespace Metal diff --git a/src/Engine/Graphics/Metal/Pipeline.mm b/src/Engine/Graphics/Metal/Pipeline.mm index 9bbbaf1..f9679b3 100644 --- a/src/Engine/Graphics/Metal/Pipeline.mm +++ b/src/Engine/Graphics/Metal/Pipeline.mm @@ -7,17 +7,22 @@ using namespace Seele; using namespace Seele::Metal; -VertexInput::VertexInput(VertexInputStateCreateInfo createInfo) : Gfx::VertexInput(createInfo) {} +VertexInput::VertexInput(VertexInputStateCreateInfo createInfo) + : Gfx::VertexInput(createInfo) {} VertexInput::~VertexInput() {} -GraphicsPipeline::GraphicsPipeline(PGraphics graphics, MTL::PrimitiveType primitive, MTL::RenderPipelineState* pipeline, +GraphicsPipeline::GraphicsPipeline(PGraphics graphics, + MTL::PrimitiveType primitive, + MTL::RenderPipelineState *pipeline, Gfx::PPipelineLayout layout) - : Gfx::GraphicsPipeline(layout), graphics(graphics), state(pipeline), primitiveType(primitive) {} + : Gfx::GraphicsPipeline(layout), graphics(graphics), state(pipeline), + primitiveType(primitive) {} GraphicsPipeline::~GraphicsPipeline() {} -ComputePipeline::ComputePipeline(PGraphics graphics, MTL::ComputePipelineState* pipeline, +ComputePipeline::ComputePipeline(PGraphics graphics, + MTL::ComputePipelineState *pipeline, Gfx::PPipelineLayout layout) : Gfx::ComputePipeline(layout), graphics(graphics), state(pipeline) {} diff --git a/src/Engine/Graphics/Metal/PipelineCache.h b/src/Engine/Graphics/Metal/PipelineCache.h index a856de7..f736524 100644 --- a/src/Engine/Graphics/Metal/PipelineCache.h +++ b/src/Engine/Graphics/Metal/PipelineCache.h @@ -4,20 +4,20 @@ namespace Seele { namespace Metal { -class PipelineCache -{ -public: - PipelineCache(PGraphics graphics, const std::string& cacheFilePath); - ~PipelineCache(); - PGraphicsPipeline createPipeline(Gfx::LegacyPipelineCreateInfo createInfo); - PGraphicsPipeline createPipeline(Gfx::MeshPipelineCreateInfo createInfo); - PComputePipeline createPipeline(Gfx::ComputePipelineCreateInfo createInfo); -private: - PGraphics graphics; - Map graphicsPipelines; - Map computePipelines; - std::string cacheFile; +class PipelineCache { + public: + PipelineCache(PGraphics graphics, const std::string& cacheFilePath); + ~PipelineCache(); + PGraphicsPipeline createPipeline(Gfx::LegacyPipelineCreateInfo createInfo); + PGraphicsPipeline createPipeline(Gfx::MeshPipelineCreateInfo createInfo); + PComputePipeline createPipeline(Gfx::ComputePipelineCreateInfo createInfo); + + private: + PGraphics graphics; + Map graphicsPipelines; + Map computePipelines; + std::string cacheFile; }; DEFINE_REF(PipelineCache) -} -} \ No newline at end of file +} // namespace Metal +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/Metal/PipelineCache.mm b/src/Engine/Graphics/Metal/PipelineCache.mm index ed5265b..10505c2 100644 --- a/src/Engine/Graphics/Metal/PipelineCache.mm +++ b/src/Engine/Graphics/Metal/PipelineCache.mm @@ -19,22 +19,30 @@ using namespace Seele; using namespace Seele::Metal; -PipelineCache::PipelineCache(PGraphics graphics, const std::string& name) : graphics(graphics), cacheFile(name) {} +PipelineCache::PipelineCache(PGraphics graphics, const std::string &name) + : graphics(graphics), cacheFile(name) {} PipelineCache::~PipelineCache() {} -PGraphicsPipeline PipelineCache::createPipeline(Gfx::LegacyPipelineCreateInfo createInfo) { - PPipelineLayout layout = Gfx::PPipelineLayout(createInfo.pipelineLayout).cast(); +PGraphicsPipeline +PipelineCache::createPipeline(Gfx::LegacyPipelineCreateInfo createInfo) { + PPipelineLayout layout = + Gfx::PPipelineLayout(createInfo.pipelineLayout).cast(); - MTL::RenderPipelineDescriptor* pipelineDescriptor = MTL::RenderPipelineDescriptor::alloc()->init(); + MTL::RenderPipelineDescriptor *pipelineDescriptor = + MTL::RenderPipelineDescriptor::alloc()->init(); - MTL::VertexDescriptor* vertexDescriptor = pipelineDescriptor->vertexDescriptor()->init(); - MTL::VertexAttributeDescriptorArray* attributes = vertexDescriptor->attributes()->init(); + MTL::VertexDescriptor *vertexDescriptor = + pipelineDescriptor->vertexDescriptor()->init(); + MTL::VertexAttributeDescriptorArray *attributes = + vertexDescriptor->attributes()->init(); if (createInfo.vertexInput != nullptr) { - const auto& vertexInfo = createInfo.vertexInput->getInfo(); + const auto &vertexInfo = createInfo.vertexInput->getInfo(); for (size_t attr = 0; attr < vertexInfo.attributes.size(); ++attr) { - MTL::VertexAttributeDescriptor* attribute = attributes->object(attr + METAL_VERTEXATTRIBUTE_OFFSET)->init(); - attribute->setBufferIndex(vertexInfo.attributes[attr].binding + METAL_VERTEXBUFFER_OFFSET); + MTL::VertexAttributeDescriptor *attribute = + attributes->object(attr + METAL_VERTEXATTRIBUTE_OFFSET)->init(); + attribute->setBufferIndex(vertexInfo.attributes[attr].binding + + METAL_VERTEXBUFFER_OFFSET); switch (vertexInfo.attributes[attr].format) { case Gfx::SE_FORMAT_R32G32B32_SFLOAT: attribute->setFormat(MTL::VertexFormatFloat3); @@ -45,9 +53,11 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::LegacyPipelineCreateInfo cr attribute->setOffset(vertexInfo.attributes[attr].offset); } - MTL::VertexBufferLayoutDescriptorArray* bufferLayout = vertexDescriptor->layouts()->init(); + MTL::VertexBufferLayoutDescriptorArray *bufferLayout = + vertexDescriptor->layouts()->init(); for (size_t binding = 0; binding < vertexInfo.bindings.size(); ++binding) { - MTL::VertexBufferLayoutDescriptor* buffer = bufferLayout->object(binding + METAL_VERTEXBUFFER_OFFSET)->init(); + MTL::VertexBufferLayoutDescriptor *buffer = + bufferLayout->object(binding + METAL_VERTEXBUFFER_OFFSET)->init(); buffer->setStride(vertexInfo.bindings[binding].stride); buffer->setStepRate(1); switch (vertexInfo.bindings[binding].inputRate) { @@ -62,19 +72,28 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::LegacyPipelineCreateInfo cr } pipelineDescriptor->setVertexDescriptor(vertexDescriptor); - pipelineDescriptor->setVertexFunction(createInfo.vertexShader.cast()->getFunction()); + pipelineDescriptor->setVertexFunction( + createInfo.vertexShader.cast()->getFunction()); if (createInfo.fragmentShader != nullptr) { - pipelineDescriptor->setFragmentFunction(createInfo.fragmentShader.cast()->getFunction()); + pipelineDescriptor->setFragmentFunction( + createInfo.fragmentShader.cast()->getFunction()); } pipelineDescriptor->setInputPrimitiveTopology(cast(createInfo.topology)); - if (createInfo.renderPass->getLayout().depthAttachment.getTexture() != nullptr) { + if (createInfo.renderPass->getLayout().depthAttachment.getTexture() != + nullptr) { pipelineDescriptor->setDepthAttachmentPixelFormat( - cast(createInfo.renderPass->getLayout().depthAttachment.getTexture().cast()->getFormat())); + cast(createInfo.renderPass->getLayout() + .depthAttachment.getTexture() + .cast() + ->getFormat())); } - pipelineDescriptor->setAlphaToCoverageEnabled(createInfo.multisampleState.alphaCoverageEnable); - pipelineDescriptor->setAlphaToOneEnabled(createInfo.multisampleState.alphaToOneEnable); + pipelineDescriptor->setAlphaToCoverageEnabled( + createInfo.multisampleState.alphaCoverageEnable); + pipelineDescriptor->setAlphaToOneEnabled( + createInfo.multisampleState.alphaToOneEnable); pipelineDescriptor->setRasterSampleCount(createInfo.multisampleState.samples); - pipelineDescriptor->setRasterizationEnabled(!createInfo.rasterizationState.rasterizerDiscardEnable); + pipelineDescriptor->setRasterizationEnabled( + !createInfo.rasterizationState.rasterizerDiscardEnable); uint32 hash = pipelineDescriptor->hash(); @@ -117,12 +136,14 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::LegacyPipelineCreateInfo cr type = MTL::PrimitiveTypeTriangle; break; } - NS::Error* error; - graphicsPipelines[hash] = - new GraphicsPipeline(graphics, type, graphics->getDevice()->newRenderPipelineState(pipelineDescriptor, &error), - std::move(createInfo.pipelineLayout)); + NS::Error *error; + graphicsPipelines[hash] = new GraphicsPipeline( + graphics, type, + graphics->getDevice()->newRenderPipelineState(pipelineDescriptor, &error), + std::move(createInfo.pipelineLayout)); if (error) { - std::cout << error->localizedDescription()->cString(NS::ASCIIStringEncoding) << std::endl; + std::cout << error->localizedDescription()->cString(NS::ASCIIStringEncoding) + << std::endl; assert(false); } @@ -130,51 +151,67 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::LegacyPipelineCreateInfo cr return graphicsPipelines[hash]; } -PGraphicsPipeline PipelineCache::createPipeline(Gfx::MeshPipelineCreateInfo createInfo) { - MTL::MeshRenderPipelineDescriptor* pipelineDescriptor = MTL::MeshRenderPipelineDescriptor::alloc()->init(); +PGraphicsPipeline +PipelineCache::createPipeline(Gfx::MeshPipelineCreateInfo createInfo) { + MTL::MeshRenderPipelineDescriptor *pipelineDescriptor = + MTL::MeshRenderPipelineDescriptor::alloc()->init(); - pipelineDescriptor->setMeshFunction(createInfo.meshShader.cast()->getFunction()); + pipelineDescriptor->setMeshFunction( + createInfo.meshShader.cast()->getFunction()); if (createInfo.taskShader != nullptr) { - pipelineDescriptor->setObjectFunction(createInfo.taskShader.cast()->getFunction()); + pipelineDescriptor->setObjectFunction( + createInfo.taskShader.cast()->getFunction()); } if (createInfo.fragmentShader != nullptr) { - pipelineDescriptor->setFragmentFunction(createInfo.fragmentShader.cast()->getFunction()); + pipelineDescriptor->setFragmentFunction( + createInfo.fragmentShader.cast()->getFunction()); } - if (createInfo.renderPass->getLayout().depthAttachment.getTexture() != nullptr) { + if (createInfo.renderPass->getLayout().depthAttachment.getTexture() != + nullptr) { pipelineDescriptor->setDepthAttachmentPixelFormat( - cast(createInfo.renderPass->getLayout().depthAttachment.getTexture().cast()->getFormat())); + cast(createInfo.renderPass->getLayout() + .depthAttachment.getTexture() + .cast() + ->getFormat())); } - pipelineDescriptor->setAlphaToCoverageEnabled(createInfo.multisampleState.alphaCoverageEnable); - pipelineDescriptor->setAlphaToOneEnabled(createInfo.multisampleState.alphaToOneEnable); + pipelineDescriptor->setAlphaToCoverageEnabled( + createInfo.multisampleState.alphaCoverageEnable); + pipelineDescriptor->setAlphaToOneEnabled( + createInfo.multisampleState.alphaToOneEnable); pipelineDescriptor->setRasterSampleCount(createInfo.multisampleState.samples); - pipelineDescriptor->setRasterizationEnabled(!createInfo.rasterizationState.rasterizerDiscardEnable); + pipelineDescriptor->setRasterizationEnabled( + !createInfo.rasterizationState.rasterizerDiscardEnable); uint32 hash = pipelineDescriptor->hash(); if (graphicsPipelines.contains(hash)) { return graphicsPipelines[hash]; } - NS::Error* error = nullptr; + NS::Error *error = nullptr; MTL::AutoreleasedRenderPipelineReflection reflection; graphicsPipelines[hash] = new GraphicsPipeline( graphics, MTL::PrimitiveTypeTriangle, - graphics->getDevice()->newRenderPipelineState(pipelineDescriptor, MTL::PipelineOptionNone, &reflection, &error), + graphics->getDevice()->newRenderPipelineState( + pipelineDescriptor, MTL::PipelineOptionNone, &reflection, &error), std::move(createInfo.pipelineLayout)); pipelineDescriptor->release(); return graphicsPipelines[hash]; } -PComputePipeline PipelineCache::createPipeline(Gfx::ComputePipelineCreateInfo createInfo) { +PComputePipeline +PipelineCache::createPipeline(Gfx::ComputePipelineCreateInfo createInfo) { PComputeShader shader = createInfo.computeShader.cast(); uint32 hash = shader->getShaderHash(); if (computePipelines.contains(hash)) { return computePipelines[hash]; } - NS::Error* error; + NS::Error *error; computePipelines[hash] = - new ComputePipeline(graphics, graphics->getDevice()->newComputePipelineState(shader->getFunction(), &error), + new ComputePipeline(graphics, + graphics->getDevice()->newComputePipelineState( + shader->getFunction(), &error), std::move(createInfo.pipelineLayout)); assert(!error); return computePipelines[hash]; diff --git a/src/Engine/Graphics/Metal/RenderPass.h b/src/Engine/Graphics/Metal/RenderPass.h index 753eddf..e837424 100644 --- a/src/Engine/Graphics/Metal/RenderPass.h +++ b/src/Engine/Graphics/Metal/RenderPass.h @@ -2,22 +2,17 @@ #include "Graphics/RenderTarget.h" #include "Resources.h" -namespace Seele -{ -namespace Metal -{ +namespace Seele { +namespace Metal { DECLARE_REF(Graphics) -class RenderPass : public Gfx::RenderPass -{ -public: +class RenderPass : public Gfx::RenderPass { + public: RenderPass(PGraphics graphics, Gfx::RenderTargetLayout layout, Array dependencies, Gfx::PViewport viewport); virtual ~RenderPass(); void updateRenderPass(); - MTL::RenderPassDescriptor* getDescriptor() const - { - return renderPass; - } -private: + MTL::RenderPassDescriptor* getDescriptor() const { return renderPass; } + + private: PGraphics graphics; Gfx::PViewport viewport; MTL::RenderPassDescriptor* renderPass; diff --git a/src/Engine/Graphics/Metal/RenderPass.mm b/src/Engine/Graphics/Metal/RenderPass.mm index 3c11a81..fda60c4 100644 --- a/src/Engine/Graphics/Metal/RenderPass.mm +++ b/src/Engine/Graphics/Metal/RenderPass.mm @@ -7,9 +7,11 @@ using namespace Seele; using namespace Seele::Metal; -RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout layout, Array dependencies, +RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout layout, + Array dependencies, Gfx::PViewport viewport) - : Gfx::RenderPass(layout, dependencies), graphics(graphics), viewport(viewport) { + : Gfx::RenderPass(layout, dependencies), graphics(graphics), + viewport(viewport) { renderPass = MTL::RenderPassDescriptor::renderPassDescriptor(); renderPass->setRenderTargetArrayLength(1); renderPass->setRenderTargetWidth(viewport->getWidth()); @@ -17,18 +19,21 @@ RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout layout, Array renderPass->setDefaultRasterSampleCount(viewport->getSamples()); for (size_t i = 0; i < layout.colorAttachments.size(); ++i) { - const auto& color = layout.colorAttachments[i]; - MTL::RenderPassColorAttachmentDescriptor* desc = renderPass->colorAttachments()->object(i); - desc->setClearColor(MTL::ClearColor(color.clear.color.float32[0], color.clear.color.float32[1], - color.clear.color.float32[2], color.clear.color.float32[3])); + const auto &color = layout.colorAttachments[i]; + MTL::RenderPassColorAttachmentDescriptor *desc = + renderPass->colorAttachments()->object(i); + desc->setClearColor(MTL::ClearColor( + color.clear.color.float32[0], color.clear.color.float32[1], + color.clear.color.float32[2], color.clear.color.float32[3])); desc->setLoadAction(cast(color.getLoadOp())); desc->setStoreAction(cast(color.getStoreOp())); desc->setLevel(0); if (!layout.resolveAttachments.empty()) { - const auto& resolve = layout.resolveAttachments[i]; + const auto &resolve = layout.resolveAttachments[i]; desc->setResolveLevel(0); desc->setStoreAction(MTL::StoreActionStoreAndMultisampleResolve); - desc->setResolveTexture(resolve.getTexture().cast()->getTexture()); + desc->setResolveTexture( + resolve.getTexture().cast()->getTexture()); } } if (layout.depthAttachment.getTexture() != nullptr) { @@ -38,7 +43,9 @@ RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout layout, Array depth->setStoreAction(cast(layout.depthAttachment.getStoreOp())); if (layout.depthResolveAttachment.getTexture() != nullptr) { - depth->setResolveTexture(layout.depthResolveAttachment.getTexture().cast()->getTexture()); + depth->setResolveTexture(layout.depthResolveAttachment.getTexture() + .cast() + ->getTexture()); depth->setStoreAction(MTL::StoreActionStoreAndMultisampleResolve); } } @@ -48,12 +55,13 @@ RenderPass::~RenderPass() {} void RenderPass::updateRenderPass() { for (size_t i = 0; i < layout.colorAttachments.size(); ++i) { - const auto& color = layout.colorAttachments[i]; + const auto &color = layout.colorAttachments[i]; auto desc = renderPass->colorAttachments()->object(i); desc->setTexture(color.getTexture().cast()->getTexture()); } if (layout.depthAttachment.getTexture() != nullptr) { auto depth = renderPass->depthAttachment(); - depth->setTexture(layout.depthAttachment.getTexture().cast()->getTexture()); + depth->setTexture( + layout.depthAttachment.getTexture().cast()->getTexture()); } } \ No newline at end of file diff --git a/src/Engine/Graphics/Metal/Resources.h b/src/Engine/Graphics/Metal/Resources.h index eeffd9a..7d2513b 100644 --- a/src/Engine/Graphics/Metal/Resources.h +++ b/src/Engine/Graphics/Metal/Resources.h @@ -10,58 +10,51 @@ namespace Seele { namespace Metal { DECLARE_REF(Graphics); -class CommandBoundResource -{ -public: - CommandBoundResource(PGraphics graphics) - : graphics(graphics) - { - } - virtual ~CommandBoundResource() - { +class CommandBoundResource { + public: + CommandBoundResource(PGraphics graphics) : graphics(graphics) {} + virtual ~CommandBoundResource() { if (isCurrentlyBound()) abort(); } constexpr bool isCurrentlyBound() const { return bindCount > 0; } constexpr void bind() { bindCount++; } constexpr void unbind() { bindCount--; } -protected: + + protected: PGraphics graphics; uint64 bindCount = 0; }; DEFINE_REF(CommandBoundResource) class Fence { -public: - Fence(PGraphics graphics); - ~Fence(); - MTL::Fence *getHandle() const { return handle; } + public: + Fence(PGraphics graphics); + ~Fence(); + MTL::Fence* getHandle() const { return handle; } -private: - MTL::Fence *handle; + private: + MTL::Fence* handle; }; DEFINE_REF(Fence); class Event { -public: - Event(PGraphics graphics); - ~Event(); - MTL::Event *getHandle() const { return handle; } + public: + Event(PGraphics graphics); + ~Event(); + MTL::Event* getHandle() const { return handle; } -private: - MTL::Event *handle; + private: + MTL::Event* handle; }; DEFINE_REF(Event) -class Sampler : public Gfx::Sampler -{ -public: - Sampler(PGraphics graphics, const SamplerCreateInfo& createInfo); - virtual ~Sampler(); - MTL::SamplerState* getHandle() const - { - return sampler; - } -private: - MTL::SamplerState* sampler; +class Sampler : public Gfx::Sampler { + public: + Sampler(PGraphics graphics, const SamplerCreateInfo& createInfo); + virtual ~Sampler(); + MTL::SamplerState* getHandle() const { return sampler; } + + private: + MTL::SamplerState* sampler; }; DEFINE_REF(Sampler) } // namespace Metal diff --git a/src/Engine/Graphics/Metal/Resources.mm b/src/Engine/Graphics/Metal/Resources.mm index c84577a..cd5dba6 100644 --- a/src/Engine/Graphics/Metal/Resources.mm +++ b/src/Engine/Graphics/Metal/Resources.mm @@ -1,7 +1,8 @@ #include "Resources.h" +#include "Enums.h" #include "Graphics.h" #include "Metal/MTLSampler.hpp" -#include "Enums.h" + using namespace Seele; using namespace Seele::Metal; @@ -14,9 +15,8 @@ Event::Event(PGraphics graphics) : handle(graphics->getDevice()->newEvent()) {} Event::~Event() { handle->release(); } -Sampler::Sampler(PGraphics graphics, const SamplerCreateInfo& createInfo) -{ - MTL::SamplerDescriptor* desc = MTL::SamplerDescriptor::alloc()->init(); +Sampler::Sampler(PGraphics graphics, const SamplerCreateInfo &createInfo) { + MTL::SamplerDescriptor *desc = MTL::SamplerDescriptor::alloc()->init(); desc->setBorderColor(cast(createInfo.borderColor)); desc->setCompareFunction(cast(createInfo.compareOp)); desc->setLodAverage(createInfo.mipLodBias); @@ -35,7 +35,4 @@ Sampler::Sampler(PGraphics graphics, const SamplerCreateInfo& createInfo) desc->release(); } -Sampler::~Sampler() -{ - sampler->release(); -} \ No newline at end of file +Sampler::~Sampler() { sampler->release(); } \ No newline at end of file diff --git a/src/Engine/Graphics/Metal/Shader.h b/src/Engine/Graphics/Metal/Shader.h index 683ef26..05a8829 100644 --- a/src/Engine/Graphics/Metal/Shader.h +++ b/src/Engine/Graphics/Metal/Shader.h @@ -7,32 +7,32 @@ namespace Seele { namespace Metal { class Shader { -public: - Shader(PGraphics graphics, Gfx::SeShaderStageFlags stage); - virtual ~Shader(); + public: + Shader(PGraphics graphics, Gfx::SeShaderStageFlags stage); + virtual ~Shader(); - void create(const ShaderCreateInfo &createInfo); + void create(const ShaderCreateInfo& createInfo); - constexpr MTL::Function *getFunction() const { return function; } - constexpr const char *getEntryPointName() const { - // SLang renames all entry points to main, so we dont need that - return "main"; // entryPointName.c_str(); - } - uint32 getShaderHash() const; + constexpr MTL::Function* getFunction() const { return function; } + constexpr const char* getEntryPointName() const { + // SLang renames all entry points to main, so we dont need that + return "main"; // entryPointName.c_str(); + } + uint32 getShaderHash() const; -private: - Gfx::SeShaderStageFlags stage; - PGraphics graphics; - MTL::Library* library; - MTL::Function *function; - uint32 hash; + private: + Gfx::SeShaderStageFlags stage; + PGraphics graphics; + MTL::Library* library; + MTL::Function* function; + uint32 hash; }; DEFINE_REF(Shader) template class ShaderBase : public Base, public Shader { -public: - ShaderBase(PGraphics graphics) : Shader(graphics, flags) {} - virtual ~ShaderBase() {} + public: + ShaderBase(PGraphics graphics) : Shader(graphics, flags) {} + virtual ~ShaderBase() {} }; using VertexShader = ShaderBase; using FragmentShader = ShaderBase; diff --git a/src/Engine/Graphics/Metal/Shader.mm b/src/Engine/Graphics/Metal/Shader.mm index 3296ef0..51978e7 100644 --- a/src/Engine/Graphics/Metal/Shader.mm +++ b/src/Engine/Graphics/Metal/Shader.mm @@ -29,7 +29,7 @@ void Shader::create(const ShaderCreateInfo &createInfo) { Map paramMapping; Slang::ComPtr kernelBlob = generateShader(createInfo, SLANG_METAL, paramMapping); - std::cout << (char*)kernelBlob->getBufferPointer() << std::endl; + std::cout << (char *)kernelBlob->getBufferPointer() << std::endl; hash = CRC::Calculate(kernelBlob->getBufferPointer(), kernelBlob->getBufferSize(), CRC::CRC_32()); NS::Error *error; @@ -43,8 +43,8 @@ void Shader::create(const ShaderCreateInfo &createInfo) { std::cout << error->localizedDescription()->cString(NS::ASCIIStringEncoding) << std::endl; } - function = - library->newFunction(NS::String::string(createInfo.entryPoint.c_str(), NS::ASCIIStringEncoding)); + function = library->newFunction(NS::String::string( + createInfo.entryPoint.c_str(), NS::ASCIIStringEncoding)); if (!function) { assert(false); } diff --git a/src/Engine/Graphics/Metal/Texture.h b/src/Engine/Graphics/Metal/Texture.h index 81814b1..24c458c 100644 --- a/src/Engine/Graphics/Metal/Texture.h +++ b/src/Engine/Graphics/Metal/Texture.h @@ -1,62 +1,33 @@ #pragma once -#include "Graphics/Texture.h" #include "Graphics.h" +#include "Graphics/Texture.h" -namespace Seele -{ -namespace Metal -{ -class TextureBase -{ -public: - TextureBase(PGraphics graphics, MTL::TextureType type, const TextureCreateInfo& createInfo, Gfx::QueueType& owner, MTL::Texture* existingImage = nullptr); + +namespace Seele { +namespace Metal { +class TextureBase { + public: + TextureBase(PGraphics graphics, MTL::TextureType type, const TextureCreateInfo& createInfo, Gfx::QueueType& owner, + MTL::Texture* existingImage = nullptr); virtual ~TextureBase(); - uint32 getWidth() const - { - return width; - } - uint32 getHeight() const - { - return height; - } - uint32 getDepth() const - { - return depth; - } - constexpr MTL::Texture* getTexture() const - { - return texture; - } - constexpr Gfx::SeImageLayout getLayout() const - { - return layout; - } - void setLayout(Gfx::SeImageLayout val) - { - layout = val; - } - constexpr Gfx::SeFormat getFormat() const - { - return format; - } - constexpr Gfx::SeSampleCountFlags getNumSamples() const - { - return samples; - } - constexpr uint32 getMipLevels() const - { - return mipLevels; - } + uint32 getWidth() const { return width; } + uint32 getHeight() const { return height; } + uint32 getDepth() const { return depth; } + constexpr MTL::Texture* getTexture() const { return texture; } + constexpr Gfx::SeImageLayout getLayout() const { return layout; } + void setLayout(Gfx::SeImageLayout val) { layout = val; } + constexpr Gfx::SeFormat getFormat() const { return format; } + constexpr Gfx::SeSampleCountFlags getNumSamples() const { return samples; } + constexpr uint32 getMipLevels() const { return mipLevels; } void executeOwnershipBarrier(Gfx::QueueType newOwner) { currentOwner = newOwner; } - void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage); - void changeLayout(Gfx::SeImageLayout newLayout, - Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage); + void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage); + void changeLayout(Gfx::SeImageLayout newLayout, Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage); void download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer); -protected: - //Updates via reference + protected: + // Updates via reference Gfx::QueueType& currentOwner; PGraphics graphics; uint32 width; @@ -75,128 +46,68 @@ protected: friend class Graphics; }; DEFINE_REF(TextureBase) -class Texture2D : public Gfx::Texture2D, public TextureBase -{ -public: +class Texture2D : public Gfx::Texture2D, public TextureBase { + public: Texture2D(PGraphics graphics, const TextureCreateInfo& createInfo, MTL::Texture* exisitingTexture = nullptr); virtual ~Texture2D(); - virtual uint32 getWidth() const override - { - return width; - } - virtual uint32 getHeight() const override - { - return height; - } - virtual uint32 getDepth() const override - { - return depth; - } - virtual Gfx::SeFormat getFormat() const override - { - return format; - } - virtual Gfx::SeSampleCountFlags getNumSamples() const override - { - return samples; - } - virtual uint32 getMipLevels() const override - { - return mipLevels; - } - virtual void changeLayout(Gfx::SeImageLayout newLayout, - Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; + virtual uint32 getWidth() const override { return width; } + virtual uint32 getHeight() const override { return height; } + virtual uint32 getDepth() const override { return depth; } + virtual Gfx::SeFormat getFormat() const override { return format; } + virtual Gfx::SeSampleCountFlags getNumSamples() const override { return samples; } + virtual uint32 getMipLevels() const override { return mipLevels; } + virtual void changeLayout(Gfx::SeImageLayout newLayout, Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; virtual void download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) override; -protected: + protected: // Inherited via QueueOwnedResource virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; - virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; + virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) override; }; DEFINE_REF(Texture2D) -class Texture3D : public Gfx::Texture3D, public TextureBase -{ -public: +class Texture3D : public Gfx::Texture3D, public TextureBase { + public: Texture3D(PGraphics graphics, const TextureCreateInfo& createInfo); virtual ~Texture3D(); - virtual uint32 getWidth() const override - { - return width; - } - virtual uint32 getHeight() const override - { - return height; - } - virtual uint32 getDepth() const override - { - return depth; - } - virtual Gfx::SeFormat getFormat() const override - { - return format; - } - virtual Gfx::SeSampleCountFlags getNumSamples() const override - { - return samples; - } - virtual uint32 getMipLevels() const override - { - return mipLevels; - } - virtual void changeLayout(Gfx::SeImageLayout newLayout, - Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; + virtual uint32 getWidth() const override { return width; } + virtual uint32 getHeight() const override { return height; } + virtual uint32 getDepth() const override { return depth; } + virtual Gfx::SeFormat getFormat() const override { return format; } + virtual Gfx::SeSampleCountFlags getNumSamples() const override { return samples; } + virtual uint32 getMipLevels() const override { return mipLevels; } + virtual void changeLayout(Gfx::SeImageLayout newLayout, Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; virtual void download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) override; -protected: + protected: // Inherited via QueueOwnedResource virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; - virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; - + virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) override; }; DEFINE_REF(Texture3D) -class TextureCube : public Gfx::TextureCube, TextureBase -{ -public: +class TextureCube : public Gfx::TextureCube, TextureBase { + public: TextureCube(PGraphics graphics, const TextureCreateInfo& createInfo); virtual ~TextureCube(); - virtual uint32 getWidth() const override - { - return width; - } - virtual uint32 getHeight() const override - { - return height; - } - virtual uint32 getDepth() const override - { - return depth; - } - virtual Gfx::SeFormat getFormat() const override - { - return format; - } - virtual Gfx::SeSampleCountFlags getNumSamples() const override - { - return samples; - } - virtual uint32 getMipLevels() const override - { - return mipLevels; - } - virtual void changeLayout(Gfx::SeImageLayout newLayout, - Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; + virtual uint32 getWidth() const override { return width; } + virtual uint32 getHeight() const override { return height; } + virtual uint32 getDepth() const override { return depth; } + virtual Gfx::SeFormat getFormat() const override { return format; } + virtual Gfx::SeSampleCountFlags getNumSamples() const override { return samples; } + virtual uint32 getMipLevels() const override { return mipLevels; } + virtual void changeLayout(Gfx::SeImageLayout newLayout, Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; virtual void download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) override; -protected: + + protected: // Inherited via QueueOwnedResource virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; - virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; + virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) override; }; DEFINE_REF(TextureCube) -} -} \ No newline at end of file +} // namespace Metal +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/Metal/Texture.mm b/src/Engine/Graphics/Metal/Texture.mm index a5cbac1..b268016 100644 --- a/src/Engine/Graphics/Metal/Texture.mm +++ b/src/Engine/Graphics/Metal/Texture.mm @@ -21,18 +21,16 @@ TextureBase::TextureBase(PGraphics graphics, MTL::TextureType type, ownsImage(existingImage == nullptr) { if (existingImage == nullptr) { MTL::TextureUsage mtlUsage = 0; - if(usage & Gfx::SE_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT || usage & Gfx::SE_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) - { - mtlUsage |= MTL::TextureUsageRenderTarget; + if (usage & Gfx::SE_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT || + usage & Gfx::SE_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) { + mtlUsage |= MTL::TextureUsageRenderTarget; } - if(usage & Gfx::SE_IMAGE_USAGE_SAMPLED_BIT) - { - mtlUsage |= MTL::TextureUsageShaderRead; + if (usage & Gfx::SE_IMAGE_USAGE_SAMPLED_BIT) { + mtlUsage |= MTL::TextureUsageShaderRead; + } + if (usage & Gfx::SE_IMAGE_USAGE_STORAGE_BIT) { + mtlUsage |= MTL::TextureUsageShaderWrite; } - if(usage & Gfx::SE_IMAGE_USAGE_STORAGE_BIT) - { - mtlUsage |= MTL::TextureUsageShaderWrite; - } MTL::TextureDescriptor *descriptor = MTL::TextureDescriptor::alloc()->init(); descriptor->setPixelFormat(cast(format)); @@ -44,16 +42,17 @@ TextureBase::TextureBase(PGraphics graphics, MTL::TextureType type, descriptor->setTextureType(type); descriptor->setSampleCount(samples); descriptor->setUsage(mtlUsage); - + texture = graphics->getDevice()->newTexture(descriptor); descriptor->release(); } -// if(createInfo.sourceData.data != nullptr) -// { -// MTL::Region region(0, 0, 0, width, height, depth); -// texture->replaceRegion(region, 0, createInfo.sourceData.data, createInfo.sourceData.size / (depth * height)); -// } + // if(createInfo.sourceData.data != nullptr) + // { + // MTL::Region region(0, 0, 0, width, height, depth); + // texture->replaceRegion(region, 0, createInfo.sourceData.data, + // createInfo.sourceData.size / (depth * height)); + // } } TextureBase::~TextureBase() { @@ -71,8 +70,7 @@ void TextureBase::changeLayout(Gfx::SeImageLayout, Gfx::SeAccessFlags, Gfx::SePipelineStageFlags, Gfx::SeAccessFlags, Gfx::SePipelineStageFlags) {} -void TextureBase::download(uint32, uint32, uint32, Array&) -{} +void TextureBase::download(uint32, uint32, uint32, Array &) {} Texture2D::Texture2D(PGraphics graphics, const TextureCreateInfo &createInfo, MTL::Texture *exisitingTexture) @@ -86,93 +84,95 @@ Texture2D::Texture2D(PGraphics graphics, const TextureCreateInfo &createInfo, : MTL::TextureType2D), createInfo, Gfx::Texture2D::currentOwner, exisitingTexture) {} -Texture2D::~Texture2D() -{ +Texture2D::~Texture2D() {} + +void Texture2D::changeLayout(Gfx::SeImageLayout newLayout, + Gfx::SeAccessFlags srcAccess, + Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) { + TextureBase::changeLayout(newLayout, srcAccess, srcStage, dstAccess, + dstStage); } -void Texture2D::changeLayout(Gfx::SeImageLayout newLayout, - Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) -{ - TextureBase::changeLayout(newLayout, srcAccess, srcStage, dstAccess, dstStage); +void Texture2D::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, + Array &buffer) { + TextureBase::download(mipLevel, arrayLayer, face, buffer); } -void Texture2D::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) -{ - TextureBase::download(mipLevel, arrayLayer, face, buffer); +void Texture2D::executeOwnershipBarrier(Gfx::QueueType newOwner) { + TextureBase::executeOwnershipBarrier(newOwner); } -void Texture2D::executeOwnershipBarrier(Gfx::QueueType newOwner) -{ - TextureBase::executeOwnershipBarrier(newOwner); +void Texture2D::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, + Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) { + TextureBase::executePipelineBarrier(srcAccess, srcStage, dstAccess, dstStage); } -void Texture2D::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) -{ - TextureBase::executePipelineBarrier(srcAccess, srcStage, dstAccess, dstStage); +Texture3D::Texture3D(PGraphics graphics, const TextureCreateInfo &createInfo) + : Gfx::Texture3D(graphics->getFamilyMapping(), createInfo.sourceData.owner), + TextureBase(graphics, MTL::TextureType3D, createInfo, + Gfx::Texture3D::currentOwner) {} + +Texture3D::~Texture3D() {} + +void Texture3D::changeLayout(Gfx::SeImageLayout newLayout, + Gfx::SeAccessFlags srcAccess, + Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) { + TextureBase::changeLayout(newLayout, srcAccess, srcStage, dstAccess, + dstStage); } -Texture3D::Texture3D(PGraphics graphics, const TextureCreateInfo& createInfo) - : Gfx::Texture3D(graphics->getFamilyMapping(), createInfo.sourceData.owner) - , TextureBase(graphics, MTL::TextureType3D, createInfo, Gfx::Texture3D::currentOwner) {} - - -Texture3D::~Texture3D() -{ +void Texture3D::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, + Array &buffer) { + TextureBase::download(mipLevel, arrayLayer, face, buffer); +} +void Texture3D::executeOwnershipBarrier(Gfx::QueueType newOwner) { + TextureBase::executeOwnershipBarrier(newOwner); } -void Texture3D::changeLayout(Gfx::SeImageLayout newLayout, - Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) -{ - TextureBase::changeLayout(newLayout, srcAccess, srcStage, dstAccess, dstStage); +void Texture3D::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, + Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) { + TextureBase::executePipelineBarrier(srcAccess, srcStage, dstAccess, dstStage); } -void Texture3D::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) -{ - TextureBase::download(mipLevel, arrayLayer, face, buffer); -} -void Texture3D::executeOwnershipBarrier(Gfx::QueueType newOwner) -{ - TextureBase::executeOwnershipBarrier(newOwner); +TextureCube::TextureCube(PGraphics graphics, + const TextureCreateInfo &createInfo) + : Gfx::TextureCube(graphics->getFamilyMapping(), + createInfo.sourceData.owner), + TextureBase(graphics, + createInfo.elements > 1 ? MTL::TextureTypeCubeArray + : MTL::TextureTypeCube, + createInfo, Gfx::TextureCube::currentOwner) {} + +TextureCube::~TextureCube() {} + +void TextureCube::changeLayout(Gfx::SeImageLayout newLayout, + Gfx::SeAccessFlags srcAccess, + Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) { + TextureBase::changeLayout(newLayout, srcAccess, srcStage, dstAccess, + dstStage); } -void Texture3D::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) -{ - TextureBase::executePipelineBarrier(srcAccess, srcStage, dstAccess, dstStage); +void TextureCube::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, + Array &buffer) { + TextureBase::download(mipLevel, arrayLayer, face, buffer); +} +void TextureCube::executeOwnershipBarrier(Gfx::QueueType newOwner) { + TextureBase::executeOwnershipBarrier(newOwner); } -TextureCube::TextureCube(PGraphics graphics, const TextureCreateInfo& createInfo) - : Gfx::TextureCube(graphics->getFamilyMapping(), createInfo.sourceData.owner) - , TextureBase(graphics, createInfo.elements > 1 ? MTL::TextureTypeCubeArray : MTL::TextureTypeCube, - createInfo, Gfx::TextureCube::currentOwner) -{ -} - -TextureCube::~TextureCube() -{ -} - -void TextureCube::changeLayout(Gfx::SeImageLayout newLayout, - Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) -{ - TextureBase::changeLayout(newLayout, srcAccess, srcStage, dstAccess, dstStage); -} - -void TextureCube::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) -{ - TextureBase::download(mipLevel, arrayLayer, face, buffer); -} -void TextureCube::executeOwnershipBarrier(Gfx::QueueType newOwner) -{ - TextureBase::executeOwnershipBarrier(newOwner); -} - -void TextureCube::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) -{ - TextureBase::executePipelineBarrier(srcAccess, srcStage, dstAccess, dstStage); +void TextureCube::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, + Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) { + TextureBase::executePipelineBarrier(srcAccess, srcStage, dstAccess, dstStage); } diff --git a/src/Engine/Graphics/Metal/Window.h b/src/Engine/Graphics/Metal/Window.h index 42c18d6..bdabb44 100644 --- a/src/Engine/Graphics/Metal/Window.h +++ b/src/Engine/Graphics/Metal/Window.h @@ -17,60 +17,60 @@ namespace Seele { namespace Metal { class Window : public Gfx::Window { -public: - Window(PGraphics graphics, const WindowCreateInfo& createInfo); - virtual ~Window(); - virtual void pollInput() override; - virtual void beginFrame() override; - virtual void endFrame() override; - virtual Gfx::PTexture2D getBackBuffer() const override; - virtual void onWindowCloseEvent() override; - virtual void setKeyCallback(std::function callback) override; - virtual void setMouseMoveCallback(std::function callback) override; - virtual void setMouseButtonCallback(std::function callback) override; - virtual void setScrollCallback(std::function callback) override; - virtual void setFileCallback(std::function callback) override; - virtual void setCloseCallback(std::function callback) override; - virtual void setResizeCallback(std::function callback) override; + public: + Window(PGraphics graphics, const WindowCreateInfo& createInfo); + virtual ~Window(); + virtual void pollInput() override; + virtual void beginFrame() override; + virtual void endFrame() override; + virtual Gfx::PTexture2D getBackBuffer() const override; + virtual void onWindowCloseEvent() override; + virtual void setKeyCallback(std::function callback) override; + virtual void setMouseMoveCallback(std::function callback) override; + virtual void setMouseButtonCallback(std::function callback) override; + virtual void setScrollCallback(std::function callback) override; + virtual void setFileCallback(std::function callback) override; + virtual void setCloseCallback(std::function callback) override; + virtual void setResizeCallback(std::function callback) override; - void keyPress(KeyCode code, InputAction action, KeyModifier modifier); - void mouseMove(double x, double y); - void mouseButton(MouseButton button, InputAction action, KeyModifier modifier); - void scroll(double x, double y); - void fileDrop(int num, const char** files); - void close(); - void resize(int width, int height); + void keyPress(KeyCode code, InputAction action, KeyModifier modifier); + void mouseMove(double x, double y); + void mouseButton(MouseButton button, InputAction action, KeyModifier modifier); + void scroll(double x, double y); + void fileDrop(int num, const char** files); + void close(); + void resize(int width, int height); -private: - void createBackBuffer(); + private: + void createBackBuffer(); - PGraphics graphics; - WindowCreateInfo preferences; - GLFWwindow* windowHandle; - NSWindow* metalWindow; - CAMetalLayer* metalLayer; - CA::MetalDrawable* drawable; - OTexture2D backBuffer; + PGraphics graphics; + WindowCreateInfo preferences; + GLFWwindow* windowHandle; + NSWindow* metalWindow; + CAMetalLayer* metalLayer; + CA::MetalDrawable* drawable; + OTexture2D backBuffer; - std::function keyCallback; - std::function mouseMoveCallback; - std::function mouseButtonCallback; - std::function scrollCallback; - std::function fileCallback; - std::function closeCallback; - std::function resizeCallback; + std::function keyCallback; + std::function mouseMoveCallback; + std::function mouseButtonCallback; + std::function scrollCallback; + std::function fileCallback; + std::function closeCallback; + std::function resizeCallback; }; DEFINE_REF(Window); class Viewport : public Gfx::Viewport { -public: - Viewport(PWindow owner, const ViewportCreateInfo& createInfo); - virtual ~Viewport(); - constexpr MTL::Viewport getHandle() const { return viewport; } - virtual void resize(uint32 newX, uint32 newY); - virtual void move(uint32 newOffset, uint32 newOffsetY); + public: + Viewport(PWindow owner, const ViewportCreateInfo& createInfo); + virtual ~Viewport(); + constexpr MTL::Viewport getHandle() const { return viewport; } + virtual void resize(uint32 newX, uint32 newY); + virtual void move(uint32 newOffset, uint32 newOffsetY); -private: - MTL::Viewport viewport; + private: + MTL::Viewport viewport; }; } // namespace Metal } // namespace Seele diff --git a/src/Engine/Graphics/Metal/Window.mm b/src/Engine/Graphics/Metal/Window.mm index 834333e..3755b0d 100644 --- a/src/Engine/Graphics/Metal/Window.mm +++ b/src/Engine/Graphics/Metal/Window.mm @@ -20,51 +20,58 @@ double Gfx::getCurrentFrameDelta() { return currentFrameDelta; } uint32 currentFrameIndex = 0; uint32 Gfx::getCurrentFrameIndex() { return currentFrameIndex; } -void glfwKeyCallback(GLFWwindow* handle, int key, int, int action, int modifier) { +void glfwKeyCallback(GLFWwindow *handle, int key, int, int action, + int modifier) { if (key == -1) { return; } - Window* window = (Window*)glfwGetWindowUserPointer(handle); + Window *window = (Window *)glfwGetWindowUserPointer(handle); window->keyPress((KeyCode)key, (InputAction)action, (KeyModifier)modifier); } -void glfwMouseMoveCallback(GLFWwindow* handle, double xpos, double ypos) { - Window* window = (Window*)glfwGetWindowUserPointer(handle); +void glfwMouseMoveCallback(GLFWwindow *handle, double xpos, double ypos) { + Window *window = (Window *)glfwGetWindowUserPointer(handle); window->mouseMove(xpos, ypos); } -void glfwMouseButtonCallback(GLFWwindow* handle, int button, int action, int modifier) { - Window* window = (Window*)glfwGetWindowUserPointer(handle); - window->mouseButton((MouseButton)button, (InputAction)action, (KeyModifier)modifier); +void glfwMouseButtonCallback(GLFWwindow *handle, int button, int action, + int modifier) { + Window *window = (Window *)glfwGetWindowUserPointer(handle); + window->mouseButton((MouseButton)button, (InputAction)action, + (KeyModifier)modifier); } -void glfwScrollCallback(GLFWwindow* handle, double xoffset, double yoffset) { - Window* window = (Window*)glfwGetWindowUserPointer(handle); +void glfwScrollCallback(GLFWwindow *handle, double xoffset, double yoffset) { + Window *window = (Window *)glfwGetWindowUserPointer(handle); window->scroll(xoffset, yoffset); } -void glfwFileCallback(GLFWwindow* handle, int count, const char** paths) { - Window* window = (Window*)glfwGetWindowUserPointer(handle); +void glfwFileCallback(GLFWwindow *handle, int count, const char **paths) { + Window *window = (Window *)glfwGetWindowUserPointer(handle); window->fileDrop(count, paths); } -void glfwCloseCallback(GLFWwindow* handle) { - Window* window = (Window*)glfwGetWindowUserPointer(handle); +void glfwCloseCallback(GLFWwindow *handle) { + Window *window = (Window *)glfwGetWindowUserPointer(handle); window->close(); } -void glfwFramebufferResizeCallback(GLFWwindow* handle, int width, int height) { - Window* window = (Window*)glfwGetWindowUserPointer(handle); +void glfwFramebufferResizeCallback(GLFWwindow *handle, int width, int height) { + Window *window = (Window *)glfwGetWindowUserPointer(handle); window->resize(width, height); } -Window::Window(PGraphics graphics, const WindowCreateInfo& createInfo) : graphics(graphics), preferences(createInfo) { - glfwSetErrorCallback([](int, const char* description) { std::cout << description << std::endl; }); +Window::Window(PGraphics graphics, const WindowCreateInfo &createInfo) + : graphics(graphics), preferences(createInfo) { + glfwSetErrorCallback([](int, const char *description) { + std::cout << description << std::endl; + }); float xscale = 1, yscale = 1; glfwGetMonitorContentScale(glfwGetPrimaryMonitor(), &xscale, &yscale); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - GLFWwindow* handle = - glfwCreateWindow(createInfo.width / xscale, createInfo.height / yscale, createInfo.title, nullptr, nullptr); + GLFWwindow *handle = + glfwCreateWindow(createInfo.width / xscale, createInfo.height / yscale, + createInfo.title, nullptr, nullptr); windowHandle = handle; glfwSetWindowUserPointer(handle, this); @@ -89,12 +96,14 @@ Window::Window(PGraphics graphics, const WindowCreateInfo& createInfo) : graphic metalWindow.contentView.wantsLayer = YES; } -Window::~Window() { glfwDestroyWindow(static_cast(windowHandle)); } +Window::~Window() { + glfwDestroyWindow(static_cast(windowHandle)); +} void Window::pollInput() { glfwPollEvents(); } void Window::beginFrame() { - drawable = (__bridge CA::MetalDrawable*)[metalLayer nextDrawable]; + drawable = (__bridge CA::MetalDrawable *)[metalLayer nextDrawable]; createBackBuffer(); } @@ -108,33 +117,51 @@ void Window::onWindowCloseEvent() {} Gfx::PTexture2D Window::getBackBuffer() const { return PTexture2D(backBuffer); } -void Window::setKeyCallback(std::function callback) { keyCallback = callback; } +void Window::setKeyCallback( + std::function callback) { + keyCallback = callback; +} -void Window::setMouseMoveCallback(std::function callback) { mouseMoveCallback = callback; } +void Window::setMouseMoveCallback( + std::function callback) { + mouseMoveCallback = callback; +} -void Window::setMouseButtonCallback(std::function callback) { +void Window::setMouseButtonCallback( + std::function callback) { mouseButtonCallback = callback; } -void Window::setScrollCallback(std::function callback) { scrollCallback = callback; } +void Window::setScrollCallback(std::function callback) { + scrollCallback = callback; +} -void Window::setFileCallback(std::function callback) { fileCallback = callback; } +void Window::setFileCallback(std::function callback) { + fileCallback = callback; +} -void Window::setCloseCallback(std::function callback) { closeCallback = callback; } +void Window::setCloseCallback(std::function callback) { + closeCallback = callback; +} -void Window::setResizeCallback(std::function callback) { resizeCallback = callback; } +void Window::setResizeCallback(std::function callback) { + resizeCallback = callback; +} -void Window::keyPress(KeyCode code, InputAction action, KeyModifier modifier) { keyCallback(code, action, modifier); } +void Window::keyPress(KeyCode code, InputAction action, KeyModifier modifier) { + keyCallback(code, action, modifier); +} void Window::mouseMove(double x, double y) { mouseMoveCallback(x, y); } -void Window::mouseButton(MouseButton button, InputAction action, KeyModifier modifier) { +void Window::mouseButton(MouseButton button, InputAction action, + KeyModifier modifier) { mouseButtonCallback(button, action, modifier); } void Window::scroll(double x, double y) { scrollCallback(x, y); } -void Window::fileDrop(int num, const char** files) { fileCallback(num, files); } +void Window::fileDrop(int num, const char **files) { fileCallback(num, files); } void Window::close() { closeCallback(); } @@ -149,28 +176,31 @@ void Window::resize(int width, int height) { framebufferWidth = width; framebufferHeight = height; // Deallocate the textures if they have been created - drawable = (__bridge CA::MetalDrawable*)[[metalLayer nextDrawable] autorelease]; + drawable = + (__bridge CA::MetalDrawable *)[[metalLayer nextDrawable] autorelease]; createBackBuffer(); resizeCallback(width, height); } void Window::createBackBuffer() { - MTL::Texture* buf = drawable->texture(); - backBuffer = new Texture2D(graphics, - TextureCreateInfo{ - .width = static_cast(buf->width()), - .height = static_cast(buf->height()), - .depth = static_cast(buf->depth()), - .elements = static_cast(buf->arrayLength()), - .mipLevels = static_cast(buf->mipmapLevelCount()), - .format = cast(buf->pixelFormat()), - .usage = MTL::TextureUsageRenderTarget, - .samples = static_cast(buf->sampleCount()), - }, - buf); + MTL::Texture *buf = drawable->texture(); + backBuffer = new Texture2D( + graphics, + TextureCreateInfo{ + .width = static_cast(buf->width()), + .height = static_cast(buf->height()), + .depth = static_cast(buf->depth()), + .elements = static_cast(buf->arrayLength()), + .mipLevels = static_cast(buf->mipmapLevelCount()), + .format = cast(buf->pixelFormat()), + .usage = MTL::TextureUsageRenderTarget, + .samples = static_cast(buf->sampleCount()), + }, + buf); } -Viewport::Viewport(PWindow owner, const ViewportCreateInfo& createInfo) : Gfx::Viewport(owner, createInfo) { +Viewport::Viewport(PWindow owner, const ViewportCreateInfo &createInfo) + : Gfx::Viewport(owner, createInfo) { viewport.width = sizeX; viewport.height = sizeY; viewport.originX = offsetX; diff --git a/src/Engine/Graphics/Pipeline.cpp b/src/Engine/Graphics/Pipeline.cpp index e8a0728..5609f27 100644 --- a/src/Engine/Graphics/Pipeline.cpp +++ b/src/Engine/Graphics/Pipeline.cpp @@ -3,39 +3,18 @@ using namespace Seele; using namespace Seele::Gfx; -VertexInput::VertexInput(VertexInputStateCreateInfo createInfo) - : createInfo(createInfo) -{ -} +VertexInput::VertexInput(VertexInputStateCreateInfo createInfo) : createInfo(createInfo) {} -VertexInput::~VertexInput() -{ -} +VertexInput::~VertexInput() {} -GraphicsPipeline::GraphicsPipeline(PPipelineLayout layout) - : layout(layout) -{ -} +GraphicsPipeline::GraphicsPipeline(PPipelineLayout layout) : layout(layout) {} -GraphicsPipeline::~GraphicsPipeline() -{ -} +GraphicsPipeline::~GraphicsPipeline() {} -PPipelineLayout GraphicsPipeline::getPipelineLayout() const -{ - return layout; -} +PPipelineLayout GraphicsPipeline::getPipelineLayout() const { return layout; } -ComputePipeline::ComputePipeline(PPipelineLayout layout) - : layout(layout) -{ -} +ComputePipeline::ComputePipeline(PPipelineLayout layout) : layout(layout) {} -ComputePipeline::~ComputePipeline() -{ -} +ComputePipeline::~ComputePipeline() {} -PPipelineLayout ComputePipeline::getPipelineLayout() const -{ - return layout; -} +PPipelineLayout ComputePipeline::getPipelineLayout() const { return layout; } diff --git a/src/Engine/Graphics/Pipeline.h b/src/Engine/Graphics/Pipeline.h index cbd3165..cb21583 100644 --- a/src/Engine/Graphics/Pipeline.h +++ b/src/Engine/Graphics/Pipeline.h @@ -1,40 +1,39 @@ #pragma once -#include "Enums.h" #include "Descriptor.h" +#include "Enums.h" -namespace Seele -{ -namespace Gfx -{ -class VertexInput -{ -public: + +namespace Seele { +namespace Gfx { +class VertexInput { + public: VertexInput(VertexInputStateCreateInfo createInfo); virtual ~VertexInput(); const VertexInputStateCreateInfo& getInfo() const { return createInfo; } -private: + + private: VertexInputStateCreateInfo createInfo; }; -class GraphicsPipeline -{ -public: +class GraphicsPipeline { + public: GraphicsPipeline(PPipelineLayout layout); virtual ~GraphicsPipeline(); PPipelineLayout getPipelineLayout() const; -protected: + + protected: PPipelineLayout layout; }; DEFINE_REF(GraphicsPipeline) -class ComputePipeline -{ -public: +class ComputePipeline { + public: ComputePipeline(PPipelineLayout layout); virtual ~ComputePipeline(); PPipelineLayout getPipelineLayout() const; -protected: + + protected: PPipelineLayout layout; }; DEFINE_REF(ComputePipeline) -} -} +} // namespace Gfx +} // namespace Seele diff --git a/src/Engine/Graphics/RayTracing.cpp b/src/Engine/Graphics/RayTracing.cpp index f542472..ac5edf9 100644 --- a/src/Engine/Graphics/RayTracing.cpp +++ b/src/Engine/Graphics/RayTracing.cpp @@ -2,14 +2,10 @@ using namespace Seele::Gfx; -BottomLevelAS::BottomLevelAS() -{} +BottomLevelAS::BottomLevelAS() {} -BottomLevelAS::~BottomLevelAS() -{} +BottomLevelAS::~BottomLevelAS() {} -TopLevelAS::TopLevelAS() -{} +TopLevelAS::TopLevelAS() {} -TopLevelAS::~TopLevelAS() -{} \ No newline at end of file +TopLevelAS::~TopLevelAS() {} \ No newline at end of file diff --git a/src/Engine/Graphics/RayTracing.h b/src/Engine/Graphics/RayTracing.h index 274f140..682aca4 100644 --- a/src/Engine/Graphics/RayTracing.h +++ b/src/Engine/Graphics/RayTracing.h @@ -1,25 +1,23 @@ #pragma once #include "Resources.h" -namespace Seele -{ -namespace Gfx -{ -class BottomLevelAS -{ -public: +namespace Seele { +namespace Gfx { +class BottomLevelAS { + public: BottomLevelAS(); ~BottomLevelAS(); -private: + + private: }; DEFINE_REF(BottomLevelAS) -class TopLevelAS -{ -public: +class TopLevelAS { + public: TopLevelAS(); ~TopLevelAS(); -private: + + private: }; DEFINE_REF(TopLevelAS) -} -} \ No newline at end of file +} // namespace Gfx +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/RenderPass/BasePass.cpp b/src/Engine/Graphics/RenderPass/BasePass.cpp index 2a72b81..08db7bb 100644 --- a/src/Engine/Graphics/RenderPass/BasePass.cpp +++ b/src/Engine/Graphics/RenderPass/BasePass.cpp @@ -1,26 +1,25 @@ #include "BasePass.h" +#include "Actor/CameraActor.h" +#include "Component/Camera.h" +#include "Component/Mesh.h" +#include "Graphics/Command.h" +#include "Graphics/Descriptor.h" #include "Graphics/Enums.h" #include "Graphics/Graphics.h" #include "Graphics/Initializer.h" #include "Graphics/Shader.h" -#include "Window/Window.h" -#include "Component/Camera.h" -#include "Component/Mesh.h" -#include "Actor/CameraActor.h" +#include "Graphics/StaticMeshVertexData.h" +#include "Material/MaterialInstance.h" #include "Math/Vector.h" #include "RenderGraph.h" -#include "Material/MaterialInstance.h" -#include "Graphics/Descriptor.h" -#include "Graphics/Command.h" -#include "Graphics/StaticMeshVertexData.h" +#include "Window/Window.h" + using namespace Seele; extern bool useViewCulling; -BasePass::BasePass(Gfx::PGraphics graphics, PScene scene) - : RenderPass(graphics, scene) -{ +BasePass::BasePass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics, scene) { basePassLayout = graphics->createPipelineLayout("BasePassLayout"); basePassLayout->addDescriptorLayout(viewParamsLayout); @@ -28,9 +27,15 @@ BasePass::BasePass(Gfx::PGraphics graphics, PScene scene) lightCullingLayout = graphics->createDescriptorLayout("pLightCullingData"); // oLightIndexList - lightCullingLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 0, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, }); + lightCullingLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 0, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, + }); // oLightGrid - lightCullingLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 1, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_IMAGE, }); + lightCullingLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 1, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_IMAGE, + }); lightCullingLayout->create(); basePassLayout->addDescriptorLayout(lightCullingLayout); @@ -38,44 +43,38 @@ BasePass::BasePass(Gfx::PGraphics graphics, PScene scene) .stageFlags = Gfx::SE_SHADER_STAGE_TASK_BIT_EXT | Gfx::SE_SHADER_STAGE_VERTEX_BIT, .offset = 0, .size = sizeof(VertexData::DrawCallOffsets), - }); + }); - if (graphics->supportMeshShading()) - { - graphics->getShaderCompiler()->registerRenderPass("BasePass", Gfx::PassConfig { - .baseLayout = basePassLayout, - .taskFile = "DrawListTask", - .mainFile = "DrawListMesh", - .fragmentFile = "BasePass", - .hasFragmentShader = true, - .useMeshShading = true, - .hasTaskShader = true, - .useMaterial = true, - .useVisibility = false, - }); - } - else - { - graphics->getShaderCompiler()->registerRenderPass("BasePass", Gfx::PassConfig { - .baseLayout = basePassLayout, - .taskFile = "", - .mainFile = "LegacyPass", - .fragmentFile = "BasePass", - .hasFragmentShader = true, - .useMeshShading = false, - .hasTaskShader = false, - .useMaterial = true, - .useVisibility = false, - }); + if (graphics->supportMeshShading()) { + graphics->getShaderCompiler()->registerRenderPass("BasePass", Gfx::PassConfig{ + .baseLayout = basePassLayout, + .taskFile = "DrawListTask", + .mainFile = "DrawListMesh", + .fragmentFile = "BasePass", + .hasFragmentShader = true, + .useMeshShading = true, + .hasTaskShader = true, + .useMaterial = true, + .useVisibility = false, + }); + } else { + graphics->getShaderCompiler()->registerRenderPass("BasePass", Gfx::PassConfig{ + .baseLayout = basePassLayout, + .taskFile = "", + .mainFile = "LegacyPass", + .fragmentFile = "BasePass", + .hasFragmentShader = true, + .useMeshShading = false, + .hasTaskShader = false, + .useMaterial = true, + .useVisibility = false, + }); } } -BasePass::~BasePass() -{ -} +BasePass::~BasePass() {} -void BasePass::beginFrame(const Component::Camera& cam) -{ +void BasePass::beginFrame(const Component::Camera& cam) { RenderPass::beginFrame(cam); lightCullingLayout->reset(); @@ -83,8 +82,7 @@ void BasePass::beginFrame(const Component::Camera& cam) transparentCulling = lightCullingLayout->allocateDescriptorSet(); } -void BasePass::render() -{ +void BasePass::render() { opaqueCulling->updateBuffer(0, oLightIndexList); opaqueCulling->updateTexture(1, oLightGrid); transparentCulling->updateBuffer(0, tLightIndexList); @@ -97,14 +95,12 @@ void BasePass::render() Gfx::ShaderPermutation permutation = graphics->getShaderCompiler()->getTemplate("BasePass"); permutation.setViewCulling(useViewCulling); - for (VertexData* vertexData : VertexData::getList()) - { + for (VertexData* vertexData : VertexData::getList()) { vertexData->getInstanceDataSet()->updateBuffer(6, cullingBuffer); vertexData->getInstanceDataSet()->writeChanges(); permutation.setVertexData(vertexData->getTypeName()); const auto& materials = vertexData->getMaterialData(); - for (const auto& materialData : materials) - { + for (const auto& materialData : materials) { // material not used for any active meshes, skip if (materialData.instances.size() == 0) continue; @@ -124,43 +120,46 @@ void BasePass::render() const Gfx::ShaderCollection* collection = graphics->getShaderCompiler()->findShaders(id); assert(collection != nullptr); - if (graphics->supportMeshShading()) - { + if (graphics->supportMeshShading()) { Gfx::MeshPipelineCreateInfo pipelineInfo = { .taskShader = collection->taskShader, .meshShader = collection->meshShader, .fragmentShader = collection->fragmentShader, .renderPass = renderPass, .pipelineLayout = collection->pipelineLayout, - .multisampleState = { - .samples = viewport->getSamples(), - }, - .depthStencilState = { - .depthCompareOp = Gfx::SE_COMPARE_OP_GREATER_OR_EQUAL, - }, - .colorBlend = { - .attachmentCount = 1, - }, + .multisampleState = + { + .samples = viewport->getSamples(), + }, + .depthStencilState = + { + .depthCompareOp = Gfx::SE_COMPARE_OP_GREATER_OR_EQUAL, + }, + .colorBlend = + { + .attachmentCount = 1, + }, }; Gfx::PGraphicsPipeline pipeline = graphics->createGraphicsPipeline(std::move(pipelineInfo)); command->bindPipeline(pipeline); - } - else - { + } else { Gfx::LegacyPipelineCreateInfo pipelineInfo = { .vertexShader = collection->vertexShader, .fragmentShader = collection->fragmentShader, .renderPass = renderPass, .pipelineLayout = collection->pipelineLayout, - .multisampleState = { - .samples = viewport->getSamples(), - }, - .depthStencilState = { - .depthCompareOp = Gfx::SE_COMPARE_OP_GREATER_OR_EQUAL, - }, - .colorBlend = { - .attachmentCount = 1, - }, + .multisampleState = + { + .samples = viewport->getSamples(), + }, + .depthStencilState = + { + .depthCompareOp = Gfx::SE_COMPARE_OP_GREATER_OR_EQUAL, + }, + .colorBlend = + { + .attachmentCount = 1, + }, }; Gfx::PGraphicsPipeline pipeline = graphics->createGraphicsPipeline(std::move(pipelineInfo)); command->bindPipeline(pipeline); @@ -170,21 +169,18 @@ void BasePass::render() command->bindDescriptor(vertexData->getInstanceDataSet()); command->bindDescriptor(scene->getLightEnvironment()->getDescriptorSet()); command->bindDescriptor(opaqueCulling); - for (const auto& drawCall : materialData.instances) - { + for (const auto& drawCall : materialData.instances) { command->bindDescriptor(drawCall.materialInstance->getDescriptorSet()); - command->pushConstants(Gfx::SE_SHADER_STAGE_TASK_BIT_EXT | Gfx::SE_SHADER_STAGE_VERTEX_BIT, 0, sizeof(VertexData::DrawCallOffsets), &drawCall.offsets); - if (graphics->supportMeshShading()) - { + command->pushConstants(Gfx::SE_SHADER_STAGE_TASK_BIT_EXT | Gfx::SE_SHADER_STAGE_VERTEX_BIT, 0, + sizeof(VertexData::DrawCallOffsets), &drawCall.offsets); + if (graphics->supportMeshShading()) { command->drawMesh(drawCall.instanceMeshData.size(), 1, 1); - } - else - { + } else { command->bindIndexBuffer(vertexData->getIndexBuffer()); - for (const auto& meshData : drawCall.instanceMeshData) - { + for (const auto& meshData : drawCall.instanceMeshData) { // all meshlets of a mesh share the same indices offset - command->drawIndexed(meshData.numIndices, 1, meshData.firstIndex, vertexData->getIndicesOffset(meshData.meshletOffset), 0); + command->drawIndexed(meshData.numIndices, 1, meshData.firstIndex, + vertexData->getIndicesOffset(meshData.meshletOffset), 0); } } } @@ -195,14 +191,14 @@ void BasePass::render() graphics->executeCommands(std::move(commands)); graphics->endRenderPass(); // Sync color write with next pass/swapchain present - //colorAttachment.getTexture()->pipelineBarrier( + // colorAttachment.getTexture()->pipelineBarrier( // Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT //); // Sync depth with next pass/next frame - //depthAttachment.getTexture()->pipelineBarrier( + // depthAttachment.getTexture()->pipelineBarrier( // Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, // Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, // Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, @@ -210,20 +206,15 @@ void BasePass::render() //); } -void BasePass::endFrame() -{ -} +void BasePass::endFrame() {} -void BasePass::publishOutputs() -{ - colorAttachment = Gfx::RenderTargetAttachment(viewport, - Gfx::SE_IMAGE_LAYOUT_UNDEFINED, Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - Gfx::SE_ATTACHMENT_LOAD_OP_CLEAR, Gfx::SE_ATTACHMENT_STORE_OP_STORE); +void BasePass::publishOutputs() { + colorAttachment = Gfx::RenderTargetAttachment(viewport, Gfx::SE_IMAGE_LAYOUT_UNDEFINED, Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + Gfx::SE_ATTACHMENT_LOAD_OP_CLEAR, Gfx::SE_ATTACHMENT_STORE_OP_STORE); resources->registerRenderPassOutput("BASEPASS_COLOR", colorAttachment); } -void BasePass::createRenderPass() -{ +void BasePass::createRenderPass() { cullingBuffer = resources->requestBuffer("CULLINGBUFFER"); depthAttachment = resources->requestRenderTarget("DEPTHPREPASS_DEPTH"); @@ -231,7 +222,7 @@ void BasePass::createRenderPass() depthAttachment.setInitialLayout(Gfx::SE_IMAGE_LAYOUT_GENERAL); depthAttachment.setFinalLayout(Gfx::SE_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); Gfx::RenderTargetLayout layout = Gfx::RenderTargetLayout{ - .colorAttachments = { colorAttachment }, + .colorAttachments = {colorAttachment}, .depthAttachment = depthAttachment, }; Array dependency = { @@ -240,16 +231,20 @@ void BasePass::createRenderPass() .dstSubpass = 0, .srcStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, .dstStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, - .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, - .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, }, { .srcSubpass = 0, .dstSubpass = ~0U, .srcStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, .dstStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, - .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, - .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, }, }; renderPass = graphics->createRenderPass(std::move(layout), std::move(dependency), viewport); diff --git a/src/Engine/Graphics/RenderPass/BasePass.h b/src/Engine/Graphics/RenderPass/BasePass.h index 9366568..c186ab0 100644 --- a/src/Engine/Graphics/RenderPass/BasePass.h +++ b/src/Engine/Graphics/RenderPass/BasePass.h @@ -2,12 +2,10 @@ #include "MinimalEngine.h" #include "RenderPass.h" -namespace Seele -{ +namespace Seele { DECLARE_REF(CameraActor) -class BasePass : public RenderPass -{ -public: +class BasePass : public RenderPass { + public: BasePass(Gfx::PGraphics graphics, PScene scene); BasePass(BasePass&&) = default; BasePass& operator=(BasePass&&) = default; @@ -17,7 +15,8 @@ public: virtual void endFrame() override; virtual void publishOutputs() override; virtual void createRenderPass() override; -private: + + private: Gfx::RenderTargetAttachment colorAttachment; Gfx::RenderTargetAttachment depthAttachment; Gfx::RenderTargetAttachment visibilityAttachment; @@ -25,7 +24,7 @@ private: Gfx::PShaderBuffer tLightIndexList; Gfx::PTexture2D oLightGrid; Gfx::PTexture2D tLightGrid; - + Gfx::PDescriptorSet opaqueCulling; Gfx::PDescriptorSet transparentCulling; diff --git a/src/Engine/Graphics/RenderPass/CachedDepthPass.cpp b/src/Engine/Graphics/RenderPass/CachedDepthPass.cpp index d1cd368..ffc907f 100644 --- a/src/Engine/Graphics/RenderPass/CachedDepthPass.cpp +++ b/src/Engine/Graphics/RenderPass/CachedDepthPass.cpp @@ -6,9 +6,7 @@ using namespace Seele; extern bool usePositionOnly; extern bool useViewCulling; -CachedDepthPass::CachedDepthPass(Gfx::PGraphics graphics, PScene scene) - : RenderPass(graphics, scene) -{ +CachedDepthPass::CachedDepthPass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics, scene) { depthPrepassLayout = graphics->createPipelineLayout("CachedDepthLayout"); depthPrepassLayout->addDescriptorLayout(viewParamsLayout); depthPrepassLayout->addPushConstants(Gfx::SePushConstantRange{ @@ -16,55 +14,45 @@ CachedDepthPass::CachedDepthPass(Gfx::PGraphics graphics, PScene scene) .offset = 0, .size = sizeof(VertexData::DrawCallOffsets), }); - if (graphics->supportMeshShading()) - { + if (graphics->supportMeshShading()) { graphics->getShaderCompiler()->registerRenderPass("CachedDepthPass", Gfx::PassConfig{ - .baseLayout = depthPrepassLayout, - .taskFile = "DrawListTask", - .mainFile = "DrawListMesh", - .fragmentFile = "VisibilityPass", - .hasFragmentShader = true, - .useMeshShading = true, - .hasTaskShader = true, - .useMaterial = false, - .useVisibility = true, - }); - } - else - { + .baseLayout = depthPrepassLayout, + .taskFile = "DrawListTask", + .mainFile = "DrawListMesh", + .fragmentFile = "VisibilityPass", + .hasFragmentShader = true, + .useMeshShading = true, + .hasTaskShader = true, + .useMaterial = false, + .useVisibility = true, + }); + } else { graphics->getShaderCompiler()->registerRenderPass("CachedDepthPass", Gfx::PassConfig{ - .baseLayout = depthPrepassLayout, - .taskFile = "", - .mainFile = "LegacyPass", - .fragmentFile = "VisibilityPass", - .hasFragmentShader = true, - .useMeshShading = false, - .hasTaskShader = false, - .useMaterial = false, - .useVisibility = true, - }); + .baseLayout = depthPrepassLayout, + .taskFile = "", + .mainFile = "LegacyPass", + .fragmentFile = "VisibilityPass", + .hasFragmentShader = true, + .useMeshShading = false, + .hasTaskShader = false, + .useMaterial = false, + .useVisibility = true, + }); } } -CachedDepthPass::~CachedDepthPass() -{ -} +CachedDepthPass::~CachedDepthPass() {} -void CachedDepthPass::beginFrame(const Component::Camera &cam) -{ - RenderPass::beginFrame(cam); -} +void CachedDepthPass::beginFrame(const Component::Camera& cam) { RenderPass::beginFrame(cam); } -void CachedDepthPass::render() -{ +void CachedDepthPass::render() { graphics->beginRenderPass(renderPass); Array commands; Gfx::ShaderPermutation permutation = graphics->getShaderCompiler()->getTemplate("CachedDepthPass"); permutation.setPositionOnly(usePositionOnly); permutation.setViewCulling(useViewCulling); - for (VertexData *vertexData : VertexData::getList()) - { + for (VertexData* vertexData : VertexData::getList()) { permutation.setVertexData(vertexData->getTypeName()); vertexData->getInstanceDataSet()->updateBuffer(6, cullingBuffer); vertexData->getInstanceDataSet()->writeChanges(); @@ -79,45 +67,48 @@ void CachedDepthPass::render() Gfx::ORenderCommand command = graphics->createRenderCommand("DepthRender"); command->setViewport(viewport); - const Gfx::ShaderCollection *collection = graphics->getShaderCompiler()->findShaders(id); + const Gfx::ShaderCollection* collection = graphics->getShaderCompiler()->findShaders(id); assert(collection != nullptr); - if (graphics->supportMeshShading()) - { + if (graphics->supportMeshShading()) { Gfx::MeshPipelineCreateInfo pipelineInfo = { .taskShader = collection->taskShader, .meshShader = collection->meshShader, .fragmentShader = collection->fragmentShader, .renderPass = renderPass, .pipelineLayout = collection->pipelineLayout, - .multisampleState = { - .samples = viewport->getSamples(), - }, - .depthStencilState = { - .depthCompareOp = Gfx::SE_COMPARE_OP_GREATER, - }, - .colorBlend = { - .attachmentCount = 1, - }, + .multisampleState = + { + .samples = viewport->getSamples(), + }, + .depthStencilState = + { + .depthCompareOp = Gfx::SE_COMPARE_OP_GREATER, + }, + .colorBlend = + { + .attachmentCount = 1, + }, }; Gfx::PGraphicsPipeline pipeline = graphics->createGraphicsPipeline(std::move(pipelineInfo)); command->bindPipeline(pipeline); - } - else - { + } else { Gfx::LegacyPipelineCreateInfo pipelineInfo = { .vertexShader = collection->vertexShader, .fragmentShader = collection->fragmentShader, .renderPass = renderPass, .pipelineLayout = collection->pipelineLayout, - .multisampleState = { - .samples = viewport->getSamples(), - }, - .depthStencilState = { - .depthCompareOp = Gfx::SE_COMPARE_OP_GREATER, - }, - .colorBlend = { - .attachmentCount = 1, - }, + .multisampleState = + { + .samples = viewport->getSamples(), + }, + .depthStencilState = + { + .depthCompareOp = Gfx::SE_COMPARE_OP_GREATER, + }, + .colorBlend = + { + .attachmentCount = 1, + }, }; Gfx::PGraphicsPipeline pipeline = graphics->createGraphicsPipeline(std::move(pipelineInfo)); command->bindPipeline(pipeline); @@ -126,27 +117,23 @@ void CachedDepthPass::render() command->bindDescriptor(vertexData->getVertexDataSet()); command->bindDescriptor(vertexData->getInstanceDataSet()); uint32 offset = 0; - command->pushConstants(Gfx::SE_SHADER_STAGE_TASK_BIT_EXT | Gfx::SE_SHADER_STAGE_VERTEX_BIT, 0, sizeof(VertexData::DrawCallOffsets), &offset); - if (graphics->supportMeshShading()) - { + command->pushConstants(Gfx::SE_SHADER_STAGE_TASK_BIT_EXT | Gfx::SE_SHADER_STAGE_VERTEX_BIT, 0, sizeof(VertexData::DrawCallOffsets), + &offset); + if (graphics->supportMeshShading()) { command->drawMesh(vertexData->getNumInstances(), 1, 1); - } - else - { - const auto &materials = vertexData->getMaterialData(); - for (const auto &materialData : materials) - { + } else { + const auto& materials = vertexData->getMaterialData(); + for (const auto& materialData : materials) { // material not used for any active meshes, skip if (materialData.instances.size() == 0) continue; - for (const auto &drawCall : materialData.instances) - { + for (const auto& drawCall : materialData.instances) { command->bindIndexBuffer(vertexData->getIndexBuffer()); uint32 inst = drawCall.offsets.instanceOffset; - for (const auto &meshData : drawCall.instanceMeshData) - { + for (const auto& meshData : drawCall.instanceMeshData) { // all meshlets of a mesh share the same indices offset - command->drawIndexed(meshData.numIndices, 1, meshData.firstIndex, vertexData->getIndicesOffset(meshData.meshletOffset), inst++); + command->drawIndexed(meshData.numIndices, 1, meshData.firstIndex, + vertexData->getIndicesOffset(meshData.meshletOffset), inst++); } } } @@ -157,25 +144,22 @@ void CachedDepthPass::render() graphics->executeCommands(std::move(commands)); graphics->endRenderPass(); // Sync depth read/write with depth pass depth read - //depthBuffer->pipelineBarrier( + // depthBuffer->pipelineBarrier( // Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, // Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, // Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, // Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT); // sync visibility write with depth pass visibility write - //visibilityBuffer->pipelineBarrier( + // visibilityBuffer->pipelineBarrier( // Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); } -void CachedDepthPass::endFrame() -{ -} +void CachedDepthPass::endFrame() {} -void CachedDepthPass::publishOutputs() -{ +void CachedDepthPass::publishOutputs() { // If we render to a part of an image, the depth buffer itself must // still match the size of the whole image or their coordinate systems go out of sync TextureCreateInfo depthBufferInfo = { @@ -186,8 +170,7 @@ void CachedDepthPass::publishOutputs() }; depthBuffer = graphics->createTexture2D(depthBufferInfo); depthAttachment = - Gfx::RenderTargetAttachment(depthBuffer, - Gfx::SE_IMAGE_LAYOUT_UNDEFINED, Gfx::SE_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + Gfx::RenderTargetAttachment(depthBuffer, Gfx::SE_IMAGE_LAYOUT_UNDEFINED, Gfx::SE_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, Gfx::SE_ATTACHMENT_LOAD_OP_CLEAR, Gfx::SE_ATTACHMENT_STORE_OP_STORE); resources->registerRenderPassOutput("DEPTHPREPASS_DEPTH", depthAttachment); @@ -199,14 +182,12 @@ void CachedDepthPass::publishOutputs() }; visibilityBuffer = graphics->createTexture2D(visibilityInfo); visibilityAttachment = - Gfx::RenderTargetAttachment(visibilityBuffer, - Gfx::SE_IMAGE_LAYOUT_UNDEFINED, Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + Gfx::RenderTargetAttachment(visibilityBuffer, Gfx::SE_IMAGE_LAYOUT_UNDEFINED, Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, Gfx::SE_ATTACHMENT_LOAD_OP_CLEAR, Gfx::SE_ATTACHMENT_STORE_OP_STORE); resources->registerRenderPassOutput("VISIBILITY", visibilityAttachment); } -void CachedDepthPass::createRenderPass() -{ +void CachedDepthPass::createRenderPass() { cullingBuffer = resources->requestBuffer("CULLINGBUFFER"); Gfx::RenderTargetLayout layout = Gfx::RenderTargetLayout{ @@ -219,16 +200,20 @@ void CachedDepthPass::createRenderPass() .dstSubpass = 0, .srcStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, .dstStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, - .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, - .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, }, { .srcSubpass = 0, .dstSubpass = ~0U, .srcStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, .dstStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, - .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, - .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, }, }; renderPass = graphics->createRenderPass(std::move(layout), std::move(dependency), viewport); diff --git a/src/Engine/Graphics/RenderPass/CachedDepthPass.h b/src/Engine/Graphics/RenderPass/CachedDepthPass.h index 810f9d2..56388db 100644 --- a/src/Engine/Graphics/RenderPass/CachedDepthPass.h +++ b/src/Engine/Graphics/RenderPass/CachedDepthPass.h @@ -1,11 +1,9 @@ #pragma once #include "RenderPass.h" -namespace Seele -{ -class CachedDepthPass : public RenderPass -{ -public: +namespace Seele { +class CachedDepthPass : public RenderPass { + public: CachedDepthPass(Gfx::PGraphics graphics, PScene scene); CachedDepthPass(CachedDepthPass&&) = default; CachedDepthPass& operator=(CachedDepthPass&&) = default; @@ -15,14 +13,15 @@ public: virtual void endFrame() override; virtual void publishOutputs() override; virtual void createRenderPass() override; -private: + + private: Gfx::RenderTargetAttachment depthAttachment; Gfx::RenderTargetAttachment visibilityAttachment; Gfx::OTexture2D depthBuffer; Gfx::OTexture2D visibilityBuffer; Gfx::OPipelineLayout depthPrepassLayout; - + Gfx::PShaderBuffer cullingBuffer; }; DEFINE_REF(CachedDepthPass) -} \ No newline at end of file +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/RenderPass/DebugPass.cpp b/src/Engine/Graphics/RenderPass/DebugPass.cpp index b930b41..8b200e4 100644 --- a/src/Engine/Graphics/RenderPass/DebugPass.cpp +++ b/src/Engine/Graphics/RenderPass/DebugPass.cpp @@ -1,77 +1,62 @@ #include "DebugPass.h" #include "Graphics/Graphics.h" -#include "Graphics/RenderTarget.h" #include "Graphics/Pipeline.h" +#include "Graphics/RenderTarget.h" #include "Graphics/Shader.h" + using namespace Seele; Array gDebugVertices; -void Seele::addDebugVertex(DebugVertex vert) -{ - gDebugVertices.add(vert); -} +void Seele::addDebugVertex(DebugVertex vert) { gDebugVertices.add(vert); } -void Seele::addDebugVertices(Array verts) -{ - gDebugVertices.addAll(verts); -} +void Seele::addDebugVertices(Array verts) { gDebugVertices.addAll(verts); } -DebugPass::DebugPass(Gfx::PGraphics graphics, PScene scene) - : RenderPass(graphics, scene) -{ - -} +DebugPass::DebugPass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics, scene) {} -DebugPass::~DebugPass() -{ - -} +DebugPass::~DebugPass() {} -void DebugPass::beginFrame(const Component::Camera& cam) -{ +void DebugPass::beginFrame(const Component::Camera& cam) { RenderPass::beginFrame(cam); - + VertexBufferCreateInfo vertexBufferInfo = { - .sourceData = { - .size = sizeof(DebugVertex) * gDebugVertices.size(), - .data = (uint8*)gDebugVertices.data(), - }, + .sourceData = + { + .size = sizeof(DebugVertex) * gDebugVertices.size(), + .data = (uint8*)gDebugVertices.data(), + }, .vertexSize = sizeof(DebugVertex), .numVertices = (uint32)gDebugVertices.size(), .name = "DebugVertices", }; debugVertices = graphics->createVertexBuffer(vertexBufferInfo); - } -void DebugPass::render() -{ +void DebugPass::render() { graphics->beginRenderPass(renderPass); - if (gDebugVertices.size() > 0) - { + if (gDebugVertices.size() > 0) { Gfx::ORenderCommand renderCommand = graphics->createRenderCommand("DebugRender"); renderCommand->setViewport(viewport); renderCommand->bindPipeline(pipeline); renderCommand->bindDescriptor(viewParamsSet); - renderCommand->bindVertexBuffer({ debugVertices }); + renderCommand->bindVertexBuffer({debugVertices}); renderCommand->draw((uint32)gDebugVertices.size(), 1, 0, 0); Array commands; commands.add(std::move(renderCommand)); - graphics->executeCommands({ std::move(commands) }); + graphics->executeCommands({std::move(commands)}); } graphics->endRenderPass(); gDebugVertices.clear(); // Sync color write with next pass/swapchain present - //colorAttachment.getTexture()->pipelineBarrier( + // colorAttachment.getTexture()->pipelineBarrier( // Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT //); // Sync depth with next pass/next frame - //depthAttachment.getTexture()->pipelineBarrier( + // depthAttachment.getTexture()->pipelineBarrier( // Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, // Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, // Gfx::SE_ACCESS_MEMORY_WRITE_BIT, @@ -79,28 +64,22 @@ void DebugPass::render() //); } -void DebugPass::endFrame() -{ - -} +void DebugPass::endFrame() {} -void DebugPass::publishOutputs() -{ -} +void DebugPass::publishOutputs() {} -void DebugPass::createRenderPass() -{ +void DebugPass::createRenderPass() { colorAttachment = resources->requestRenderTarget("BASEPASS_COLOR"); colorAttachment.setLoadOp(Gfx::SE_ATTACHMENT_LOAD_OP_LOAD); colorAttachment.setInitialLayout(Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); colorAttachment.setInitialLayout(Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - + depthAttachment = resources->requestRenderTarget("DEPTHPREPASS_DEPTH"); depthAttachment.setLoadOp(Gfx::SE_ATTACHMENT_LOAD_OP_LOAD); depthAttachment.setInitialLayout(Gfx::SE_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); depthAttachment.setFinalLayout(Gfx::SE_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); Gfx::RenderTargetLayout layout = Gfx::RenderTargetLayout{ - .colorAttachments = {colorAttachment}, + .colorAttachments = {colorAttachment}, .depthAttachment = depthAttachment, }; @@ -110,20 +89,24 @@ void DebugPass::createRenderPass() .dstSubpass = 0, .srcStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, .dstStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, - .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, - .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, }, { .srcSubpass = 0, .dstSubpass = ~0U, .srcStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, .dstStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, - .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, - .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, }, }; renderPass = graphics->createRenderPass(std::move(layout), dependency, viewport); - + pipelineLayout = graphics->createPipelineLayout("DebugPassLayout"); pipelineLayout->addDescriptorLayout(viewParamsLayout); @@ -141,27 +124,22 @@ void DebugPass::createRenderPass() pipelineLayout->create(); VertexInputStateCreateInfo inputCreate = { - .bindings = { - VertexInputBinding { - .binding = 0, - .stride = sizeof(DebugVertex), - .inputRate = Gfx::SE_VERTEX_INPUT_RATE_VERTEX, + .bindings = + { + VertexInputBinding{ + .binding = 0, + .stride = sizeof(DebugVertex), + .inputRate = Gfx::SE_VERTEX_INPUT_RATE_VERTEX, + }, }, - }, - .attributes = { - VertexInputAttribute { - .location = 0, - .binding = 0, - .format = Gfx::SE_FORMAT_R32G32B32_SFLOAT, - .offset = 0, - }, - VertexInputAttribute { - .location = 1, - .binding = 0, - .format = Gfx::SE_FORMAT_R32G32B32_SFLOAT, - .offset = sizeof(Vector) - } - }, + .attributes = {VertexInputAttribute{ + .location = 0, + .binding = 0, + .format = Gfx::SE_FORMAT_R32G32B32_SFLOAT, + .offset = 0, + }, + VertexInputAttribute{ + .location = 1, .binding = 0, .format = Gfx::SE_FORMAT_R32G32B32_SFLOAT, .offset = sizeof(Vector)}}, }; vertexInput = graphics->createVertexInput(inputCreate); Gfx::LegacyPipelineCreateInfo gfxInfo; diff --git a/src/Engine/Graphics/RenderPass/DebugPass.h b/src/Engine/Graphics/RenderPass/DebugPass.h index aa0d726..b69253f 100644 --- a/src/Engine/Graphics/RenderPass/DebugPass.h +++ b/src/Engine/Graphics/RenderPass/DebugPass.h @@ -1,17 +1,16 @@ #pragma once -#include "RenderPass.h" -#include "Scene/Scene.h" #include "Graphics/DebugVertex.h" #include "Graphics/Pipeline.h" +#include "RenderPass.h" +#include "Scene/Scene.h" -namespace Seele -{ + +namespace Seele { DECLARE_REF(CameraActor) DECLARE_REF(Scene) DECLARE_REF(Viewport) -class DebugPass : public RenderPass -{ -public: +class DebugPass : public RenderPass { + public: DebugPass(Gfx::PGraphics graphics, PScene scene); DebugPass(DebugPass&&) = default; DebugPass& operator=(DebugPass&&) = default; @@ -21,7 +20,8 @@ public: virtual void endFrame() override; virtual void publishOutputs() override; virtual void createRenderPass() override; -private: + + private: Gfx::RenderTargetAttachment colorAttachment; Gfx::RenderTargetAttachment depthAttachment; Gfx::OVertexInput vertexInput; diff --git a/src/Engine/Graphics/RenderPass/DepthPrepass.cpp b/src/Engine/Graphics/RenderPass/DepthPrepass.cpp index fb857bc..5bc851f 100644 --- a/src/Engine/Graphics/RenderPass/DepthPrepass.cpp +++ b/src/Engine/Graphics/RenderPass/DepthPrepass.cpp @@ -6,9 +6,7 @@ using namespace Seele; extern bool usePositionOnly; extern bool useViewCulling; -DepthPrepass::DepthPrepass(Gfx::PGraphics graphics, PScene scene) - : RenderPass(graphics, scene) -{ +DepthPrepass::DepthPrepass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics, scene) { depthPrepassLayout = graphics->createPipelineLayout("DepthPrepassLayout"); depthPrepassLayout->addDescriptorLayout(viewParamsLayout); depthPrepassLayout->addPushConstants(Gfx::SePushConstantRange{ @@ -16,55 +14,45 @@ DepthPrepass::DepthPrepass(Gfx::PGraphics graphics, PScene scene) .offset = 0, .size = sizeof(VertexData::DrawCallOffsets), }); - if (graphics->supportMeshShading()) - { + if (graphics->supportMeshShading()) { graphics->getShaderCompiler()->registerRenderPass("DepthPass", Gfx::PassConfig{ - .baseLayout = depthPrepassLayout, - .taskFile = "DepthCullingTask", - .mainFile = "DepthCullingMesh", - .fragmentFile = "VisibilityPass", - .hasFragmentShader = true, - .useMeshShading = true, - .hasTaskShader = true, - .useMaterial = false, - .useVisibility = true, - }); - } - else - { + .baseLayout = depthPrepassLayout, + .taskFile = "DepthCullingTask", + .mainFile = "DepthCullingMesh", + .fragmentFile = "VisibilityPass", + .hasFragmentShader = true, + .useMeshShading = true, + .hasTaskShader = true, + .useMaterial = false, + .useVisibility = true, + }); + } else { graphics->getShaderCompiler()->registerRenderPass("DepthPass", Gfx::PassConfig{ - .baseLayout = depthPrepassLayout, - .taskFile = "", - .mainFile = "LegacyPass", - .fragmentFile = "VisibilityPass", - .hasFragmentShader = true, - .useMeshShading = false, - .hasTaskShader = false, - .useMaterial = false, - .useVisibility = true, - }); + .baseLayout = depthPrepassLayout, + .taskFile = "", + .mainFile = "LegacyPass", + .fragmentFile = "VisibilityPass", + .hasFragmentShader = true, + .useMeshShading = false, + .hasTaskShader = false, + .useMaterial = false, + .useVisibility = true, + }); } } -DepthPrepass::~DepthPrepass() -{ -} +DepthPrepass::~DepthPrepass() {} -void DepthPrepass::beginFrame(const Component::Camera &cam) -{ - RenderPass::beginFrame(cam); -} +void DepthPrepass::beginFrame(const Component::Camera& cam) { RenderPass::beginFrame(cam); } -void DepthPrepass::render() -{ +void DepthPrepass::render() { graphics->beginRenderPass(renderPass); Array commands; Gfx::ShaderPermutation permutation = graphics->getShaderCompiler()->getTemplate("DepthPass"); permutation.setPositionOnly(usePositionOnly); permutation.setViewCulling(useViewCulling); - for (VertexData *vertexData : VertexData::getList()) - { + for (VertexData* vertexData : VertexData::getList()) { permutation.setVertexData(vertexData->getTypeName()); vertexData->getInstanceDataSet()->updateBuffer(6, cullingBuffer); vertexData->getInstanceDataSet()->writeChanges(); @@ -78,45 +66,48 @@ void DepthPrepass::render() Gfx::ORenderCommand command = graphics->createRenderCommand("DepthRender"); command->setViewport(viewport); - const Gfx::ShaderCollection *collection = graphics->getShaderCompiler()->findShaders(id); + const Gfx::ShaderCollection* collection = graphics->getShaderCompiler()->findShaders(id); assert(collection != nullptr); - if (graphics->supportMeshShading()) - { + if (graphics->supportMeshShading()) { Gfx::MeshPipelineCreateInfo pipelineInfo = { .taskShader = collection->taskShader, .meshShader = collection->meshShader, .fragmentShader = collection->fragmentShader, .renderPass = renderPass, .pipelineLayout = collection->pipelineLayout, - .multisampleState = { - .samples = viewport->getSamples(), - }, - .depthStencilState = { - .depthCompareOp = Gfx::SE_COMPARE_OP_GREATER, - }, - .colorBlend = { - .attachmentCount = 1, - }, + .multisampleState = + { + .samples = viewport->getSamples(), + }, + .depthStencilState = + { + .depthCompareOp = Gfx::SE_COMPARE_OP_GREATER, + }, + .colorBlend = + { + .attachmentCount = 1, + }, }; Gfx::PGraphicsPipeline pipeline = graphics->createGraphicsPipeline(std::move(pipelineInfo)); command->bindPipeline(pipeline); - } - else - { + } else { Gfx::LegacyPipelineCreateInfo pipelineInfo = { .vertexShader = collection->vertexShader, .fragmentShader = collection->fragmentShader, .renderPass = renderPass, .pipelineLayout = collection->pipelineLayout, - .multisampleState = { - .samples = viewport->getSamples(), - }, - .depthStencilState = { - .depthCompareOp = Gfx::SE_COMPARE_OP_GREATER, - }, - .colorBlend = { - .attachmentCount = 1, - }, + .multisampleState = + { + .samples = viewport->getSamples(), + }, + .depthStencilState = + { + .depthCompareOp = Gfx::SE_COMPARE_OP_GREATER, + }, + .colorBlend = + { + .attachmentCount = 1, + }, }; Gfx::PGraphicsPipeline pipeline = graphics->createGraphicsPipeline(std::move(pipelineInfo)); command->bindPipeline(pipeline); @@ -125,27 +116,23 @@ void DepthPrepass::render() command->bindDescriptor(vertexData->getVertexDataSet()); command->bindDescriptor(vertexData->getInstanceDataSet()); uint32 offset = 0; - command->pushConstants(Gfx::SE_SHADER_STAGE_TASK_BIT_EXT | Gfx::SE_SHADER_STAGE_VERTEX_BIT, 0, sizeof(VertexData::DrawCallOffsets), &offset); - if (graphics->supportMeshShading()) - { + command->pushConstants(Gfx::SE_SHADER_STAGE_TASK_BIT_EXT | Gfx::SE_SHADER_STAGE_VERTEX_BIT, 0, sizeof(VertexData::DrawCallOffsets), + &offset); + if (graphics->supportMeshShading()) { command->drawMesh(vertexData->getNumInstances(), 1, 1); - } - else - { - const auto &materials = vertexData->getMaterialData(); - for (const auto &materialData : materials) - { - for (const auto &drawCall : materialData.instances) - { + } else { + const auto& materials = vertexData->getMaterialData(); + for (const auto& materialData : materials) { + for (const auto& drawCall : materialData.instances) { // material not used for any active meshes, skip if (materialData.instances.size() == 0) continue; command->bindIndexBuffer(vertexData->getIndexBuffer()); uint32 inst = drawCall.offsets.instanceOffset; - for (const auto &meshData : drawCall.instanceMeshData) - { + for (const auto& meshData : drawCall.instanceMeshData) { // all meshlets of a mesh share the same indices offset - command->drawIndexed(meshData.numIndices, 1, meshData.firstIndex, vertexData->getIndicesOffset(meshData.meshletOffset), inst++); + command->drawIndexed(meshData.numIndices, 1, meshData.firstIndex, + vertexData->getIndicesOffset(meshData.meshletOffset), inst++); } } } @@ -156,38 +143,27 @@ void DepthPrepass::render() graphics->executeCommands(std::move(commands)); graphics->endRenderPass(); // Sync depth read/write with compute read - depthAttachment.getTexture()->pipelineBarrier( + depthAttachment.getTexture()->pipelineBarrier( Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, - Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, - Gfx::SE_ACCESS_SHADER_READ_BIT, - Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT - ); + Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT); // Sync depth read/write with base pass read - //depthAttachment.getTexture()->pipelineBarrier( + // depthAttachment.getTexture()->pipelineBarrier( // Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, // Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, // Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, // Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT //); // Sync visibility write with compute read - visibilityAttachment.getTexture()->pipelineBarrier( - Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - Gfx::SE_ACCESS_SHADER_READ_BIT, - Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT - ); + visibilityAttachment.getTexture()->pipelineBarrier(Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT, + Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT); } -void DepthPrepass::endFrame() -{ -} +void DepthPrepass::endFrame() {} -void DepthPrepass::publishOutputs() -{ -} +void DepthPrepass::publishOutputs() {} -void DepthPrepass::createRenderPass() -{ +void DepthPrepass::createRenderPass() { cullingBuffer = resources->requestBuffer("CULLINGBUFFER"); depthAttachment = resources->requestRenderTarget("DEPTHPREPASS_DEPTH"); @@ -209,16 +185,20 @@ void DepthPrepass::createRenderPass() .dstSubpass = 0, .srcStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, .dstStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, - .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, - .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, }, { .srcSubpass = 0, .dstSubpass = ~0U, .srcStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, .dstStage = Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, - .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, - .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .srcAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + .dstAccess = Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, }, }; renderPass = graphics->createRenderPass(std::move(layout), std::move(dependency), viewport); diff --git a/src/Engine/Graphics/RenderPass/DepthPrepass.h b/src/Engine/Graphics/RenderPass/DepthPrepass.h index c5cd744..667c073 100644 --- a/src/Engine/Graphics/RenderPass/DepthPrepass.h +++ b/src/Engine/Graphics/RenderPass/DepthPrepass.h @@ -2,11 +2,9 @@ #include "MinimalEngine.h" #include "RenderPass.h" -namespace Seele -{ -class DepthPrepass : public RenderPass -{ -public: +namespace Seele { +class DepthPrepass : public RenderPass { + public: DepthPrepass(Gfx::PGraphics graphics, PScene scene); DepthPrepass(DepthPrepass&&) = default; DepthPrepass& operator=(DepthPrepass&&) = default; @@ -16,7 +14,8 @@ public: virtual void endFrame() override; virtual void publishOutputs() override; virtual void createRenderPass() override; -private: + + private: Gfx::RenderTargetAttachment depthAttachment; Gfx::RenderTargetAttachment visibilityAttachment; Gfx::OPipelineLayout depthPrepassLayout; diff --git a/src/Engine/Graphics/RenderPass/LightCullingPass.cpp b/src/Engine/Graphics/RenderPass/LightCullingPass.cpp index 6d11158..e893df9 100644 --- a/src/Engine/Graphics/RenderPass/LightCullingPass.cpp +++ b/src/Engine/Graphics/RenderPass/LightCullingPass.cpp @@ -1,62 +1,46 @@ #include "LightCullingPass.h" -#include "Graphics/Graphics.h" -#include "Scene/Scene.h" #include "Actor/CameraActor.h" #include "Component/Camera.h" -#include "RenderGraph.h" #include "Graphics/Command.h" +#include "Graphics/Graphics.h" +#include "RenderGraph.h" +#include "Scene/Scene.h" + using namespace Seele; extern bool useLightCulling; -LightCullingPass::LightCullingPass(Gfx::PGraphics graphics, PScene scene) - : RenderPass(graphics, scene) -{ -} +LightCullingPass::LightCullingPass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics, scene) {} -LightCullingPass::~LightCullingPass() -{ +LightCullingPass::~LightCullingPass() {} -} - -void LightCullingPass::beginFrame(const Component::Camera& cam) -{ +void LightCullingPass::beginFrame(const Component::Camera& cam) { RenderPass::beginFrame(cam); - oLightIndexCounter->pipelineBarrier( - Gfx::SE_ACCESS_MEMORY_WRITE_BIT | Gfx::SE_ACCESS_MEMORY_READ_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - Gfx::SE_ACCESS_MEMORY_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT - ); - tLightIndexCounter->pipelineBarrier( - Gfx::SE_ACCESS_MEMORY_WRITE_BIT | Gfx::SE_ACCESS_MEMORY_READ_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - Gfx::SE_ACCESS_MEMORY_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT - ); + oLightIndexCounter->pipelineBarrier(Gfx::SE_ACCESS_MEMORY_WRITE_BIT | Gfx::SE_ACCESS_MEMORY_READ_BIT, + Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_MEMORY_WRITE_BIT, + Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT); + tLightIndexCounter->pipelineBarrier(Gfx::SE_ACCESS_MEMORY_WRITE_BIT | Gfx::SE_ACCESS_MEMORY_READ_BIT, + Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_MEMORY_WRITE_BIT, + Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT); uint32 reset = 0; ShaderBufferCreateInfo counterReset = { - .sourceData = { - .size = sizeof(uint32), - .data = (uint8*)&reset, - .owner = Gfx::QueueType::COMPUTE - } - }; + .sourceData = {.size = sizeof(uint32), .data = (uint8*)&reset, .owner = Gfx::QueueType::COMPUTE}}; oLightIndexCounter->rotateBuffer(sizeof(uint32)); oLightIndexCounter->updateContents(counterReset); tLightIndexCounter->rotateBuffer(sizeof(uint32)); tLightIndexCounter->updateContents(counterReset); - oLightIndexCounter->pipelineBarrier( - Gfx::SE_ACCESS_MEMORY_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, - Gfx::SE_ACCESS_MEMORY_READ_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT); - tLightIndexCounter->pipelineBarrier( - Gfx::SE_ACCESS_MEMORY_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, - Gfx::SE_ACCESS_MEMORY_READ_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + oLightIndexCounter->pipelineBarrier(Gfx::SE_ACCESS_MEMORY_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, + Gfx::SE_ACCESS_MEMORY_READ_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + tLightIndexCounter->pipelineBarrier(Gfx::SE_ACCESS_MEMORY_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, + Gfx::SE_ACCESS_MEMORY_READ_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT); cullingDescriptorLayout->reset(); cullingDescriptorSet = cullingDescriptorLayout->allocateDescriptorSet(); } -void LightCullingPass::render() -{ +void LightCullingPass::render() { depthAttachment->transferOwnership(Gfx::QueueType::COMPUTE); cullingDescriptorSet->updateTexture(0, depthAttachment); cullingDescriptorSet->updateBuffer(1, oLightIndexCounter); @@ -67,41 +51,31 @@ void LightCullingPass::render() cullingDescriptorSet->updateTexture(6, Gfx::PTexture2D(tLightGrid)); cullingDescriptorSet->writeChanges(); Gfx::OComputeCommand computeCommand = graphics->createComputeCommand("CullingCommand"); - if (useLightCulling) - { + if (useLightCulling) { computeCommand->bindPipeline(cullingEnabledPipeline); - } - else - { + } else { computeCommand->bindPipeline(cullingPipeline); } - computeCommand->bindDescriptor({ viewParamsSet, dispatchParamsSet, cullingDescriptorSet, lightEnv->getDescriptorSet() }); + computeCommand->bindDescriptor({viewParamsSet, dispatchParamsSet, cullingDescriptorSet, lightEnv->getDescriptorSet()}); computeCommand->dispatch(dispatchParams.numThreadGroups.x, dispatchParams.numThreadGroups.y, dispatchParams.numThreadGroups.z); Array commands; commands.add(std::move(computeCommand)); - //std::cout << "Execute" << std::endl; + // std::cout << "Execute" << std::endl; graphics->executeCommands(std::move(commands)); - - oLightIndexList->pipelineBarrier( - Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); - tLightIndexList->pipelineBarrier( - Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); - oLightGrid->pipelineBarrier( - Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); - tLightGrid->pipelineBarrier( - Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + + oLightIndexList->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + tLightIndexList->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + oLightGrid->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT, + Gfx::SE_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + tLightGrid->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT, + Gfx::SE_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); } -void LightCullingPass::endFrame() -{ -} +void LightCullingPass::endFrame() {} -void LightCullingPass::publishOutputs() -{ +void LightCullingPass::publishOutputs() { setupFrustums(); uint32_t viewportWidth = viewport->getWidth(); uint32_t viewportHeight = viewport->getHeight(); @@ -109,14 +83,10 @@ void LightCullingPass::publishOutputs() dispatchParams.numThreadGroups = numThreadGroups; dispatchParams.numThreads = numThreadGroups * glm::uvec3(BLOCK_SIZE, BLOCK_SIZE, 1); dispatchParamsBuffer = graphics->createUniformBuffer(UniformBufferCreateInfo{ - .sourceData = { - .size = sizeof(DispatchParams), - .data = (uint8*)&dispatchParams, - .owner = Gfx::QueueType::COMPUTE - }, + .sourceData = {.size = sizeof(DispatchParams), .data = (uint8*)&dispatchParams, .owner = Gfx::QueueType::COMPUTE}, .dynamic = false, .name = "DispatchParams", - }); + }); dispatchParamsSet = dispatchParamsLayout->allocateDescriptorSet(); dispatchParamsSet->updateBuffer(0, dispatchParamsBuffer); @@ -125,20 +95,29 @@ void LightCullingPass::publishOutputs() cullingDescriptorLayout = graphics->createDescriptorLayout("pCullingParams"); - //DepthTexture - cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 0, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, }); - //o_lightIndexCounter - cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 1, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT }); - //t_lightIndexCounter - cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 2, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT }); - //o_lightIndexList - cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 3, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT }); - //t_lightIndexList - cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 4, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT }); - //o_lightGrid - cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 5, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_IMAGE, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT }); - //t_lightGrid - cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 6, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_IMAGE, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT }); + // DepthTexture + cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 0, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, + }); + // o_lightIndexCounter + cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 1, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT}); + // t_lightIndexCounter + cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 2, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT}); + // o_lightIndexList + cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 3, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT}); + // t_lightIndexList + cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 4, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT}); + // o_lightGrid + cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 5, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_IMAGE, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT}); + // t_lightGrid + cullingDescriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 6, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_IMAGE, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT}); cullingDescriptorLayout->create(); @@ -172,7 +151,7 @@ void LightCullingPass::publishOutputs() cullingEnableLayout->addDescriptorLayout(dispatchParamsLayout); cullingEnableLayout->addDescriptorLayout(cullingDescriptorLayout); cullingEnableLayout->addDescriptorLayout(lightEnv->getDescriptorLayout()); - + ShaderCreateInfo createInfo = { .name = "Culling", .mainModule = "LightCulling", @@ -182,20 +161,21 @@ void LightCullingPass::publishOutputs() createInfo.defines["LIGHT_CULLING"] = "1"; cullingEnabledShader = graphics->createComputeShader(createInfo); cullingEnableLayout->create(); - + Gfx::ComputePipelineCreateInfo pipelineInfo; pipelineInfo.computeShader = cullingShader; pipelineInfo.pipelineLayout = std::move(cullingEnableLayout); cullingEnabledPipeline = graphics->createComputePipeline(std::move(pipelineInfo)); } - + uint32 counterReset = 0; ShaderBufferCreateInfo structInfo = { - .sourceData = { - .size = sizeof(uint32), - .data = (uint8*)&counterReset, - .owner = Gfx::QueueType::COMPUTE, - }, + .sourceData = + { + .size = sizeof(uint32), + .data = (uint8*)&counterReset, + .owner = Gfx::QueueType::COMPUTE, + }, .numElements = 1, .dynamic = true, .name = "oLightIndexCounter", @@ -204,14 +184,10 @@ void LightCullingPass::publishOutputs() structInfo.name = "tLightIndexCounter"; tLightIndexCounter = graphics->createShaderBuffer(structInfo); structInfo = { - .sourceData = { - .size = (uint32)sizeof(uint32) - * dispatchParams.numThreadGroups.x - * dispatchParams.numThreadGroups.y - * dispatchParams.numThreadGroups.z * 8192, - .data = nullptr, - .owner = Gfx::QueueType::COMPUTE - }, + .sourceData = {.size = (uint32)sizeof(uint32) * dispatchParams.numThreadGroups.x * dispatchParams.numThreadGroups.y * + dispatchParams.numThreadGroups.z * 8192, + .data = nullptr, + .owner = Gfx::QueueType::COMPUTE}, .dynamic = false, .name = "oLightIndexList", }; @@ -234,15 +210,9 @@ void LightCullingPass::publishOutputs() resources->registerTextureOutput("LIGHTCULLING_TLIGHTGRID", Gfx::PTexture2D(tLightGrid)); } +void LightCullingPass::createRenderPass() { depthAttachment = resources->requestRenderTarget("DEPTHPREPASS_DEPTH").getTexture(); } -void LightCullingPass::createRenderPass() -{ - depthAttachment = resources->requestRenderTarget("DEPTHPREPASS_DEPTH").getTexture(); -} - - -void LightCullingPass::setupFrustums() -{ +void LightCullingPass::setupFrustums() { uint32_t viewportWidth = viewport->getWidth(); uint32_t viewportHeight = viewport->getHeight(); @@ -254,8 +224,12 @@ void LightCullingPass::setupFrustums() dispatchParams.numThreadGroups = numThreadGroups; dispatchParamsLayout = graphics->createDescriptorLayout("pDispatchParams"); - dispatchParamsLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 0, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER, }); - dispatchParamsLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 1, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .access = Gfx::SE_DESCRIPTOR_ACCESS_WRITE_ONLY_BIT }); + dispatchParamsLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 0, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + }); + dispatchParamsLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 1, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .access = Gfx::SE_DESCRIPTOR_ACCESS_WRITE_ONLY_BIT}); frustumLayout = graphics->createPipelineLayout("FrustumLayout"); frustumLayout->addDescriptorLayout(viewParamsLayout); frustumLayout->addDescriptorLayout(dispatchParamsLayout); @@ -277,25 +251,17 @@ void LightCullingPass::setupFrustums() frustumPipeline = graphics->createComputePipeline(pipelineInfo); Gfx::OUniformBuffer frustumDispatchParamsBuffer = graphics->createUniformBuffer(UniformBufferCreateInfo{ - .sourceData = { - .size = sizeof(DispatchParams), - .data = (uint8*)&dispatchParams, - .owner = Gfx::QueueType::COMPUTE - }, + .sourceData = {.size = sizeof(DispatchParams), .data = (uint8*)&dispatchParams, .owner = Gfx::QueueType::COMPUTE}, .dynamic = false, - .name = "FrustumDispatch" - }); + .name = "FrustumDispatch"}); - frustumBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{ - .sourceData = { - .size = sizeof(Frustum) * numThreads.x * numThreads.y * numThreads.z, - .data = nullptr, - .owner = Gfx::QueueType::COMPUTE - }, - .numElements = numThreads.x * numThreads.y * numThreads.z, - .dynamic = false, - .name = "FrustumBuffer" - }); + frustumBuffer = graphics->createShaderBuffer( + ShaderBufferCreateInfo{.sourceData = {.size = sizeof(Frustum) * numThreads.x * numThreads.y * numThreads.z, + .data = nullptr, + .owner = Gfx::QueueType::COMPUTE}, + .numElements = numThreads.x * numThreads.y * numThreads.z, + .dynamic = false, + .name = "FrustumBuffer"}); Gfx::PDescriptorSet dispatchParamsSet = dispatchParamsLayout->allocateDescriptorSet(); dispatchParamsSet->updateBuffer(0, frustumDispatchParamsBuffer); @@ -304,11 +270,11 @@ void LightCullingPass::setupFrustums() Gfx::OComputeCommand command = graphics->createComputeCommand("FrustumCommand"); command->bindPipeline(frustumPipeline); - command->bindDescriptor({ viewParamsSet, dispatchParamsSet }); + command->bindDescriptor({viewParamsSet, dispatchParamsSet}); command->dispatch(numThreadGroups.x, numThreadGroups.y, numThreadGroups.z); Array commands; commands.add(std::move(command)); graphics->executeCommands(std::move(commands)); frustumBuffer->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT); + Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT); } diff --git a/src/Engine/Graphics/RenderPass/LightCullingPass.h b/src/Engine/Graphics/RenderPass/LightCullingPass.h index 87f64c8..9341de2 100644 --- a/src/Engine/Graphics/RenderPass/LightCullingPass.h +++ b/src/Engine/Graphics/RenderPass/LightCullingPass.h @@ -1,16 +1,15 @@ #pragma once -#include "RenderPass.h" #include "Graphics/Shader.h" +#include "RenderPass.h" #include "Scene/Scene.h" -namespace Seele -{ + +namespace Seele { DECLARE_REF(CameraActor) DECLARE_REF(Scene) DECLARE_REF(Viewport) -class LightCullingPass : public RenderPass -{ -public: +class LightCullingPass : public RenderPass { + public: LightCullingPass(Gfx::PGraphics graphics, PScene scene); LightCullingPass(LightCullingPass&&) = default; LightCullingPass& operator=(LightCullingPass&&) = default; @@ -20,24 +19,22 @@ public: virtual void endFrame() override; virtual void publishOutputs() override; virtual void createRenderPass() override; -private: + + private: void setupFrustums(); static constexpr uint32 BLOCK_SIZE = 32; static constexpr uint32 INDEX_LIGHT_ENV = 1; - struct DispatchParams - { + struct DispatchParams { glm::uvec3 numThreadGroups; uint32_t pad0; glm::uvec3 numThreads; uint32_t pad1; } dispatchParams; - struct Plane - { + struct Plane { Vector n; float d; }; - struct Frustum - { + struct Frustum { Plane planes[4]; }; @@ -49,7 +46,7 @@ private: Gfx::OComputeShader frustumShader; Gfx::PComputePipeline frustumPipeline; Gfx::OPipelineLayout frustumLayout; - + PLightEnvironment lightEnv; Gfx::PTexture2D depthAttachment; Gfx::OShaderBuffer oLightIndexCounter; diff --git a/src/Engine/Graphics/RenderPass/RayTracingPass.h b/src/Engine/Graphics/RenderPass/RayTracingPass.h index ed995b3..de8ee45 100644 --- a/src/Engine/Graphics/RenderPass/RayTracingPass.h +++ b/src/Engine/Graphics/RenderPass/RayTracingPass.h @@ -1,11 +1,9 @@ #pragma once #include "RenderPass.h" -namespace Seele -{ -class RayTracingPass : public RenderPass -{ -public: +namespace Seele { +class RayTracingPass : public RenderPass { + public: RayTracingPass(Gfx::PGraphics graphics, PScene scene); RayTracingPass(RayTracingPass&& other) = default; RayTracingPass& operator=(RayTracingPass&& other) = default; @@ -14,7 +12,7 @@ public: virtual void endFrame() override; virtual void publishOutputs() override; virtual void createRenderPass() override; -private: - + + private: }; -} \ No newline at end of file +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/RenderPass/RenderGraph.h b/src/Engine/Graphics/RenderPass/RenderGraph.h index 6869d81..62efcbc 100644 --- a/src/Engine/Graphics/RenderPass/RenderGraph.h +++ b/src/Engine/Graphics/RenderPass/RenderGraph.h @@ -1,54 +1,40 @@ #pragma once #include "RenderPass.h" -namespace Seele -{ -class RenderGraph -{ -public: - RenderGraph() - { - res = new RenderGraphResources(); - } - void addPass(ORenderPass pass) - { +namespace Seele { +class RenderGraph { + public: + RenderGraph() { res = new RenderGraphResources(); } + void addPass(ORenderPass pass) { pass->setResources(res); - passes.add(std::move(pass)); + passes.add(std::move(pass)); } - void setViewport(Gfx::PViewport viewport) - { - for (auto& pass : passes) - { + void setViewport(Gfx::PViewport viewport) { + for (auto& pass : passes) { pass->setViewport(viewport); } } - void createRenderPass() - { - for (auto& pass : passes) - { + void createRenderPass() { + for (auto& pass : passes) { pass->publishOutputs(); } - for (auto& pass : passes) - { + for (auto& pass : passes) { pass->createRenderPass(); } } - void render(const Component::Camera& cam) - { - for (auto& pass : passes) - { + void render(const Component::Camera& cam) { + for (auto& pass : passes) { pass->beginFrame(cam); } - for (auto& pass : passes) - { + for (auto& pass : passes) { pass->render(); } - for (auto& pass : passes) - { + for (auto& pass : passes) { pass->endFrame(); } } -private: + + private: PRenderGraphResources res; List passes; }; diff --git a/src/Engine/Graphics/RenderPass/RenderGraphResources.cpp b/src/Engine/Graphics/RenderPass/RenderGraphResources.cpp index 3f2983b..794bca6 100644 --- a/src/Engine/Graphics/RenderPass/RenderGraphResources.cpp +++ b/src/Engine/Graphics/RenderPass/RenderGraphResources.cpp @@ -3,51 +3,31 @@ using namespace Seele; -RenderGraphResources::RenderGraphResources() -{ - -} +RenderGraphResources::RenderGraphResources() {} -RenderGraphResources::~RenderGraphResources() -{ - -} +RenderGraphResources::~RenderGraphResources() {} -Gfx::RenderTargetAttachment RenderGraphResources::requestRenderTarget(const std::string& outputName) -{ +Gfx::RenderTargetAttachment RenderGraphResources::requestRenderTarget(const std::string& outputName) { return registeredAttachments.at(outputName); } -Gfx::PTexture RenderGraphResources::requestTexture(const std::string& outputName) -{ - return registeredTextures.at(outputName); -} +Gfx::PTexture RenderGraphResources::requestTexture(const std::string& outputName) { return registeredTextures.at(outputName); } -Gfx::PShaderBuffer RenderGraphResources::requestBuffer(const std::string& outputName) -{ - return registeredBuffers.at(outputName); -} +Gfx::PShaderBuffer RenderGraphResources::requestBuffer(const std::string& outputName) { return registeredBuffers.at(outputName); } -Gfx::PUniformBuffer RenderGraphResources::requestUniform(const std::string& outputName) -{ - return registeredUniforms.at(outputName); -} +Gfx::PUniformBuffer RenderGraphResources::requestUniform(const std::string& outputName) { return registeredUniforms.at(outputName); } -void RenderGraphResources::registerRenderPassOutput(const std::string& outputName, Gfx::RenderTargetAttachment attachment) -{ +void RenderGraphResources::registerRenderPassOutput(const std::string& outputName, Gfx::RenderTargetAttachment attachment) { registeredAttachments[outputName] = attachment; } -void RenderGraphResources::registerTextureOutput(const std::string& outputName, Gfx::PTexture texture) -{ +void RenderGraphResources::registerTextureOutput(const std::string& outputName, Gfx::PTexture texture) { registeredTextures[outputName] = texture; } -void RenderGraphResources::registerBufferOutput(const std::string& outputName, Gfx::PShaderBuffer buffer) -{ +void RenderGraphResources::registerBufferOutput(const std::string& outputName, Gfx::PShaderBuffer buffer) { registeredBuffers[outputName] = buffer; } -void RenderGraphResources::registerUniformOutput(const std::string& outputName, Gfx::PUniformBuffer buffer) -{ +void RenderGraphResources::registerUniformOutput(const std::string& outputName, Gfx::PUniformBuffer buffer) { registeredUniforms[outputName] = buffer; } \ No newline at end of file diff --git a/src/Engine/Graphics/RenderPass/RenderGraphResources.h b/src/Engine/Graphics/RenderPass/RenderGraphResources.h index bc9d96a..86666c4 100644 --- a/src/Engine/Graphics/RenderPass/RenderGraphResources.h +++ b/src/Engine/Graphics/RenderPass/RenderGraphResources.h @@ -1,16 +1,15 @@ #pragma once -#include "MinimalEngine.h" +#include "Graphics/Buffer.h" #include "Graphics/RenderTarget.h" #include "Graphics/Texture.h" -#include "Graphics/Buffer.h" +#include "MinimalEngine.h" -namespace Seele -{ + +namespace Seele { DECLARE_REF(ViewFrame) -class RenderGraphResources -{ -public: +class RenderGraphResources { + public: RenderGraphResources(); ~RenderGraphResources(); Gfx::RenderTargetAttachment requestRenderTarget(const std::string& outputName); @@ -21,7 +20,8 @@ public: void registerTextureOutput(const std::string& outputName, Gfx::PTexture buffer); void registerBufferOutput(const std::string& outputName, Gfx::PShaderBuffer buffer); void registerUniformOutput(const std::string& outputName, Gfx::PUniformBuffer buffer); -protected: + + protected: Map registeredAttachments; Map registeredTextures; Map registeredBuffers; diff --git a/src/Engine/Graphics/RenderPass/RenderPass.cpp b/src/Engine/Graphics/RenderPass/RenderPass.cpp index bba69c4..e1a81f7 100644 --- a/src/Engine/Graphics/RenderPass/RenderPass.cpp +++ b/src/Engine/Graphics/RenderPass/RenderPass.cpp @@ -2,18 +2,19 @@ using namespace Seele; -RenderPass::RenderPass(Gfx::PGraphics graphics, PScene scene) - : graphics(graphics) - , scene(scene) -{ +RenderPass::RenderPass(Gfx::PGraphics graphics, PScene scene) : graphics(graphics), scene(scene) { viewParamsLayout = graphics->createDescriptorLayout("pViewParams"); - viewParamsLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 0, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,}); + viewParamsLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 0, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + }); UniformBufferCreateInfo uniformInitializer = { - .sourceData = { - .size = sizeof(ViewParameter), - .data = (uint8*)&viewParams, - }, + .sourceData = + { + .size = sizeof(ViewParameter), + .data = (uint8*)&viewParams, + }, .dynamic = true, .name = "viewParamsBuffer", }; @@ -21,11 +22,9 @@ RenderPass::RenderPass(Gfx::PGraphics graphics, PScene scene) viewParamsLayout->create(); } -RenderPass::~RenderPass() -{} +RenderPass::~RenderPass() {} -void RenderPass::beginFrame(const Component::Camera& cam) -{ +void RenderPass::beginFrame(const Component::Camera& cam) { viewParams = { .viewMatrix = cam.getViewMatrix(), .inverseViewMatrix = glm::inverse(cam.getViewMatrix()), @@ -40,23 +39,14 @@ void RenderPass::beginFrame(const Component::Camera& cam) }; viewParamsBuffer->rotateBuffer(sizeof(ViewParameter)); viewParamsBuffer->updateContents(uniformUpdate); - viewParamsBuffer->pipelineBarrier( - Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, - Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, - Gfx::SE_ACCESS_MEMORY_READ_BIT, - Gfx::SE_PIPELINE_STAGE_ALL_COMMANDS_BIT); + viewParamsBuffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, + Gfx::SE_ACCESS_MEMORY_READ_BIT, Gfx::SE_PIPELINE_STAGE_ALL_COMMANDS_BIT); viewParamsLayout->reset(); viewParamsSet = viewParamsLayout->allocateDescriptorSet(); viewParamsSet->updateBuffer(0, viewParamsBuffer); viewParamsSet->writeChanges(); } -void RenderPass::setResources(PRenderGraphResources _resources) -{ - resources = _resources; -} +void RenderPass::setResources(PRenderGraphResources _resources) { resources = _resources; } -void RenderPass::setViewport(Gfx::PViewport _viewport) -{ - viewport = _viewport; -} +void RenderPass::setViewport(Gfx::PViewport _viewport) { viewport = _viewport; } diff --git a/src/Engine/Graphics/RenderPass/RenderPass.h b/src/Engine/Graphics/RenderPass/RenderPass.h index ad382ea..5e6140c 100644 --- a/src/Engine/Graphics/RenderPass/RenderPass.h +++ b/src/Engine/Graphics/RenderPass/RenderPass.h @@ -1,20 +1,19 @@ #pragma once -#include "MinimalEngine.h" -#include "Math/Math.h" -#include "RenderGraphResources.h" #include "Component/Camera.h" -#include "Scene/Scene.h" -#include "Material/MaterialInstance.h" #include "Graphics/VertexData.h" +#include "Material/MaterialInstance.h" +#include "Math/Math.h" +#include "MinimalEngine.h" +#include "RenderGraphResources.h" +#include "Scene/Scene.h" -namespace Seele -{ + +namespace Seele { DECLARE_NAME_REF(Gfx, Viewport) DECLARE_NAME_REF(Gfx, Graphics) DECLARE_NAME_REF(Gfx, RenderPass) -class RenderPass -{ -public: +class RenderPass { + public: RenderPass(Gfx::PGraphics graphics, PScene scene); RenderPass(RenderPass&&) = default; RenderPass& operator=(RenderPass&&) = default; @@ -26,9 +25,9 @@ public: virtual void createRenderPass() = 0; void setResources(PRenderGraphResources _resources); void setViewport(Gfx::PViewport _viewport); -protected: - struct ViewParameter - { + + protected: + struct ViewParameter { Matrix4 viewMatrix; Matrix4 inverseViewMatrix; Matrix4 projectionMatrix; @@ -46,7 +45,7 @@ protected: PScene scene; }; DEFINE_REF(RenderPass) -template +template concept RenderPassType = std::derived_from; } // namespace Seele diff --git a/src/Engine/Graphics/RenderPass/SkyboxRenderPass.cpp b/src/Engine/Graphics/RenderPass/SkyboxRenderPass.cpp index 050de4f..b023352 100644 --- a/src/Engine/Graphics/RenderPass/SkyboxRenderPass.cpp +++ b/src/Engine/Graphics/RenderPass/SkyboxRenderPass.cpp @@ -1,13 +1,12 @@ #include "SkyboxRenderPass.h" -#include "Graphics/Graphics.h" #include "Asset/AssetRegistry.h" #include "Graphics/Command.h" +#include "Graphics/Graphics.h" + using namespace Seele; -SkyboxRenderPass::SkyboxRenderPass(Gfx::PGraphics graphics, PScene scene) - : RenderPass(graphics, scene) -{ +SkyboxRenderPass::SkyboxRenderPass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics, scene) { skybox = Seele::Component::Skybox{ //.day = AssetRegistry::findTexture("FS000_Day_01")->getTexture().cast(), //.night = AssetRegistry::findTexture("FS000_Night_01")->getTexture().cast(), @@ -15,13 +14,9 @@ SkyboxRenderPass::SkyboxRenderPass(Gfx::PGraphics graphics, PScene scene) .blendFactor = 0, }; } -SkyboxRenderPass::~SkyboxRenderPass() -{ +SkyboxRenderPass::~SkyboxRenderPass() {} -} - -void SkyboxRenderPass::beginFrame(const Component::Camera& cam) -{ +void SkyboxRenderPass::beginFrame(const Component::Camera& cam) { RenderPass::beginFrame(cam); skyboxDataLayout->reset(); @@ -30,14 +25,12 @@ void SkyboxRenderPass::beginFrame(const Component::Camera& cam) skyboxBuffer->updateContents(DataSource{ .size = sizeof(SkyboxData), .data = (uint8*)&skyboxData, - }); + }); skyboxDataSet = skyboxDataLayout->allocateDescriptorSet(); skyboxDataSet->updateBuffer(0, skyboxBuffer); skyboxDataSet->writeChanges(); - skyboxBuffer->pipelineBarrier( - Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, - Gfx::SE_ACCESS_MEMORY_READ_BIT, Gfx::SE_PIPELINE_STAGE_VERTEX_SHADER_BIT - ); + skyboxBuffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, Gfx::SE_ACCESS_MEMORY_READ_BIT, + Gfx::SE_PIPELINE_STAGE_VERTEX_SHADER_BIT); textureSet = textureLayout->allocateDescriptorSet(); textureSet->updateTexture(0, skybox.day); textureSet->updateTexture(1, skybox.night); @@ -45,16 +38,13 @@ void SkyboxRenderPass::beginFrame(const Component::Camera& cam) textureSet->writeChanges(); } -void SkyboxRenderPass::render() -{ +void SkyboxRenderPass::render() { colorAttachment.getTexture()->pipelineBarrier( Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - Gfx::SE_ACCESS_COLOR_ATTACHMENT_READ_BIT, Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT - ); + Gfx::SE_ACCESS_COLOR_ATTACHMENT_READ_BIT, Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); depthAttachment.getTexture()->pipelineBarrier( Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, - Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT - ); + Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT); graphics->beginRenderPass(renderPass); Gfx::ORenderCommand renderCommand = graphics->createRenderCommand("SkyboxRender"); renderCommand->setViewport(viewport); @@ -67,48 +57,56 @@ void SkyboxRenderPass::render() graphics->endRenderPass(); } -void SkyboxRenderPass::endFrame() -{ +void SkyboxRenderPass::endFrame() {} -} - -void SkyboxRenderPass::publishOutputs() -{ +void SkyboxRenderPass::publishOutputs() { skyboxDataLayout = graphics->createDescriptorLayout("pSkyboxData"); - skyboxDataLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 0, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,}); + skyboxDataLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 0, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + }); skyboxDataLayout->create(); textureLayout = graphics->createDescriptorLayout("pSkyboxTextures"); - textureLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 0, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE,}); - textureLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 1, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE,}); - textureLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 2, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER,}); + textureLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 0, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, + }); + textureLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 1, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, + }); + textureLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 2, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER, + }); textureLayout->create(); skyboxSampler = graphics->createSampler({}); } -void SkyboxRenderPass::createRenderPass() -{ +void SkyboxRenderPass::createRenderPass() { colorAttachment = resources->requestRenderTarget("BASEPASS_COLOR"); - //colorAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_LOAD; + // colorAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_LOAD; depthAttachment = resources->requestRenderTarget("DEPTHPREPASS_DEPTH"); - //depthAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_LOAD; - //Gfx::ORenderTargetLayout layout = new Gfx::RenderTargetLayout{ - // .colorAttachments = { colorAttachment }, - // .depthAttachment = depthAttachment - //}; - //renderPass = graphics->createRenderPass(std::move(layout), viewport); + // depthAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_LOAD; + // Gfx::ORenderTargetLayout layout = new Gfx::RenderTargetLayout{ + // .colorAttachments = { colorAttachment }, + // .depthAttachment = depthAttachment + // }; + // renderPass = graphics->createRenderPass(std::move(layout), viewport); skyboxData.transformMatrix = Matrix4(1); skyboxData.fogColor = skybox.fogColor; skyboxData.blendFactor = skybox.blendFactor; skyboxBuffer = graphics->createUniformBuffer(UniformBufferCreateInfo{ - .sourceData = { - .size = sizeof(SkyboxData), - .data = (uint8*)&skyboxData, - }, + .sourceData = + { + .size = sizeof(SkyboxData), + .data = (uint8*)&skyboxData, + }, .dynamic = true, - }); + }); ShaderCreateInfo createInfo = { .name = "SkyboxVertex", diff --git a/src/Engine/Graphics/RenderPass/SkyboxRenderPass.h b/src/Engine/Graphics/RenderPass/SkyboxRenderPass.h index 8169045..024c3b7 100644 --- a/src/Engine/Graphics/RenderPass/SkyboxRenderPass.h +++ b/src/Engine/Graphics/RenderPass/SkyboxRenderPass.h @@ -1,13 +1,12 @@ #pragma once -#include "RenderPass.h" -#include "Graphics/Shader.h" #include "Component/Skybox.h" +#include "Graphics/Shader.h" +#include "RenderPass.h" -namespace Seele -{ -class SkyboxRenderPass : public RenderPass -{ -public: + +namespace Seele { +class SkyboxRenderPass : public RenderPass { + public: SkyboxRenderPass(Gfx::PGraphics graphics, PScene scene); SkyboxRenderPass(SkyboxRenderPass&&) = default; SkyboxRenderPass& operator=(SkyboxRenderPass&&) = default; @@ -17,7 +16,8 @@ public: virtual void endFrame() override; virtual void publishOutputs() override; virtual void createRenderPass() override; -private: + + private: Gfx::RenderTargetAttachment colorAttachment; Gfx::RenderTargetAttachment depthAttachment; Gfx::ODescriptorLayout skyboxDataLayout; @@ -29,8 +29,7 @@ private: Gfx::OPipelineLayout pipelineLayout; Gfx::PGraphicsPipeline pipeline; Gfx::OSampler skyboxSampler; - struct SkyboxData - { + struct SkyboxData { Matrix4 transformMatrix; Vector fogColor; float blendFactor; diff --git a/src/Engine/Graphics/RenderPass/TextPass.cpp b/src/Engine/Graphics/RenderPass/TextPass.cpp index ceeacf8..867f8c6 100644 --- a/src/Engine/Graphics/RenderPass/TextPass.cpp +++ b/src/Engine/Graphics/RenderPass/TextPass.cpp @@ -1,40 +1,32 @@ #include "TextPass.h" +#include "Graphics/Command.h" #include "Graphics/Enums.h" -#include "RenderGraph.h" #include "Graphics/Graphics.h" #include "Graphics/RenderTarget.h" -#include "Graphics/Command.h" +#include "RenderGraph.h" + using namespace Seele; -TextPass::TextPass(Gfx::PGraphics graphics, PScene scene) - : RenderPass(graphics, scene) -{ -} +TextPass::TextPass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics, scene) {} -TextPass::~TextPass() -{ - -} +TextPass::~TextPass() {} -void TextPass::beginFrame(const Component::Camera& cam) -{ +void TextPass::beginFrame(const Component::Camera& cam) { RenderPass::beginFrame(cam); - for(TextRender& render : texts) - { + for (TextRender& render : texts) { FontData& fd = getFontData(render.font); TextResources& res = textResources[render.font].add(); Array instanceData; float x = render.position.x; float y = render.position.y; - for(uint32 c : render.text) - { + for (uint32 c : render.text) { const GlyphData& glyph = fd.glyphDataSet[fd.characterToGlyphIndex[c]]; Vector2 bearing = glyph.bearing; Vector2 size = glyph.size; float xpos = x + bearing.x * render.scale; float ypos = y - (size.y - bearing.y) * render.scale; - + float w = size.x * render.scale; float h = size.y * render.scale; @@ -46,10 +38,11 @@ void TextPass::beginFrame(const Component::Camera& cam) x += (glyph.advance >> 6) * render.scale; } res.instanceBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{ - .sourceData = { - .size = static_cast(instanceData.size() * sizeof(GlyphInstanceData)), - .data = reinterpret_cast(instanceData.data()), - }, + .sourceData = + { + .size = static_cast(instanceData.size() * sizeof(GlyphInstanceData)), + .data = reinterpret_cast(instanceData.data()), + }, .numElements = instanceData.size(), }); @@ -68,48 +61,42 @@ void TextPass::beginFrame(const Component::Camera& cam) projectionBuffer->updateContents(projectionUpdate); generalSet->updateBuffer(1, projectionBuffer); generalSet->writeChanges(); - //co_return; + // co_return; } -void TextPass::render() -{ +void TextPass::render() { graphics->beginRenderPass(renderPass); Array commands; - for(const auto& [fontAsset, res] : textResources) - { + for (const auto& [fontAsset, res] : textResources) { Gfx::ORenderCommand command = graphics->createRenderCommand("TextPassCommand"); command->setViewport(viewport); command->bindPipeline(pipeline); - for(const auto& resource : res) - { + for (const auto& resource : res) { command->bindDescriptor({generalSet, resource.textureArraySet}); - //command->bindVertexBuffer({resource.vertexBuffer}); - - command->pushConstants(Gfx::SE_SHADER_STAGE_VERTEX_BIT | Gfx::SE_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(TextData), &resource.textData); - //command->draw(4, static_cast(resource.vertexBuffer->getNumVertices()), 0, 0); + // command->bindVertexBuffer({resource.vertexBuffer}); + + command->pushConstants(Gfx::SE_SHADER_STAGE_VERTEX_BIT | Gfx::SE_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(TextData), + &resource.textData); + // command->draw(4, static_cast(resource.vertexBuffer->getNumVertices()), 0, 0); } commands.add(std::move(command)); } graphics->executeCommands(std::move(commands)); graphics->endRenderPass(); textResources.clear(); - //co_return; + // co_return; } -void TextPass::endFrame() -{ - //co_return; +void TextPass::endFrame() { + // co_return; } -void TextPass::publishOutputs() -{ -} +void TextPass::publishOutputs() {} -void TextPass::createRenderPass() -{ +void TextPass::createRenderPass() { renderTarget = resources->requestRenderTarget("UIPASS_COLOR"); depthAttachment = resources->requestRenderTarget("UIPASS_DEPTH"); - + ShaderCreateInfo createInfo = { .name = "TextVertex", .mainModule = "TextPass", @@ -118,22 +105,35 @@ void TextPass::createRenderPass() vertexShader = graphics->createVertexShader(createInfo); createInfo.name = "TextFragment"; - createInfo.entryPoint = "fragmentMain"; + createInfo.entryPoint = "fragmentMain"; fragmentShader = graphics->createFragmentShader(createInfo); generalLayout = graphics->createDescriptorLayout("pRender"); - generalLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 0, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,}); - generalLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 1, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER,}); + generalLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 0, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + }); + generalLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 1, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER, + }); generalLayout->create(); textureArrayLayout = graphics->createDescriptorLayout("pGlyphTextures"); - textureArrayLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 0, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, .textureType = Gfx::SE_IMAGE_VIEW_TYPE_2D_ARRAY, .descriptorCount = 256, .bindingFlags = Gfx::SE_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT,}); + textureArrayLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 0, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, + .textureType = Gfx::SE_IMAGE_VIEW_TYPE_2D_ARRAY, + .descriptorCount = 256, + .bindingFlags = Gfx::SE_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT, + }); textureArrayLayout->create(); projectionBuffer = graphics->createUniformBuffer({ - .sourceData = { - .size = sizeof(Matrix4), - .data = nullptr, - }, + .sourceData = + { + .size = sizeof(Matrix4), + .data = nullptr, + }, .dynamic = true, }); @@ -148,22 +148,17 @@ void TextPass::createRenderPass() generalSet->updateBuffer(0, projectionBuffer); generalSet->updateSampler(1, glyphSampler); generalSet->writeChanges(); - + pipelineLayout = graphics->createPipelineLayout(); pipelineLayout->addDescriptorLayout(generalLayout); pipelineLayout->addDescriptorLayout(textureArrayLayout); - pipelineLayout->addPushConstants({ - .stageFlags = Gfx::SE_SHADER_STAGE_VERTEX_BIT | Gfx::SE_SHADER_STAGE_FRAGMENT_BIT, - .offset = 0, - .size = sizeof(TextData)}); + pipelineLayout->addPushConstants( + {.stageFlags = Gfx::SE_SHADER_STAGE_VERTEX_BIT | Gfx::SE_SHADER_STAGE_FRAGMENT_BIT, .offset = 0, .size = sizeof(TextData)}); pipelineLayout->create(); - Gfx::RenderTargetLayout layout = Gfx::RenderTargetLayout{ - .colorAttachments = {renderTarget}, - .depthAttachment = depthAttachment - }; + Gfx::RenderTargetLayout layout = Gfx::RenderTargetLayout{.colorAttachments = {renderTarget}, .depthAttachment = depthAttachment}; renderPass = graphics->createRenderPass(std::move(layout), {}, viewport); - + Gfx::LegacyPipelineCreateInfo pipelineInfo; pipelineInfo.vertexShader = vertexShader; pipelineInfo.fragmentShader = fragmentShader; @@ -172,7 +167,8 @@ void TextPass::createRenderPass() pipelineInfo.rasterizationState.cullMode = Gfx::SE_CULL_MODE_NONE; pipelineInfo.colorBlend.attachmentCount = 1; pipelineInfo.colorBlend.blendAttachments[0].blendEnable = true; - pipelineInfo.colorBlend.blendAttachments[0].colorWriteMask = Gfx::SE_COLOR_COMPONENT_R_BIT | Gfx::SE_COLOR_COMPONENT_G_BIT | Gfx::SE_COLOR_COMPONENT_B_BIT | Gfx::SE_COLOR_COMPONENT_A_BIT; + pipelineInfo.colorBlend.blendAttachments[0].colorWriteMask = + Gfx::SE_COLOR_COMPONENT_R_BIT | Gfx::SE_COLOR_COMPONENT_G_BIT | Gfx::SE_COLOR_COMPONENT_B_BIT | Gfx::SE_COLOR_COMPONENT_A_BIT; pipelineInfo.colorBlend.blendAttachments[0].srcColorBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA; pipelineInfo.colorBlend.blendAttachments[0].dstColorBlendFactor = Gfx::SE_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; pipelineInfo.colorBlend.blendAttachments[0].alphaBlendOp = Gfx::SE_BLEND_OP_ADD; @@ -183,19 +179,16 @@ void TextPass::createRenderPass() pipeline = graphics->createGraphicsPipeline(std::move(pipelineInfo)); } -TextPass::FontData& TextPass::getFontData(PFontAsset font) -{ - if(fontData.exists(font)) - { +TextPass::FontData& TextPass::getFontData(PFontAsset font) { + if (fontData.exists(font)) { return fontData[font]; - } + } const auto& fontGlyphs = font->getGlyphData(); FontData& fd = fontData[font]; Array glyphData; Array textures; glyphData.reserve(fontGlyphs.size()); - for(const auto& [key, value] : fontGlyphs) - { + for (const auto& [key, value] : fontGlyphs) { fd.characterToGlyphIndex[key] = static_cast(glyphData.size()); GlyphData& gd = glyphData.add(); gd.bearing = value.bearing; @@ -204,7 +197,7 @@ TextPass::FontData& TextPass::getFontData(PFontAsset font) textures.add(font->getTexture(value.textureIndex)); } fd.glyphDataSet = glyphData; - + textureArrayLayout->reset(); fd.textureArraySet = textureArrayLayout->allocateDescriptorSet(); fd.textureArraySet->updateTextureArray(0, textures); diff --git a/src/Engine/Graphics/RenderPass/TextPass.h b/src/Engine/Graphics/RenderPass/TextPass.h index 22b71b7..e4c1cd8 100644 --- a/src/Engine/Graphics/RenderPass/TextPass.h +++ b/src/Engine/Graphics/RenderPass/TextPass.h @@ -1,24 +1,22 @@ #pragma once -#include "RenderPass.h" -#include "UI/RenderHierarchy.h" #include "Asset/FontAsset.h" #include "Graphics/Shader.h" +#include "RenderPass.h" +#include "UI/RenderHierarchy.h" -namespace Seele -{ + +namespace Seele { DECLARE_NAME_REF(Gfx, Texture2D) DECLARE_NAME_REF(Gfx, ShaderBuffer) -struct TextRender -{ +struct TextRender { std::string text; PFontAsset font; Vector4 textColor; Vector2 position; float scale; }; -class TextPass : public RenderPass -{ -public: +class TextPass : public RenderPass { + public: TextPass(Gfx::PGraphics graphics, PScene scene); TextPass(TextPass&&) = default; TextPass& operator=(TextPass&&) = default; @@ -28,26 +26,23 @@ public: virtual void endFrame() override; virtual void publishOutputs() override; virtual void createRenderPass() override; -private: - struct GlyphData - { + + private: + struct GlyphData { Vector2 bearing; Vector2 size; uint32 advance; }; - struct GlyphInstanceData - { + struct GlyphInstanceData { Vector2 position; Vector2 widthHeight; uint32 glyphIndex; }; - struct TextData - { + struct TextData { Vector4 textColor; float scale; }; - struct FontData - { + struct FontData { Gfx::PDescriptorSet textureArraySet; Array glyphDataSet; Map characterToGlyphIndex; @@ -55,8 +50,7 @@ private: FontData& getFontData(PFontAsset font); Map fontData; - struct TextResources - { + struct TextResources { Gfx::PShaderBuffer instanceBuffer; Gfx::PDescriptorSet textureArraySet; TextData textData; diff --git a/src/Engine/Graphics/RenderPass/UIPass.cpp b/src/Engine/Graphics/RenderPass/UIPass.cpp index 4d88aef..c1ebc2e 100644 --- a/src/Engine/Graphics/RenderPass/UIPass.cpp +++ b/src/Engine/Graphics/RenderPass/UIPass.cpp @@ -1,30 +1,21 @@ #include "UIPass.h" +#include "Graphics/Command.h" #include "Graphics/Enums.h" -#include "RenderGraph.h" #include "Graphics/Graphics.h" #include "Graphics/RenderTarget.h" -#include "Graphics/Command.h" +#include "RenderGraph.h" + using namespace Seele; -UIPass::UIPass(Gfx::PGraphics graphics, PScene scene) - : RenderPass(graphics, scene) -{ -} +UIPass::UIPass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics, scene) {} -UIPass::~UIPass() -{ - -} +UIPass::~UIPass() {} -void UIPass::beginFrame(const Component::Camera& cam) -{ +void UIPass::beginFrame(const Component::Camera& cam) { RenderPass::beginFrame(cam); VertexBufferCreateInfo info = { - .sourceData = { - .size = (uint32)(sizeof(UI::RenderElementStyle) * renderElements.size()), - .data = (uint8*)renderElements.data() - }, + .sourceData = {.size = (uint32)(sizeof(UI::RenderElementStyle) * renderElements.size()), .data = (uint8*)renderElements.data()}, .vertexSize = sizeof(UI::RenderElementStyle), .numVertices = (uint32)renderElements.size(), }; @@ -37,11 +28,10 @@ void UIPass::beginFrame(const Component::Camera& cam) descriptorSet->updateBuffer(2, numTexturesBuffer); descriptorSet->updateTextureArray(3, usedTextures); descriptorSet->writeChanges(); - //co_return; + // co_return; } -void UIPass::render() -{ +void UIPass::render() { graphics->beginRenderPass(renderPass); Gfx::ORenderCommand command = graphics->createRenderCommand("UIPassCommand"); command->setViewport(viewport); @@ -53,17 +43,15 @@ void UIPass::render() commands.add(std::move(command)); graphics->executeCommands(std::move(commands)); graphics->endRenderPass(); - - //co_return; + + // co_return; } -void UIPass::endFrame() -{ - //co_return; +void UIPass::endFrame() { + // co_return; } -void UIPass::publishOutputs() -{ +void UIPass::publishOutputs() { TextureCreateInfo depthBufferInfo = { .format = Gfx::SE_FORMAT_D32_SFLOAT, .width = viewport->getWidth(), @@ -72,10 +60,9 @@ void UIPass::publishOutputs() }; depthBuffer = graphics->createTexture2D(depthBufferInfo); - depthAttachment = - Gfx::RenderTargetAttachment(depthBuffer, - Gfx::SE_IMAGE_LAYOUT_UNDEFINED, Gfx::SE_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, - Gfx::SE_ATTACHMENT_LOAD_OP_CLEAR, Gfx::SE_ATTACHMENT_STORE_OP_STORE); + depthAttachment = + Gfx::RenderTargetAttachment(depthBuffer, Gfx::SE_IMAGE_LAYOUT_UNDEFINED, Gfx::SE_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + Gfx::SE_ATTACHMENT_LOAD_OP_CLEAR, Gfx::SE_ATTACHMENT_STORE_OP_STORE); resources->registerRenderPassOutput("UIPASS_DEPTH", depthAttachment); TextureCreateInfo colorBufferInfo = { @@ -85,16 +72,14 @@ void UIPass::publishOutputs() .usage = Gfx::SE_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, }; colorBuffer = graphics->createTexture2D(colorBufferInfo); - renderTarget = - Gfx::RenderTargetAttachment(colorBuffer, - Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - Gfx::SE_ATTACHMENT_LOAD_OP_CLEAR, Gfx::SE_ATTACHMENT_STORE_OP_STORE); - renderTarget.clear.color = { {0.0f, 0.0f, 0.0f, 1.0f} }; + renderTarget = Gfx::RenderTargetAttachment(colorBuffer, Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, Gfx::SE_ATTACHMENT_LOAD_OP_CLEAR, + Gfx::SE_ATTACHMENT_STORE_OP_STORE); + renderTarget.clear.color = {{0.0f, 0.0f, 0.0f, 1.0f}}; resources->registerRenderPassOutput("UIPASS_COLOR", renderTarget); } -void UIPass::createRenderPass() -{ +void UIPass::createRenderPass() { ShaderCreateInfo createInfo = { .name = "UIVertex", .mainModule = "UIPass", @@ -103,32 +88,45 @@ void UIPass::createRenderPass() vertexShader = graphics->createVertexShader(createInfo); createInfo.name = "UIFragment"; - createInfo.entryPoint = "fragmentMain"; + createInfo.entryPoint = "fragmentMain"; fragmentShader = graphics->createFragmentShader(createInfo); descriptorLayout = graphics->createDescriptorLayout("pParams"); - descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 0, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,}); - descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 1, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER,}); - descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 2, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,}); - descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 3, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, .textureType = Gfx::SE_IMAGE_VIEW_TYPE_2D_ARRAY, .descriptorCount = 256, .bindingFlags = Gfx::SE_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT | Gfx::SE_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT,}); + descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 0, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + }); + descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 1, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER, + }); + descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 2, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + }); + descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 3, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, + .textureType = Gfx::SE_IMAGE_VIEW_TYPE_2D_ARRAY, + .descriptorCount = 256, + .bindingFlags = Gfx::SE_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT | Gfx::SE_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT, + }); descriptorLayout->create(); Matrix4 projectionMatrix = glm::ortho(0, 1, 1, 0); UniformBufferCreateInfo info = { - .sourceData = { - .size = sizeof(Matrix4), - .data = (uint8*)&projectionMatrix, - }, + .sourceData = + { + .size = sizeof(Matrix4), + .data = (uint8*)&projectionMatrix, + }, .dynamic = false, }; Gfx::OUniformBuffer uniformBuffer = graphics->createUniformBuffer(info); Gfx::OSampler backgroundSampler = graphics->createSampler({}); info = { - .sourceData = { - .size = sizeof(uint32), - .data = nullptr - }, + .sourceData = {.size = sizeof(uint32), .data = nullptr}, .dynamic = true, }; @@ -143,12 +141,9 @@ void UIPass::createRenderPass() pipelineLayout->addDescriptorLayout(descriptorLayout); pipelineLayout->create(); - Gfx::RenderTargetLayout layout = Gfx::RenderTargetLayout{ - .colorAttachments = { renderTarget }, - .depthAttachment = depthAttachment - }; + Gfx::RenderTargetLayout layout = Gfx::RenderTargetLayout{.colorAttachments = {renderTarget}, .depthAttachment = depthAttachment}; renderPass = graphics->createRenderPass(std::move(layout), {}, viewport); - + Gfx::LegacyPipelineCreateInfo pipelineInfo; pipelineInfo.vertexShader = vertexShader; pipelineInfo.fragmentShader = fragmentShader; diff --git a/src/Engine/Graphics/RenderPass/UIPass.h b/src/Engine/Graphics/RenderPass/UIPass.h index f1dd870..e716033 100644 --- a/src/Engine/Graphics/RenderPass/UIPass.h +++ b/src/Engine/Graphics/RenderPass/UIPass.h @@ -1,15 +1,14 @@ #pragma once +#include "Graphics/Shader.h" #include "RenderPass.h" #include "UI/RenderHierarchy.h" -#include "Graphics/Shader.h" -namespace Seele -{ + +namespace Seele { DECLARE_NAME_REF(Gfx, Texture2D) DECLARE_NAME_REF(Gfx, RenderTargetAttachment) -class UIPass : public RenderPass -{ -public: +class UIPass : public RenderPass { + public: UIPass(Gfx::PGraphics graphics, PScene scene); UIPass(UIPass&&) = default; UIPass& operator=(UIPass&&) = default; @@ -19,7 +18,8 @@ public: virtual void endFrame() override; virtual void publishOutputs() override; virtual void createRenderPass() override; -private: + + private: Gfx::RenderTargetAttachment renderTarget; Gfx::OTexture2D colorBuffer; Gfx::RenderTargetAttachment depthAttachment; diff --git a/src/Engine/Graphics/RenderPass/VisibilityPass.cpp b/src/Engine/Graphics/RenderPass/VisibilityPass.cpp index 68dde9a..959dbc1 100644 --- a/src/Engine/Graphics/RenderPass/VisibilityPass.cpp +++ b/src/Engine/Graphics/RenderPass/VisibilityPass.cpp @@ -5,64 +5,44 @@ using namespace Seele; extern bool resetVisibility; -VisibilityPass::VisibilityPass(Gfx::PGraphics graphics, PScene scene) - : RenderPass(graphics, scene) -{ -} +VisibilityPass::VisibilityPass(Gfx::PGraphics graphics, PScene scene) : RenderPass(graphics, scene) {} -VisibilityPass::~VisibilityPass() -{ +VisibilityPass::~VisibilityPass() {} -} - -void VisibilityPass::beginFrame(const Component::Camera& cam) -{ +void VisibilityPass::beginFrame(const Component::Camera& cam) { RenderPass::beginFrame(cam); cullingBuffer->rotateBuffer(VertexData::getMeshletCount() * sizeof(VertexData::MeshletCullingInfo), true); - if (resetVisibility) - { + if (resetVisibility) { Array cullingData(VertexData::getMeshletCount()); std::memset(cullingData.data(), 0xffff, cullingData.size() * sizeof(VertexData::MeshletCullingInfo)); - cullingBuffer->updateContents(ShaderBufferCreateInfo{ - .sourceData = { - .size = VertexData::getMeshletCount() * sizeof(VertexData::MeshletCullingInfo), - .data = (uint8 *)cullingData.data(), - }, - .numElements = VertexData::getMeshletCount()}); - cullingBuffer->pipelineBarrier( - Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, - Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, - Gfx::SE_ACCESS_MEMORY_WRITE_BIT, - Gfx::SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT); + cullingBuffer->updateContents( + ShaderBufferCreateInfo{.sourceData = + { + .size = VertexData::getMeshletCount() * sizeof(VertexData::MeshletCullingInfo), + .data = (uint8*)cullingData.data(), + }, + .numElements = VertexData::getMeshletCount()}); + cullingBuffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, + Gfx::SE_ACCESS_MEMORY_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT); resetVisibility = false; } - } -void VisibilityPass::render() -{ - cullingBuffer->pipelineBarrier( - Gfx::SE_ACCESS_SHADER_READ_BIT, - Gfx::SE_PIPELINE_STAGE_MESH_SHADER_BIT_EXT, - Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, - Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT - ); +void VisibilityPass::render() { + cullingBuffer->pipelineBarrier(Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_MESH_SHADER_BIT_EXT, + Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT); cullingBuffer->clear(); - cullingBuffer->pipelineBarrier( - Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, - Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, - Gfx::SE_ACCESS_SHADER_READ_BIT, - Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT - ); + cullingBuffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT, + Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT); visibilityDescriptor->reset(); visibilitySet = visibilityDescriptor->allocateDescriptorSet(); visibilitySet->updateTexture(0, visibilityAttachment.getTexture()); visibilitySet->updateBuffer(1, cullingBuffer); visibilitySet->writeChanges(); - + Gfx::OComputeCommand command = graphics->createComputeCommand("VisibilityCommand"); command->bindPipeline(visibilityPipeline); command->bindDescriptor({viewParamsSet, visibilitySet}); @@ -71,33 +51,33 @@ void VisibilityPass::render() commands.add(std::move(command)); graphics->executeCommands(std::move(commands)); - cullingBuffer->pipelineBarrier( - Gfx::SE_ACCESS_SHADER_WRITE_BIT, - Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - Gfx::SE_ACCESS_SHADER_READ_BIT, - Gfx::SE_PIPELINE_STAGE_TASK_SHADER_BIT_EXT | Gfx::SE_PIPELINE_STAGE_MESH_SHADER_BIT_EXT - ); + cullingBuffer->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + Gfx::SE_ACCESS_SHADER_READ_BIT, + Gfx::SE_PIPELINE_STAGE_TASK_SHADER_BIT_EXT | Gfx::SE_PIPELINE_STAGE_MESH_SHADER_BIT_EXT); } -void VisibilityPass::endFrame() -{ +void VisibilityPass::endFrame() {} -} - -void VisibilityPass::publishOutputs() -{ +void VisibilityPass::publishOutputs() { uint32_t viewportWidth = viewport->getWidth(); uint32_t viewportHeight = viewport->getHeight(); threadGroupSize = glm::ceil(glm::vec3(viewportWidth / (float)BLOCK_SIZE, viewportHeight / (float)BLOCK_SIZE, 1)); visibilityDescriptor = graphics->createDescriptorLayout("pVisibilityParams"); - visibilityDescriptor->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 0, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, }); - visibilityDescriptor->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 1, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT, }); + visibilityDescriptor->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 0, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, + }); + visibilityDescriptor->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 1, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, + .access = Gfx::SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT, + }); visibilityDescriptor->create(); visibilityLayout = graphics->createPipelineLayout("VisibilityLayout"); visibilityLayout->addDescriptorLayout(viewParamsLayout); visibilityLayout->addDescriptorLayout(visibilityDescriptor); - + ShaderCreateInfo createInfo = { .name = "Visibility", .mainModule = "VisibilityCompute", @@ -116,7 +96,4 @@ void VisibilityPass::publishOutputs() resources->registerBufferOutput("CULLINGBUFFER", cullingBuffer); } -void VisibilityPass::createRenderPass() -{ - visibilityAttachment = resources->requestRenderTarget("VISIBILITY"); -} +void VisibilityPass::createRenderPass() { visibilityAttachment = resources->requestRenderTarget("VISIBILITY"); } diff --git a/src/Engine/Graphics/RenderPass/VisibilityPass.h b/src/Engine/Graphics/RenderPass/VisibilityPass.h index 21e843d..a2ffce7 100644 --- a/src/Engine/Graphics/RenderPass/VisibilityPass.h +++ b/src/Engine/Graphics/RenderPass/VisibilityPass.h @@ -1,11 +1,9 @@ #pragma once #include "RenderPass.h" -namespace Seele -{ -class VisibilityPass : public RenderPass -{ -public: +namespace Seele { +class VisibilityPass : public RenderPass { + public: VisibilityPass(Gfx::PGraphics graphics, PScene scene); VisibilityPass(VisibilityPass&&) = default; VisibilityPass& operator=(VisibilityPass&&) = default; @@ -15,7 +13,8 @@ public: virtual void endFrame() override; virtual void publishOutputs() override; virtual void createRenderPass() override; -private: + + private: static constexpr uint32 BLOCK_SIZE = 32; Gfx::RenderTargetAttachment visibilityAttachment; Gfx::PDescriptorSet visibilitySet; @@ -29,4 +28,4 @@ private: glm::uvec3 threadGroupSize; }; DEFINE_REF(VisibilityPass) -} \ No newline at end of file +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/RenderTarget.cpp b/src/Engine/Graphics/RenderTarget.cpp index 55ec81f..d2ec3e0 100644 --- a/src/Engine/Graphics/RenderTarget.cpp +++ b/src/Engine/Graphics/RenderTarget.cpp @@ -3,44 +3,16 @@ using namespace Seele; using namespace Seele::Gfx; -RenderTargetAttachment::RenderTargetAttachment(PTexture2D texture, - SeImageLayout initialLayout, - SeImageLayout finalLayout, - SeAttachmentLoadOp loadOp, - SeAttachmentStoreOp storeOp, - SeAttachmentLoadOp stencilLoadOp, - SeAttachmentStoreOp stencilStoreOp) - : clear() - , componentFlags(0) - , texture(texture) - , initialLayout(initialLayout) - , finalLayout(finalLayout) - , loadOp(loadOp) - , storeOp(storeOp) - , stencilLoadOp(stencilLoadOp) - , stencilStoreOp(stencilStoreOp) -{ -} +RenderTargetAttachment::RenderTargetAttachment(PTexture2D texture, SeImageLayout initialLayout, SeImageLayout finalLayout, + SeAttachmentLoadOp loadOp, SeAttachmentStoreOp storeOp, SeAttachmentLoadOp stencilLoadOp, + SeAttachmentStoreOp stencilStoreOp) + : clear(), componentFlags(0), texture(texture), initialLayout(initialLayout), finalLayout(finalLayout), loadOp(loadOp), + storeOp(storeOp), stencilLoadOp(stencilLoadOp), stencilStoreOp(stencilStoreOp) {} -RenderTargetAttachment::RenderTargetAttachment(PViewport viewport, - SeImageLayout initialLayout, - SeImageLayout finalLayout, - SeAttachmentLoadOp loadOp, - SeAttachmentStoreOp storeOp, - SeAttachmentLoadOp stencilLoadOp, - SeAttachmentStoreOp stencilStoreOp) - : clear() - , componentFlags(0) - , viewport(viewport) - , initialLayout(initialLayout) - , finalLayout(finalLayout) - , loadOp(loadOp) - , storeOp(storeOp) - , stencilLoadOp(stencilLoadOp) - , stencilStoreOp(stencilStoreOp) -{ -} +RenderTargetAttachment::RenderTargetAttachment(PViewport viewport, SeImageLayout initialLayout, SeImageLayout finalLayout, + SeAttachmentLoadOp loadOp, SeAttachmentStoreOp storeOp, SeAttachmentLoadOp stencilLoadOp, + SeAttachmentStoreOp stencilStoreOp) + : clear(), componentFlags(0), viewport(viewport), initialLayout(initialLayout), finalLayout(finalLayout), loadOp(loadOp), + storeOp(storeOp), stencilLoadOp(stencilLoadOp), stencilStoreOp(stencilStoreOp) {} -RenderTargetAttachment::~RenderTargetAttachment() -{ -} +RenderTargetAttachment::~RenderTargetAttachment() {} diff --git a/src/Engine/Graphics/RenderTarget.h b/src/Engine/Graphics/RenderTarget.h index 7fbe7d8..6468c1e 100644 --- a/src/Engine/Graphics/RenderTarget.h +++ b/src/Engine/Graphics/RenderTarget.h @@ -4,70 +4,52 @@ #include "Texture.h" #include "Window.h" -namespace Seele -{ -namespace Gfx -{ -class RenderTargetAttachment -{ -public: - RenderTargetAttachment() - {} - RenderTargetAttachment(PTexture2D texture, - SeImageLayout initialLayout, - SeImageLayout finalLayout, - SeAttachmentLoadOp loadOp = SE_ATTACHMENT_LOAD_OP_LOAD, - SeAttachmentStoreOp storeOp = SE_ATTACHMENT_STORE_OP_STORE, - SeAttachmentLoadOp stencilLoadOp = SE_ATTACHMENT_LOAD_OP_DONT_CARE, - SeAttachmentStoreOp stencilStoreOp = SE_ATTACHMENT_STORE_OP_DONT_CARE); +namespace Seele { +namespace Gfx { +class RenderTargetAttachment { + public: + RenderTargetAttachment() {} + RenderTargetAttachment(PTexture2D texture, SeImageLayout initialLayout, SeImageLayout finalLayout, + SeAttachmentLoadOp loadOp = SE_ATTACHMENT_LOAD_OP_LOAD, + SeAttachmentStoreOp storeOp = SE_ATTACHMENT_STORE_OP_STORE, + SeAttachmentLoadOp stencilLoadOp = SE_ATTACHMENT_LOAD_OP_DONT_CARE, + SeAttachmentStoreOp stencilStoreOp = SE_ATTACHMENT_STORE_OP_DONT_CARE); - RenderTargetAttachment(PViewport viewport, - SeImageLayout initialLayout, - SeImageLayout finalLayout, - SeAttachmentLoadOp loadOp = SE_ATTACHMENT_LOAD_OP_LOAD, - SeAttachmentStoreOp storeOp = SE_ATTACHMENT_STORE_OP_STORE, - SeAttachmentLoadOp stencilLoadOp = SE_ATTACHMENT_LOAD_OP_DONT_CARE, - SeAttachmentStoreOp stencilStoreOp = SE_ATTACHMENT_STORE_OP_DONT_CARE); + RenderTargetAttachment(PViewport viewport, SeImageLayout initialLayout, SeImageLayout finalLayout, + SeAttachmentLoadOp loadOp = SE_ATTACHMENT_LOAD_OP_LOAD, + SeAttachmentStoreOp storeOp = SE_ATTACHMENT_STORE_OP_STORE, + SeAttachmentLoadOp stencilLoadOp = SE_ATTACHMENT_LOAD_OP_DONT_CARE, + SeAttachmentStoreOp stencilStoreOp = SE_ATTACHMENT_STORE_OP_DONT_CARE); ~RenderTargetAttachment(); - PTexture2D getTexture() const - { - if(viewport != nullptr) - { + PTexture2D getTexture() const { + if (viewport != nullptr) { return viewport->getOwner()->getBackBuffer(); } return texture; } - SeFormat getFormat() const - { - if(viewport != nullptr) - { + SeFormat getFormat() const { + if (viewport != nullptr) { return viewport->getOwner()->getSwapchainFormat(); } return texture->getFormat(); } - SeSampleCountFlags getNumSamples() const - { - if(viewport != nullptr) - { + SeSampleCountFlags getNumSamples() const { + if (viewport != nullptr) { return viewport->getSamples(); } return texture->getNumSamples(); } - uint32 getWidth() const - { - if(viewport != nullptr) - { + uint32 getWidth() const { + if (viewport != nullptr) { return viewport->getWidth(); } - return texture->getWidth(); + return texture->getWidth(); } - uint32 getHeight() const - { - if(viewport != nullptr) - { + uint32 getHeight() const { + if (viewport != nullptr) { return viewport->getHeight(); } - return texture->getHeight(); + return texture->getHeight(); } constexpr SeAttachmentLoadOp getLoadOp() const { return loadOp; } constexpr SeAttachmentStoreOp getStoreOp() const { return storeOp; } @@ -81,9 +63,10 @@ public: constexpr void setStencilStoreOp(SeAttachmentStoreOp val) { stencilStoreOp = val; } constexpr void setInitialLayout(SeImageLayout val) { initialLayout = val; } constexpr void setFinalLayout(SeImageLayout val) { finalLayout = val; } - SeClearValue clear = { { { 0 } } }; + SeClearValue clear = {{{0}}}; SeColorComponentFlags componentFlags = 0; -protected: + + protected: PTexture2D texture = nullptr; PViewport viewport = nullptr; SeImageLayout initialLayout = SE_IMAGE_LAYOUT_UNDEFINED; @@ -94,8 +77,7 @@ protected: SeAttachmentStoreOp stencilStoreOp = SE_ATTACHMENT_STORE_OP_DONT_CARE; }; -struct RenderTargetLayout -{ +struct RenderTargetLayout { Array inputAttachments; Array colorAttachments; Array resolveAttachments; @@ -103,8 +85,7 @@ struct RenderTargetLayout RenderTargetAttachment depthResolveAttachment; }; -struct SubPassDependency -{ +struct SubPassDependency { uint32 srcSubpass; uint32 dstSubpass; SePipelineStageFlags srcStage; @@ -113,22 +94,19 @@ struct SubPassDependency SeAccessFlags dstAccess; }; -class RenderPass -{ -public: - RenderPass(RenderTargetLayout layout, Array dependencies) - : layout(std::move(layout)) - , dependencies(std::move(dependencies)) - {} +class RenderPass { + public: + RenderPass(RenderTargetLayout layout, Array dependencies) + : layout(std::move(layout)), dependencies(std::move(dependencies)) {} virtual ~RenderPass() {} RenderPass(RenderPass&&) = default; RenderPass& operator=(RenderPass&&) = default; const RenderTargetLayout& getLayout() const { return layout; } -protected: + protected: RenderTargetLayout layout; Array dependencies; }; DEFINE_REF(RenderPass) -} -} \ No newline at end of file +} // namespace Gfx +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/Resources.cpp b/src/Engine/Graphics/Resources.cpp index 5107bf6..b8c8213 100644 --- a/src/Engine/Graphics/Resources.cpp +++ b/src/Engine/Graphics/Resources.cpp @@ -1,35 +1,28 @@ #include "Resources.h" #include "Graphics.h" -#include "RenderPass/DepthPrepass.h" -#include "RenderPass/BasePass.h" #include "Material/Material.h" +#include "RenderPass/BasePass.h" +#include "RenderPass/DepthPrepass.h" #include "Resources.h" + using namespace Seele; using namespace Seele::Gfx; QueueOwnedResource::QueueOwnedResource(QueueFamilyMapping mapping, QueueType startQueueType) - : currentOwner(startQueueType) - , mapping(mapping) -{ + : currentOwner(startQueueType), mapping(mapping) {} + +QueueOwnedResource::~QueueOwnedResource() {} + +void QueueOwnedResource::transferOwnership(QueueType newOwner) { + if (mapping.needsTransfer(currentOwner, newOwner)) { + executeOwnershipBarrier(newOwner); + } + currentOwner = newOwner; } -QueueOwnedResource::~QueueOwnedResource() -{ +void QueueOwnedResource::pipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, + SePipelineStageFlags dstStage) { + // maybe add some checks + executePipelineBarrier(srcAccess, srcStage, dstAccess, dstStage); } - -void QueueOwnedResource::transferOwnership(QueueType newOwner) -{ - if(mapping.needsTransfer(currentOwner, newOwner)) - { - executeOwnershipBarrier(newOwner); - } - currentOwner = newOwner; -} - -void QueueOwnedResource::pipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, SePipelineStageFlags dstStage) -{ - // maybe add some checks - executePipelineBarrier(srcAccess, srcStage, dstAccess, dstStage); -} - diff --git a/src/Engine/Graphics/Resources.h b/src/Engine/Graphics/Resources.h index 1d167df..2b69dad 100644 --- a/src/Engine/Graphics/Resources.h +++ b/src/Engine/Graphics/Resources.h @@ -1,41 +1,34 @@ #pragma once -#include "Math/Math.h" -#include "Enums.h" #include "Containers/Array.h" +#include "Enums.h" +#include "Math/Math.h" + #ifndef ENABLE_VALIDATION #define ENABLE_VALIDATION 1 #endif -namespace Seele -{ +namespace Seele { DECLARE_REF(Material) -namespace Gfx -{ +namespace Gfx { DECLARE_REF(DescriptorSet) DECLARE_REF(Graphics) DECLARE_REF(VertexBuffer) DECLARE_REF(IndexBuffer) DECLARE_REF(GraphicsPipeline) DECLARE_REF(ComputePipeline) -class Sampler -{ -public: - virtual ~Sampler() - { - } +class Sampler { + public: + virtual ~Sampler() {} }; DEFINE_REF(Sampler) -struct QueueFamilyMapping -{ +struct QueueFamilyMapping { uint32 graphicsFamily; uint32 computeFamily; uint32 transferFamily; - uint32 getQueueTypeFamilyIndex(Gfx::QueueType type) const - { - switch (type) - { + uint32 getQueueTypeFamilyIndex(Gfx::QueueType type) const { + switch (type) { case Gfx::QueueType::GRAPHICS: return graphicsFamily; case Gfx::QueueType::COMPUTE: @@ -46,28 +39,26 @@ struct QueueFamilyMapping return 0x7fff; } } - bool needsTransfer(Gfx::QueueType src, Gfx::QueueType dst) const - { + bool needsTransfer(Gfx::QueueType src, Gfx::QueueType dst) const { uint32 srcIndex = getQueueTypeFamilyIndex(src); uint32 dstIndex = getQueueTypeFamilyIndex(dst); return srcIndex != dstIndex; } }; -class QueueOwnedResource -{ -public: +class QueueOwnedResource { + public: QueueOwnedResource(QueueFamilyMapping mapping, QueueType startQueueType); virtual ~QueueOwnedResource(); - //Preliminary checks to see if the barrier should be executed at all + // Preliminary checks to see if the barrier should be executed at all void transferOwnership(QueueType newOwner); void pipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, SePipelineStageFlags dstStage); -protected: + protected: virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, + SePipelineStageFlags dstStage) = 0; Gfx::QueueType currentOwner; QueueFamilyMapping mapping; }; diff --git a/src/Engine/Graphics/Shader.cpp b/src/Engine/Graphics/Shader.cpp index b775b67..3895887 100644 --- a/src/Engine/Graphics/Shader.cpp +++ b/src/Engine/Graphics/Shader.cpp @@ -1,117 +1,90 @@ #include "Shader.h" -#include "ThreadPool.h" #include "Graphics/Initializer.h" -#include "Graphics/RenderPass/DepthPrepass.h" #include "Graphics/RenderPass/BasePass.h" +#include "Graphics/RenderPass/DepthPrepass.h" +#include "ThreadPool.h" #include + using namespace Seele; using namespace Seele::Gfx; -ShaderCompiler::ShaderCompiler(Gfx::PGraphics graphics) - : graphics(graphics) -{ -} +ShaderCompiler::ShaderCompiler(Gfx::PGraphics graphics) : graphics(graphics) {} -ShaderCompiler::~ShaderCompiler() -{ -} +ShaderCompiler::~ShaderCompiler() {} -const ShaderCollection *ShaderCompiler::findShaders(PermutationId id) const -{ - return &shaders[id]; -} +const ShaderCollection* ShaderCompiler::findShaders(PermutationId id) const { return &shaders[id]; } -void ShaderCompiler::registerMaterial(PMaterial material) -{ +void ShaderCompiler::registerMaterial(PMaterial material) { materials[material->getName()] = material; compile(); } -void ShaderCompiler::registerVertexData(VertexData *vd) -{ +void ShaderCompiler::registerVertexData(VertexData* vd) { vertexData[vd->getTypeName()] = vd; compile(); } -void ShaderCompiler::registerRenderPass(std::string name, PassConfig config) -{ +void ShaderCompiler::registerRenderPass(std::string name, PassConfig config) { passes[name] = std::move(config); compile(); } -ShaderPermutation ShaderCompiler::getTemplate(std::string name) -{ +ShaderPermutation ShaderCompiler::getTemplate(std::string name) { std::scoped_lock lock(shadersLock); ShaderPermutation permutation; - PassConfig &pass = passes[name]; - if (pass.useMeshShading) - { + PassConfig& pass = passes[name]; + if (pass.useMeshShading) { permutation.setMeshFile(pass.mainFile); - } - else - { + } else { permutation.setVertexFile(pass.mainFile); } - if (pass.hasFragmentShader) - { + if (pass.hasFragmentShader) { permutation.setFragmentFile(pass.fragmentFile); } - if (pass.hasTaskShader) - { + if (pass.hasTaskShader) { permutation.setTaskFile(pass.taskFile); } permutation.setVisibilityPass(pass.useVisibility); return permutation; } -void ShaderCompiler::compile() -{ +void ShaderCompiler::compile() { List> work; - for (const auto &[name, pass] : passes) - { - for (const auto &[vdName, vd] : vertexData) - { - if (pass.useMaterial) - { - for (const auto &[matName, mat] : materials) - { - for (int x = 0; x < 2; x++) - { - for (int y = 0; y < 2; y++) - { - work.add([=]() - { - ShaderPermutation permutation = getTemplate(name); - permutation.setPositionOnly(x); - permutation.setViewCulling(y); - permutation.setVertexData(vd->getTypeName()); - OPipelineLayout layout = graphics->createPipelineLayout(pass.baseLayout->getName(), pass.baseLayout); - layout->addDescriptorLayout(vd->getVertexDataLayout()); - layout->addDescriptorLayout(vd->getInstanceDataLayout()); - layout->addDescriptorLayout(mat->getDescriptorLayout()); - permutation.setMaterial(mat->getName()); - createShaders(permutation, std::move(layout)); }); + for (const auto& [name, pass] : passes) { + for (const auto& [vdName, vd] : vertexData) { + if (pass.useMaterial) { + for (const auto& [matName, mat] : materials) { + for (int x = 0; x < 2; x++) { + for (int y = 0; y < 2; y++) { + work.add([=]() { + ShaderPermutation permutation = getTemplate(name); + permutation.setPositionOnly(x); + permutation.setViewCulling(y); + permutation.setVertexData(vd->getTypeName()); + OPipelineLayout layout = graphics->createPipelineLayout(pass.baseLayout->getName(), pass.baseLayout); + layout->addDescriptorLayout(vd->getVertexDataLayout()); + layout->addDescriptorLayout(vd->getInstanceDataLayout()); + layout->addDescriptorLayout(mat->getDescriptorLayout()); + permutation.setMaterial(mat->getName()); + createShaders(permutation, std::move(layout)); + }); } } } - } - else - { - for (int x = 0; x < 2; x++) - { - for (int y = 0; y < 2; y++) - { - work.add([=]() - { - ShaderPermutation permutation = getTemplate(name); - permutation.setPositionOnly(x); - permutation.setViewCulling(y); - permutation.setVertexData(vd->getTypeName()); - OPipelineLayout layout = graphics->createPipelineLayout(pass.baseLayout->getName(), pass.baseLayout); - layout->addDescriptorLayout(vd->getVertexDataLayout()); - layout->addDescriptorLayout(vd->getInstanceDataLayout()); - createShaders(permutation, std::move(layout)); }); + } else { + for (int x = 0; x < 2; x++) { + for (int y = 0; y < 2; y++) { + work.add([=]() { + ShaderPermutation permutation = getTemplate(name); + permutation.setPositionOnly(x); + permutation.setViewCulling(y); + permutation.setVertexData(vd->getTypeName()); + OPipelineLayout layout = graphics->createPipelineLayout(pass.baseLayout->getName(), pass.baseLayout); + layout->addDescriptorLayout(vd->getVertexDataLayout()); + layout->addDescriptorLayout(vd->getInstanceDataLayout()); + createShaders(permutation, std::move(layout)); + }); } } } @@ -120,8 +93,7 @@ void ShaderCompiler::compile() getThreadPool().runAndWait(std::move(work)); } -void ShaderCompiler::createShaders(ShaderPermutation permutation, Gfx::OPipelineLayout layout) -{ +void ShaderCompiler::createShaders(ShaderPermutation permutation, Gfx::OPipelineLayout layout) { PermutationId perm = PermutationId(permutation); { std::scoped_lock lock(shadersLock); @@ -134,30 +106,24 @@ void ShaderCompiler::createShaders(ShaderPermutation permutation, Gfx::OPipeline ShaderCreateInfo createInfo; createInfo.name = fmt::format("Material {0}", permutation.materialName); createInfo.rootSignature = collection.pipelineLayout; - if (std::strlen(permutation.materialName) > 0) - { + if (std::strlen(permutation.materialName) > 0) { createInfo.additionalModules.add(permutation.materialName); createInfo.defines["MATERIAL_FILE_NAME"] = permutation.materialName; } - if (permutation.positionOnly) - { + if (permutation.positionOnly) { createInfo.defines["POS_ONLY"] = "1"; } - if (permutation.viewCulling) - { + if (permutation.viewCulling) { createInfo.defines["VIEW_CULLING"] = "1"; } - if (permutation.visibilityPass) - { + if (permutation.visibilityPass) { createInfo.defines["VISIBILITY"] = "1"; } - createInfo.typeParameter.add({Pair("IVertexData", permutation.vertexDataName)}); + createInfo.typeParameter.add({Pair("IVertexData", permutation.vertexDataName)}); createInfo.additionalModules.add(permutation.vertexDataName); - if (permutation.useMeshShading) - { - if (permutation.hasTaskShader) - { + if (permutation.useMeshShading) { + if (permutation.hasTaskShader) { createInfo.mainModule = permutation.taskFile; createInfo.entryPoint = "taskMain"; collection.taskShader = graphics->createTaskShader(createInfo); @@ -165,16 +131,13 @@ void ShaderCompiler::createShaders(ShaderPermutation permutation, Gfx::OPipeline createInfo.mainModule = permutation.vertexMeshFile; createInfo.entryPoint = "meshMain"; collection.meshShader = graphics->createMeshShader(createInfo); - } - else - { + } else { createInfo.mainModule = permutation.vertexMeshFile; createInfo.entryPoint = "vertexMain"; collection.vertexShader = graphics->createVertexShader(createInfo); } - if (permutation.hasFragment) - { + if (permutation.hasFragment) { createInfo.mainModule = permutation.fragmentFile; createInfo.entryPoint = "fragmentMain"; collection.fragmentShader = graphics->createFragmentShader(createInfo); diff --git a/src/Engine/Graphics/Shader.h b/src/Engine/Graphics/Shader.h index a6b341f..887fbba 100644 --- a/src/Engine/Graphics/Shader.h +++ b/src/Engine/Graphics/Shader.h @@ -1,58 +1,50 @@ #pragma once -#include "Enums.h" #include "CRC.h" +#include "Enums.h" #include "Resources.h" #include "VertexData.h" -namespace Seele -{ -namespace Gfx -{ -class Shader -{}; +namespace Seele { +namespace Gfx { + +class Shader {}; DEFINE_REF(Shader) -class TaskShader -{ -public: +class TaskShader { + public: TaskShader() {} virtual ~TaskShader() {} }; DEFINE_REF(TaskShader) -class MeshShader -{ -public: +class MeshShader { + public: MeshShader() {} virtual ~MeshShader() {} }; DEFINE_REF(MeshShader) -class VertexShader -{ -public: +class VertexShader { + public: VertexShader() {} virtual ~VertexShader() {} }; DEFINE_REF(VertexShader) -class FragmentShader -{ -public: +class FragmentShader { + public: FragmentShader() {} virtual ~FragmentShader() {} }; DEFINE_REF(FragmentShader) -class ComputeShader -{ -public: +class ComputeShader { + public: ComputeShader() {} virtual ~ComputeShader() {} }; DEFINE_REF(ComputeShader) -//Uniquely identifies a permutation of shaders -//using the type parameters used to generate it -struct ShaderPermutation -{ +// Uniquely identifies a permutation of shaders +// using the type parameters used to generate it +struct ShaderPermutation { char taskFile[32]; char vertexMeshFile[32]; char fragmentFile[32]; @@ -65,80 +57,50 @@ struct ShaderPermutation uint8 positionOnly; uint8 viewCulling; uint8 visibilityPass; - //TODO: lightmapping etc - ShaderPermutation() - { - std::memset(this, 0, sizeof(ShaderPermutation)); - } - void setTaskFile(std::string_view name) - { + // TODO: lightmapping etc + ShaderPermutation() { std::memset(this, 0, sizeof(ShaderPermutation)); } + void setTaskFile(std::string_view name) { std::memset(taskFile, 0, sizeof(taskFile)); hasTaskShader = 1; strncpy(taskFile, name.data(), sizeof(taskFile)); } - void setVertexFile(std::string_view name) - { + void setVertexFile(std::string_view name) { std::memset(vertexMeshFile, 0, sizeof(vertexMeshFile)); useMeshShading = 0; strncpy(vertexMeshFile, name.data(), sizeof(vertexMeshFile)); } - void setMeshFile(std::string_view name) - { + void setMeshFile(std::string_view name) { std::memset(vertexMeshFile, 0, sizeof(vertexMeshFile)); useMeshShading = 1; strncpy(vertexMeshFile, name.data(), sizeof(vertexMeshFile)); } - void setFragmentFile(std::string_view name) - { + void setFragmentFile(std::string_view name) { std::memset(fragmentFile, 0, sizeof(fragmentFile)); hasFragment = 1; strncpy(fragmentFile, name.data(), sizeof(fragmentFile)); } - void setVertexData(std::string_view name) - { + void setVertexData(std::string_view name) { std::memset(vertexDataName, 0, sizeof(vertexDataName)); strncpy(vertexDataName, name.data(), sizeof(vertexDataName)); } - void setMaterial(std::string_view name) - { + void setMaterial(std::string_view name) { std::memset(materialName, 0, sizeof(materialName)); useMaterial = 1; strncpy(materialName, name.data(), sizeof(materialName)); } - void setPositionOnly(bool enable) - { - positionOnly = enable; - } - void setViewCulling(bool enable) - { - viewCulling = enable; - } - void setVisibilityPass(bool enable) - { - visibilityPass = enable; - } + void setPositionOnly(bool enable) { positionOnly = enable; } + void setViewCulling(bool enable) { viewCulling = enable; } + void setVisibilityPass(bool enable) { visibilityPass = enable; } }; -//Hashed ShaderPermutation for fast lookup -struct PermutationId -{ +// Hashed ShaderPermutation for fast lookup +struct PermutationId { uint32 hash; - PermutationId() - : hash(0) - {} - PermutationId(ShaderPermutation permutation) - : hash(CRC::Calculate(&permutation, sizeof(ShaderPermutation), CRC::CRC_32())) - {} - friend constexpr bool operator==(const PermutationId& lhs, const PermutationId& rhs) - { - return lhs.hash == rhs.hash; - } - friend constexpr auto operator<=>(const PermutationId& lhs, const PermutationId& rhs) - { - return lhs.hash <=> rhs.hash; - } + PermutationId() : hash(0) {} + PermutationId(ShaderPermutation permutation) : hash(CRC::Calculate(&permutation, sizeof(ShaderPermutation), CRC::CRC_32())) {} + friend constexpr bool operator==(const PermutationId& lhs, const PermutationId& rhs) { return lhs.hash == rhs.hash; } + friend constexpr auto operator<=>(const PermutationId& lhs, const PermutationId& rhs) { return lhs.hash <=> rhs.hash; } }; -struct ShaderCollection -{ +struct ShaderCollection { OPipelineLayout pipelineLayout; OVertexShader vertexShader; OTaskShader taskShader; @@ -146,8 +108,7 @@ struct ShaderCollection OFragmentShader fragmentShader; }; -struct PassConfig -{ +struct PassConfig { Gfx::PPipelineLayout baseLayout; std::string taskFile = ""; std::string mainFile = ""; @@ -158,9 +119,8 @@ struct PassConfig bool useMaterial = false; bool useVisibility = false; }; -class ShaderCompiler -{ -public: +class ShaderCompiler { + public: ShaderCompiler(Gfx::PGraphics graphics); ~ShaderCompiler(); const ShaderCollection* findShaders(PermutationId id) const; @@ -168,7 +128,8 @@ public: void registerVertexData(VertexData* vertexData); void registerRenderPass(std::string name, PassConfig config); ShaderPermutation getTemplate(std::string name); -private: + + private: void compile(); void createShaders(ShaderPermutation permutation, OPipelineLayout layout); std::mutex shadersLock; @@ -179,5 +140,5 @@ private: Gfx::PGraphics graphics; }; DEFINE_REF(ShaderCompiler) -} +} // namespace Gfx } // namespace Seele diff --git a/src/Engine/Graphics/StaticMeshVertexData.cpp b/src/Engine/Graphics/StaticMeshVertexData.cpp index e6ecb3a..bb445cf 100644 --- a/src/Engine/Graphics/StaticMeshVertexData.cpp +++ b/src/Engine/Graphics/StaticMeshVertexData.cpp @@ -7,22 +7,16 @@ using namespace Seele; extern List vertexDataList; -StaticMeshVertexData::StaticMeshVertexData() -{ - vertexDataList.add(this); -} +StaticMeshVertexData::StaticMeshVertexData() { vertexDataList.add(this); } -StaticMeshVertexData::~StaticMeshVertexData() -{} +StaticMeshVertexData::~StaticMeshVertexData() {} -StaticMeshVertexData* StaticMeshVertexData::getInstance() -{ +StaticMeshVertexData* StaticMeshVertexData::getInstance() { static StaticMeshVertexData instance; return &instance; } -void StaticMeshVertexData::loadPositions(MeshId id, const Array& data) -{ +void StaticMeshVertexData::loadPositions(MeshId id, const Array& data) { uint64 offset; { std::unique_lock l(mutex); @@ -33,8 +27,7 @@ void StaticMeshVertexData::loadPositions(MeshId id, const Array& data) dirty = true; } -void StaticMeshVertexData::loadTexCoords(MeshId id, uint64 index, const Array& data) -{ +void StaticMeshVertexData::loadTexCoords(MeshId id, uint64 index, const Array& data) { uint64 offset; { std::unique_lock l(mutex); @@ -45,8 +38,7 @@ void StaticMeshVertexData::loadTexCoords(MeshId id, uint64 index, const Array& data) -{ +void StaticMeshVertexData::loadNormals(MeshId id, const Array& data) { uint64 offset; { std::unique_lock l(mutex); @@ -57,8 +49,7 @@ void StaticMeshVertexData::loadNormals(MeshId id, const Array& data) dirty = true; } -void StaticMeshVertexData::loadTangents(MeshId id, const Array& data) -{ +void StaticMeshVertexData::loadTangents(MeshId id, const Array& data) { uint64 offset; { std::unique_lock l(mutex); @@ -69,8 +60,7 @@ void StaticMeshVertexData::loadTangents(MeshId id, const Array& data) dirty = true; } -void StaticMeshVertexData::loadBiTangents(MeshId id, const Array& data) -{ +void StaticMeshVertexData::loadBiTangents(MeshId id, const Array& data) { uint64 offset; { std::unique_lock l(mutex); @@ -81,8 +71,7 @@ void StaticMeshVertexData::loadBiTangents(MeshId id, const Array& data) dirty = true; } -void Seele::StaticMeshVertexData::loadColors(MeshId id, const Array& data) -{ +void Seele::StaticMeshVertexData::loadColors(MeshId id, const Array& data) { uint64 offset; { std::unique_lock l(mutex); @@ -93,8 +82,7 @@ void Seele::StaticMeshVertexData::loadColors(MeshId id, const Array& dat dirty = true; } -void StaticMeshVertexData::serializeMesh(MeshId id, uint64 numVertices, ArchiveBuffer& buffer) -{ +void StaticMeshVertexData::serializeMesh(MeshId id, uint64 numVertices, ArchiveBuffer& buffer) { uint64 offset; { std::unique_lock l(mutex); @@ -102,8 +90,7 @@ void StaticMeshVertexData::serializeMesh(MeshId id, uint64 numVertices, ArchiveB } Array pos(numVertices); Array tex[MAX_TEXCOORDS]; - for (size_t i = 0; i < MAX_TEXCOORDS; ++i) - { + for (size_t i = 0; i < MAX_TEXCOORDS; ++i) { tex[i].resize(numVertices); std::memcpy(tex[i].data(), texCoordsData[i].data() + offset, numVertices * sizeof(Vector2)); Serialization::save(buffer, tex[i]); @@ -124,12 +111,10 @@ void StaticMeshVertexData::serializeMesh(MeshId id, uint64 numVertices, ArchiveB Serialization::save(buffer, col); } -void StaticMeshVertexData::deserializeMesh(MeshId id, ArchiveBuffer& buffer) -{ +void StaticMeshVertexData::deserializeMesh(MeshId id, ArchiveBuffer& buffer) { Array pos; Array tex[MAX_TEXCOORDS]; - for (size_t i = 0; i < MAX_TEXCOORDS; ++i) - { + for (size_t i = 0; i < MAX_TEXCOORDS; ++i) { Serialization::load(buffer, tex[i]); loadTexCoords(id, i, tex[i]); } @@ -149,26 +134,24 @@ void StaticMeshVertexData::deserializeMesh(MeshId id, ArchiveBuffer& buffer) loadColors(id, col); } -void StaticMeshVertexData::init(Gfx::PGraphics _graphics) -{ +void StaticMeshVertexData::init(Gfx::PGraphics _graphics) { VertexData::init(_graphics); descriptorLayout = _graphics->createDescriptorLayout("pVertexData"); - descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 0, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER }); - descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 1, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER }); - descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 2, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER }); - descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 3, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER }); - descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 4, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER }); - descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = 5, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .descriptorCount = MAX_TEXCOORDS }); + descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 0, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER}); + descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 1, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER}); + descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 2, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER}); + descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 3, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER}); + descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 4, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER}); + descriptorLayout->addDescriptorBinding( + Gfx::DescriptorBinding{.binding = 5, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, .descriptorCount = MAX_TEXCOORDS}); descriptorLayout->create(); descriptorSet = descriptorLayout->allocateDescriptorSet(); } -void StaticMeshVertexData::destroy() -{ +void StaticMeshVertexData::destroy() { VertexData::destroy(); positions = nullptr; - for (size_t i = 0; i < MAX_TEXCOORDS; ++i) - { + for (size_t i = 0; i < MAX_TEXCOORDS; ++i) { texCoords[i] = nullptr; } normals = nullptr; @@ -178,27 +161,20 @@ void StaticMeshVertexData::destroy() descriptorLayout = nullptr; } -void StaticMeshVertexData::bindBuffers(Gfx::PRenderCommand) -{ +void StaticMeshVertexData::bindBuffers(Gfx::PRenderCommand) { // TODO: for legacy vertex buffer binding } -Gfx::PDescriptorLayout StaticMeshVertexData::getVertexDataLayout() -{ - return descriptorLayout; -} +Gfx::PDescriptorLayout StaticMeshVertexData::getVertexDataLayout() { return descriptorLayout; } -Gfx::PDescriptorSet StaticMeshVertexData::getVertexDataSet() -{ - return descriptorSet; -} +Gfx::PDescriptorSet StaticMeshVertexData::getVertexDataSet() { return descriptorSet; } -void StaticMeshVertexData::resizeBuffers() -{ +void StaticMeshVertexData::resizeBuffers() { ShaderBufferCreateInfo createInfo = { - .sourceData = { - .size = verticesAllocated * sizeof(Vector), - }, + .sourceData = + { + .size = verticesAllocated * sizeof(Vector), + }, .numElements = verticesAllocated * 3, .dynamic = false, .vertexBuffer = 1, @@ -217,8 +193,7 @@ void StaticMeshVertexData::resizeBuffers() createInfo.sourceData.size = verticesAllocated * sizeof(Vector2); createInfo.name = "TexCoords"; createInfo.numElements = verticesAllocated * 2; - for (size_t i = 0; i < MAX_TEXCOORDS; ++i) - { + for (size_t i = 0; i < MAX_TEXCOORDS; ++i) { texCoords[i] = graphics->createShaderBuffer(createInfo); texCoordsData[i].resize(verticesAllocated); } @@ -230,53 +205,50 @@ void StaticMeshVertexData::resizeBuffers() colorData.resize(verticesAllocated); } -void StaticMeshVertexData::updateBuffers() -{ +void StaticMeshVertexData::updateBuffers() { positions->updateContents(ShaderBufferCreateInfo{ .sourceData{ .size = positionData.size() * sizeof(Vector), .data = (uint8*)positionData.data(), }, .numElements = positionData.size(), - }); - for (size_t i = 0; i < MAX_TEXCOORDS; ++i) - { - texCoords[i]->updateContents(ShaderBufferCreateInfo { - .sourceData = { - .size = texCoordsData[i].size() * sizeof(Vector2), - .data = (uint8*)texCoordsData[i].data(), - }, + }); + for (size_t i = 0; i < MAX_TEXCOORDS; ++i) { + texCoords[i]->updateContents(ShaderBufferCreateInfo{ + .sourceData = + { + .size = texCoordsData[i].size() * sizeof(Vector2), + .data = (uint8*)texCoordsData[i].data(), + }, .numElements = texCoordsData[i].size(), - }); + }); } - normals->updateContents(ShaderBufferCreateInfo { - .sourceData = { - .size = normalData.size() * sizeof(Vector), - .data = (uint8*)normalData.data(), - }, + normals->updateContents(ShaderBufferCreateInfo{ + .sourceData = + { + .size = normalData.size() * sizeof(Vector), + .data = (uint8*)normalData.data(), + }, .numElements = normalData.size(), - }); - tangents->updateContents(ShaderBufferCreateInfo { - .sourceData = { - .size = tangentData.size() * sizeof(Vector), - .data = (uint8*)tangentData.data(), - }, - .numElements = tangentData.size() - }); - biTangents->updateContents(ShaderBufferCreateInfo { - .sourceData = { - .size = biTangentData.size() * sizeof(Vector), - .data = (uint8*)biTangentData.data(), - }, + }); + tangents->updateContents(ShaderBufferCreateInfo{.sourceData = + { + .size = tangentData.size() * sizeof(Vector), + .data = (uint8*)tangentData.data(), + }, + .numElements = tangentData.size()}); + biTangents->updateContents(ShaderBufferCreateInfo{ + .sourceData = + { + .size = biTangentData.size() * sizeof(Vector), + .data = (uint8*)biTangentData.data(), + }, .numElements = biTangentData.size(), - }); - colors->updateContents(ShaderBufferCreateInfo { - .sourceData = { - .size = colorData.size() * sizeof(Vector), - .data = (uint8*)colorData.data() - }, + }); + colors->updateContents(ShaderBufferCreateInfo{ + .sourceData = {.size = colorData.size() * sizeof(Vector), .data = (uint8*)colorData.data()}, .numElements = colorData.size(), - }); + }); descriptorLayout->reset(); descriptorSet = descriptorLayout->allocateDescriptorSet(); descriptorSet->updateBuffer(0, positions); diff --git a/src/Engine/Graphics/StaticMeshVertexData.h b/src/Engine/Graphics/StaticMeshVertexData.h index 2382ff9..97264df 100644 --- a/src/Engine/Graphics/StaticMeshVertexData.h +++ b/src/Engine/Graphics/StaticMeshVertexData.h @@ -1,64 +1,63 @@ #pragma once -#include "Graphics/Initializer.h" #include "Graphics/Command.h" +#include "Graphics/Initializer.h" #include "Math/Vector.h" #include "VertexData.h" #include "entt/entt.hpp" -namespace Seele -{ -class StaticMeshVertexData : public VertexData -{ -public: - struct StaticMatInstance - { - PMaterialInstance instance; - Array meshletIds; - Gfx::OShaderBuffer culledMeshletBuffer; - //Gfx::OShaderBuffer indirectDrawBuffer; - }; - struct StaticMatData - { - PMaterial material; - Array staticInstance; - }; + +namespace Seele { +class StaticMeshVertexData : public VertexData { + public: + struct StaticMatInstance { + PMaterialInstance instance; + Array meshletIds; + Gfx::OShaderBuffer culledMeshletBuffer; + // Gfx::OShaderBuffer indirectDrawBuffer; + }; + struct StaticMatData { + PMaterial material; + Array staticInstance; + }; StaticMeshVertexData(); virtual ~StaticMeshVertexData(); - static StaticMeshVertexData* getInstance(); - void loadPositions(MeshId id, const Array& data); - void loadTexCoords(MeshId id, uint64 index, const Array& data); - void loadNormals(MeshId id, const Array& data); - void loadTangents(MeshId id, const Array& data); - void loadBiTangents(MeshId id, const Array& data); - void loadColors(MeshId id, const Array& data); - virtual void serializeMesh(MeshId id, uint64 numVertices, ArchiveBuffer& buffer) override; - virtual void deserializeMesh(MeshId id, ArchiveBuffer& buffer) override; - virtual void init(Gfx::PGraphics graphics) override; - virtual void destroy() override; - virtual void bindBuffers(Gfx::PRenderCommand command) override; - virtual Gfx::PDescriptorLayout getVertexDataLayout() override; - virtual Gfx::PDescriptorSet getVertexDataSet() override; - virtual std::string getTypeName() const override { return "StaticMeshVertexData"; } - constexpr const Array& getStaticMeshes() const { return staticData; } -private: - virtual void resizeBuffers() override; - virtual void updateBuffers() override; - Array staticData; + static StaticMeshVertexData* getInstance(); + void loadPositions(MeshId id, const Array& data); + void loadTexCoords(MeshId id, uint64 index, const Array& data); + void loadNormals(MeshId id, const Array& data); + void loadTangents(MeshId id, const Array& data); + void loadBiTangents(MeshId id, const Array& data); + void loadColors(MeshId id, const Array& data); + virtual void serializeMesh(MeshId id, uint64 numVertices, ArchiveBuffer& buffer) override; + virtual void deserializeMesh(MeshId id, ArchiveBuffer& buffer) override; + virtual void init(Gfx::PGraphics graphics) override; + virtual void destroy() override; + virtual void bindBuffers(Gfx::PRenderCommand command) override; + virtual Gfx::PDescriptorLayout getVertexDataLayout() override; + virtual Gfx::PDescriptorSet getVertexDataSet() override; + virtual std::string getTypeName() const override { return "StaticMeshVertexData"; } + virtual Gfx::PShaderBuffer getPositionBuffer() const override { return positions; } + constexpr const Array& getStaticMeshes() const { return staticData; } - std::mutex mutex; + private: + virtual void resizeBuffers() override; + virtual void updateBuffers() override; + Array staticData; + + std::mutex mutex; Gfx::OShaderBuffer positions; - Array positionData; + Array positionData; Gfx::OShaderBuffer texCoords[MAX_TEXCOORDS]; - Array texCoordsData[MAX_TEXCOORDS]; + Array texCoordsData[MAX_TEXCOORDS]; Gfx::OShaderBuffer normals; - Array normalData; + Array normalData; Gfx::OShaderBuffer tangents; - Array tangentData; + Array tangentData; Gfx::OShaderBuffer biTangents; - Array biTangentData; - Gfx::OShaderBuffer colors; - Array colorData; - Gfx::ODescriptorLayout descriptorLayout; - Gfx::PDescriptorSet descriptorSet; + Array biTangentData; + Gfx::OShaderBuffer colors; + Array colorData; + Gfx::ODescriptorLayout descriptorLayout; + Gfx::PDescriptorSet descriptorSet; }; -} +} // namespace Seele diff --git a/src/Engine/Graphics/Texture.cpp b/src/Engine/Graphics/Texture.cpp index 9defc17..179415a 100644 --- a/src/Engine/Graphics/Texture.cpp +++ b/src/Engine/Graphics/Texture.cpp @@ -1,42 +1,21 @@ #include "Texture.h" -#include "Texture.h" + using namespace Seele; using namespace Seele::Gfx; +Texture::Texture(QueueFamilyMapping mapping, Gfx::QueueType startQueueType) : QueueOwnedResource(mapping, startQueueType) {} -Texture::Texture(QueueFamilyMapping mapping, Gfx::QueueType startQueueType) - : QueueOwnedResource(mapping, startQueueType) -{ -} +Texture::~Texture() {} -Texture::~Texture() -{ -} +Texture2D::Texture2D(QueueFamilyMapping mapping, Gfx::QueueType startQueueType) : Texture(mapping, startQueueType) {} -Texture2D::Texture2D(QueueFamilyMapping mapping, Gfx::QueueType startQueueType) - : Texture(mapping, startQueueType) -{ -} +Texture2D::~Texture2D() {} -Texture2D::~Texture2D() -{ -} +Texture3D::Texture3D(QueueFamilyMapping mapping, Gfx::QueueType startQueueType) : Texture(mapping, startQueueType) {} -Texture3D::Texture3D(QueueFamilyMapping mapping, Gfx::QueueType startQueueType) - : Texture(mapping, startQueueType) -{ -} +Texture3D::~Texture3D() {} -Texture3D::~Texture3D() -{ -} +TextureCube::TextureCube(QueueFamilyMapping mapping, Gfx::QueueType startQueueType) : Texture(mapping, startQueueType) {} -TextureCube::TextureCube(QueueFamilyMapping mapping, Gfx::QueueType startQueueType) - : Texture(mapping, startQueueType) -{ -} - -TextureCube::~TextureCube() -{ -} +TextureCube::~TextureCube() {} diff --git a/src/Engine/Graphics/Texture.h b/src/Engine/Graphics/Texture.h index d03766f..73ccbca 100644 --- a/src/Engine/Graphics/Texture.h +++ b/src/Engine/Graphics/Texture.h @@ -1,13 +1,10 @@ #pragma once #include "Resources.h" -namespace Seele -{ -namespace Gfx -{ -class Texture : public QueueOwnedResource -{ -public: +namespace Seele { +namespace Gfx { +class Texture : public QueueOwnedResource { + public: Texture(QueueFamilyMapping mapping, QueueType startQueueType); virtual ~Texture(); @@ -18,21 +15,20 @@ public: virtual uint32 getNumFaces() const { return 1; } virtual SeSampleCountFlags getNumSamples() const = 0; virtual uint32 getMipLevels() const = 0; - virtual void changeLayout(SeImageLayout newLayout, - SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; + virtual void changeLayout(SeImageLayout newLayout, SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, + SePipelineStageFlags dstStage) = 0; virtual void download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) = 0; -protected: + + protected: // Inherited via QueueOwnedResource virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, + SePipelineStageFlags dstStage) = 0; }; DEFINE_REF(Texture) -class Texture2D : public Texture -{ -public: +class Texture2D : public Texture { + public: Texture2D(QueueFamilyMapping mapping, QueueType startQueueType); virtual ~Texture2D(); @@ -42,20 +38,19 @@ public: virtual uint32 getDepth() const = 0; virtual SeSampleCountFlags getNumSamples() const = 0; virtual uint32 getMipLevels() const = 0; - virtual void changeLayout(SeImageLayout newLayout, - SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; -protected: - //Inherited via QueueOwnedResource + virtual void changeLayout(SeImageLayout newLayout, SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, + SePipelineStageFlags dstStage) = 0; + + protected: + // Inherited via QueueOwnedResource virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, + SePipelineStageFlags dstStage) = 0; }; DEFINE_REF(Texture2D) -class Texture3D : public Texture -{ -public: +class Texture3D : public Texture { + public: Texture3D(QueueFamilyMapping mapping, QueueType startQueueType); virtual ~Texture3D(); @@ -65,20 +60,19 @@ public: virtual uint32 getDepth() const = 0; virtual SeSampleCountFlags getNumSamples() const = 0; virtual uint32 getMipLevels() const = 0; - virtual void changeLayout(SeImageLayout newLayout, - SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; -protected: - //Inherited via QueueOwnedResource + virtual void changeLayout(SeImageLayout newLayout, SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, + SePipelineStageFlags dstStage) = 0; + + protected: + // Inherited via QueueOwnedResource virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, + SePipelineStageFlags dstStage) = 0; }; DEFINE_REF(Texture3D) -class TextureCube : public Texture -{ -public: +class TextureCube : public Texture { + public: TextureCube(QueueFamilyMapping mapping, QueueType startQueueType); virtual ~TextureCube(); @@ -89,15 +83,15 @@ public: virtual uint32 getNumFaces() const { return 6; } virtual SeSampleCountFlags getNumSamples() const = 0; virtual uint32 getMipLevels() const = 0; - virtual void changeLayout(SeImageLayout newLayout, - SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; -protected: - //Inherited via QueueOwnedResource + virtual void changeLayout(SeImageLayout newLayout, SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, + SePipelineStageFlags dstStage) = 0; + + protected: + // Inherited via QueueOwnedResource virtual void executeOwnershipBarrier(QueueType newOwner) = 0; - virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, - SeAccessFlags dstAccess, SePipelineStageFlags dstStage) = 0; + virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess, + SePipelineStageFlags dstStage) = 0; }; DEFINE_REF(TextureCube) -} -} \ No newline at end of file +} // namespace Gfx +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/VertexData.cpp b/src/Engine/Graphics/VertexData.cpp index 34537aa..fa7dc1f 100644 --- a/src/Engine/Graphics/VertexData.cpp +++ b/src/Engine/Graphics/VertexData.cpp @@ -1,13 +1,14 @@ #include "VertexData.h" -#include "Graphics/Enums.h" -#include "Graphics/Initializer.h" -#include "Material/Material.h" -#include "Graphics/Graphics.h" #include "Graphics/Descriptor.h" -#include "Graphics/Shader.h" +#include "Graphics/Enums.h" +#include "Graphics/Graphics.h" +#include "Graphics/Initializer.h" #include "Graphics/Mesh.h" +#include "Graphics/Shader.h" +#include "Material/Material.h" #include "Material/MaterialInstance.h" + using namespace Seele; constexpr static uint64 NUM_DEFAULT_ELEMENTS = 1024 * 1024; @@ -15,44 +16,36 @@ Map VertexData::instanceIdM uint64 VertexData::instanceCount = 0; uint64 VertexData::meshletCount = 0; -void VertexData::resetMeshData() -{ +void VertexData::resetMeshData() { std::unique_lock l(materialDataLock); - for (auto &mat : materialData) - { - for (auto &inst : mat.instances) - { + for (auto& mat : materialData) { + for (auto& inst : mat.instances) { inst.instanceData.clear(); inst.instanceMeshData.clear(); } - if (mat.material != nullptr) - { + if (mat.material != nullptr) { mat.material->getDescriptorLayout()->reset(); } } - if (dirty) - { + if (dirty) { updateBuffers(); dirty = false; } } -void VertexData::updateMesh(entt::entity id, uint32 meshIndex, PMesh mesh, Component::Transform &transform) -{ +void VertexData::updateMesh(entt::entity id, uint32 meshIndex, PMesh mesh, Component::Transform& transform) { std::unique_lock l(materialDataLock); PMaterialInstance referencedInstance = mesh->referencedMaterial->getHandle(); PMaterial mat = referencedInstance->getBaseMaterial(); - if (materialData.size() <= mat->getId()) - { + if (materialData.size() <= mat->getId()) { materialData.resize(mat->getId() + 1); } - MaterialData &matData = materialData[mat->getId()]; + MaterialData& matData = materialData[mat->getId()]; matData.material = mat; - if (matData.instances.size() <= referencedInstance->getId()) - { + if (matData.instances.size() <= referencedInstance->getId()) { matData.instances.resize(referencedInstance->getId() + 1); } - BatchedDrawCall &matInstanceData = matData.instances[referencedInstance->getId()]; + BatchedDrawCall& matInstanceData = matData.instances[referencedInstance->getId()]; matInstanceData.materialInstance = referencedInstance; Matrix4 transformMatrix = transform.toMatrix() * mesh->transform; @@ -60,13 +53,12 @@ void VertexData::updateMesh(entt::entity id, uint32 meshIndex, PMesh mesh, Compo .transformMatrix = transformMatrix, .inverseTransformMatrix = glm::inverse(transformMatrix), }); - const auto &data = meshData[mesh->id]; + const auto& data = meshData[mesh->id]; auto [instanceId, meshletOffset] = getCullingMapping(id, meshIndex, data.numMeshlets); matInstanceData.instanceMeshData.add(data); matInstanceData.cullingOffsets.add(meshletOffset); referencedInstance->updateDescriptor(); - for (size_t i = 0; i < 0; ++i) - { + for (size_t i = 0; i < 0; ++i) { auto bounding = meshlets[data.meshletOffset + i].bounding; StaticArray corners; Vector min = bounding.min; // bounding.center - bounding.radius * Vector(1, 1, 1); @@ -106,23 +98,19 @@ void VertexData::updateMesh(entt::entity id, uint32 meshIndex, PMesh mesh, Compo } } -void VertexData::createDescriptors() -{ +void VertexData::createDescriptors() { std::unique_lock l(materialDataLock); instanceData.clear(); instanceMeshData.clear(); Array cullingOffsets; - for (auto &mat : materialData) - { - for (auto &instance : mat.instances) - { + for (auto& mat : materialData) { + for (auto& instance : mat.instances) { instance.offsets.instanceOffset = instanceData.size(); // instance.offsets.cullingCounterOffset = cullingOffsets.size(); // instance.numMeshlets = 0; - for (size_t i = 0; i < instance.instanceData.size(); ++i) - { + for (size_t i = 0; i < instance.instanceData.size(); ++i) { cullingOffsets.add(instance.cullingOffsets[i]); instanceData.add(instance.instanceData[i]); instanceMeshData.add(instance.instanceMeshData[i]); @@ -132,43 +120,34 @@ void VertexData::createDescriptors() } } cullingOffsetBuffer->rotateBuffer(cullingOffsets.size() * sizeof(uint32)); - cullingOffsetBuffer->updateContents(ShaderBufferCreateInfo{ - .sourceData = { - .size = cullingOffsets.size() * sizeof(uint32), - .data = (uint8 *)cullingOffsets.data(), - }, - .numElements = cullingOffsets.size()}); - cullingOffsetBuffer->pipelineBarrier( - Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, - Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, - Gfx::SE_ACCESS_MEMORY_READ_BIT, - Gfx::SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT); + cullingOffsetBuffer->updateContents(ShaderBufferCreateInfo{.sourceData = + { + .size = cullingOffsets.size() * sizeof(uint32), + .data = (uint8*)cullingOffsets.data(), + }, + .numElements = cullingOffsets.size()}); + cullingOffsetBuffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, + Gfx::SE_ACCESS_MEMORY_READ_BIT, Gfx::SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT); instanceBuffer->rotateBuffer(instanceData.size() * sizeof(InstanceData)); - instanceBuffer->updateContents(ShaderBufferCreateInfo{ - .sourceData = { - .size = instanceData.size() * sizeof(InstanceData), - .data = (uint8 *)instanceData.data(), - }, - .numElements = instanceData.size()}); - instanceBuffer->pipelineBarrier( - Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, - Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, - Gfx::SE_ACCESS_MEMORY_READ_BIT, - Gfx::SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT); + instanceBuffer->updateContents(ShaderBufferCreateInfo{.sourceData = + { + .size = instanceData.size() * sizeof(InstanceData), + .data = (uint8*)instanceData.data(), + }, + .numElements = instanceData.size()}); + instanceBuffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, Gfx::SE_ACCESS_MEMORY_READ_BIT, + Gfx::SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT); instanceMeshDataBuffer->rotateBuffer(sizeof(MeshData) * instanceMeshData.size()); - instanceMeshDataBuffer->updateContents(ShaderBufferCreateInfo{ - .sourceData = { - .size = sizeof(MeshData) * instanceMeshData.size(), - .data = (uint8 *)instanceMeshData.data(), - }, - .numElements = instanceMeshData.size()}); - instanceMeshDataBuffer->pipelineBarrier( - Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, - Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, - Gfx::SE_ACCESS_MEMORY_READ_BIT, - Gfx::SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT); + instanceMeshDataBuffer->updateContents(ShaderBufferCreateInfo{.sourceData = + { + .size = sizeof(MeshData) * instanceMeshData.size(), + .data = (uint8*)instanceMeshData.data(), + }, + .numElements = instanceMeshData.size()}); + instanceMeshDataBuffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, + Gfx::SE_ACCESS_MEMORY_READ_BIT, Gfx::SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT); instanceDataLayout->reset(); descriptorSet = instanceDataLayout->allocateDescriptorSet(); descriptorSet->updateBuffer(0, instanceBuffer); @@ -179,8 +158,7 @@ void VertexData::createDescriptors() descriptorSet->updateBuffer(5, cullingOffsetBuffer); } -void VertexData::loadMesh(MeshId id, Array loadedIndices, Array loadedMeshlets) -{ +void VertexData::loadMesh(MeshId id, Array loadedIndices, Array loadedMeshlets) { assert(loadedMeshlets.size() < 2048); std::unique_lock l(vertexDataLock); meshlets.reserve(meshlets.size() + loadedMeshlets.size()); @@ -188,9 +166,8 @@ void VertexData::loadMesh(MeshId id, Array loadedIndices, Array primitiveIndices.reserve(primitiveIndices.size() + loadedMeshlets.size() * Gfx::numPrimitivesPerMeshlet * 3); uint32 meshletOffset = meshlets.size(); AABB meshAABB; - for (uint32 i = 0; i < loadedMeshlets.size(); ++i) - { - Meshlet &m = loadedMeshlets[i]; + for (uint32 i = 0; i < loadedMeshlets.size(); ++i) { + Meshlet& m = loadedMeshlets[i]; meshAABB = meshAABB.combine(m.boundingBox); uint32 vertexOffset = vertexIndices.size(); vertexIndices.resize(vertexOffset + m.numVertices); @@ -216,93 +193,75 @@ void VertexData::loadMesh(MeshId id, Array loadedIndices, Array .numIndices = (uint32)loadedIndices.size(), }; - if (!graphics->supportMeshShading()) - { - indices.resize(indices.size() + loadedIndices.size()); - std::memcpy(indices.data() + meshData[id].firstIndex, loadedIndices.data(), loadedIndices.size() * sizeof(uint32)); - indexBuffer = graphics->createIndexBuffer(IndexBufferCreateInfo{ - .sourceData = { + indices.resize(indices.size() + loadedIndices.size()); + std::memcpy(indices.data() + meshData[id].firstIndex, loadedIndices.data(), loadedIndices.size() * sizeof(uint32)); + indexBuffer = graphics->createIndexBuffer(IndexBufferCreateInfo{ + .sourceData = + { .size = sizeof(uint32) * indices.size(), - .data = (uint8 *)indices.data(), + .data = (uint8*)indices.data(), }, - .indexType = Gfx::SE_INDEX_TYPE_UINT32, - .name = "IndexBuffer", - }); - } - meshletBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{ - .sourceData = { - .size = sizeof(MeshletDescription) * meshlets.size(), - .data = (uint8 *)meshlets.data()}, - .numElements = meshlets.size(), - .dynamic = false, - .name = "MeshletBuffer"}); + .indexType = Gfx::SE_INDEX_TYPE_UINT32, + .name = "IndexBuffer", + }); + meshletBuffer = graphics->createShaderBuffer( + ShaderBufferCreateInfo{.sourceData = {.size = sizeof(MeshletDescription) * meshlets.size(), .data = (uint8*)meshlets.data()}, + .numElements = meshlets.size(), + .dynamic = false, + .name = "MeshletBuffer"}); - vertexIndicesBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{ - .sourceData = { - .size = sizeof(uint32) * vertexIndices.size(), - .data = (uint8 *)vertexIndices.data(), - }, - .numElements = vertexIndices.size(), - .dynamic = false, - .name = "VertexIndicesBuffer"}); + vertexIndicesBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{.sourceData = + { + .size = sizeof(uint32) * vertexIndices.size(), + .data = (uint8*)vertexIndices.data(), + }, + .numElements = vertexIndices.size(), + .dynamic = false, + .name = "VertexIndicesBuffer"}); primitiveIndicesBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{ - .sourceData = { - .size = sizeof(uint8) * primitiveIndices.size(), - .data = (uint8 *)primitiveIndices.data(), - }, + .sourceData = + { + .size = sizeof(uint8) * primitiveIndices.size(), + .data = (uint8*)primitiveIndices.data(), + }, .numElements = primitiveIndices.size(), .dynamic = false, .name = "PrimitiveIndicesBuffer", }); } -MeshId VertexData::allocateVertexData(uint64 numVertices) -{ +MeshId VertexData::allocateVertexData(uint64 numVertices) { std::unique_lock l(vertexDataLock); MeshId res{idCounter++}; meshOffsets[res] = head; meshVertexCounts[res] = numVertices; head += numVertices; - if (head > verticesAllocated) - { + if (head > verticesAllocated) { verticesAllocated = std::max(head, verticesAllocated + NUM_DEFAULT_ELEMENTS); resizeBuffers(); } return res; } -uint64 VertexData::getMeshOffset(MeshId id) -{ - return meshOffsets[id]; -} +uint64 VertexData::getMeshOffset(MeshId id) { return meshOffsets[id]; } -uint64 VertexData::getMeshVertexCount(MeshId id) -{ - return meshVertexCounts[id]; -} +uint64 VertexData::getMeshVertexCount(MeshId id) { return meshVertexCounts[id]; } -List vertexDataList; +List vertexDataList; -List VertexData::getList() -{ - return vertexDataList; -} +List VertexData::getList() { return vertexDataList; } -VertexData *VertexData::findByTypeName(std::string name) -{ - for (auto vd : vertexDataList) - { - if (vd->getTypeName() == name) - { +VertexData* VertexData::findByTypeName(std::string name) { + for (auto vd : vertexDataList) { + if (vd->getTypeName() == name) { return vd; } } return nullptr; } -void VertexData::init(Gfx::PGraphics _graphics) -{ +void VertexData::init(Gfx::PGraphics _graphics) { graphics = _graphics; verticesAllocated = NUM_DEFAULT_ELEMENTS; instanceDataLayout = graphics->createDescriptorLayout("pScene"); @@ -318,15 +277,20 @@ void VertexData::init(Gfx::PGraphics _graphics) .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, }); // meshletData - instanceDataLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 2, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER}); + instanceDataLayout->addDescriptorBinding( + Gfx::DescriptorBinding{.binding = 2, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER}); // primitiveIndices - instanceDataLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 3, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER}); + instanceDataLayout->addDescriptorBinding( + Gfx::DescriptorBinding{.binding = 3, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER}); // vertexIndices - instanceDataLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 4, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER}); + instanceDataLayout->addDescriptorBinding( + Gfx::DescriptorBinding{.binding = 4, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER}); // cullingOffset - instanceDataLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 5, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER}); + instanceDataLayout->addDescriptorBinding( + Gfx::DescriptorBinding{.binding = 5, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER}); // cullingInfos - instanceDataLayout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 6, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER}); + instanceDataLayout->addDescriptorBinding( + Gfx::DescriptorBinding{.binding = 6, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER}); instanceDataLayout->create(); @@ -346,8 +310,7 @@ void VertexData::init(Gfx::PGraphics _graphics) graphics->getShaderCompiler()->registerVertexData(this); } -void VertexData::destroy() -{ +void VertexData::destroy() { instanceBuffer = nullptr; instanceMeshDataBuffer = nullptr; instanceDataLayout = nullptr; @@ -359,18 +322,13 @@ void VertexData::destroy() materialData.clear(); } -VertexData::CullingMapping VertexData::getCullingMapping(entt::entity id, uint32 meshIndex, uint32 numMeshlets) -{ +VertexData::CullingMapping VertexData::getCullingMapping(entt::entity id, uint32 meshIndex, uint32 numMeshlets) { MeshMapping key = MeshMapping{.id = id, .meshId = meshIndex}; - if (!instanceIdMap.contains(key)) - { + if (!instanceIdMap.contains(key)) { instanceIdMap[key] = CullingMapping{.instanceId = instanceCount++, .cullingOffset = uint32(meshletCount)}; meshletCount += numMeshlets; } return instanceIdMap[key]; } -VertexData::VertexData() - : idCounter(0), head(0), verticesAllocated(0), dirty(false) -{ -} +VertexData::VertexData() : idCounter(0), head(0), verticesAllocated(0), dirty(false) {} diff --git a/src/Engine/Graphics/VertexData.h b/src/Engine/Graphics/VertexData.h index a9c548a..f6461ec 100644 --- a/src/Engine/Graphics/VertexData.h +++ b/src/Engine/Graphics/VertexData.h @@ -8,128 +8,121 @@ #include "Meshlet.h" #include - constexpr uint64 MAX_TEXCOORDS = 8; namespace Seele { DECLARE_REF(MaterialInstance) DECLARE_REF(Mesh) struct MeshId { - uint64 id; - std::strong_ordering operator<=>(const MeshId &other) const { - return id <=> other.id; - } - bool operator==(const MeshId &other) const { return id == other.id; } + uint64 id; + std::strong_ordering operator<=>(const MeshId& other) const { return id <=> other.id; } + bool operator==(const MeshId& other) const { return id == other.id; } }; class VertexData { -public: - struct DrawCallOffsets { - uint32 instanceOffset = 0; - }; + public: + struct DrawCallOffsets { + uint32 instanceOffset = 0; + }; - struct MeshletCullingInfo { - uint64_t cull[256 / 64]; - }; - struct BatchedDrawCall { - PMaterialInstance materialInstance; - DrawCallOffsets offsets; + struct MeshletCullingInfo { + uint64_t cull[256 / 64]; + }; + struct BatchedDrawCall { + PMaterialInstance materialInstance; + DrawCallOffsets offsets; + Array instanceData; + Array instanceMeshData; + Array cullingOffsets; + }; + struct MaterialData { + PMaterial material; + Array instances; + }; + void resetMeshData(); + void updateMesh(entt::entity id, uint32 meshIndex, PMesh mesh, Component::Transform& transform); + void createDescriptors(); + void loadMesh(MeshId id, Array indices, Array meshlets); + MeshId allocateVertexData(uint64 numVertices); + uint64 getMeshOffset(MeshId id); + uint64 getMeshVertexCount(MeshId id); + virtual void serializeMesh(MeshId id, uint64 numVertices, ArchiveBuffer& buffer) = 0; + virtual void deserializeMesh(MeshId id, ArchiveBuffer& buffer) = 0; + virtual void bindBuffers(Gfx::PRenderCommand command) = 0; + virtual Gfx::PDescriptorLayout getVertexDataLayout() = 0; + virtual Gfx::PDescriptorSet getVertexDataSet() = 0; + virtual std::string getTypeName() const = 0; + virtual Gfx::PShaderBuffer getPositionBuffer() const = 0; + Gfx::PIndexBuffer getIndexBuffer() { return indexBuffer; } + Gfx::PDescriptorLayout getInstanceDataLayout() { return instanceDataLayout; } + Gfx::PDescriptorSet getInstanceDataSet() { return descriptorSet; } + const Array& getMaterialData() const { return materialData; } + const MeshData& getMeshData(MeshId id) { return meshData[id]; } + uint64 getIndicesOffset(uint32 meshletIndex) { return meshlets[meshletIndex].indicesOffset; } + uint64 getNumInstances() const { return instanceData.size(); } + static List getList(); + static VertexData* findByTypeName(std::string name); + virtual void init(Gfx::PGraphics graphics); + virtual void destroy(); + + struct CullingMapping { + uint64 instanceId; + uint32 cullingOffset; + }; + static CullingMapping getCullingMapping(entt::entity id, uint32 meshIndex, uint32 numMeshlets); + static uint64 getInstanceCount() { return instanceCount; } + static uint64 getMeshletCount() { return meshletCount; } + + protected: + virtual void resizeBuffers() = 0; + virtual void updateBuffers() = 0; + VertexData(); + struct MeshletDescription { + AABB bounding; + uint32 vertexCount; + uint32 primitiveCount; + uint32 vertexOffset; + uint32 primitiveOffset; + Vector color; + uint32 indicesOffset = 0; + }; + std::mutex materialDataLock; + Array materialData; + std::mutex vertexDataLock; + Map meshData; + Map meshOffsets; + Map meshVertexCounts; + Array meshlets; + Array primitiveIndices; + Array vertexIndices; + Array indices; + + struct MeshMapping { + entt::entity id; + uint32 meshId; + auto operator<=>(const MeshMapping& other) const = default; + }; + static Map instanceIdMap; + static uint64 instanceCount; + static uint64 meshletCount; + + Gfx::PGraphics graphics; + Gfx::ODescriptorLayout instanceDataLayout; + // for mesh shading + Gfx::OShaderBuffer meshletBuffer; + Gfx::OShaderBuffer vertexIndicesBuffer; + Gfx::OShaderBuffer primitiveIndicesBuffer; + Gfx::OShaderBuffer cullingOffsetBuffer; + // for legacy pipeline + Gfx::OIndexBuffer indexBuffer; + // Material data Array instanceData; + Gfx::OShaderBuffer instanceBuffer; Array instanceMeshData; - Array cullingOffsets; - }; - struct MaterialData { - PMaterial material; - Array instances; - }; - void resetMeshData(); - void updateMesh(entt::entity id, uint32 meshIndex, PMesh mesh, - Component::Transform &transform); - void createDescriptors(); - void loadMesh(MeshId id, Array indices, Array meshlets); - MeshId allocateVertexData(uint64 numVertices); - uint64 getMeshOffset(MeshId id); - uint64 getMeshVertexCount(MeshId id); - virtual void serializeMesh(MeshId id, uint64 numVertices, - ArchiveBuffer &buffer) = 0; - virtual void deserializeMesh(MeshId id, ArchiveBuffer &buffer) = 0; - virtual void bindBuffers(Gfx::PRenderCommand command) = 0; - virtual Gfx::PDescriptorLayout getVertexDataLayout() = 0; - virtual Gfx::PDescriptorSet getVertexDataSet() = 0; - virtual std::string getTypeName() const = 0; - Gfx::PIndexBuffer getIndexBuffer() { return indexBuffer; } - Gfx::PDescriptorLayout getInstanceDataLayout() { return instanceDataLayout; } - Gfx::PDescriptorSet getInstanceDataSet() { return descriptorSet; } - const Array &getMaterialData() const { return materialData; } - const MeshData &getMeshData(MeshId id) { return meshData[id]; } - uint64 getIndicesOffset(uint32 meshletIndex) { - return meshlets[meshletIndex].indicesOffset; - } - uint64 getNumInstances() const { return instanceData.size(); } - static List getList(); - static VertexData *findByTypeName(std::string name); - virtual void init(Gfx::PGraphics graphics); - virtual void destroy(); - - struct CullingMapping { - uint64 instanceId; - uint32 cullingOffset; - }; - static CullingMapping getCullingMapping(entt::entity id, uint32 meshIndex, - uint32 numMeshlets); - static uint64 getInstanceCount() { return instanceCount; } - static uint64 getMeshletCount() { return meshletCount; } - -protected: - virtual void resizeBuffers() = 0; - virtual void updateBuffers() = 0; - VertexData(); - struct MeshletDescription { - AABB bounding; - uint32 vertexCount; - uint32 primitiveCount; - uint32 vertexOffset; - uint32 primitiveOffset; - Vector color; - uint32 indicesOffset = 0; - }; - std::mutex materialDataLock; - Array materialData; - std::mutex vertexDataLock; - Map meshData; - Map meshOffsets; - Map meshVertexCounts; - Array meshlets; - Array primitiveIndices; - Array vertexIndices; - Array indices; - - struct MeshMapping { - entt::entity id; - uint32 meshId; - auto operator<=>(const MeshMapping &other) const = default; - }; - static Map instanceIdMap; - static uint64 instanceCount; - static uint64 meshletCount; - - Gfx::PGraphics graphics; - Gfx::ODescriptorLayout instanceDataLayout; - // for mesh shading - Gfx::OShaderBuffer meshletBuffer; - Gfx::OShaderBuffer vertexIndicesBuffer; - Gfx::OShaderBuffer primitiveIndicesBuffer; - Gfx::OShaderBuffer cullingOffsetBuffer; - // for legacy pipeline - Gfx::OIndexBuffer indexBuffer; - // Material data - Array instanceData; - Gfx::OShaderBuffer instanceBuffer; - Array instanceMeshData; - Gfx::OShaderBuffer instanceMeshDataBuffer; - Gfx::PDescriptorSet descriptorSet; - uint64 idCounter; - uint64 head; - uint64 verticesAllocated; - bool dirty; + Gfx::OShaderBuffer instanceMeshDataBuffer; + Gfx::PDescriptorSet descriptorSet; + uint64 idCounter; + uint64 head; + uint64 verticesAllocated; + bool dirty; }; } // namespace Seele diff --git a/src/Engine/Graphics/Vulkan/Allocator.cpp b/src/Engine/Graphics/Vulkan/Allocator.cpp index 3adade3..eed7982 100644 --- a/src/Engine/Graphics/Vulkan/Allocator.cpp +++ b/src/Engine/Graphics/Vulkan/Allocator.cpp @@ -6,7 +6,8 @@ // using namespace Seele::Vulkan; -// SubAllocation::SubAllocation(PAllocation owner, VkDeviceSize requestedSize, VkDeviceSize allocatedOffset, VkDeviceSize allocatedSize, VkDeviceSize alignedOffset) +// SubAllocation::SubAllocation(PAllocation owner, VkDeviceSize requestedSize, VkDeviceSize allocatedOffset, VkDeviceSize allocatedSize, +// VkDeviceSize alignedOffset) // : owner(owner) // , requestedSize(requestedSize) // , allocatedOffset(allocatedOffset) @@ -112,10 +113,9 @@ // void Allocation::markFree(PSubAllocation allocation) // { -// //std::cout << "Freeing " << allocation->allocatedOffset << "-" << allocation->allocatedOffset + allocation->allocatedSize << std::endl; -// assert(activeAllocations.find(allocation) != activeAllocations.end()); -// VkDeviceSize lowerBound = allocation->allocatedOffset; -// VkDeviceSize upperBound = allocation->allocatedOffset + allocation->allocatedSize; +// //std::cout << "Freeing " << allocation->allocatedOffset << "-" << allocation->allocatedOffset + allocation->allocatedSize << +// std::endl; assert(activeAllocations.find(allocation) != activeAllocations.end()); VkDeviceSize lowerBound = +// allocation->allocatedOffset; VkDeviceSize upperBound = allocation->allocatedOffset + allocation->allocatedSize; // freeRanges[lowerBound] = allocation->allocatedSize; // for (const auto& [lower, size] : freeRanges) // { @@ -171,7 +171,7 @@ // for (size_t i = 0; i < memProperties.memoryHeapCount; ++i) // { // VkMemoryHeap memoryHeap = memProperties.memoryHeaps[i]; -// HeapInfo heapInfo; +// HeapInfo heapInfo; // heapInfo.maxSize = memoryHeap.size; // //std::cout << "Creating heap " << i << " with properties " << memoryHeap.flags << " size " << memoryHeap.size << std::endl; // heaps.add(std::move(heapInfo)); @@ -182,7 +182,8 @@ // { // } -// OSubAllocation Allocator::allocate(const VkMemoryRequirements2 &memRequirements2, VkMemoryPropertyFlags properties, VkMemoryDedicatedAllocateInfo *dedicatedInfo) +// OSubAllocation Allocator::allocate(const VkMemoryRequirements2 &memRequirements2, VkMemoryPropertyFlags properties, +// VkMemoryDedicatedAllocateInfo *dedicatedInfo) // { // const VkMemoryRequirements &requirements = memRequirements2.memoryRequirements; // uint32 memoryTypeIndex = findMemoryType(requirements.memoryTypeBits, properties); @@ -195,10 +196,10 @@ // { // OAllocation newAllocation = new Allocation(graphics, this, requirements.size, memoryTypeIndex, properties, dedicatedInfo); // heaps[heapIndex].inUse += newAllocation->bytesAllocated; -// std::cout << "Heap " << heapIndex << ": " << (float)heaps[heapIndex].inUse / heaps[heapIndex].maxSize * 100 << "%" << std::endl; -// heaps[heapIndex].allocations.add(std::move(newAllocation)); -// return heaps[heapIndex].allocations.back()->getSuballocation(requirements.size, requirements.alignment); -// } +// std::cout << "Heap " << heapIndex << ": " << (float)heaps[heapIndex].inUse / heaps[heapIndex].maxSize * 100 << "%" << +// std::endl; heaps[heapIndex].allocations.add(std::move(newAllocation)); return +// heaps[heapIndex].allocations.back()->getSuballocation(requirements.size, requirements.alignment); +// } // } // for (auto& alloc : heaps[heapIndex].allocations) // { @@ -213,9 +214,9 @@ // } // // no suitable allocations found, allocate new block -// OAllocation newAllocation = new Allocation(graphics, this, (requirements.size > DEFAULT_ALLOCATION) ? requirements.size : DEFAULT_ALLOCATION, memoryTypeIndex, properties, nullptr); -// heaps[heapIndex].inUse += newAllocation->bytesAllocated; -// std::cout << "Heap " << heapIndex << ": " << (float)heaps[heapIndex].inUse / heaps[heapIndex].maxSize * 100 << "%" << std::endl; +// OAllocation newAllocation = new Allocation(graphics, this, (requirements.size > DEFAULT_ALLOCATION) ? requirements.size : +// DEFAULT_ALLOCATION, memoryTypeIndex, properties, nullptr); heaps[heapIndex].inUse += newAllocation->bytesAllocated; std::cout << +// "Heap " << heapIndex << ": " << (float)heaps[heapIndex].inUse / heaps[heapIndex].maxSize * 100 << "%" << std::endl; // heaps[heapIndex].allocations.add(std::move(newAllocation)); // return heaps[heapIndex].allocations.back()->getSuballocation(requirements.size, requirements.alignment); // } @@ -241,16 +242,17 @@ // std::cout << "Heap " << heapIndex << std::endl; // for (uint32 alloc = 0; alloc < heaps[heapIndex].allocations.size(); ++alloc) // { -// std::cout << "[" << alloc << "]: " << (float)heaps[heapIndex].allocations[alloc]->bytesUsed / heaps[heapIndex].allocations[alloc]->bytesAllocated << std::endl; +// std::cout << "[" << alloc << "]: " << (float)heaps[heapIndex].allocations[alloc]->bytesUsed / +// heaps[heapIndex].allocations[alloc]->bytesAllocated << std::endl; // } // } // } // uint32 Allocator::findMemoryType(uint32 typeFilter, VkMemoryPropertyFlags properties) // { -// for (uint32 i = 0; i < memProperties.memoryTypeCount; i++) +// for (uint32 i = 0; i < memProperties.memoryTypeCount; i++) // { -// if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) +// if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) // { // return i; // } @@ -334,7 +336,7 @@ // .queueFamilyIndexCount = 1, // .pQueueFamilyIndices = &queueIndex, // }; - + // VkBuffer buffer; // VK_CHECK(vkCreateBuffer(graphics->getDevice(), &stagingBufferCreateInfo, nullptr, &buffer)); @@ -361,7 +363,7 @@ // owner // ); // vkBindBufferMemory(graphics->getDevice(), buffer, stagingBuffer->getMemory(), stagingBuffer->getOffset()); - + // return stagingBuffer; // } diff --git a/src/Engine/Graphics/Vulkan/Allocator.h b/src/Engine/Graphics/Vulkan/Allocator.h index 3ca9bda..db82483 100644 --- a/src/Engine/Graphics/Vulkan/Allocator.h +++ b/src/Engine/Graphics/Vulkan/Allocator.h @@ -16,9 +16,8 @@ // class SubAllocation // { // public: -// SubAllocation(PAllocation owner, VkDeviceSize requestedSize, VkDeviceSize allocatedOffset, VkDeviceSize allocatedSize, VkDeviceSize alignedOffset); -// ~SubAllocation(); -// VkDeviceMemory getHandle() const; +// SubAllocation(PAllocation owner, VkDeviceSize requestedSize, VkDeviceSize allocatedOffset, VkDeviceSize allocatedSize, VkDeviceSize +// alignedOffset); ~SubAllocation(); VkDeviceMemory getHandle() const; // constexpr VkDeviceSize getSize() const // { diff --git a/src/Engine/Graphics/Vulkan/Buffer.cpp b/src/Engine/Graphics/Vulkan/Buffer.cpp index 59a6c42..d5ae274 100644 --- a/src/Engine/Graphics/Vulkan/Buffer.cpp +++ b/src/Engine/Graphics/Vulkan/Buffer.cpp @@ -6,579 +6,472 @@ using namespace Seele; using namespace Seele::Vulkan; -BufferAllocation::BufferAllocation(PGraphics graphics) - : CommandBoundResource(graphics) {} +BufferAllocation::BufferAllocation(PGraphics graphics) : CommandBoundResource(graphics) {} BufferAllocation::~BufferAllocation() { - if (buffer != VK_NULL_HANDLE) { - vmaDestroyBuffer(graphics->getAllocator(), buffer, allocation); - } + if (buffer != VK_NULL_HANDLE) { + vmaDestroyBuffer(graphics->getAllocator(), buffer, allocation); + } } struct PendingBuffer { - OBufferAllocation allocation; - uint64 offset; - Gfx::QueueType prevQueue; - bool writeOnly; + OBufferAllocation allocation; + uint64 offset; + Gfx::QueueType prevQueue; + bool writeOnly; }; -static Map pendingBuffers; +static Map pendingBuffers; -Buffer::Buffer(PGraphics graphics, uint64 size, VkBufferUsageFlags usage, - Gfx::QueueType &queueType, bool dynamic, std::string name) +Buffer::Buffer(PGraphics graphics, uint64 size, VkBufferUsageFlags usage, Gfx::QueueType& queueType, bool dynamic, std::string name) : graphics(graphics), currentBuffer(0), owner(queueType), - usage(usage | VK_BUFFER_USAGE_TRANSFER_DST_BIT | - VK_BUFFER_USAGE_TRANSFER_SRC_BIT), - dynamic(dynamic), name(name) { - createBuffer(size); + usage(usage | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT), dynamic(dynamic), name(name) { + createBuffer(size); } Buffer::~Buffer() { - for (uint32 i = 0; i < buffers.size(); ++i) { - graphics->getDestructionManager()->queueResourceForDestruction( - std::move(buffers[i])); - } + for (uint32 i = 0; i < buffers.size(); ++i) { + graphics->getDestructionManager()->queueResourceForDestruction(std::move(buffers[i])); + } } void Buffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { - if (getSize() == 0) - return; - Gfx::QueueFamilyMapping mapping = graphics->getFamilyMapping(); - VkBufferMemoryBarrier barrier = { - .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, - .pNext = nullptr, - .srcQueueFamilyIndex = mapping.getQueueTypeFamilyIndex(owner), - .dstQueueFamilyIndex = mapping.getQueueTypeFamilyIndex(newOwner), - .buffer = getHandle(), - .offset = 0, - .size = getSize(), - }; - PCommandPool sourcePool = graphics->getQueueCommands(owner); - PCommandPool dstPool = nullptr; - VkPipelineStageFlags srcStage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; - VkPipelineStageFlags dstStage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; - assert(barrier.srcQueueFamilyIndex != barrier.dstQueueFamilyIndex); - if (owner == Gfx::QueueType::TRANSFER) { - barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT; - } else if (owner == Gfx::QueueType::COMPUTE) { - barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - srcStage = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - } else if (owner == Gfx::QueueType::GRAPHICS) { - barrier.srcAccessMask = getSourceAccessMask(); - srcStage = VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT; - } - if (newOwner == Gfx::QueueType::TRANSFER) { - barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT; - dstPool = graphics->getTransferCommands(); - } else if (newOwner == Gfx::QueueType::COMPUTE) { - barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - dstStage = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - dstPool = graphics->getComputeCommands(); - } else if (newOwner == Gfx::QueueType::GRAPHICS) { - barrier.dstAccessMask = getDestAccessMask(); - dstStage = VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT; - dstPool = graphics->getGraphicsCommands(); - } - VkCommandBuffer srcCommand = sourcePool->getCommands()->getHandle(); - VkCommandBuffer dstCommand = dstPool->getCommands()->getHandle(); - vkCmdPipelineBarrier(srcCommand, srcStage, srcStage, 0, 0, nullptr, 1, - &barrier, 0, nullptr); - vkCmdPipelineBarrier(dstCommand, dstStage, dstStage, 0, 0, nullptr, 1, - &barrier, 0, nullptr); - sourcePool->submitCommands(); -} - -void Buffer::executePipelineBarrier(VkAccessFlags srcAccess, - VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, - VkPipelineStageFlags dstStage) { - if (getSize() == 0) - return; - PCommand commandBuffer = graphics->getQueueCommands(owner)->getCommands(); - VkBufferMemoryBarrier barrier = { - .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, - .pNext = nullptr, - .srcAccessMask = srcAccess, - .dstAccessMask = dstAccess, - .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .buffer = getHandle(), - .offset = 0, - .size = getSize(), - }; - vkCmdPipelineBarrier(commandBuffer->getHandle(), srcStage, dstStage, 0, 0, - nullptr, 1, &barrier, 0, nullptr); -} - -void *Buffer::map(bool writeOnly) { return mapRegion(0, getSize(), writeOnly); } - -void *Buffer::mapRegion(uint64 regionOffset, uint64 regionSize, - bool writeOnly) { - if (regionSize == 0) - return nullptr; - void *data = nullptr; - - PendingBuffer pending; - pending.allocation = new BufferAllocation(graphics); - pending.allocation->size = regionSize; - pending.writeOnly = writeOnly; - pending.prevQueue = owner; - pending.offset = regionOffset; - if (writeOnly) { - if (buffers[currentBuffer]->properties & - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) { - VK_CHECK(vmaMapMemory(graphics->getAllocator(), - buffers[currentBuffer]->allocation, &data)); - } else { - VkBufferCreateInfo stagingInfo = { - .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .size = regionSize, - .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT, - .sharingMode = VK_SHARING_MODE_EXCLUSIVE, - }; - VmaAllocationCreateInfo allocInfo = { - .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | - VMA_ALLOCATION_CREATE_MAPPED_BIT, - .usage = VMA_MEMORY_USAGE_AUTO, - .requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, - }; - VK_CHECK(vmaCreateBuffer(graphics->getAllocator(), &stagingInfo, - &allocInfo, &pending.allocation->buffer, - &pending.allocation->allocation, nullptr)); - vmaMapMemory(graphics->getAllocator(), pending.allocation->allocation, - &data); - vmaSetAllocationName(graphics->getAllocator(), - pending.allocation->allocation, "MappingStaging"); + if (getSize() == 0) + return; + Gfx::QueueFamilyMapping mapping = graphics->getFamilyMapping(); + VkBufferMemoryBarrier barrier = { + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcQueueFamilyIndex = mapping.getQueueTypeFamilyIndex(owner), + .dstQueueFamilyIndex = mapping.getQueueTypeFamilyIndex(newOwner), + .buffer = getHandle(), + .offset = 0, + .size = getSize(), + }; + PCommandPool sourcePool = graphics->getQueueCommands(owner); + PCommandPool dstPool = nullptr; + VkPipelineStageFlags srcStage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; + VkPipelineStageFlags dstStage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; + assert(barrier.srcQueueFamilyIndex != barrier.dstQueueFamilyIndex); + if (owner == Gfx::QueueType::TRANSFER) { + barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT; + } else if (owner == Gfx::QueueType::COMPUTE) { + barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + srcStage = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; + } else if (owner == Gfx::QueueType::GRAPHICS) { + barrier.srcAccessMask = getSourceAccessMask(); + srcStage = VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT; } - } else { - assert(false); - } - pendingBuffers[this] = std::move(pending); + if (newOwner == Gfx::QueueType::TRANSFER) { + barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT; + dstPool = graphics->getTransferCommands(); + } else if (newOwner == Gfx::QueueType::COMPUTE) { + barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + dstStage = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; + dstPool = graphics->getComputeCommands(); + } else if (newOwner == Gfx::QueueType::GRAPHICS) { + barrier.dstAccessMask = getDestAccessMask(); + dstStage = VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT; + dstPool = graphics->getGraphicsCommands(); + } + VkCommandBuffer srcCommand = sourcePool->getCommands()->getHandle(); + VkCommandBuffer dstCommand = dstPool->getCommands()->getHandle(); + vkCmdPipelineBarrier(srcCommand, srcStage, srcStage, 0, 0, nullptr, 1, &barrier, 0, nullptr); + vkCmdPipelineBarrier(dstCommand, dstStage, dstStage, 0, 0, nullptr, 1, &barrier, 0, nullptr); + sourcePool->submitCommands(); +} - assert(data); - return data; +void Buffer::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, VkAccessFlags dstAccess, + VkPipelineStageFlags dstStage) { + if (getSize() == 0) + return; + PCommand commandBuffer = graphics->getQueueCommands(owner)->getCommands(); + VkBufferMemoryBarrier barrier = { + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = srcAccess, + .dstAccessMask = dstAccess, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .buffer = getHandle(), + .offset = 0, + .size = getSize(), + }; + vkCmdPipelineBarrier(commandBuffer->getHandle(), srcStage, dstStage, 0, 0, nullptr, 1, &barrier, 0, nullptr); +} + +void* Buffer::map(bool writeOnly) { return mapRegion(0, getSize(), writeOnly); } + +void* Buffer::mapRegion(uint64 regionOffset, uint64 regionSize, bool writeOnly) { + if (regionSize == 0) + return nullptr; + void* data = nullptr; + + PendingBuffer pending; + pending.allocation = new BufferAllocation(graphics); + pending.allocation->size = regionSize; + pending.writeOnly = writeOnly; + pending.prevQueue = owner; + pending.offset = regionOffset; + if (writeOnly) { + if (buffers[currentBuffer]->properties & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) { + VK_CHECK(vmaMapMemory(graphics->getAllocator(), buffers[currentBuffer]->allocation, &data)); + } else { + VkBufferCreateInfo stagingInfo = { + .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .size = regionSize, + .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + }; + VmaAllocationCreateInfo allocInfo = { + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + .requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, + }; + VK_CHECK(vmaCreateBuffer(graphics->getAllocator(), &stagingInfo, &allocInfo, &pending.allocation->buffer, + &pending.allocation->allocation, nullptr)); + vmaMapMemory(graphics->getAllocator(), pending.allocation->allocation, &data); + vmaSetAllocationName(graphics->getAllocator(), pending.allocation->allocation, "MappingStaging"); + } + } else { + assert(false); + } + pendingBuffers[this] = std::move(pending); + + assert(data); + return data; } void Buffer::unmap() { - auto found = pendingBuffers.find(this); - if (found != pendingBuffers.end()) { - PendingBuffer &pending = found->value; - if (pending.writeOnly) { - if (buffers[currentBuffer]->properties & - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) { - vmaUnmapMemory(graphics->getAllocator(), - buffers[currentBuffer]->allocation); - } else { - vmaFlushAllocation(graphics->getAllocator(), - pending.allocation->allocation, 0, VK_WHOLE_SIZE); - vmaUnmapMemory(graphics->getAllocator(), - pending.allocation->allocation); - PCommand command = graphics->getQueueCommands(owner)->getCommands(); - command->bindResource(PBufferAllocation(pending.allocation)); - VkCommandBuffer cmdHandle = command->getHandle(); + auto found = pendingBuffers.find(this); + if (found != pendingBuffers.end()) { + PendingBuffer& pending = found->value; + if (pending.writeOnly) { + if (buffers[currentBuffer]->properties & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) { + vmaUnmapMemory(graphics->getAllocator(), buffers[currentBuffer]->allocation); + } else { + vmaFlushAllocation(graphics->getAllocator(), pending.allocation->allocation, 0, VK_WHOLE_SIZE); + vmaUnmapMemory(graphics->getAllocator(), pending.allocation->allocation); + PCommand command = graphics->getQueueCommands(owner)->getCommands(); + command->bindResource(PBufferAllocation(pending.allocation)); + VkCommandBuffer cmdHandle = command->getHandle(); - VkBufferCopy region = { - .srcOffset = 0, - .dstOffset = pending.offset, - .size = pending.allocation->size, - }; - VkBufferMemoryBarrier barrier = { - .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, - .pNext = nullptr, - .srcAccessMask = VK_ACCESS_MEMORY_READ_BIT, - .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, - .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .buffer = buffers[currentBuffer]->buffer, - .offset = 0, - .size = buffers[currentBuffer]->size, - }; - vkCmdPipelineBarrier(cmdHandle, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 1, - &barrier, 0, nullptr); - vkCmdCopyBuffer(cmdHandle, pending.allocation->buffer, - buffers[currentBuffer]->buffer, 1, ®ion); - barrier = { - .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, - .pNext = nullptr, - .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, - .dstAccessMask = VK_ACCESS_MEMORY_READ_BIT, - .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .buffer = buffers[currentBuffer]->buffer, - .offset = 0, - .size = buffers[currentBuffer]->size, - }; - vkCmdPipelineBarrier(cmdHandle, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, - 1, &barrier, 0, nullptr); - graphics->getDestructionManager()->queueResourceForDestruction( - std::move(pending.allocation)); - } + VkBufferCopy region = { + .srcOffset = 0, + .dstOffset = pending.offset, + .size = pending.allocation->size, + }; + VkBufferMemoryBarrier barrier = { + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_MEMORY_READ_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .buffer = buffers[currentBuffer]->buffer, + .offset = 0, + .size = buffers[currentBuffer]->size, + }; + vkCmdPipelineBarrier(cmdHandle, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 1, + &barrier, 0, nullptr); + vkCmdCopyBuffer(cmdHandle, pending.allocation->buffer, buffers[currentBuffer]->buffer, 1, ®ion); + barrier = { + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_MEMORY_READ_BIT, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .buffer = buffers[currentBuffer]->buffer, + .offset = 0, + .size = buffers[currentBuffer]->size, + }; + vkCmdPipelineBarrier(cmdHandle, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 1, + &barrier, 0, nullptr); + graphics->getDestructionManager()->queueResourceForDestruction(std::move(pending.allocation)); + } + } + pendingBuffers.erase(this); } - pendingBuffers.erase(this); - } } void Buffer::rotateBuffer(uint64 size, bool preserveContents) { - assert(dynamic); - size = std::max(getSize(), size); - for (size_t i = 0; i < buffers.size(); ++i) { - if (buffers[i]->isCurrentlyBound()) { - continue; - } - if (buffers[i]->size < size) { - vmaDestroyBuffer(graphics->getAllocator(), buffers[i]->buffer, - buffers[i]->allocation); - VkBufferCreateInfo info = { - .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, - .pNext = nullptr, - .size = size, - .usage = usage, - .sharingMode = VK_SHARING_MODE_EXCLUSIVE, - }; - VmaAllocationCreateInfo allocInfo = { - .flags = - VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT | - VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, - .usage = VMA_MEMORY_USAGE_AUTO, - }; - VK_CHECK(vmaCreateBuffer(graphics->getAllocator(), &info, &allocInfo, - &buffers[i]->buffer, &buffers[i]->allocation, - &buffers[i]->info)); - vmaGetAllocationMemoryProperties(graphics->getAllocator(), - buffers[i]->allocation, - &buffers[i]->properties); - if (!name.empty()) { - VkDebugUtilsObjectNameInfoEXT nameInfo = { - .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT, - .pNext = nullptr, - .objectType = VK_OBJECT_TYPE_BUFFER, - .objectHandle = (uint64)buffers[i]->buffer, - .pObjectName = this->name.c_str()}; - graphics->vkSetDebugUtilsObjectNameEXT(&nameInfo); - } - buffers[i]->size = size; + assert(dynamic); + size = std::max(getSize(), size); + for (size_t i = 0; i < buffers.size(); ++i) { + if (buffers[i]->isCurrentlyBound()) { + continue; + } + if (buffers[i]->size < size) { + vmaDestroyBuffer(graphics->getAllocator(), buffers[i]->buffer, buffers[i]->allocation); + VkBufferCreateInfo info = { + .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .pNext = nullptr, + .size = size, + .usage = usage, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + }; + VmaAllocationCreateInfo allocInfo = { + .flags = + VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + }; + VK_CHECK(vmaCreateBuffer(graphics->getAllocator(), &info, &allocInfo, &buffers[i]->buffer, &buffers[i]->allocation, + &buffers[i]->info)); + vmaGetAllocationMemoryProperties(graphics->getAllocator(), buffers[i]->allocation, &buffers[i]->properties); + if (!name.empty()) { + VkDebugUtilsObjectNameInfoEXT nameInfo = {.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT, + .pNext = nullptr, + .objectType = VK_OBJECT_TYPE_BUFFER, + .objectHandle = (uint64)buffers[i]->buffer, + .pObjectName = this->name.c_str()}; + graphics->vkSetDebugUtilsObjectNameEXT(&nameInfo); + } + buffers[i]->size = size; + } + if (preserveContents) { + copyBuffer(currentBuffer, i); + } + currentBuffer = i; + return; } + createBuffer(size); if (preserveContents) { - copyBuffer(currentBuffer, i); + copyBuffer(currentBuffer, buffers.size() - 1); } - currentBuffer = i; - return; - } - createBuffer(size); - if (preserveContents) { - copyBuffer(currentBuffer, buffers.size() - 1); - } - currentBuffer = buffers.size() - 1; + currentBuffer = buffers.size() - 1; } void Buffer::createBuffer(uint64 size) { - VkBufferCreateInfo info = { - .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, - .pNext = nullptr, - .size = size, - .usage = usage, - .sharingMode = VK_SHARING_MODE_EXCLUSIVE, - }; - VmaAllocationCreateInfo allocInfo = { - .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT | - VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, - .usage = VMA_MEMORY_USAGE_AUTO, - }; - buffers.add(new BufferAllocation(graphics)); - if (size > 0) { - VK_CHECK(vmaCreateBuffer( - graphics->getAllocator(), &info, &allocInfo, &buffers.back()->buffer, - &buffers.back()->allocation, &buffers.back()->info)); - buffers.back()->size = size; - vmaGetAllocationMemoryProperties(graphics->getAllocator(), - buffers.back()->allocation, - &buffers.back()->properties); - VkBufferDeviceAddressInfo addrInfo = { - .sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO_KHR, + VkBufferCreateInfo info = { + .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .pNext = nullptr, - .buffer = buffers.back()->buffer, + .size = size, + .usage = usage, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, }; - buffers.back()->deviceAddress = - vkGetBufferDeviceAddress(graphics->getDevice(), &addrInfo); - if (!name.empty()) { - VkDebugUtilsObjectNameInfoEXT nameInfo = { - .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT, - .pNext = nullptr, - .objectType = VK_OBJECT_TYPE_BUFFER, - .objectHandle = (uint64)buffers.back()->buffer, - .pObjectName = this->name.c_str()}; - graphics->vkSetDebugUtilsObjectNameEXT(&nameInfo); + VmaAllocationCreateInfo allocInfo = { + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + }; + buffers.add(new BufferAllocation(graphics)); + if (size > 0) { + VK_CHECK(vmaCreateBuffer(graphics->getAllocator(), &info, &allocInfo, &buffers.back()->buffer, &buffers.back()->allocation, + &buffers.back()->info)); + buffers.back()->size = size; + vmaGetAllocationMemoryProperties(graphics->getAllocator(), buffers.back()->allocation, &buffers.back()->properties); + VkBufferDeviceAddressInfo addrInfo = { + .sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO_KHR, + .pNext = nullptr, + .buffer = buffers.back()->buffer, + }; + buffers.back()->deviceAddress = vkGetBufferDeviceAddress(graphics->getDevice(), &addrInfo); + if (!name.empty()) { + VkDebugUtilsObjectNameInfoEXT nameInfo = {.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT, + .pNext = nullptr, + .objectType = VK_OBJECT_TYPE_BUFFER, + .objectHandle = (uint64)buffers.back()->buffer, + .pObjectName = this->name.c_str()}; + graphics->vkSetDebugUtilsObjectNameEXT(&nameInfo); + } } - } } void Buffer::copyBuffer(uint64 src, uint64 dst) { - if (src == dst) { - return; - } - PCommand command = graphics->getQueueCommands(owner)->getCommands(); - VkBufferMemoryBarrier srcBarrier = { - .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, - .pNext = nullptr, - .srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT, - .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT, - .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .buffer = buffers[src]->buffer, - .offset = 0, - .size = buffers[src]->size, - }; - vkCmdPipelineBarrier(command->getHandle(), - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 1, - &srcBarrier, 0, nullptr); - VkBufferCopy region = { - .srcOffset = 0, .dstOffset = 0, .size = buffers[src]->size}; - vkCmdCopyBuffer(command->getHandle(), buffers[src]->buffer, - buffers[dst]->buffer, 1, ®ion); - VkBufferMemoryBarrier dstBarrier = { - .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, - .pNext = nullptr, - .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, - .dstAccessMask = VK_ACCESS_MEMORY_READ_BIT, - .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .buffer = buffers[dst]->buffer, - .offset = 0, - .size = buffers[dst]->size, - }; - vkCmdPipelineBarrier(command->getHandle(), VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0, nullptr, 1, - &dstBarrier, 0, nullptr); + if (src == dst) { + return; + } + PCommand command = graphics->getQueueCommands(owner)->getCommands(); + VkBufferMemoryBarrier srcBarrier = { + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .buffer = buffers[src]->buffer, + .offset = 0, + .size = buffers[src]->size, + }; + vkCmdPipelineBarrier(command->getHandle(), VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 1, + &srcBarrier, 0, nullptr); + VkBufferCopy region = {.srcOffset = 0, .dstOffset = 0, .size = buffers[src]->size}; + vkCmdCopyBuffer(command->getHandle(), buffers[src]->buffer, buffers[dst]->buffer, 1, ®ion); + VkBufferMemoryBarrier dstBarrier = { + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_MEMORY_READ_BIT, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .buffer = buffers[dst]->buffer, + .offset = 0, + .size = buffers[dst]->size, + }; + vkCmdPipelineBarrier(command->getHandle(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0, nullptr, 1, + &dstBarrier, 0, nullptr); } -UniformBuffer::UniformBuffer(PGraphics graphics, - const UniformBufferCreateInfo &createInfo) +UniformBuffer::UniformBuffer(PGraphics graphics, const UniformBufferCreateInfo& createInfo) : Gfx::UniformBuffer(graphics->getFamilyMapping(), createInfo.sourceData), - Vulkan::Buffer(graphics, createInfo.sourceData.size, - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, currentOwner, - createInfo.dynamic, createInfo.name) { - if (getSize() > 0 && createInfo.sourceData.data != nullptr) { - void *data = map(); - std::memcpy(data, createInfo.sourceData.data, createInfo.sourceData.size); - unmap(); - } + Vulkan::Buffer(graphics, createInfo.sourceData.size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, currentOwner, createInfo.dynamic, + createInfo.name) { + if (getSize() > 0 && createInfo.sourceData.data != nullptr) { + void* data = map(); + std::memcpy(data, createInfo.sourceData.data, createInfo.sourceData.size); + unmap(); + } } UniformBuffer::~UniformBuffer() {} -void UniformBuffer::updateContents(const DataSource &sourceData) { - void *data = map(); - std::memcpy(data, sourceData.data, sourceData.size); - unmap(); -} - -void UniformBuffer::rotateBuffer(uint64 size) { - Vulkan::Buffer::rotateBuffer(size); -} - -void UniformBuffer::requestOwnershipTransfer(Gfx::QueueType newOwner) { - Gfx::QueueOwnedResource::transferOwnership(newOwner); -} - -void UniformBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { - Vulkan::Buffer::executeOwnershipBarrier(newOwner); -} - -void UniformBuffer::executePipelineBarrier(VkAccessFlags srcAccess, - VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, - VkPipelineStageFlags dstStage) { - Vulkan::Buffer::executePipelineBarrier(srcAccess, srcStage, dstAccess, - dstStage); -} - -VkAccessFlags UniformBuffer::getSourceAccessMask() { - return VK_ACCESS_MEMORY_WRITE_BIT; -} - -VkAccessFlags UniformBuffer::getDestAccessMask() { - return VK_ACCESS_UNIFORM_READ_BIT; -} - -ShaderBuffer::ShaderBuffer(PGraphics graphics, - const ShaderBufferCreateInfo &sourceData) - : Gfx::ShaderBuffer(graphics->getFamilyMapping(), sourceData.numElements, - sourceData.sourceData), - Vulkan::Buffer( - graphics, sourceData.sourceData.size, - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | - (sourceData.vertexBuffer - ? VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | - VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT - : 0), - currentOwner, sourceData.dynamic, sourceData.name) { - if (getSize() > 0 && sourceData.sourceData.data != nullptr) { - void *data = map(); - std::memcpy(data, sourceData.sourceData.data, sourceData.sourceData.size); +void UniformBuffer::updateContents(const DataSource& sourceData) { + void* data = map(); + std::memcpy(data, sourceData.data, sourceData.size); unmap(); - } +} + +void UniformBuffer::rotateBuffer(uint64 size) { Vulkan::Buffer::rotateBuffer(size); } + +void UniformBuffer::requestOwnershipTransfer(Gfx::QueueType newOwner) { Gfx::QueueOwnedResource::transferOwnership(newOwner); } + +void UniformBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { Vulkan::Buffer::executeOwnershipBarrier(newOwner); } + +void UniformBuffer::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, VkAccessFlags dstAccess, + VkPipelineStageFlags dstStage) { + Vulkan::Buffer::executePipelineBarrier(srcAccess, srcStage, dstAccess, dstStage); +} + +VkAccessFlags UniformBuffer::getSourceAccessMask() { return VK_ACCESS_MEMORY_WRITE_BIT; } + +VkAccessFlags UniformBuffer::getDestAccessMask() { return VK_ACCESS_UNIFORM_READ_BIT; } + +ShaderBuffer::ShaderBuffer(PGraphics graphics, const ShaderBufferCreateInfo& sourceData) + : Gfx::ShaderBuffer(graphics->getFamilyMapping(), sourceData.numElements, sourceData.sourceData), + Vulkan::Buffer(graphics, sourceData.sourceData.size, + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + (sourceData.vertexBuffer ? VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT + : 0), + currentOwner, sourceData.dynamic, sourceData.name) { + if (getSize() > 0 && sourceData.sourceData.data != nullptr) { + void* data = map(); + std::memcpy(data, sourceData.sourceData.data, sourceData.sourceData.size); + unmap(); + } } ShaderBuffer::~ShaderBuffer() {} -void ShaderBuffer::updateContents(const ShaderBufferCreateInfo &createInfo) { - if (createInfo.sourceData.data == nullptr) { - return; - } - // We always want to update, as the contents could be different on the GPU - void *data = map(); - std::memcpy((char *)data + createInfo.sourceData.offset, - createInfo.sourceData.data, createInfo.sourceData.size); - unmap(); +void ShaderBuffer::updateContents(const ShaderBufferCreateInfo& createInfo) { + if (createInfo.sourceData.data == nullptr) { + return; + } + // We always want to update, as the contents could be different on the GPU + void* data = map(); + std::memcpy((char*)data + createInfo.sourceData.offset, createInfo.sourceData.data, createInfo.sourceData.size); + unmap(); } -void Seele::Vulkan::ShaderBuffer::rotateBuffer(uint64 size, - bool preserveContents) { - assert(dynamic); - Vulkan::Buffer::rotateBuffer(size, preserveContents); +void Seele::Vulkan::ShaderBuffer::rotateBuffer(uint64 size, bool preserveContents) { + assert(dynamic); + Vulkan::Buffer::rotateBuffer(size, preserveContents); } -void *ShaderBuffer::mapRegion(uint64 offset, uint64 size, bool writeOnly) { - return Vulkan::Buffer::mapRegion(offset, size, writeOnly); -} +void* ShaderBuffer::mapRegion(uint64 offset, uint64 size, bool writeOnly) { return Vulkan::Buffer::mapRegion(offset, size, writeOnly); } void ShaderBuffer::unmap() { Vulkan::Buffer::unmap(); } void ShaderBuffer::clear() { - vkCmdFillBuffer(graphics->getQueueCommands(owner)->getCommands()->getHandle(), - Vulkan::Buffer::getHandle(), 0, VK_WHOLE_SIZE, 0); + vkCmdFillBuffer(graphics->getQueueCommands(owner)->getCommands()->getHandle(), Vulkan::Buffer::getHandle(), 0, VK_WHOLE_SIZE, 0); } -void ShaderBuffer::requestOwnershipTransfer(Gfx::QueueType newOwner) { - Gfx::QueueOwnedResource::transferOwnership(newOwner); -} +void ShaderBuffer::requestOwnershipTransfer(Gfx::QueueType newOwner) { Gfx::QueueOwnedResource::transferOwnership(newOwner); } -void ShaderBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { - Vulkan::Buffer::executeOwnershipBarrier(newOwner); -} +void ShaderBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { Vulkan::Buffer::executeOwnershipBarrier(newOwner); } -void ShaderBuffer::executePipelineBarrier(VkAccessFlags srcAccess, - VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, +void ShaderBuffer::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, VkAccessFlags dstAccess, VkPipelineStageFlags dstStage) { - Vulkan::Buffer::executePipelineBarrier(srcAccess, srcStage, dstAccess, - dstStage); + Vulkan::Buffer::executePipelineBarrier(srcAccess, srcStage, dstAccess, dstStage); } -VkAccessFlags ShaderBuffer::getSourceAccessMask() { - return VK_ACCESS_MEMORY_WRITE_BIT; -} +VkAccessFlags ShaderBuffer::getSourceAccessMask() { return VK_ACCESS_MEMORY_WRITE_BIT; } -VkAccessFlags ShaderBuffer::getDestAccessMask() { - return VK_ACCESS_MEMORY_READ_BIT; -} +VkAccessFlags ShaderBuffer::getDestAccessMask() { return VK_ACCESS_MEMORY_READ_BIT; } -VertexBuffer::VertexBuffer(PGraphics graphics, - const VertexBufferCreateInfo &sourceData) - : Gfx::VertexBuffer(graphics->getFamilyMapping(), sourceData.numVertices, - sourceData.vertexSize, sourceData.sourceData.owner), - Vulkan::Buffer(graphics, sourceData.sourceData.size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, currentOwner, false, - sourceData.name) { - if (sourceData.sourceData.data != nullptr) { - void *data = map(); - std::memcpy(data, sourceData.sourceData.data, sourceData.sourceData.size); - unmap(); - } +VertexBuffer::VertexBuffer(PGraphics graphics, const VertexBufferCreateInfo& sourceData) + : Gfx::VertexBuffer(graphics->getFamilyMapping(), sourceData.numVertices, sourceData.vertexSize, sourceData.sourceData.owner), + Vulkan::Buffer(graphics, sourceData.sourceData.size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, currentOwner, false, sourceData.name) { + if (sourceData.sourceData.data != nullptr) { + void* data = map(); + std::memcpy(data, sourceData.sourceData.data, sourceData.sourceData.size); + unmap(); + } } VertexBuffer::~VertexBuffer() {} void VertexBuffer::updateRegion(DataSource update) { - void *data = mapRegion(update.offset, update.size); - std::memcpy(data, update.data, update.size); - unmap(); -} - -void VertexBuffer::download(Array &buffer) { - void *data = map(false); - buffer.resize(getSize()); - std::memcpy(buffer.data(), data, getSize()); - unmap(); -} - -void VertexBuffer::requestOwnershipTransfer(Gfx::QueueType newOwner) { - Gfx::QueueOwnedResource::transferOwnership(newOwner); -} - -void VertexBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { - Vulkan::Buffer::executeOwnershipBarrier(newOwner); -} - -void VertexBuffer::executePipelineBarrier(VkAccessFlags srcAccess, - VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, - VkPipelineStageFlags dstStage) { - Vulkan::Buffer::executePipelineBarrier(srcAccess, srcStage, dstAccess, - dstStage); -} - -VkAccessFlags VertexBuffer::getSourceAccessMask() { - return VK_ACCESS_MEMORY_WRITE_BIT; -} - -VkAccessFlags VertexBuffer::getDestAccessMask() { - return VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT; -} - -IndexBuffer::IndexBuffer(PGraphics graphics, - const IndexBufferCreateInfo &sourceData) - : Gfx::IndexBuffer(graphics->getFamilyMapping(), sourceData.sourceData.size, - sourceData.indexType, sourceData.sourceData.owner), - Vulkan::Buffer( - graphics, sourceData.sourceData.size, - VK_BUFFER_USAGE_INDEX_BUFFER_BIT | - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | - VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - currentOwner, false, sourceData.name) { - if (sourceData.sourceData.data != nullptr) { - void *data = map(); - std::memcpy(data, sourceData.sourceData.data, sourceData.sourceData.size); + void* data = mapRegion(update.offset, update.size); + std::memcpy(data, update.data, update.size); unmap(); - } +} + +void VertexBuffer::download(Array& buffer) { + void* data = map(false); + buffer.resize(getSize()); + std::memcpy(buffer.data(), data, getSize()); + unmap(); +} + +void VertexBuffer::requestOwnershipTransfer(Gfx::QueueType newOwner) { Gfx::QueueOwnedResource::transferOwnership(newOwner); } + +void VertexBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { Vulkan::Buffer::executeOwnershipBarrier(newOwner); } + +void VertexBuffer::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, VkAccessFlags dstAccess, + VkPipelineStageFlags dstStage) { + Vulkan::Buffer::executePipelineBarrier(srcAccess, srcStage, dstAccess, dstStage); +} + +VkAccessFlags VertexBuffer::getSourceAccessMask() { return VK_ACCESS_MEMORY_WRITE_BIT; } + +VkAccessFlags VertexBuffer::getDestAccessMask() { return VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT; } + +IndexBuffer::IndexBuffer(PGraphics graphics, const IndexBufferCreateInfo& sourceData) + : Gfx::IndexBuffer(graphics->getFamilyMapping(), sourceData.sourceData.size, sourceData.indexType, sourceData.sourceData.owner), + Vulkan::Buffer(graphics, sourceData.sourceData.size, + VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + currentOwner, false, sourceData.name) { + if (sourceData.sourceData.data != nullptr) { + void* data = map(); + std::memcpy(data, sourceData.sourceData.data, sourceData.sourceData.size); + unmap(); + } } IndexBuffer::~IndexBuffer() {} -void IndexBuffer::download(Array &buffer) { - void *data = map(false); - buffer.resize(getSize()); - std::memcpy(buffer.data(), data, getSize()); - unmap(); +void IndexBuffer::download(Array& buffer) { + void* data = map(false); + buffer.resize(getSize()); + std::memcpy(buffer.data(), data, getSize()); + unmap(); } -void IndexBuffer::requestOwnershipTransfer(Gfx::QueueType newOwner) { - Gfx::QueueOwnedResource::transferOwnership(newOwner); -} +void IndexBuffer::requestOwnershipTransfer(Gfx::QueueType newOwner) { Gfx::QueueOwnedResource::transferOwnership(newOwner); } -void IndexBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { - Vulkan::Buffer::executeOwnershipBarrier(newOwner); -} +void IndexBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { Vulkan::Buffer::executeOwnershipBarrier(newOwner); } -void IndexBuffer::executePipelineBarrier(VkAccessFlags srcAccess, - VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, +void IndexBuffer::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, VkAccessFlags dstAccess, VkPipelineStageFlags dstStage) { - Vulkan::Buffer::executePipelineBarrier(srcAccess, srcStage, dstAccess, - dstStage); + Vulkan::Buffer::executePipelineBarrier(srcAccess, srcStage, dstAccess, dstStage); } -VkAccessFlags IndexBuffer::getSourceAccessMask() { - return VK_ACCESS_MEMORY_WRITE_BIT; -} +VkAccessFlags IndexBuffer::getSourceAccessMask() { return VK_ACCESS_MEMORY_WRITE_BIT; } -VkAccessFlags IndexBuffer::getDestAccessMask() { - return VK_ACCESS_INDEX_READ_BIT; -} \ No newline at end of file +VkAccessFlags IndexBuffer::getDestAccessMask() { return VK_ACCESS_INDEX_READ_BIT; } \ No newline at end of file diff --git a/src/Engine/Graphics/Vulkan/Buffer.h b/src/Engine/Graphics/Vulkan/Buffer.h index 92539fc..60e889a 100644 --- a/src/Engine/Graphics/Vulkan/Buffer.h +++ b/src/Engine/Graphics/Vulkan/Buffer.h @@ -8,153 +8,133 @@ namespace Vulkan { DECLARE_REF(Command) DECLARE_REF(Fence) class BufferAllocation : public CommandBoundResource { -public: - BufferAllocation(PGraphics graphics); - virtual ~BufferAllocation(); - VkBuffer buffer = VK_NULL_HANDLE; - VmaAllocation allocation = VmaAllocation(); - VmaAllocationInfo info = VmaAllocationInfo(); - VkMemoryPropertyFlags properties = 0; - uint64 size = 0; - VkDeviceAddress deviceAddress; + public: + BufferAllocation(PGraphics graphics); + virtual ~BufferAllocation(); + VkBuffer buffer = VK_NULL_HANDLE; + VmaAllocation allocation = VmaAllocation(); + VmaAllocationInfo info = VmaAllocationInfo(); + VkMemoryPropertyFlags properties = 0; + uint64 size = 0; + VkDeviceAddress deviceAddress; }; DEFINE_REF(BufferAllocation); class Buffer { -public: - Buffer(PGraphics graphics, uint64 size, VkBufferUsageFlags usage, - Gfx::QueueType &queueType, bool dynamic, std::string name); - virtual ~Buffer(); - VkBuffer getHandle() const { return buffers[currentBuffer]->buffer; } - VkDeviceAddress getDeviceAddress() const { - return buffers[currentBuffer]->deviceAddress; - } - PBufferAllocation getAlloc() const { return buffers[currentBuffer]; } - uint64 getSize() const { return buffers[currentBuffer]->size; } - void *map(bool writeOnly = true); - void *mapRegion(uint64 regionOffset, uint64 regionSize, - bool writeOnly = true); - void unmap(); + public: + Buffer(PGraphics graphics, uint64 size, VkBufferUsageFlags usage, Gfx::QueueType& queueType, bool dynamic, std::string name); + virtual ~Buffer(); + VkBuffer getHandle() const { return buffers[currentBuffer]->buffer; } + VkDeviceAddress getDeviceAddress() const { return buffers[currentBuffer]->deviceAddress; } + PBufferAllocation getAlloc() const { return buffers[currentBuffer]; } + uint64 getSize() const { return buffers[currentBuffer]->size; } + void* map(bool writeOnly = true); + void* mapRegion(uint64 regionOffset, uint64 regionSize, bool writeOnly = true); + void unmap(); -protected: - PGraphics graphics; - uint32 currentBuffer; - Gfx::QueueType &owner; - Array buffers; - VkBufferUsageFlags usage; - bool dynamic; - std::string name; - void rotateBuffer(uint64 size, bool preserveContents = false); - void createBuffer(uint64 size); - void copyBuffer(uint64 src, uint64 dest); + protected: + PGraphics graphics; + uint32 currentBuffer; + Gfx::QueueType& owner; + Array buffers; + VkBufferUsageFlags usage; + bool dynamic; + std::string name; + void rotateBuffer(uint64 size, bool preserveContents = false); + void createBuffer(uint64 size); + void copyBuffer(uint64 src, uint64 dest); - void executeOwnershipBarrier(Gfx::QueueType newOwner); - void executePipelineBarrier(VkAccessFlags srcAccess, - VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, - VkPipelineStageFlags dstStage); + void executeOwnershipBarrier(Gfx::QueueType newOwner); + void executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, VkAccessFlags dstAccess, + VkPipelineStageFlags dstStage); - virtual void requestOwnershipTransfer(Gfx::QueueType newOwner) = 0; + virtual void requestOwnershipTransfer(Gfx::QueueType newOwner) = 0; - virtual VkAccessFlags getSourceAccessMask() = 0; - virtual VkAccessFlags getDestAccessMask() = 0; + virtual VkAccessFlags getSourceAccessMask() = 0; + virtual VkAccessFlags getDestAccessMask() = 0; }; DEFINE_REF(Buffer) class VertexBuffer : public Gfx::VertexBuffer, public Buffer { -public: - VertexBuffer(PGraphics graphics, const VertexBufferCreateInfo &sourceData); - virtual ~VertexBuffer(); + public: + VertexBuffer(PGraphics graphics, const VertexBufferCreateInfo& sourceData); + virtual ~VertexBuffer(); - virtual void updateRegion(DataSource update) override; - virtual void download(Array &buffer) override; + virtual void updateRegion(DataSource update) override; + virtual void download(Array& buffer) override; -protected: - // Inherited via Vulkan::Buffer - virtual VkAccessFlags getSourceAccessMask() override; - virtual VkAccessFlags getDestAccessMask() override; - virtual void requestOwnershipTransfer(Gfx::QueueType newOwner) override; - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; - virtual void - executePipelineBarrier(Gfx::SeAccessFlags srcAccess, - Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, - Gfx::SePipelineStageFlags dstStage) override; + protected: + // Inherited via Vulkan::Buffer + virtual VkAccessFlags getSourceAccessMask() override; + virtual VkAccessFlags getDestAccessMask() override; + virtual void requestOwnershipTransfer(Gfx::QueueType newOwner) override; + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; + virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) override; }; DEFINE_REF(VertexBuffer) class IndexBuffer : public Gfx::IndexBuffer, public Buffer { -public: - IndexBuffer(PGraphics graphics, const IndexBufferCreateInfo &sourceData); - virtual ~IndexBuffer(); + public: + IndexBuffer(PGraphics graphics, const IndexBufferCreateInfo& sourceData); + virtual ~IndexBuffer(); - virtual void download(Array &buffer) override; + virtual void download(Array& buffer) override; -protected: - // Inherited via Vulkan::Buffer - virtual VkAccessFlags getSourceAccessMask() override; - virtual VkAccessFlags getDestAccessMask() override; - virtual void requestOwnershipTransfer(Gfx::QueueType newOwner) override; - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; - virtual void - executePipelineBarrier(Gfx::SeAccessFlags srcAccess, - Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, - Gfx::SePipelineStageFlags dstStage) override; + protected: + // Inherited via Vulkan::Buffer + virtual VkAccessFlags getSourceAccessMask() override; + virtual VkAccessFlags getDestAccessMask() override; + virtual void requestOwnershipTransfer(Gfx::QueueType newOwner) override; + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; + virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) override; }; DEFINE_REF(IndexBuffer) class UniformBuffer : public Gfx::UniformBuffer, public Buffer { -public: - UniformBuffer(PGraphics graphics, const UniformBufferCreateInfo &sourceData); - virtual ~UniformBuffer(); - virtual void updateContents(const DataSource &sourceData) override; - virtual void rotateBuffer(uint64 size) override; + public: + UniformBuffer(PGraphics graphics, const UniformBufferCreateInfo& sourceData); + virtual ~UniformBuffer(); + virtual void updateContents(const DataSource& sourceData) override; + virtual void rotateBuffer(uint64 size) override; -protected: - // Inherited via Vulkan::Buffer - virtual VkAccessFlags getSourceAccessMask() override; - virtual VkAccessFlags getDestAccessMask() override; - virtual void requestOwnershipTransfer(Gfx::QueueType newOwner) override; - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; - virtual void - executePipelineBarrier(Gfx::SeAccessFlags srcAccess, - Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, - Gfx::SePipelineStageFlags dstStage) override; + protected: + // Inherited via Vulkan::Buffer + virtual VkAccessFlags getSourceAccessMask() override; + virtual VkAccessFlags getDestAccessMask() override; + virtual void requestOwnershipTransfer(Gfx::QueueType newOwner) override; + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; + virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) override; -private: + private: }; DEFINE_REF(UniformBuffer) class ShaderBuffer : public Gfx::ShaderBuffer, public Buffer { -public: - ShaderBuffer(PGraphics graphics, const ShaderBufferCreateInfo &sourceData); - virtual ~ShaderBuffer(); - virtual void - updateContents(const ShaderBufferCreateInfo &createInfo) override; - virtual void rotateBuffer(uint64 size, - bool preserveContents = false) override; - virtual void *mapRegion(uint64 offset, uint64 size, bool writeOnly) override; - virtual void unmap() override; + public: + ShaderBuffer(PGraphics graphics, const ShaderBufferCreateInfo& sourceData); + virtual ~ShaderBuffer(); + virtual void updateContents(const ShaderBufferCreateInfo& createInfo) override; + virtual void rotateBuffer(uint64 size, bool preserveContents = false) override; + virtual void* mapRegion(uint64 offset, uint64 size, bool writeOnly) override; + virtual void unmap() override; - virtual void clear() override; + virtual void clear() override; -protected: - // Inherited via Vulkan::Buffer - virtual VkAccessFlags getSourceAccessMask() override; - virtual VkAccessFlags getDestAccessMask() override; - virtual void requestOwnershipTransfer(Gfx::QueueType newOwner) override; - // Inherited via QueueOwnedResource - virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; - virtual void - executePipelineBarrier(Gfx::SeAccessFlags srcAccess, - Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, - Gfx::SePipelineStageFlags dstStage) override; + protected: + // Inherited via Vulkan::Buffer + virtual VkAccessFlags getSourceAccessMask() override; + virtual VkAccessFlags getDestAccessMask() override; + virtual void requestOwnershipTransfer(Gfx::QueueType newOwner) override; + // Inherited via QueueOwnedResource + virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; + virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess, + Gfx::SePipelineStageFlags dstStage) override; -private: + private: }; DEFINE_REF(ShaderBuffer) diff --git a/src/Engine/Graphics/Vulkan/Command.cpp b/src/Engine/Graphics/Vulkan/Command.cpp index 8739928..386ade4 100644 --- a/src/Engine/Graphics/Vulkan/Command.cpp +++ b/src/Engine/Graphics/Vulkan/Command.cpp @@ -1,21 +1,17 @@ #include "Command.h" -#include "Graphics.h" -#include "Pipeline.h" +#include "Descriptor.h" #include "Enums.h" #include "Framebuffer.h" -#include "RenderPass.h" +#include "Graphics.h" #include "Pipeline.h" -#include "Descriptor.h" +#include "RenderPass.h" #include "Window.h" + using namespace Seele; using namespace Seele::Vulkan; - -Command::Command(PGraphics graphics, PCommandPool pool) - : graphics(graphics) - , pool(pool) -{ +Command::Command(PGraphics graphics, PCommandPool pool) : graphics(graphics), pool(pool) { VkCommandBufferAllocateInfo allocInfo = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .pNext = nullptr, @@ -28,17 +24,15 @@ Command::Command(PGraphics graphics, PCommandPool pool) fence = new Fence(graphics); signalSemaphore = new Semaphore(graphics); state = State::Init; - //std::cout << "Cmd " << handle << " semaphore " << signalSemaphore->getHandle() << std::endl; + // std::cout << "Cmd " << handle << " semaphore " << signalSemaphore->getHandle() << std::endl; } -Command::~Command() -{ +Command::~Command() { vkFreeCommandBuffers(graphics->getDevice(), pool->getHandle(), 1, &handle); waitSemaphores.clear(); } -void Command::begin() -{ +void Command::begin() { VkCommandBufferBeginInfo beginInfo = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .pNext = nullptr, @@ -49,14 +43,12 @@ void Command::begin() state = State::Begin; } -void Command::end() -{ +void Command::end() { VK_CHECK(vkEndCommandBuffer(handle)); state = State::End; } -void Command::beginRenderPass(PRenderPass renderPass, PFramebuffer framebuffer) -{ +void Command::beginRenderPass(PRenderPass renderPass, PFramebuffer framebuffer) { assert(state == State::Begin); boundRenderPass = renderPass; boundFramebuffer = framebuffer; @@ -73,8 +65,7 @@ void Command::beginRenderPass(PRenderPass renderPass, PFramebuffer framebuffer) state = State::RenderPass; } -void Command::endRenderPass() -{ +void Command::endRenderPass() { boundRenderPass->endRenderPass(); boundRenderPass = nullptr; boundFramebuffer = nullptr; @@ -82,23 +73,19 @@ void Command::endRenderPass() state = State::Begin; } -void Command::executeCommands(Array commands) -{ +void Command::executeCommands(Array commands) { assert(state == State::RenderPass); - if(commands.size() == 0) - { - //std::cout << "No commands provided" << std::endl; + if (commands.size() == 0) { + // std::cout << "No commands provided" << std::endl; return; } Array cmdBuffers(commands.size()); - for (uint32 i = 0; i < commands.size(); ++i) - { + for (uint32 i = 0; i < commands.size(); ++i) { auto command = Gfx::PRenderCommand(commands[i]).cast(); command->end(); - for(auto& descriptor : command->boundResources) - { + for (auto& descriptor : command->boundResources) { boundResources.add(descriptor); - //std::cout << "Cmd " << handle << " bound descriptor " << descriptor->getHandle() << std::endl; + // std::cout << "Cmd " << handle << " bound descriptor " << descriptor->getHandle() << std::endl; } cmdBuffers[i] = command->getHandle(); executingRenders.add(std::move(commands[i])); @@ -106,21 +93,17 @@ void Command::executeCommands(Array commands) vkCmdExecuteCommands(handle, (uint32)cmdBuffers.size(), cmdBuffers.data()); } -void Command::executeCommands(Array commands) -{ - if(commands.size() == 0) - { +void Command::executeCommands(Array commands) { + if (commands.size() == 0) { return; } Array cmdBuffers(commands.size()); - for (uint32 i = 0; i < commands.size(); ++i) - { + for (uint32 i = 0; i < commands.size(); ++i) { auto command = Gfx::PComputeCommand(commands[i]).cast(); command->end(); - for(auto& descriptor : command->boundResources) - { + for (auto& descriptor : command->boundResources) { boundResources.add(descriptor); - //std::cout << "Cmd " << handle << " bound descriptor " << descriptor->getHandle() << std::endl; + // std::cout << "Cmd " << handle << " bound descriptor " << descriptor->getHandle() << std::endl; } cmdBuffers[i] = command->getHandle(); executingComputes.add(std::move(commands[i])); @@ -128,35 +111,29 @@ void Command::executeCommands(Array commands) vkCmdExecuteCommands(handle, (uint32)cmdBuffers.size(), cmdBuffers.data()); } -void Command::waitForSemaphore(VkPipelineStageFlags flags, PSemaphore semaphore) -{ +void Command::waitForSemaphore(VkPipelineStageFlags flags, PSemaphore semaphore) { waitSemaphores.add(semaphore); waitFlags.add(flags); - //std::cout << "Cmd " << handle << " wait for " << semaphore->getHandle() << std::endl; + // std::cout << "Cmd " << handle << " wait for " << semaphore->getHandle() << std::endl; } -void Command::checkFence() -{ +void Command::checkFence() { assert(state == State::Submit || !fence->isSignaled()); - if (fence->isSignaled()) - { - //std::cout << "Cmd " << handle << " was signaled" << std::endl; + if (fence->isSignaled()) { + // std::cout << "Cmd " << handle << " was signaled" << std::endl; vkResetCommandBuffer(handle, VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT); fence->reset(); - for(auto& command : executingComputes) - { + for (auto& command : executingComputes) { command->reset(); } pool->cacheCommands(std::move(executingComputes)); - for(auto& command : executingRenders) - { + for (auto& command : executingRenders) { command->reset(); } pool->cacheCommands(std::move(executingRenders)); - for(auto& descriptor : boundResources) - { + for (auto& descriptor : boundResources) { descriptor->unbind(); - //std::cout << "Cmd " << handle << " unbind " << descriptor->getHandle() << std::endl; + // std::cout << "Cmd " << handle << " unbind " << descriptor->getHandle() << std::endl; } boundResources.clear(); graphics->getDestructionManager()->notifyCommandComplete(); @@ -164,11 +141,9 @@ void Command::checkFence() } } -void Command::waitForCommand(uint32 timeout) -{ +void Command::waitForCommand(uint32 timeout) { pool->submitCommands(); - if (state == State::Begin) - { + if (state == State::Begin) { // is already done return; } @@ -176,26 +151,16 @@ void Command::waitForCommand(uint32 timeout) checkFence(); } -void Command::bindResource(PCommandBoundResource resource) -{ +void Command::bindResource(PCommandBoundResource resource) { resource->bind(); boundResources.add(resource); } -PFence Command::getFence() -{ - return fence; -} +PFence Command::getFence() { return fence; } -PCommandPool Command::getPool() -{ - return pool; -} +PCommandPool Command::getPool() { return pool; } -RenderCommand::RenderCommand(PGraphics graphics, VkCommandPool cmdPool) - : graphics(graphics) - , owner(cmdPool) -{ +RenderCommand::RenderCommand(PGraphics graphics, VkCommandPool cmdPool) : graphics(graphics), owner(cmdPool) { VkCommandBufferAllocateInfo allocInfo = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .pNext = nullptr, @@ -206,14 +171,9 @@ RenderCommand::RenderCommand(PGraphics graphics, VkCommandPool cmdPool) VK_CHECK(vkAllocateCommandBuffers(graphics->getDevice(), &allocInfo, &handle)); } +RenderCommand::~RenderCommand() { vkFreeCommandBuffers(graphics->getDevice(), owner, 1, &handle); } -RenderCommand::~RenderCommand() -{ - vkFreeCommandBuffers(graphics->getDevice(), owner, 1, &handle); -} - -void RenderCommand::begin(PRenderPass renderPass, PFramebuffer framebuffer) -{ +void RenderCommand::begin(PRenderPass renderPass, PFramebuffer framebuffer) { threadId = std::this_thread::get_id(); ready = false; VkCommandBufferInheritanceInfo inheritanceInfo = { @@ -234,93 +194,81 @@ void RenderCommand::begin(PRenderPass renderPass, PFramebuffer framebuffer) VK_CHECK(vkBeginCommandBuffer(handle, &beginInfo)); } -void RenderCommand::end() -{ - VK_CHECK(vkEndCommandBuffer(handle)); -} +void RenderCommand::end() { VK_CHECK(vkEndCommandBuffer(handle)); } -void RenderCommand::reset() -{ +void RenderCommand::reset() { vkResetCommandBuffer(handle, VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT); boundResources.clear(); ready = true; } -bool RenderCommand::isReady() -{ - return ready; -} +bool RenderCommand::isReady() { return ready; } -void RenderCommand::setViewport(Gfx::PViewport viewport) -{ +void RenderCommand::setViewport(Gfx::PViewport viewport) { assert(threadId == std::this_thread::get_id()); VkViewport vp = viewport.cast()->getHandle(); VkRect2D scissors = { - .offset = { - .x = (int32)viewport->getOffsetX(), - .y = (int32)viewport->getOffsetY(), - }, - .extent = { - .width = viewport->getWidth(), - .height = viewport->getHeight(), - }, + .offset = + { + .x = (int32)viewport->getOffsetX(), + .y = (int32)viewport->getOffsetY(), + }, + .extent = + { + .width = viewport->getWidth(), + .height = viewport->getHeight(), + }, }; vkCmdSetViewport(handle, 0, 1, &vp); vkCmdSetScissor(handle, 0, 1, &scissors); } -void RenderCommand::bindPipeline(Gfx::PGraphicsPipeline gfxPipeline) -{ +void RenderCommand::bindPipeline(Gfx::PGraphicsPipeline gfxPipeline) { assert(threadId == std::this_thread::get_id()); pipeline = gfxPipeline.cast(); pipeline->bind(handle); } -void RenderCommand::bindDescriptor(Gfx::PDescriptorSet descriptorSet, Array dynamicOffsets) -{ +void RenderCommand::bindDescriptor(Gfx::PDescriptorSet descriptorSet, Array dynamicOffsets) { assert(threadId == std::this_thread::get_id()); auto descriptor = descriptorSet.cast(); assert(descriptor->writeDescriptors.size() == 0); descriptor->bind(); boundResources.add(descriptor.getHandle()); - for (auto binding : descriptor->boundResources) - { + for (auto binding : descriptor->boundResources) { binding->bind(); boundResources.add(binding); } VkDescriptorSet setHandle = descriptor->getHandle(); - vkCmdBindDescriptorSets(handle, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->getLayout(), pipeline->getPipelineLayout()->findParameter(descriptorSet->getName()), 1, &setHandle, dynamicOffsets.size(), dynamicOffsets.data()); + vkCmdBindDescriptorSets(handle, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->getLayout(), + pipeline->getPipelineLayout()->findParameter(descriptorSet->getName()), 1, &setHandle, dynamicOffsets.size(), + dynamicOffsets.data()); } -void RenderCommand::bindDescriptor(const Array& descriptorSets, Array dynamicOffsets) -{ +void RenderCommand::bindDescriptor(const Array& descriptorSets, Array dynamicOffsets) { assert(threadId == std::this_thread::get_id()); VkDescriptorSet* sets = new VkDescriptorSet[descriptorSets.size()]; - for(uint32 i = 0; i < descriptorSets.size(); ++i) - { + for (uint32 i = 0; i < descriptorSets.size(); ++i) { auto descriptorSet = descriptorSets[i].cast(); assert(descriptorSet->writeDescriptors.size() == 0); descriptorSet->bind(); boundResources.add(descriptorSet.getHandle()); - for (auto binding : descriptorSet->boundResources) - { + for (auto binding : descriptorSet->boundResources) { binding->bind(); boundResources.add(binding); } sets[pipeline->getPipelineLayout()->findParameter(descriptorSet->getName())] = descriptorSet->getHandle(); } - vkCmdBindDescriptorSets(handle, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->getLayout(), 0, (uint32)descriptorSets.size(), sets, dynamicOffsets.size(), dynamicOffsets.data()); + vkCmdBindDescriptorSets(handle, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->getLayout(), 0, (uint32)descriptorSets.size(), sets, + dynamicOffsets.size(), dynamicOffsets.data()); delete[] sets; - } -void RenderCommand::bindVertexBuffer(const Array& streams) -{ +void RenderCommand::bindVertexBuffer(const Array& streams) { assert(threadId == std::this_thread::get_id()); Array buffers(streams.size()); Array offsets(streams.size()); - for(uint32 i = 0; i < streams.size(); ++i) - { + for (uint32 i = 0; i < streams.size(); ++i) { PVertexBuffer buf = streams[i].cast(); buffers[i] = buf->getHandle(); offsets[i] = 0; @@ -329,8 +277,7 @@ void RenderCommand::bindVertexBuffer(const Array& streams) }; vkCmdBindVertexBuffers(handle, 0, (uint32)streams.size(), buffers.data(), offsets.data()); } -void RenderCommand::bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) -{ +void RenderCommand::bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) { assert(threadId == std::this_thread::get_id()); PIndexBuffer buf = indexBuffer.cast(); buf->getAlloc()->bind(); @@ -338,39 +285,31 @@ void RenderCommand::bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) vkCmdBindIndexBuffer(handle, buf->getHandle(), 0, cast(buf->getIndexType())); } -void RenderCommand::pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, const void* data) -{ +void RenderCommand::pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, const void* data) { assert(threadId == std::this_thread::get_id()); vkCmdPushConstants(handle, pipeline->getLayout(), stage, offset, size, data); } -void RenderCommand::draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) -{ +void RenderCommand::draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) { assert(threadId == std::this_thread::get_id()); vkCmdDraw(handle, vertexCount, instanceCount, firstVertex, firstInstance); } -void RenderCommand::drawIndexed(uint32 indexCount, uint32 instanceCount, int32 firstIndex, uint32 vertexOffset, uint32 firstInstance) -{ +void RenderCommand::drawIndexed(uint32 indexCount, uint32 instanceCount, int32 firstIndex, uint32 vertexOffset, uint32 firstInstance) { assert(threadId == std::this_thread::get_id()); vkCmdDrawIndexed(handle, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance); } -void RenderCommand::drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) -{ +void RenderCommand::drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) { assert(threadId == std::this_thread::get_id()); graphics->vkCmdDrawMeshTasksEXT(handle, groupX, groupY, groupZ); } -void RenderCommand::drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) -{ +void RenderCommand::drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) { assert(threadId == std::this_thread::get_id()); graphics->vkCmdDrawMeshTasksIndirectEXT(handle, buffer.cast()->getHandle(), offset, drawCount, stride); } -ComputeCommand::ComputeCommand(PGraphics graphics, VkCommandPool cmdPool) - : graphics(graphics) - , owner(cmdPool) -{ +ComputeCommand::ComputeCommand(PGraphics graphics, VkCommandPool cmdPool) : graphics(graphics), owner(cmdPool) { VkCommandBufferAllocateInfo allocInfo = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .pNext = nullptr, @@ -381,14 +320,9 @@ ComputeCommand::ComputeCommand(PGraphics graphics, VkCommandPool cmdPool) VK_CHECK(vkAllocateCommandBuffers(graphics->getDevice(), &allocInfo, &handle)); } +ComputeCommand::~ComputeCommand() { vkFreeCommandBuffers(graphics->getDevice(), owner, 1, &handle); } -ComputeCommand::~ComputeCommand() -{ - vkFreeCommandBuffers(graphics->getDevice(), owner, 1, &handle); -} - -void ComputeCommand::begin() -{ +void ComputeCommand::begin() { threadId = std::this_thread::get_id(); ready = false; VkCommandBufferInheritanceInfo inheritanceInfo = { @@ -409,86 +343,74 @@ void ComputeCommand::begin() VK_CHECK(vkBeginCommandBuffer(handle, &beginInfo)); } -void ComputeCommand::end() -{ +void ComputeCommand::end() { assert(threadId == std::this_thread::get_id()); VK_CHECK(vkEndCommandBuffer(handle)); } -void ComputeCommand::reset() -{ +void ComputeCommand::reset() { assert(threadId == std::this_thread::get_id()); vkResetCommandBuffer(handle, VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT); boundResources.clear(); ready = true; } -bool ComputeCommand::isReady() -{ - return ready; -} +bool ComputeCommand::isReady() { return ready; } -void ComputeCommand::bindPipeline(Gfx::PComputePipeline computePipeline) -{ +void ComputeCommand::bindPipeline(Gfx::PComputePipeline computePipeline) { assert(threadId == std::this_thread::get_id()); pipeline = computePipeline.cast(); pipeline->bind(handle); } -void ComputeCommand::bindDescriptor(Gfx::PDescriptorSet descriptorSet, Array dynamicOffsets) -{ +void ComputeCommand::bindDescriptor(Gfx::PDescriptorSet descriptorSet, Array dynamicOffsets) { assert(threadId == std::this_thread::get_id()); auto descriptor = descriptorSet.cast(); assert(descriptor->writeDescriptors.size() == 0); boundResources.add(descriptor.getHandle()); - for (auto binding : descriptor->boundResources) - { + for (auto binding : descriptor->boundResources) { binding->bind(); boundResources.add(binding); } - + VkDescriptorSet setHandle = descriptor->getHandle(); - vkCmdBindDescriptorSets(handle, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline->getLayout(), pipeline->getPipelineLayout()->findParameter(descriptorSet->getName()), 1, &setHandle, dynamicOffsets.size(), dynamicOffsets.data()); + vkCmdBindDescriptorSets(handle, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline->getLayout(), + pipeline->getPipelineLayout()->findParameter(descriptorSet->getName()), 1, &setHandle, dynamicOffsets.size(), + dynamicOffsets.data()); } -void ComputeCommand::bindDescriptor(const Array& descriptorSets, Array dynamicOffsets) -{ +void ComputeCommand::bindDescriptor(const Array& descriptorSets, Array dynamicOffsets) { assert(threadId == std::this_thread::get_id()); VkDescriptorSet* sets = new VkDescriptorSet[descriptorSets.size()]; - for(uint32 i = 0; i < descriptorSets.size(); ++i) - { + for (uint32 i = 0; i < descriptorSets.size(); ++i) { auto descriptorSet = descriptorSets[i].cast(); assert(descriptorSet->writeDescriptors.size() == 0); descriptorSet->bind(); boundResources.add(descriptorSet.getHandle()); - //std::cout << "Binding descriptor " << descriptorSet->getHandle() << " to cmd " << handle << std::endl; - for (auto binding : descriptorSet->boundResources) - { + // std::cout << "Binding descriptor " << descriptorSet->getHandle() << " to cmd " << handle << std::endl; + for (auto binding : descriptorSet->boundResources) { binding->bind(); boundResources.add(binding); } sets[pipeline->getPipelineLayout()->findParameter(descriptorSet->getName())] = descriptorSet->getHandle(); } - vkCmdBindDescriptorSets(handle, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline->getLayout(), 0, (uint32)descriptorSets.size(), sets, dynamicOffsets.size(), dynamicOffsets.data()); + vkCmdBindDescriptorSets(handle, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline->getLayout(), 0, (uint32)descriptorSets.size(), sets, + dynamicOffsets.size(), dynamicOffsets.data()); delete[] sets; } -void ComputeCommand::pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, const void* data) -{ +void ComputeCommand::pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, const void* data) { assert(threadId == std::this_thread::get_id()); vkCmdPushConstants(handle, pipeline->getLayout(), stage, offset, size, data); } -void ComputeCommand::dispatch(uint32 threadX, uint32 threadY, uint32 threadZ) -{ +void ComputeCommand::dispatch(uint32 threadX, uint32 threadY, uint32 threadZ) { assert(threadId == std::this_thread::get_id()); vkCmdDispatch(handle, threadX, threadY, threadZ); } -CommandPool::CommandPool(PGraphics graphics, PQueue queue) - : graphics(graphics), queue(queue), queueFamilyIndex(queue->getFamilyIndex()) -{ +CommandPool::CommandPool(PGraphics graphics, PQueue queue) : graphics(graphics), queue(queue), queueFamilyIndex(queue->getFamilyIndex()) { VkCommandPoolCreateInfo info = { .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, .pNext = nullptr, @@ -498,16 +420,14 @@ CommandPool::CommandPool(PGraphics graphics, PQueue queue) VK_CHECK(vkCreateCommandPool(graphics->getDevice(), &info, nullptr, &commandPool)); // TODO: dont reset individual commands, reset pool instead allocatedBuffers.add(new Command(graphics, this)); - + command = allocatedBuffers.back(); command->begin(); } -CommandPool::~CommandPool() -{ +CommandPool::~CommandPool() { vkDeviceWaitIdle(graphics->getDevice()); - for (auto& cmd : allocatedBuffers) - { + for (auto& cmd : allocatedBuffers) { cmd->checkFence(); } allocatedRenderCommands.clear(); @@ -518,32 +438,22 @@ CommandPool::~CommandPool() queue = nullptr; } -PCommand CommandPool::getCommands() -{ - return command; -} -void CommandPool::cacheCommands(Array commands) -{ - for(auto&& cmd : commands) - { - allocatedRenderCommands.add(std::move(cmd)); - } +PCommand CommandPool::getCommands() { return command; } +void CommandPool::cacheCommands(Array commands) { + for (auto&& cmd : commands) { + allocatedRenderCommands.add(std::move(cmd)); + } } -void CommandPool::cacheCommands(Array commands) -{ - for(auto&& cmd : commands) - { - allocatedComputeCommands.add(std::move(cmd)); - } +void CommandPool::cacheCommands(Array commands) { + for (auto&& cmd : commands) { + allocatedComputeCommands.add(std::move(cmd)); + } } -ORenderCommand CommandPool::createRenderCommand(const std::string& name) -{ - for (uint32 i = 0; i < allocatedRenderCommands.size(); ++i) - { - if (allocatedRenderCommands[i]->isReady()) - { +ORenderCommand CommandPool::createRenderCommand(const std::string& name) { + for (uint32 i = 0; i < allocatedRenderCommands.size(); ++i) { + if (allocatedRenderCommands[i]->isReady()) { ORenderCommand cmdBuffer = std::move(allocatedRenderCommands[i]); allocatedRenderCommands.removeAt(i, false); cmdBuffer->name = name; @@ -557,12 +467,9 @@ ORenderCommand CommandPool::createRenderCommand(const std::string& name) return result; } -OComputeCommand CommandPool::createComputeCommand(const std::string& name) -{ - for (uint32 i = 0; i < allocatedComputeCommands.size(); ++i) - { - if (allocatedComputeCommands[i]->isReady()) - { +OComputeCommand CommandPool::createComputeCommand(const std::string& name) { + for (uint32 i = 0; i < allocatedComputeCommands.size(); ++i) { + if (allocatedComputeCommands[i]->isReady()) { OComputeCommand cmdBuffer = std::move(allocatedComputeCommands[i]); allocatedComputeCommands.removeAt(i, false); cmdBuffer->name = name; @@ -576,32 +483,26 @@ OComputeCommand CommandPool::createComputeCommand(const std::string& name) return result; } -void CommandPool::submitCommands(PSemaphore signalSemaphore) -{ +void CommandPool::submitCommands(PSemaphore signalSemaphore) { assert(command->state == Command::State::Begin); // Not in a renderpass command->end(); - Array semaphores = { command->signalSemaphore->getHandle() }; - if (signalSemaphore != nullptr) - { + Array semaphores = {command->signalSemaphore->getHandle()}; + if (signalSemaphore != nullptr) { semaphores.add(signalSemaphore->getHandle()); } queue->submitCommandBuffer(command, semaphores); - //std::cout << "Cmd " << command->getHandle() << " signalling " << command->signalSemaphore->getHandle() << std::endl; + // std::cout << "Cmd " << command->getHandle() << " signalling " << command->signalSemaphore->getHandle() << std::endl; PSemaphore waitSemaphore = command->signalSemaphore; - for (uint32 i = 0; i < allocatedBuffers.size(); ++i) - { + for (uint32 i = 0; i < allocatedBuffers.size(); ++i) { PCommand cmdBuffer = allocatedBuffers[i]; cmdBuffer->checkFence(); - if (cmdBuffer->state == Command::State::Init) - { + if (cmdBuffer->state == Command::State::Init) { command = cmdBuffer; command->begin(); command->waitForSemaphore(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, waitSemaphore); return; - } - else - { + } else { assert(cmdBuffer->state == Command::State::Submit); } } diff --git a/src/Engine/Graphics/Vulkan/Command.h b/src/Engine/Graphics/Vulkan/Command.h index 5310c2a..33a9288 100644 --- a/src/Engine/Graphics/Vulkan/Command.h +++ b/src/Engine/Graphics/Vulkan/Command.h @@ -14,143 +14,140 @@ DECLARE_REF(ComputeCommand) DECLARE_REF(DescriptorSet) DECLARE_REF(CommandPool) class Command { -public: - Command(PGraphics graphics, PCommandPool pool); - ~Command(); - constexpr VkCommandBuffer getHandle() { return handle; } - void reset(); - void begin(); - void end(); - void beginRenderPass(PRenderPass renderPass, PFramebuffer framebuffer); - void endRenderPass(); - void executeCommands(Array secondaryCommands); - void executeCommands(Array secondaryCommands); - void waitForSemaphore(VkPipelineStageFlags stages, PSemaphore waitSemaphore); - void bindResource(PCommandBoundResource resource); - void checkFence(); - void waitForCommand(uint32 timeToWait = 1000000u); - PFence getFence(); - PCommandPool getPool(); - enum State { - Init, - Begin, - RenderPass, - End, - Submit, - }; + public: + Command(PGraphics graphics, PCommandPool pool); + ~Command(); + constexpr VkCommandBuffer getHandle() { return handle; } + void reset(); + void begin(); + void end(); + void beginRenderPass(PRenderPass renderPass, PFramebuffer framebuffer); + void endRenderPass(); + void executeCommands(Array secondaryCommands); + void executeCommands(Array secondaryCommands); + void waitForSemaphore(VkPipelineStageFlags stages, PSemaphore waitSemaphore); + void bindResource(PCommandBoundResource resource); + void checkFence(); + void waitForCommand(uint32 timeToWait = 1000000u); + PFence getFence(); + PCommandPool getPool(); + enum State { + Init, + Begin, + RenderPass, + End, + Submit, + }; -private: - PGraphics graphics; - PCommandPool pool; - OFence fence; - OSemaphore signalSemaphore; - State state; - VkViewport currentViewport; - VkRect2D currentScissor; - VkCommandBuffer handle; - PRenderPass boundRenderPass; - PFramebuffer boundFramebuffer; - Array waitSemaphores; - Array waitFlags; - Array executingRenders; - Array executingComputes; - Array boundResources; - friend class RenderCommand; - friend class CommandPool; - friend class Queue; + private: + PGraphics graphics; + PCommandPool pool; + OFence fence; + OSemaphore signalSemaphore; + State state; + VkViewport currentViewport; + VkRect2D currentScissor; + VkCommandBuffer handle; + PRenderPass boundRenderPass; + PFramebuffer boundFramebuffer; + Array waitSemaphores; + Array waitFlags; + Array executingRenders; + Array executingComputes; + Array boundResources; + friend class RenderCommand; + friend class CommandPool; + friend class Queue; }; DEFINE_REF(Command) DECLARE_REF(GraphicsPipeline) DECLARE_REF(ComputePipeline) class RenderCommand : public Gfx::RenderCommand { -public: - RenderCommand(PGraphics graphics, VkCommandPool cmdPool); - virtual ~RenderCommand(); - constexpr VkCommandBuffer getHandle() { return handle; } - void begin(PRenderPass renderPass, PFramebuffer framebuffer); - void end(); - void reset(); - bool isReady(); - virtual void setViewport(Gfx::PViewport viewport) override; - virtual void bindPipeline(Gfx::PGraphicsPipeline pipeline) override; - virtual void bindDescriptor(Gfx::PDescriptorSet descriptorSet, Array dynamicOffsets) override; - virtual void bindDescriptor(const Array& descriptorSets, Array dynamicOffsets) override; - virtual void bindVertexBuffer(const Array& buffers) override; - virtual void bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) override; - virtual void pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, - const void* data) override; - virtual void draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) override; - virtual void drawIndexed(uint32 indexCount, uint32 instanceCount, int32 firstIndex, uint32 vertexOffset, - uint32 firstInstance) override; - virtual void drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) override; - virtual void drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) override; + public: + RenderCommand(PGraphics graphics, VkCommandPool cmdPool); + virtual ~RenderCommand(); + constexpr VkCommandBuffer getHandle() { return handle; } + void begin(PRenderPass renderPass, PFramebuffer framebuffer); + void end(); + void reset(); + bool isReady(); + virtual void setViewport(Gfx::PViewport viewport) override; + virtual void bindPipeline(Gfx::PGraphicsPipeline pipeline) override; + virtual void bindDescriptor(Gfx::PDescriptorSet descriptorSet, Array dynamicOffsets) override; + virtual void bindDescriptor(const Array& descriptorSets, Array dynamicOffsets) override; + virtual void bindVertexBuffer(const Array& buffers) override; + virtual void bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) override; + virtual void pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, const void* data) override; + virtual void draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) override; + virtual void drawIndexed(uint32 indexCount, uint32 instanceCount, int32 firstIndex, uint32 vertexOffset, uint32 firstInstance) override; + virtual void drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) override; + virtual void drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) override; -private: - PGraphicsPipeline pipeline; - bool ready; - Array boundResources; - VkViewport currentViewport; - VkRect2D currentScissor; - PGraphics graphics; - std::thread::id threadId; - VkCommandBuffer handle; - VkCommandPool owner; - friend class Command; + private: + PGraphicsPipeline pipeline; + bool ready; + Array boundResources; + VkViewport currentViewport; + VkRect2D currentScissor; + PGraphics graphics; + std::thread::id threadId; + VkCommandBuffer handle; + VkCommandPool owner; + friend class Command; }; DEFINE_REF(RenderCommand) class ComputeCommand : public Gfx::ComputeCommand { -public: - ComputeCommand(PGraphics graphics, VkCommandPool cmdPool); - virtual ~ComputeCommand(); - inline VkCommandBuffer getHandle() { return handle; } - void begin(); - void end(); - void reset(); - bool isReady(); - virtual void bindPipeline(Gfx::PComputePipeline pipeline) override; - virtual void bindDescriptor(Gfx::PDescriptorSet set, Array dynamicOffsets) override; - virtual void bindDescriptor(const Array& sets, Array dynamicOffsets) override; - virtual void pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, - const void* data) override; - virtual void dispatch(uint32 threadX, uint32 threadY, uint32 threadZ) override; + public: + ComputeCommand(PGraphics graphics, VkCommandPool cmdPool); + virtual ~ComputeCommand(); + inline VkCommandBuffer getHandle() { return handle; } + void begin(); + void end(); + void reset(); + bool isReady(); + virtual void bindPipeline(Gfx::PComputePipeline pipeline) override; + virtual void bindDescriptor(Gfx::PDescriptorSet set, Array dynamicOffsets) override; + virtual void bindDescriptor(const Array& sets, Array dynamicOffsets) override; + virtual void pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, const void* data) override; + virtual void dispatch(uint32 threadX, uint32 threadY, uint32 threadZ) override; -private: - PComputePipeline pipeline; - bool ready; - Array boundResources; - VkViewport currentViewport; - VkRect2D currentScissor; - PGraphics graphics; - std::thread::id threadId; - VkCommandBuffer handle; - VkCommandPool owner; - friend class Command; + private: + PComputePipeline pipeline; + bool ready; + Array boundResources; + VkViewport currentViewport; + VkRect2D currentScissor; + PGraphics graphics; + std::thread::id threadId; + VkCommandBuffer handle; + VkCommandPool owner; + friend class Command; }; DEFINE_REF(ComputeCommand) class CommandPool { -public: - CommandPool(PGraphics graphics, PQueue queue); - virtual ~CommandPool(); - constexpr PQueue getQueue() const { return queue; } - PCommand getCommands(); - void cacheCommands(Array commands); - void cacheCommands(Array commands); - ORenderCommand createRenderCommand(const std::string& name); - OComputeCommand createComputeCommand(const std::string& name); - constexpr VkCommandPool getHandle() const { return commandPool; } - void submitCommands(PSemaphore signalSemaphore = nullptr); + public: + CommandPool(PGraphics graphics, PQueue queue); + virtual ~CommandPool(); + constexpr PQueue getQueue() const { return queue; } + PCommand getCommands(); + void cacheCommands(Array commands); + void cacheCommands(Array commands); + ORenderCommand createRenderCommand(const std::string& name); + OComputeCommand createComputeCommand(const std::string& name); + constexpr VkCommandPool getHandle() const { return commandPool; } + void submitCommands(PSemaphore signalSemaphore = nullptr); -private: - PGraphics graphics; - VkCommandPool commandPool; - PQueue queue; - uint32 queueFamilyIndex; - PCommand command; - Array allocatedBuffers; - Array allocatedRenderCommands; - Array allocatedComputeCommands; + private: + PGraphics graphics; + VkCommandPool commandPool; + PQueue queue; + uint32 queueFamilyIndex; + PCommand command; + Array allocatedBuffers; + Array allocatedRenderCommands; + Array allocatedComputeCommands; }; DEFINE_REF(CommandPool) } // namespace Vulkan diff --git a/src/Engine/Graphics/Vulkan/Debug.cpp b/src/Engine/Graphics/Vulkan/Debug.cpp index ace4b8b..50dc7ec 100644 --- a/src/Engine/Graphics/Vulkan/Debug.cpp +++ b/src/Engine/Graphics/Vulkan/Debug.cpp @@ -3,34 +3,26 @@ using namespace Seele::Vulkan; -VkBool32 Seele::Vulkan::debugCallback( - VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, - VkDebugUtilsMessageTypeFlagsEXT messageTypes, - const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, - void* pUserData) -{ - std::cerr << pCallbackData->pMessage << std::endl; - return VK_FALSE; +VkBool32 Seele::Vulkan::debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageTypes, + const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) { + std::cerr << pCallbackData->pMessage << std::endl; + return VK_FALSE; } -VkResult Seele::Vulkan::CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDebugUtilsMessengerEXT *pCallback) -{ - auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT"); - if (func != nullptr) - { - return func(instance, pCreateInfo, pAllocator, pCallback); - } - else - { - return VK_ERROR_EXTENSION_NOT_PRESENT; - } +VkResult Seele::Vulkan::CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, + const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pCallback) { + auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT"); + if (func != nullptr) { + return func(instance, pCreateInfo, pAllocator, pCallback); + } else { + return VK_ERROR_EXTENSION_NOT_PRESENT; + } } -void Seele::Vulkan::DestroyDebugUtilsMessengerEXT(VkInstance instance, const VkAllocationCallbacks *pAllocator, VkDebugUtilsMessengerEXT pCallback) -{ - auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT"); - if (func != nullptr) - { - func(instance, pCallback, pAllocator); - } +void Seele::Vulkan::DestroyDebugUtilsMessengerEXT(VkInstance instance, const VkAllocationCallbacks* pAllocator, + VkDebugUtilsMessengerEXT pCallback) { + auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT"); + if (func != nullptr) { + func(instance, pCallback, pAllocator); + } } diff --git a/src/Engine/Graphics/Vulkan/Debug.h b/src/Engine/Graphics/Vulkan/Debug.h index a4165cd..c4a8fc1 100644 --- a/src/Engine/Graphics/Vulkan/Debug.h +++ b/src/Engine/Graphics/Vulkan/Debug.h @@ -2,17 +2,13 @@ #include "Containers/Array.h" #include -namespace Seele -{ -namespace Vulkan -{ -VkBool32 debugCallback( - VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, - VkDebugUtilsMessageTypeFlagsEXT messageTypes, - const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, - void* pUserData); +namespace Seele { +namespace Vulkan { +VkBool32 debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageTypes, + const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData); -VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDebugUtilsMessengerEXT *pCallback); -void DestroyDebugUtilsMessengerEXT(VkInstance instance, const VkAllocationCallbacks *pAllocator, VkDebugUtilsMessengerEXT pCallback); +VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, + const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pCallback); +void DestroyDebugUtilsMessengerEXT(VkInstance instance, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT pCallback); } // namespace Vulkan } // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/Vulkan/Descriptor.cpp b/src/Engine/Graphics/Vulkan/Descriptor.cpp index c21fd69..22d63a5 100644 --- a/src/Engine/Graphics/Vulkan/Descriptor.cpp +++ b/src/Engine/Graphics/Vulkan/Descriptor.cpp @@ -1,9 +1,10 @@ #include "Descriptor.h" #include "Buffer.h" +#include "CRC.h" #include "Command.h" #include "Graphics.h" #include "Texture.h" -#include "CRC.h" + using namespace Seele; using namespace Seele::Vulkan; @@ -56,9 +57,7 @@ void DescriptorLayout::create() { } DescriptorPool::DescriptorPool(PGraphics graphics, PDescriptorLayout layout) - : CommandBoundResource(graphics) - , graphics(graphics) - , layout(layout) { + : CommandBoundResource(graphics), graphics(graphics), layout(layout) { for (uint32 i = 0; i < cachedHandles.size(); ++i) { cachedHandles[i] = nullptr; } @@ -91,10 +90,8 @@ DescriptorPool::DescriptorPool(PGraphics graphics, PDescriptorLayout layout) } DescriptorPool::~DescriptorPool() { - for (size_t i = 0; i < maxSets; ++i) - { - if (cachedHandles[i] != nullptr) - { + for (size_t i = 0; i < maxSets; ++i) { + if (cachedHandles[i] != nullptr) { cachedHandles[i] = nullptr; } } @@ -168,26 +165,16 @@ void DescriptorPool::reset() { } DescriptorSet::DescriptorSet(PGraphics graphics, PDescriptorPool owner) - : Gfx::DescriptorSet(owner->getLayout()) - , CommandBoundResource(graphics) - , setHandle(VK_NULL_HANDLE) - , graphics(graphics) - , owner(owner) - , bindCount(0) - , currentlyInUse(false) -{ + : Gfx::DescriptorSet(owner->getLayout()), CommandBoundResource(graphics), setHandle(VK_NULL_HANDLE), graphics(graphics), owner(owner), + bindCount(0), currentlyInUse(false) { boundResources.resize(owner->getLayout()->getBindings().size()); } -DescriptorSet::~DescriptorSet() -{ - vkFreeDescriptorSets(graphics->getDevice(), owner->getHandle(), 1, &setHandle); -} +DescriptorSet::~DescriptorSet() { vkFreeDescriptorSets(graphics->getDevice(), owner->getHandle(), 1, &setHandle); } void DescriptorSet::updateBuffer(uint32_t binding, Gfx::PUniformBuffer uniformBuffer) { PUniformBuffer vulkanBuffer = uniformBuffer.cast(); - if (boundResources[binding] == vulkanBuffer->getAlloc()) - { + if (boundResources[binding] == vulkanBuffer->getAlloc()) { return; } @@ -195,7 +182,7 @@ void DescriptorSet::updateBuffer(uint32_t binding, Gfx::PUniformBuffer uniformBu .buffer = vulkanBuffer->getHandle(), .offset = 0, .range = vulkanBuffer->getSize(), - }); + }); writeDescriptors.add(VkWriteDescriptorSet{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, @@ -206,15 +193,14 @@ void DescriptorSet::updateBuffer(uint32_t binding, Gfx::PUniformBuffer uniformBu .descriptorCount = 1, .descriptorType = cast(layout->getBindings()[binding].descriptorType), .pBufferInfo = &bufferInfos.back(), - }); + }); boundResources[binding] = vulkanBuffer->getAlloc(); } void DescriptorSet::updateBuffer(uint32_t binding, Gfx::PShaderBuffer shaderBuffer) { PShaderBuffer vulkanBuffer = shaderBuffer.cast(); - if (boundResources[binding] == vulkanBuffer->getAlloc()) - { + if (boundResources[binding] == vulkanBuffer->getAlloc()) { return; } @@ -222,7 +208,7 @@ void DescriptorSet::updateBuffer(uint32_t binding, Gfx::PShaderBuffer shaderBuff .buffer = vulkanBuffer->getHandle(), .offset = 0, .range = vulkanBuffer->getSize(), - }); + }); writeDescriptors.add(VkWriteDescriptorSet{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .pNext = nullptr, @@ -232,15 +218,14 @@ void DescriptorSet::updateBuffer(uint32_t binding, Gfx::PShaderBuffer shaderBuff .descriptorCount = 1, .descriptorType = cast(layout->getBindings()[binding].descriptorType), .pBufferInfo = &bufferInfos.back(), - }); + }); boundResources[binding] = vulkanBuffer->getAlloc(); } void DescriptorSet::updateBuffer(uint32_t binding, uint32 index, Gfx::PShaderBuffer shaderBuffer) { PShaderBuffer vulkanBuffer = shaderBuffer.cast(); - if (boundResources[binding] == vulkanBuffer->getAlloc()) - { + if (boundResources[binding] == vulkanBuffer->getAlloc()) { return; } @@ -248,7 +233,7 @@ void DescriptorSet::updateBuffer(uint32_t binding, uint32 index, Gfx::PShaderBuf .buffer = vulkanBuffer->getHandle(), .offset = 0, .range = vulkanBuffer->getSize(), - }); + }); writeDescriptors.add(VkWriteDescriptorSet{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, @@ -259,15 +244,14 @@ void DescriptorSet::updateBuffer(uint32_t binding, uint32 index, Gfx::PShaderBuf .descriptorCount = 1, .descriptorType = cast(layout->getBindings()[binding].descriptorType), .pBufferInfo = &bufferInfos.back(), - }); + }); boundResources[binding] = vulkanBuffer->getAlloc(); } void DescriptorSet::updateSampler(uint32_t binding, Gfx::PSampler samplerState) { PSampler vulkanSampler = samplerState.cast(); - if (boundResources[binding] == vulkanSampler->getHandle()) - { + if (boundResources[binding] == vulkanSampler->getHandle()) { return; } @@ -275,7 +259,7 @@ void DescriptorSet::updateSampler(uint32_t binding, Gfx::PSampler samplerState) .sampler = vulkanSampler->getSampler(), .imageView = VK_NULL_HANDLE, .imageLayout = VK_IMAGE_LAYOUT_UNDEFINED, - }); + }); writeDescriptors.add(VkWriteDescriptorSet{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, @@ -286,15 +270,14 @@ void DescriptorSet::updateSampler(uint32_t binding, Gfx::PSampler samplerState) .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER, .pImageInfo = &imageInfos.back(), - }); + }); boundResources[binding] = vulkanSampler->getHandle(); } void DescriptorSet::updateTexture(uint32_t binding, Gfx::PTexture texture, Gfx::PSampler samplerState) { TextureBase* vulkanTexture = texture.cast().getHandle(); - if (boundResources[binding] == vulkanTexture->getHandle()) - { + if (boundResources[binding] == vulkanTexture->getHandle()) { return; } @@ -303,12 +286,11 @@ void DescriptorSet::updateTexture(uint32_t binding, Gfx::PTexture texture, Gfx:: .sampler = samplerState != nullptr ? samplerState.cast()->getSampler() : VK_NULL_HANDLE, .imageView = vulkanTexture->getView(), .imageLayout = cast(vulkanTexture->getLayout()), - }); + }); VkDescriptorType descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; if (samplerState != nullptr) { descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - } - else if (vulkanTexture->getUsage() & VK_IMAGE_USAGE_STORAGE_BIT) { + } else if (vulkanTexture->getUsage() & VK_IMAGE_USAGE_STORAGE_BIT) { descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; } writeDescriptors.add(VkWriteDescriptorSet{ @@ -320,7 +302,7 @@ void DescriptorSet::updateTexture(uint32_t binding, Gfx::PTexture texture, Gfx:: .descriptorCount = 1, .descriptorType = descriptorType, .pImageInfo = &imageInfos.back(), - }); + }); boundResources[binding] = vulkanTexture->getHandle(); } @@ -330,15 +312,14 @@ void DescriptorSet::updateTextureArray(uint32_t binding, Array te boundResources.resize(binding + textures.size()); for (auto& gfxTexture : textures) { TextureBase* vulkanTexture = gfxTexture.cast().getHandle(); - if (boundResources[binding + arrayElement] == vulkanTexture->getHandle()) - { + if (boundResources[binding + arrayElement] == vulkanTexture->getHandle()) { continue; } imageInfos.add(VkDescriptorImageInfo{ .sampler = VK_NULL_HANDLE, .imageView = vulkanTexture->getView(), .imageLayout = cast(vulkanTexture->getLayout()), - }); + }); VkDescriptorType descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; if (vulkanTexture->getUsage() & VK_IMAGE_USAGE_STORAGE_BIT) { @@ -354,7 +335,7 @@ void DescriptorSet::updateTextureArray(uint32_t binding, Array te .descriptorCount = 1, .descriptorType = descriptorType, .pImageInfo = &imageInfos.back(), - }); + }); vulkanTexture->getHandle()->bind(); } } @@ -385,8 +366,7 @@ void PipelineLayout::create() { PDescriptorLayout layout = desc.cast(); layout->create(); uint32 parameterIndex = parameterMapping[layout->getName()]; - if (parameterIndex >= vulkanDescriptorLayouts.size()) - { + if (parameterIndex >= vulkanDescriptorLayouts.size()) { vulkanDescriptorLayouts.resize(parameterIndex + 1); } vulkanDescriptorLayouts[parameterIndex] = layout->getHandle(); @@ -409,10 +389,10 @@ void PipelineLayout::create() { .pPushConstantRanges = vkPushConstants.data(), }; - layoutHash = CRC::Calculate(createInfo.pPushConstantRanges, - sizeof(VkPushConstantRange) * createInfo.pushConstantRangeCount, CRC::CRC_32()); - layoutHash = CRC::Calculate(createInfo.pSetLayouts, sizeof(VkDescriptorSetLayout) * createInfo.setLayoutCount, - CRC::CRC_32(), layoutHash); + layoutHash = + CRC::Calculate(createInfo.pPushConstantRanges, sizeof(VkPushConstantRange) * createInfo.pushConstantRangeCount, CRC::CRC_32()); + layoutHash = + CRC::Calculate(createInfo.pSetLayouts, sizeof(VkDescriptorSetLayout) * createInfo.setLayoutCount, CRC::CRC_32(), layoutHash); std::unique_lock l(layoutLock); if (cachedLayouts.contains(layoutHash)) { diff --git a/src/Engine/Graphics/Vulkan/Descriptor.h b/src/Engine/Graphics/Vulkan/Descriptor.h index e50b5fe..8b3fc5c 100644 --- a/src/Engine/Graphics/Vulkan/Descriptor.h +++ b/src/Engine/Graphics/Vulkan/Descriptor.h @@ -8,90 +8,90 @@ namespace Seele { namespace Vulkan { DECLARE_REF(Graphics) class DescriptorLayout : public Gfx::DescriptorLayout { -public: - DescriptorLayout(PGraphics graphics, const std::string& name); - virtual ~DescriptorLayout(); - virtual void create() override; - constexpr VkDescriptorSetLayout getHandle() const { return layoutHandle; } + public: + DescriptorLayout(PGraphics graphics, const std::string& name); + virtual ~DescriptorLayout(); + virtual void create() override; + constexpr VkDescriptorSetLayout getHandle() const { return layoutHandle; } -private: - PGraphics graphics; - Array bindings; - VkDescriptorSetLayout layoutHandle; - friend class DescriptorPool; + private: + PGraphics graphics; + Array bindings; + VkDescriptorSetLayout layoutHandle; + friend class DescriptorPool; }; DEFINE_REF(DescriptorLayout) DECLARE_REF(DescriptorSet) class DescriptorPool : public Gfx::DescriptorPool, public CommandBoundResource { -public: - DescriptorPool(PGraphics graphics, PDescriptorLayout layout); - virtual ~DescriptorPool(); - virtual Gfx::PDescriptorSet allocateDescriptorSet() override; - virtual void reset() override; + public: + DescriptorPool(PGraphics graphics, PDescriptorLayout layout); + virtual ~DescriptorPool(); + virtual Gfx::PDescriptorSet allocateDescriptorSet() override; + virtual void reset() override; - constexpr VkDescriptorPool getHandle() const { return poolHandle; } - constexpr PDescriptorLayout getLayout() const { return layout; } + constexpr VkDescriptorPool getHandle() const { return poolHandle; } + constexpr PDescriptorLayout getLayout() const { return layout; } -private: - PGraphics graphics; - PDescriptorLayout layout; - const static int maxSets = 64; - StaticArray cachedHandles; - VkDescriptorPool poolHandle; - DescriptorPool* nextAlloc = nullptr; + private: + PGraphics graphics; + PDescriptorLayout layout; + const static int maxSets = 64; + StaticArray cachedHandles; + VkDescriptorPool poolHandle; + DescriptorPool* nextAlloc = nullptr; }; DEFINE_REF(DescriptorPool) class DescriptorSet : public Gfx::DescriptorSet, public CommandBoundResource { -public: - DescriptorSet(PGraphics graphics, PDescriptorPool owner); - virtual ~DescriptorSet(); - virtual void writeChanges() override; - virtual void updateBuffer(uint32_t binding, Gfx::PUniformBuffer uniformBuffer) override; - virtual void updateBuffer(uint32_t binding, Gfx::PShaderBuffer uniformBuffer) override; - virtual void updateBuffer(uint32_t binding, uint32 index, Gfx::PShaderBuffer uniformBuffer) override; - virtual void updateSampler(uint32_t binding, Gfx::PSampler samplerState) override; - virtual void updateTexture(uint32_t binding, Gfx::PTexture texture, Gfx::PSampler sampler = nullptr) override; - virtual void updateTextureArray(uint32_t binding, Array texture) override; + public: + DescriptorSet(PGraphics graphics, PDescriptorPool owner); + virtual ~DescriptorSet(); + virtual void writeChanges() override; + virtual void updateBuffer(uint32_t binding, Gfx::PUniformBuffer uniformBuffer) override; + virtual void updateBuffer(uint32_t binding, Gfx::PShaderBuffer uniformBuffer) override; + virtual void updateBuffer(uint32_t binding, uint32 index, Gfx::PShaderBuffer uniformBuffer) override; + virtual void updateSampler(uint32_t binding, Gfx::PSampler samplerState) override; + virtual void updateTexture(uint32_t binding, Gfx::PTexture texture, Gfx::PSampler sampler = nullptr) override; + virtual void updateTextureArray(uint32_t binding, Array texture) override; - constexpr bool isCurrentlyInUse() const { return currentlyInUse; } - constexpr void allocate() { currentlyInUse = true; } - constexpr void free() { currentlyInUse = false; } - constexpr VkDescriptorSet getHandle() const { return setHandle; } + constexpr bool isCurrentlyInUse() const { return currentlyInUse; } + constexpr void allocate() { currentlyInUse = true; } + constexpr void free() { currentlyInUse = false; } + constexpr VkDescriptorSet getHandle() const { return setHandle; } -private: - List imageInfos; - List bufferInfos; - Array writeDescriptors; - // contains the previously bound resources at every binding - // since the layout is fixed, trying to bind a texture to a buffer - // would not work anyways, so casts should be safe - //Array cachedData; - Array boundResources; - VkDescriptorSet setHandle; - PGraphics graphics; - PDescriptorPool owner; - uint32 bindCount; - bool currentlyInUse; - friend class DescriptorPool; - friend class Command; - friend class RenderCommand; - friend class ComputeCommand; + private: + List imageInfos; + List bufferInfos; + Array writeDescriptors; + // contains the previously bound resources at every binding + // since the layout is fixed, trying to bind a texture to a buffer + // would not work anyways, so casts should be safe + // Array cachedData; + Array boundResources; + VkDescriptorSet setHandle; + PGraphics graphics; + PDescriptorPool owner; + uint32 bindCount; + bool currentlyInUse; + friend class DescriptorPool; + friend class Command; + friend class RenderCommand; + friend class ComputeCommand; }; DEFINE_REF(DescriptorSet) class PipelineLayout : public Gfx::PipelineLayout { -public: - PipelineLayout(PGraphics graphics, const std::string& name, Gfx::PPipelineLayout baseLayout); - virtual ~PipelineLayout(); - virtual void create(); - constexpr VkPipelineLayout getHandle() const { return layoutHandle; } + public: + PipelineLayout(PGraphics graphics, const std::string& name, Gfx::PPipelineLayout baseLayout); + virtual ~PipelineLayout(); + virtual void create(); + constexpr VkPipelineLayout getHandle() const { return layoutHandle; } -private: - Array vulkanDescriptorLayouts; - PGraphics graphics; - VkPipelineLayout layoutHandle; + private: + Array vulkanDescriptorLayouts; + PGraphics graphics; + VkPipelineLayout layoutHandle; }; DEFINE_REF(PipelineLayout) diff --git a/src/Engine/Graphics/Vulkan/Enums.cpp b/src/Engine/Graphics/Vulkan/Enums.cpp index 383a058..dfa1d8c 100644 --- a/src/Engine/Graphics/Vulkan/Enums.cpp +++ b/src/Engine/Graphics/Vulkan/Enums.cpp @@ -5,10 +5,8 @@ using namespace Seele; using namespace Seele::Vulkan; using namespace Seele::Gfx; -VkDescriptorType Seele::Vulkan::cast(const Seele::Gfx::SeDescriptorType &descriptorType) -{ - switch (descriptorType) - { +VkDescriptorType Seele::Vulkan::cast(const Seele::Gfx::SeDescriptorType& descriptorType) { + switch (descriptorType) { case SE_DESCRIPTOR_TYPE_SAMPLER: return VK_DESCRIPTOR_TYPE_SAMPLER; case SE_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: @@ -43,10 +41,8 @@ VkDescriptorType Seele::Vulkan::cast(const Seele::Gfx::SeDescriptorType &descrip return VK_DESCRIPTOR_TYPE_MAX_ENUM; } -Seele::Gfx::SeDescriptorType Seele::Vulkan::cast(const VkDescriptorType &descriptorType) -{ - switch (descriptorType) - { +Seele::Gfx::SeDescriptorType Seele::Vulkan::cast(const VkDescriptorType& descriptorType) { + switch (descriptorType) { case VK_DESCRIPTOR_TYPE_SAMPLER: return SE_DESCRIPTOR_TYPE_SAMPLER; @@ -77,14 +73,12 @@ Seele::Gfx::SeDescriptorType Seele::Vulkan::cast(const VkDescriptorType &descrip return SE_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV; #endif default: - throw std::logic_error("Not implemented"); + throw std::logic_error("Not implemented"); } } -VkShaderStageFlagBits Seele::Vulkan::cast(const Seele::Gfx::SeShaderStageFlagBits &stage) -{ - switch (stage) - { +VkShaderStageFlagBits Seele::Vulkan::cast(const Seele::Gfx::SeShaderStageFlagBits& stage) { + switch (stage) { case SE_SHADER_STAGE_VERTEX_BIT: return VK_SHADER_STAGE_VERTEX_BIT; @@ -102,15 +96,13 @@ VkShaderStageFlagBits Seele::Vulkan::cast(const Seele::Gfx::SeShaderStageFlagBit return VK_SHADER_STAGE_ALL_GRAPHICS; case SE_SHADER_STAGE_ALL: return VK_SHADER_STAGE_ALL; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -Seele::Gfx::SeShaderStageFlagBits Seele::Vulkan::cast(const VkShaderStageFlagBits &stage) -{ - switch (stage) - { +Seele::Gfx::SeShaderStageFlagBits Seele::Vulkan::cast(const VkShaderStageFlagBits& stage) { + switch (stage) { case VK_SHADER_STAGE_VERTEX_BIT: return SE_SHADER_STAGE_VERTEX_BIT; case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT: @@ -127,16 +119,13 @@ Seele::Gfx::SeShaderStageFlagBits Seele::Vulkan::cast(const VkShaderStageFlagBit return SE_SHADER_STAGE_ALL_GRAPHICS; case VK_SHADER_STAGE_ALL: return SE_SHADER_STAGE_ALL; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } - } -VkFormat Seele::Vulkan::cast(const Seele::Gfx::SeFormat &format) -{ - switch (format) - { +VkFormat Seele::Vulkan::cast(const Seele::Gfx::SeFormat& format) { + switch (format) { case SE_FORMAT_UNDEFINED: return VK_FORMAT_UNDEFINED; case SE_FORMAT_R4G4_UNORM_PACK8: @@ -595,10 +584,8 @@ VkFormat Seele::Vulkan::cast(const Seele::Gfx::SeFormat &format) return VK_FORMAT_MAX_ENUM; } } -Seele::Gfx::SeFormat Seele::Vulkan::cast(const VkFormat &format) -{ - switch (format) - { +Seele::Gfx::SeFormat Seele::Vulkan::cast(const VkFormat& format) { + switch (format) { case VK_FORMAT_UNDEFINED: return SE_FORMAT_UNDEFINED; case VK_FORMAT_R4G4_UNORM_PACK8: @@ -1053,15 +1040,13 @@ Seele::Gfx::SeFormat Seele::Vulkan::cast(const VkFormat &format) return SE_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG; case VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG: return SE_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -VkImageLayout Seele::Vulkan::cast(const Gfx::SeImageLayout &imageLayout) -{ - switch (imageLayout) - { +VkImageLayout Seele::Vulkan::cast(const Gfx::SeImageLayout& imageLayout) { + switch (imageLayout) { case SE_IMAGE_LAYOUT_UNDEFINED: return VK_IMAGE_LAYOUT_UNDEFINED; case SE_IMAGE_LAYOUT_GENERAL: @@ -1092,14 +1077,12 @@ VkImageLayout Seele::Vulkan::cast(const Gfx::SeImageLayout &imageLayout) return VK_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV; case SE_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT: return VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -Gfx::SeImageLayout Seele::Vulkan::cast(const VkImageLayout &imageLayout) -{ - switch (imageLayout) - { +Gfx::SeImageLayout Seele::Vulkan::cast(const VkImageLayout& imageLayout) { + switch (imageLayout) { case VK_IMAGE_LAYOUT_UNDEFINED: return SE_IMAGE_LAYOUT_UNDEFINED; case VK_IMAGE_LAYOUT_GENERAL: @@ -1130,67 +1113,57 @@ Gfx::SeImageLayout Seele::Vulkan::cast(const VkImageLayout &imageLayout) return SE_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV; case VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT: return SE_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -VkAttachmentStoreOp Seele::Vulkan::cast(const Gfx::SeAttachmentStoreOp &storeOp) -{ - switch (storeOp) - { +VkAttachmentStoreOp Seele::Vulkan::cast(const Gfx::SeAttachmentStoreOp& storeOp) { + switch (storeOp) { case SE_ATTACHMENT_STORE_OP_STORE: return VK_ATTACHMENT_STORE_OP_STORE; case SE_ATTACHMENT_STORE_OP_DONT_CARE: return VK_ATTACHMENT_STORE_OP_DONT_CARE; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -Gfx::SeAttachmentStoreOp Seele::Vulkan::cast(const VkAttachmentStoreOp &storeOp) -{ - switch (storeOp) - { +Gfx::SeAttachmentStoreOp Seele::Vulkan::cast(const VkAttachmentStoreOp& storeOp) { + switch (storeOp) { case VK_ATTACHMENT_STORE_OP_STORE: return SE_ATTACHMENT_STORE_OP_STORE; case VK_ATTACHMENT_STORE_OP_DONT_CARE: return SE_ATTACHMENT_STORE_OP_DONT_CARE; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -VkAttachmentLoadOp Seele::Vulkan::cast(const Gfx::SeAttachmentLoadOp &loadOp) -{ - switch (loadOp) - { +VkAttachmentLoadOp Seele::Vulkan::cast(const Gfx::SeAttachmentLoadOp& loadOp) { + switch (loadOp) { case SE_ATTACHMENT_LOAD_OP_LOAD: return VK_ATTACHMENT_LOAD_OP_LOAD; case SE_ATTACHMENT_LOAD_OP_CLEAR: return VK_ATTACHMENT_LOAD_OP_CLEAR; case SE_ATTACHMENT_LOAD_OP_DONT_CARE: return VK_ATTACHMENT_LOAD_OP_DONT_CARE; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -Gfx::SeAttachmentLoadOp Seele::Vulkan::cast(const VkAttachmentLoadOp &loadOp) -{ - switch (loadOp) - { +Gfx::SeAttachmentLoadOp Seele::Vulkan::cast(const VkAttachmentLoadOp& loadOp) { + switch (loadOp) { case VK_ATTACHMENT_LOAD_OP_LOAD: return SE_ATTACHMENT_LOAD_OP_LOAD; case VK_ATTACHMENT_LOAD_OP_CLEAR: return SE_ATTACHMENT_LOAD_OP_CLEAR; case VK_ATTACHMENT_LOAD_OP_DONT_CARE: return SE_ATTACHMENT_LOAD_OP_DONT_CARE; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -VkIndexType Seele::Vulkan::cast(const Gfx::SeIndexType &indexType) -{ - switch (indexType) - { +VkIndexType Seele::Vulkan::cast(const Gfx::SeIndexType& indexType) { + switch (indexType) { case Gfx::SE_INDEX_TYPE_UINT16: return VK_INDEX_TYPE_UINT16; case Gfx::SE_INDEX_TYPE_UINT32: @@ -1199,23 +1172,19 @@ VkIndexType Seele::Vulkan::cast(const Gfx::SeIndexType &indexType) return VK_INDEX_TYPE_MAX_ENUM; } } -Gfx::SeIndexType Seele::Vulkan::cast(const VkIndexType &indexType) -{ - switch (indexType) - { +Gfx::SeIndexType Seele::Vulkan::cast(const VkIndexType& indexType) { + switch (indexType) { case VK_INDEX_TYPE_UINT16: return Gfx::SE_INDEX_TYPE_UINT16; case VK_INDEX_TYPE_UINT32: return Gfx::SE_INDEX_TYPE_UINT32; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -VkPrimitiveTopology Seele::Vulkan::cast(const Gfx::SePrimitiveTopology &topology) -{ - switch (topology) - { +VkPrimitiveTopology Seele::Vulkan::cast(const Gfx::SePrimitiveTopology& topology) { + switch (topology) { case SE_PRIMITIVE_TOPOLOGY_POINT_LIST: return VK_PRIMITIVE_TOPOLOGY_POINT_LIST; case SE_PRIMITIVE_TOPOLOGY_LINE_LIST: @@ -1242,10 +1211,8 @@ VkPrimitiveTopology Seele::Vulkan::cast(const Gfx::SePrimitiveTopology &topology return VK_PRIMITIVE_TOPOLOGY_MAX_ENUM; } } -Gfx::SePrimitiveTopology Seele::Vulkan::cast(const VkPrimitiveTopology &topology) -{ - switch (topology) - { +Gfx::SePrimitiveTopology Seele::Vulkan::cast(const VkPrimitiveTopology& topology) { + switch (topology) { case VK_PRIMITIVE_TOPOLOGY_POINT_LIST: return SE_PRIMITIVE_TOPOLOGY_POINT_LIST; case VK_PRIMITIVE_TOPOLOGY_LINE_LIST: @@ -1268,15 +1235,13 @@ Gfx::SePrimitiveTopology Seele::Vulkan::cast(const VkPrimitiveTopology &topology return SE_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; case VK_PRIMITIVE_TOPOLOGY_PATCH_LIST: return SE_PRIMITIVE_TOPOLOGY_PATCH_LIST; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -VkPolygonMode Seele::Vulkan::cast(const Gfx::SePolygonMode &mode) -{ - switch (mode) - { +VkPolygonMode Seele::Vulkan::cast(const Gfx::SePolygonMode& mode) { + switch (mode) { case SE_POLYGON_MODE_FILL: return VK_POLYGON_MODE_FILL; case SE_POLYGON_MODE_LINE: @@ -1287,24 +1252,20 @@ VkPolygonMode Seele::Vulkan::cast(const Gfx::SePolygonMode &mode) return VK_POLYGON_MODE_MAX_ENUM; } } -Gfx::SePolygonMode Seele::Vulkan::cast(const VkPolygonMode &mode) -{ - switch (mode) - { +Gfx::SePolygonMode Seele::Vulkan::cast(const VkPolygonMode& mode) { + switch (mode) { case VK_POLYGON_MODE_FILL: return SE_POLYGON_MODE_FILL; case VK_POLYGON_MODE_LINE: return SE_POLYGON_MODE_LINE; case VK_POLYGON_MODE_POINT: return SE_POLYGON_MODE_POINT; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -VkCompareOp Seele::Vulkan::cast(const Gfx::SeCompareOp &op) -{ - switch (op) - { +VkCompareOp Seele::Vulkan::cast(const Gfx::SeCompareOp& op) { + switch (op) { case SE_COMPARE_OP_NEVER: return VK_COMPARE_OP_NEVER; case SE_COMPARE_OP_LESS: @@ -1321,14 +1282,12 @@ VkCompareOp Seele::Vulkan::cast(const Gfx::SeCompareOp &op) return VK_COMPARE_OP_GREATER_OR_EQUAL; case SE_COMPARE_OP_ALWAYS: return VK_COMPARE_OP_ALWAYS; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -Gfx::SeCompareOp Seele::Vulkan::cast(const VkCompareOp &op) -{ - switch (op) - { +Gfx::SeCompareOp Seele::Vulkan::cast(const VkCompareOp& op) { + switch (op) { case VK_COMPARE_OP_NEVER: return SE_COMPARE_OP_NEVER; case VK_COMPARE_OP_LESS: @@ -1345,181 +1304,155 @@ Gfx::SeCompareOp Seele::Vulkan::cast(const VkCompareOp &op) return SE_COMPARE_OP_GREATER_OR_EQUAL; case VK_COMPARE_OP_ALWAYS: return SE_COMPARE_OP_ALWAYS; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -VkClearValue Seele::Vulkan::cast(const Gfx::SeClearValue& clear) -{ +VkClearValue Seele::Vulkan::cast(const Gfx::SeClearValue& clear) { VkClearValue result; - if constexpr (sizeof(clear) == sizeof(Gfx::SeClearColorValue)) - { + if constexpr (sizeof(clear) == sizeof(Gfx::SeClearColorValue)) { result.color.float32[0] = clear.color.float32[0]; result.color.float32[1] = clear.color.float32[1]; result.color.float32[2] = clear.color.float32[2]; result.color.float32[3] = clear.color.float32[3]; - } - else - { + } else { result.depthStencil.depth = clear.depthStencil.depth; result.depthStencil.stencil = clear.depthStencil.stencil; } return result; } -Gfx::SeClearValue Seele::Vulkan::cast(const VkClearValue& clear) -{ +Gfx::SeClearValue Seele::Vulkan::cast(const VkClearValue& clear) { Gfx::SeClearValue result; - if constexpr (sizeof(clear) == sizeof(VkClearColorValue)) - { + if constexpr (sizeof(clear) == sizeof(VkClearColorValue)) { result.color.float32[0] = clear.color.float32[0]; result.color.float32[1] = clear.color.float32[1]; result.color.float32[2] = clear.color.float32[2]; result.color.float32[3] = clear.color.float32[3]; - } - else - { + } else { result.depthStencil.depth = clear.depthStencil.depth; result.depthStencil.stencil = clear.depthStencil.stencil; } return result; } -VkSamplerAddressMode Seele::Vulkan::cast(const Gfx::SeSamplerAddressMode &mode) -{ - switch(mode) - { - case SE_SAMPLER_ADDRESS_MODE_REPEAT: +VkSamplerAddressMode Seele::Vulkan::cast(const Gfx::SeSamplerAddressMode& mode) { + switch (mode) { + case SE_SAMPLER_ADDRESS_MODE_REPEAT: return VK_SAMPLER_ADDRESS_MODE_REPEAT; - case SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT: + case SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT: return VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; - case SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE: + case SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE: return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - case SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER: + case SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER: return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; - case SE_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE: + case SE_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE: return VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE; default: return VK_SAMPLER_ADDRESS_MODE_MAX_ENUM; } } -Gfx::SeSamplerAddressMode Seele::Vulkan::cast(const VkSamplerAddressMode &mode) -{ - switch(mode) - { - case VK_SAMPLER_ADDRESS_MODE_REPEAT: +Gfx::SeSamplerAddressMode Seele::Vulkan::cast(const VkSamplerAddressMode& mode) { + switch (mode) { + case VK_SAMPLER_ADDRESS_MODE_REPEAT: return SE_SAMPLER_ADDRESS_MODE_REPEAT; - case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT: + case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT: return SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; - case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE: + case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE: return SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER: + case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER: return SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; - case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE: + case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE: return SE_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -VkBorderColor Seele::Vulkan::cast(const Gfx::SeBorderColor &color) -{ - switch(color) - { - case SE_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK: +VkBorderColor Seele::Vulkan::cast(const Gfx::SeBorderColor& color) { + switch (color) { + case SE_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK: return VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; - case SE_BORDER_COLOR_INT_TRANSPARENT_BLACK: + case SE_BORDER_COLOR_INT_TRANSPARENT_BLACK: return VK_BORDER_COLOR_INT_TRANSPARENT_BLACK; - case SE_BORDER_COLOR_FLOAT_OPAQUE_BLACK: + case SE_BORDER_COLOR_FLOAT_OPAQUE_BLACK: return VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK; - case SE_BORDER_COLOR_INT_OPAQUE_BLACK: + case SE_BORDER_COLOR_INT_OPAQUE_BLACK: return VK_BORDER_COLOR_INT_OPAQUE_BLACK; - case SE_BORDER_COLOR_FLOAT_OPAQUE_WHITE: + case SE_BORDER_COLOR_FLOAT_OPAQUE_WHITE: return VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; - case SE_BORDER_COLOR_INT_OPAQUE_WHITE: + case SE_BORDER_COLOR_INT_OPAQUE_WHITE: return VK_BORDER_COLOR_INT_OPAQUE_WHITE; default: return VK_BORDER_COLOR_MAX_ENUM; } } -Gfx::SeBorderColor Seele::Vulkan::cast(const VkBorderColor &color) -{ - switch(color) - { - case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK: - return SE_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; - case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK: - return SE_BORDER_COLOR_INT_TRANSPARENT_BLACK; - case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK: - return SE_BORDER_COLOR_FLOAT_OPAQUE_BLACK; - case VK_BORDER_COLOR_INT_OPAQUE_BLACK: - return SE_BORDER_COLOR_INT_OPAQUE_BLACK; - case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE: - return SE_BORDER_COLOR_FLOAT_OPAQUE_WHITE; - case VK_BORDER_COLOR_INT_OPAQUE_WHITE: - return SE_BORDER_COLOR_INT_OPAQUE_WHITE; - default: throw std::logic_error("Not implemented"); - +Gfx::SeBorderColor Seele::Vulkan::cast(const VkBorderColor& color) { + switch (color) { + case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK: + return SE_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; + case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK: + return SE_BORDER_COLOR_INT_TRANSPARENT_BLACK; + case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK: + return SE_BORDER_COLOR_FLOAT_OPAQUE_BLACK; + case VK_BORDER_COLOR_INT_OPAQUE_BLACK: + return SE_BORDER_COLOR_INT_OPAQUE_BLACK; + case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE: + return SE_BORDER_COLOR_FLOAT_OPAQUE_WHITE; + case VK_BORDER_COLOR_INT_OPAQUE_WHITE: + return SE_BORDER_COLOR_INT_OPAQUE_WHITE; + default: + throw std::logic_error("Not implemented"); } } -VkFilter Seele::Vulkan::cast(const Gfx::SeFilter &filter) -{ - switch(filter) - { - case SE_FILTER_NEAREST: +VkFilter Seele::Vulkan::cast(const Gfx::SeFilter& filter) { + switch (filter) { + case SE_FILTER_NEAREST: return VK_FILTER_NEAREST; - case SE_FILTER_LINEAR: + case SE_FILTER_LINEAR: return VK_FILTER_LINEAR; - case SE_FILTER_CUBIC_IMG: + case SE_FILTER_CUBIC_IMG: return VK_FILTER_CUBIC_IMG; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -Gfx::SeFilter Seele::Vulkan::cast(const VkFilter &filter) -{ - switch(filter) - { - case VK_FILTER_NEAREST: +Gfx::SeFilter Seele::Vulkan::cast(const VkFilter& filter) { + switch (filter) { + case VK_FILTER_NEAREST: return SE_FILTER_NEAREST; - case VK_FILTER_LINEAR: + case VK_FILTER_LINEAR: return SE_FILTER_LINEAR; - case VK_FILTER_CUBIC_IMG: + case VK_FILTER_CUBIC_IMG: return SE_FILTER_CUBIC_IMG; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -VkSamplerMipmapMode Seele::Vulkan::cast(const Gfx::SeSamplerMipmapMode &filter) -{ - switch(filter) - { +VkSamplerMipmapMode Seele::Vulkan::cast(const Gfx::SeSamplerMipmapMode& filter) { + switch (filter) { case SE_SAMPLER_MIPMAP_MODE_NEAREST: return VK_SAMPLER_MIPMAP_MODE_NEAREST; case SE_SAMPLER_MIPMAP_MODE_LINEAR: return VK_SAMPLER_MIPMAP_MODE_LINEAR; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -Gfx::SeSamplerMipmapMode Seele::Vulkan::cast(const VkSamplerMipmapMode &filter) -{ - switch(filter) - { +Gfx::SeSamplerMipmapMode Seele::Vulkan::cast(const VkSamplerMipmapMode& filter) { + switch (filter) { case VK_SAMPLER_MIPMAP_MODE_NEAREST: return SE_SAMPLER_MIPMAP_MODE_NEAREST; case VK_SAMPLER_MIPMAP_MODE_LINEAR: return SE_SAMPLER_MIPMAP_MODE_LINEAR; - default: throw std::logic_error("Not implemented"); - + default: + throw std::logic_error("Not implemented"); } } -VkAccessFlagBits Seele::Vulkan::cast(const Gfx::SeAccessFlagBits &flags) -{ - switch(flags) - { +VkAccessFlagBits Seele::Vulkan::cast(const Gfx::SeAccessFlagBits& flags) { + switch (flags) { case SE_ACCESS_INDIRECT_COMMAND_READ_BIT: return VK_ACCESS_INDIRECT_COMMAND_READ_BIT; case SE_ACCESS_INDEX_READ_BIT: @@ -1575,10 +1508,8 @@ VkAccessFlagBits Seele::Vulkan::cast(const Gfx::SeAccessFlagBits &flags) } } -Gfx::SeAccessFlagBits Seele::Vulkan::cast(const VkAccessFlagBits &flags) -{ - switch(flags) - { +Gfx::SeAccessFlagBits Seele::Vulkan::cast(const VkAccessFlagBits& flags) { + switch (flags) { case VK_ACCESS_INDIRECT_COMMAND_READ_BIT: return SE_ACCESS_INDIRECT_COMMAND_READ_BIT; case VK_ACCESS_INDEX_READ_BIT: @@ -1633,10 +1564,8 @@ Gfx::SeAccessFlagBits Seele::Vulkan::cast(const VkAccessFlagBits &flags) return SE_ACCESS_FLAG_BITS_MAX_ENUM; } } -VkPipelineStageFlagBits Seele::Vulkan::cast(const Gfx::SePipelineStageFlagBits &flags) -{ - switch(flags) - { +VkPipelineStageFlagBits Seele::Vulkan::cast(const Gfx::SePipelineStageFlagBits& flags) { + switch (flags) { case SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT: return VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; case SE_PIPELINE_STAGE_DRAW_INDIRECT_BIT: @@ -1695,10 +1624,8 @@ VkPipelineStageFlagBits Seele::Vulkan::cast(const Gfx::SePipelineStageFlagBits & return VK_PIPELINE_STAGE_FLAG_BITS_MAX_ENUM; } } -Gfx::SePipelineStageFlagBits Seele::Vulkan::cast(const VkPipelineStageFlagBits &flags) -{ - switch(flags) - { +Gfx::SePipelineStageFlagBits Seele::Vulkan::cast(const VkPipelineStageFlagBits& flags) { + switch (flags) { case VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT: return SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT; case VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT: diff --git a/src/Engine/Graphics/Vulkan/Enums.h b/src/Engine/Graphics/Vulkan/Enums.h index 940beb9..9f82595 100644 --- a/src/Engine/Graphics/Vulkan/Enums.h +++ b/src/Engine/Graphics/Vulkan/Enums.h @@ -1,60 +1,57 @@ #pragma once #include "Graphics/Enums.h" -#include #include #include +#include -#define VK_CHECK(f) \ - { \ - VkResult res = (f); \ - if (res != VK_SUCCESS) \ - { \ - if(res == VK_ERROR_DEVICE_LOST) \ - { \ - std::this_thread::sleep_for(std::chrono::seconds(3)); \ - } \ - std::cout << "Fatal : VkResult is " << res << " in " << __FILE__ << " at line " << __LINE__ << std::endl; \ - abort(); \ - } \ - } -namespace Seele -{ -namespace Vulkan -{ -VkDescriptorType cast(const Gfx::SeDescriptorType &descriptorType); -Gfx::SeDescriptorType cast(const VkDescriptorType &descriptorType); -VkShaderStageFlagBits cast(const Gfx::SeShaderStageFlagBits &stage); -Gfx::SeShaderStageFlagBits cast(const VkShaderStageFlagBits &stage); -VkFormat cast(const Gfx::SeFormat &format); -Gfx::SeFormat cast(const VkFormat &format); -VkImageLayout cast(const Gfx::SeImageLayout &imageLayout); -Gfx::SeImageLayout cast(const VkImageLayout &imageLayout); -VkAttachmentStoreOp cast(const Gfx::SeAttachmentStoreOp &storeOp); -Gfx::SeAttachmentStoreOp cast(const VkAttachmentStoreOp &storeOp); -VkAttachmentLoadOp cast(const Gfx::SeAttachmentLoadOp &loadOp); -Gfx::SeAttachmentLoadOp cast(const VkAttachmentLoadOp &loadOp); -VkIndexType cast(const Gfx::SeIndexType &indexType); -Gfx::SeIndexType cast(const VkIndexType &indexType); -VkPrimitiveTopology cast(const Gfx::SePrimitiveTopology &topology); -Gfx::SePrimitiveTopology cast(const VkPrimitiveTopology &topology); -VkPolygonMode cast(const Gfx::SePolygonMode &mode); -Gfx::SePolygonMode cast(const VkPolygonMode &mode); -VkCompareOp cast(const Gfx::SeCompareOp &op); -Gfx::SeCompareOp cast(const VkCompareOp &op); -VkClearValue cast(const Gfx::SeClearValue &clear); -Gfx::SeClearValue cast(const VkClearValue &clear); -VkSamplerAddressMode cast(const Gfx::SeSamplerAddressMode &mode); -Gfx::SeSamplerAddressMode cast(const VkSamplerAddressMode &mode); -VkBorderColor cast(const Gfx::SeBorderColor &color); -Gfx::SeBorderColor cast(const VkBorderColor &color); -VkFilter cast(const Gfx::SeFilter &filter); -Gfx::SeFilter cast(const VkFilter &filter); -VkSamplerMipmapMode cast(const Gfx::SeSamplerMipmapMode &filter); -Gfx::SeSamplerMipmapMode cast(const VkSamplerMipmapMode &filter); -VkAccessFlagBits cast(const Gfx::SeAccessFlagBits &flags); -Gfx::SeAccessFlagBits cast(const VkAccessFlagBits &flags); -VkPipelineStageFlagBits cast(const Gfx::SePipelineStageFlagBits &flags); -Gfx::SePipelineStageFlagBits cast(const VkPipelineStageFlagBits &flags); +#define VK_CHECK(f) \ + { \ + VkResult res = (f); \ + if (res != VK_SUCCESS) { \ + if (res == VK_ERROR_DEVICE_LOST) { \ + std::this_thread::sleep_for(std::chrono::seconds(3)); \ + } \ + std::cout << "Fatal : VkResult is " << res << " in " << __FILE__ << " at line " << __LINE__ << std::endl; \ + abort(); \ + } \ + } + +namespace Seele { +namespace Vulkan { +VkDescriptorType cast(const Gfx::SeDescriptorType& descriptorType); +Gfx::SeDescriptorType cast(const VkDescriptorType& descriptorType); +VkShaderStageFlagBits cast(const Gfx::SeShaderStageFlagBits& stage); +Gfx::SeShaderStageFlagBits cast(const VkShaderStageFlagBits& stage); +VkFormat cast(const Gfx::SeFormat& format); +Gfx::SeFormat cast(const VkFormat& format); +VkImageLayout cast(const Gfx::SeImageLayout& imageLayout); +Gfx::SeImageLayout cast(const VkImageLayout& imageLayout); +VkAttachmentStoreOp cast(const Gfx::SeAttachmentStoreOp& storeOp); +Gfx::SeAttachmentStoreOp cast(const VkAttachmentStoreOp& storeOp); +VkAttachmentLoadOp cast(const Gfx::SeAttachmentLoadOp& loadOp); +Gfx::SeAttachmentLoadOp cast(const VkAttachmentLoadOp& loadOp); +VkIndexType cast(const Gfx::SeIndexType& indexType); +Gfx::SeIndexType cast(const VkIndexType& indexType); +VkPrimitiveTopology cast(const Gfx::SePrimitiveTopology& topology); +Gfx::SePrimitiveTopology cast(const VkPrimitiveTopology& topology); +VkPolygonMode cast(const Gfx::SePolygonMode& mode); +Gfx::SePolygonMode cast(const VkPolygonMode& mode); +VkCompareOp cast(const Gfx::SeCompareOp& op); +Gfx::SeCompareOp cast(const VkCompareOp& op); +VkClearValue cast(const Gfx::SeClearValue& clear); +Gfx::SeClearValue cast(const VkClearValue& clear); +VkSamplerAddressMode cast(const Gfx::SeSamplerAddressMode& mode); +Gfx::SeSamplerAddressMode cast(const VkSamplerAddressMode& mode); +VkBorderColor cast(const Gfx::SeBorderColor& color); +Gfx::SeBorderColor cast(const VkBorderColor& color); +VkFilter cast(const Gfx::SeFilter& filter); +Gfx::SeFilter cast(const VkFilter& filter); +VkSamplerMipmapMode cast(const Gfx::SeSamplerMipmapMode& filter); +Gfx::SeSamplerMipmapMode cast(const VkSamplerMipmapMode& filter); +VkAccessFlagBits cast(const Gfx::SeAccessFlagBits& flags); +Gfx::SeAccessFlagBits cast(const VkAccessFlagBits& flags); +VkPipelineStageFlagBits cast(const Gfx::SePipelineStageFlagBits& flags); +Gfx::SePipelineStageFlagBits cast(const VkPipelineStageFlagBits& flags); } // namespace Vulkan } // namespace Seele diff --git a/src/Engine/Graphics/Vulkan/Framebuffer.cpp b/src/Engine/Graphics/Vulkan/Framebuffer.cpp index 9f5791b..7c4f00b 100644 --- a/src/Engine/Graphics/Vulkan/Framebuffer.cpp +++ b/src/Engine/Graphics/Vulkan/Framebuffer.cpp @@ -1,57 +1,50 @@ #include "Framebuffer.h" -#include "Enums.h" -#include "RenderPass.h" -#include "Graphics.h" -#include "Texture.h" #include "CRC.h" +#include "Enums.h" +#include "Graphics.h" +#include "RenderPass.h" +#include "Texture.h" + using namespace Seele; using namespace Seele::Vulkan; Framebuffer::Framebuffer(PGraphics graphics, PRenderPass renderPass, Gfx::RenderTargetLayout renderTargetLayout) - : graphics(graphics) - , layout(renderTargetLayout) - , renderPass(renderPass) -{ + : graphics(graphics), layout(renderTargetLayout), renderPass(renderPass) { FramebufferDescription description; std::memset(&description, 0, sizeof(FramebufferDescription)); Array attachments; uint32 width = 0; uint32 height = 0; - for (auto inputAttachment : layout.inputAttachments) - { + for (auto inputAttachment : layout.inputAttachments) { PTexture2D vkInputAttachment = inputAttachment.getTexture().cast(); attachments.add(vkInputAttachment->getView()); description.inputAttachments[description.numInputAttachments++] = vkInputAttachment->getView(); width = std::max(width, vkInputAttachment->getWidth()); height = std::max(height, vkInputAttachment->getHeight()); } - for (auto colorAttachment : layout.colorAttachments) - { + for (auto colorAttachment : layout.colorAttachments) { PTexture2D vkColorAttachment = colorAttachment.getTexture().cast(); attachments.add(vkColorAttachment->getView()); description.colorAttachments[description.numColorAttachments++] = vkColorAttachment->getView(); width = std::max(width, vkColorAttachment->getWidth()); height = std::max(height, vkColorAttachment->getHeight()); } - for (auto resolveAttachment : layout.resolveAttachments) - { + for (auto resolveAttachment : layout.resolveAttachments) { PTexture2D vkResolveAttachment = resolveAttachment.getTexture().cast(); attachments.add(vkResolveAttachment->getView()); description.resolveAttachments[description.numResolveAttachments++] = vkResolveAttachment->getView(); width = std::max(width, vkResolveAttachment->getWidth()); height = std::max(height, vkResolveAttachment->getHeight()); } - if (layout.depthAttachment.getTexture() != nullptr) - { + if (layout.depthAttachment.getTexture() != nullptr) { PTexture2D vkDepthAttachment = layout.depthAttachment.getTexture().cast(); attachments.add(vkDepthAttachment->getView()); description.depthAttachment = vkDepthAttachment->getView(); width = std::max(width, vkDepthAttachment->getWidth()); height = std::max(height, vkDepthAttachment->getHeight()); } - if (layout.depthResolveAttachment.getTexture() != nullptr) - { + if (layout.depthResolveAttachment.getTexture() != nullptr) { PTexture2D vkDepthAttachment = layout.depthResolveAttachment.getTexture().cast(); attachments.add(vkDepthAttachment->getView()); description.depthResolveAttachment = vkDepthAttachment->getView(); @@ -74,8 +67,7 @@ Framebuffer::Framebuffer(PGraphics graphics, PRenderPass renderPass, Gfx::Render hash = CRC::Calculate(&description, sizeof(FramebufferDescription), CRC::CRC_32()); } -Framebuffer::~Framebuffer() -{ +Framebuffer::~Framebuffer() { vkDestroyFramebuffer(graphics->getDevice(), handle, nullptr); graphics = nullptr; } \ No newline at end of file diff --git a/src/Engine/Graphics/Vulkan/Framebuffer.h b/src/Engine/Graphics/Vulkan/Framebuffer.h index 38ed4e3..1b9e246 100644 --- a/src/Engine/Graphics/Vulkan/Framebuffer.h +++ b/src/Engine/Graphics/Vulkan/Framebuffer.h @@ -3,13 +3,10 @@ #include "Graphics.h" #include "Graphics/RenderTarget.h" -namespace Seele -{ -namespace Vulkan -{ +namespace Seele { +namespace Vulkan { DECLARE_REF(RenderPass) -struct FramebufferDescription -{ +struct FramebufferDescription { StaticArray inputAttachments; StaticArray colorAttachments; StaticArray resolveAttachments; @@ -19,21 +16,14 @@ struct FramebufferDescription uint32 numColorAttachments; uint32 numResolveAttachments; }; -class Framebuffer -{ -public: +class Framebuffer { + public: Framebuffer(PGraphics graphics, PRenderPass renderpass, Gfx::RenderTargetLayout renderTargetLayout); virtual ~Framebuffer(); - constexpr VkFramebuffer getHandle() const - { - return handle; - } - constexpr uint32 getHash() const - { - return hash; - } + constexpr VkFramebuffer getHandle() const { return handle; } + constexpr uint32 getHash() const { return hash; } -private: + private: uint32 hash; PGraphics graphics; VkFramebuffer handle; diff --git a/src/Engine/Graphics/Vulkan/Graphics.cpp b/src/Engine/Graphics/Vulkan/Graphics.cpp index 2c08587..76f0044 100644 --- a/src/Engine/Graphics/Vulkan/Graphics.cpp +++ b/src/Engine/Graphics/Vulkan/Graphics.cpp @@ -1,21 +1,22 @@ #include "Graphics.h" -#include "Debug.h" #include "Allocator.h" #include "Buffer.h" +#include "Command.h" +#include "Debug.h" +#include "Descriptor.h" +#include "Framebuffer.h" #include "Graphics/Enums.h" #include "Graphics/Graphics.h" #include "Graphics/Initializer.h" #include "PipelineCache.h" -#include "Command.h" -#include "Descriptor.h" -#include "Window.h" -#include "RenderPass.h" -#include "Framebuffer.h" -#include "Shader.h" #include "RayTracing.h" +#include "RenderPass.h" +#include "Shader.h" +#include "Window.h" #include #include #include + #define VMA_IMPLEMENTATION #include "vk_mem_alloc.h" @@ -26,16 +27,9 @@ thread_local PCommandPool Seele::Vulkan::Graphics::graphicsCommands = nullptr; thread_local PCommandPool Seele::Vulkan::Graphics::computeCommands = nullptr; thread_local PCommandPool Seele::Vulkan::Graphics::transferCommands = nullptr; -Graphics::Graphics() - : instance(VK_NULL_HANDLE) - , handle(VK_NULL_HANDLE) - , physicalDevice(VK_NULL_HANDLE) - , callback(VK_NULL_HANDLE) -{ -} +Graphics::Graphics() : instance(VK_NULL_HANDLE), handle(VK_NULL_HANDLE), physicalDevice(VK_NULL_HANDLE), callback(VK_NULL_HANDLE) {} -Graphics::~Graphics() -{ +Graphics::~Graphics() { vkDeviceWaitIdle(handle); pipelineCache = nullptr; allocatedFramebuffers.clear(); @@ -49,8 +43,7 @@ Graphics::~Graphics() vkDestroyInstance(instance, nullptr); } -void Graphics::init(GraphicsInitializer initInfo) -{ +void Graphics::init(GraphicsInitializer initInfo) { initInstance(initInfo); #if ENABLE_VALIDATION setupDebugCallback(); @@ -74,152 +67,102 @@ void Graphics::init(GraphicsInitializer initInfo) destructionManager = new DestructionManager(this); } -Gfx::OWindow Graphics::createWindow(const WindowCreateInfo &createInfo) -{ - return new Window(this, createInfo); -} +Gfx::OWindow Graphics::createWindow(const WindowCreateInfo& createInfo) { return new Window(this, createInfo); } -Gfx::OViewport Graphics::createViewport(Gfx::PWindow owner, const ViewportCreateInfo &viewportInfo) -{ +Gfx::OViewport Graphics::createViewport(Gfx::PWindow owner, const ViewportCreateInfo& viewportInfo) { return new Viewport(owner, viewportInfo); } -Gfx::ORenderPass Graphics::createRenderPass(Gfx::RenderTargetLayout layout, Array dependencies, Gfx::PViewport renderArea) -{ +Gfx::ORenderPass Graphics::createRenderPass(Gfx::RenderTargetLayout layout, Array dependencies, + Gfx::PViewport renderArea) { return new RenderPass(this, std::move(layout), std::move(dependencies), renderArea); } -void Graphics::beginRenderPass(Gfx::PRenderPass renderPass) -{ +void Graphics::beginRenderPass(Gfx::PRenderPass renderPass) { PRenderPass rp = renderPass.cast(); uint32 framebufferHash = rp->getFramebufferHash(); PFramebuffer framebuffer; { auto found = allocatedFramebuffers.find(framebufferHash); - if (found == allocatedFramebuffers.end()) - { + if (found == allocatedFramebuffers.end()) { allocatedFramebuffers[framebufferHash] = new Framebuffer(this, rp, rp->getLayout()); framebuffer = allocatedFramebuffers[framebufferHash]; - } - else - { + } else { framebuffer = std::move(found->value); } } getGraphicsCommands()->getCommands()->beginRenderPass(rp, framebuffer); } -void Graphics::endRenderPass() -{ +void Graphics::endRenderPass() { getGraphicsCommands()->getCommands()->endRenderPass(); getGraphicsCommands()->submitCommands(); } -void Graphics::waitDeviceIdle() -{ - vkDeviceWaitIdle(handle); -} +void Graphics::waitDeviceIdle() { vkDeviceWaitIdle(handle); } -void Graphics::executeCommands(Array commands) -{ +void Graphics::executeCommands(Array commands) { getGraphicsCommands()->getCommands()->executeCommands(std::move(commands)); } -void Graphics::executeCommands(Array commands) -{ +void Graphics::executeCommands(Array commands) { getComputeCommands()->getCommands()->executeCommands(std::move(commands)); } -Gfx::OTexture2D Graphics::createTexture2D(const TextureCreateInfo &createInfo) -{ - return new Texture2D(this, createInfo); -} +Gfx::OTexture2D Graphics::createTexture2D(const TextureCreateInfo& createInfo) { return new Texture2D(this, createInfo); } -Gfx::OTexture3D Graphics::createTexture3D(const TextureCreateInfo &createInfo) -{ - return new Texture3D(this, createInfo); -} +Gfx::OTexture3D Graphics::createTexture3D(const TextureCreateInfo& createInfo) { return new Texture3D(this, createInfo); } -Gfx::OTextureCube Graphics::createTextureCube(const TextureCreateInfo &createInfo) -{ - return new TextureCube(this, createInfo); -} +Gfx::OTextureCube Graphics::createTextureCube(const TextureCreateInfo& createInfo) { return new TextureCube(this, createInfo); } -Gfx::OUniformBuffer Graphics::createUniformBuffer(const UniformBufferCreateInfo &bulkData) -{ - return new UniformBuffer(this, bulkData); -} +Gfx::OUniformBuffer Graphics::createUniformBuffer(const UniformBufferCreateInfo& bulkData) { return new UniformBuffer(this, bulkData); } -Gfx::OShaderBuffer Graphics::createShaderBuffer(const ShaderBufferCreateInfo &bulkData) -{ - return new ShaderBuffer(this, bulkData); -} -Gfx::OVertexBuffer Graphics::createVertexBuffer(const VertexBufferCreateInfo &bulkData) -{ - return new VertexBuffer(this, bulkData); -} +Gfx::OShaderBuffer Graphics::createShaderBuffer(const ShaderBufferCreateInfo& bulkData) { return new ShaderBuffer(this, bulkData); } +Gfx::OVertexBuffer Graphics::createVertexBuffer(const VertexBufferCreateInfo& bulkData) { return new VertexBuffer(this, bulkData); } -Gfx::OIndexBuffer Graphics::createIndexBuffer(const IndexBufferCreateInfo &bulkData) -{ - return new IndexBuffer(this, bulkData); -} -Gfx::ORenderCommand Graphics::createRenderCommand(const std::string& name) -{ - return getGraphicsCommands()->createRenderCommand(name); -} +Gfx::OIndexBuffer Graphics::createIndexBuffer(const IndexBufferCreateInfo& bulkData) { return new IndexBuffer(this, bulkData); } +Gfx::ORenderCommand Graphics::createRenderCommand(const std::string& name) { return getGraphicsCommands()->createRenderCommand(name); } -Gfx::OComputeCommand Graphics::createComputeCommand(const std::string& name) -{ - return getComputeCommands()->createComputeCommand(name); -} +Gfx::OComputeCommand Graphics::createComputeCommand(const std::string& name) { return getComputeCommands()->createComputeCommand(name); } -Gfx::OVertexShader Graphics::createVertexShader(const ShaderCreateInfo& createInfo) -{ +Gfx::OVertexShader Graphics::createVertexShader(const ShaderCreateInfo& createInfo) { OVertexShader shader = new VertexShader(this); shader->create(createInfo); return shader; } -Gfx::OFragmentShader Graphics::createFragmentShader(const ShaderCreateInfo& createInfo) -{ +Gfx::OFragmentShader Graphics::createFragmentShader(const ShaderCreateInfo& createInfo) { OFragmentShader shader = new FragmentShader(this); shader->create(createInfo); return shader; } -Gfx::OComputeShader Graphics::createComputeShader(const ShaderCreateInfo& createInfo) -{ +Gfx::OComputeShader Graphics::createComputeShader(const ShaderCreateInfo& createInfo) { OComputeShader shader = new ComputeShader(this); shader->create(createInfo); return shader; } -Gfx::OTaskShader Graphics::createTaskShader(const ShaderCreateInfo& createInfo) -{ +Gfx::OTaskShader Graphics::createTaskShader(const ShaderCreateInfo& createInfo) { OTaskShader shader = new TaskShader(this); shader->create(createInfo); return shader; } -Gfx::OMeshShader Graphics::createMeshShader(const ShaderCreateInfo& createInfo) -{ +Gfx::OMeshShader Graphics::createMeshShader(const ShaderCreateInfo& createInfo) { OMeshShader shader = new MeshShader(this); shader->create(createInfo); return shader; } -Gfx::PGraphicsPipeline Graphics::createGraphicsPipeline(Gfx::LegacyPipelineCreateInfo createInfo) -{ +Gfx::PGraphicsPipeline Graphics::createGraphicsPipeline(Gfx::LegacyPipelineCreateInfo createInfo) { return pipelineCache->createPipeline(std::move(createInfo)); } -Gfx::PGraphicsPipeline Graphics::createGraphicsPipeline(Gfx::MeshPipelineCreateInfo createInfo) -{ +Gfx::PGraphicsPipeline Graphics::createGraphicsPipeline(Gfx::MeshPipelineCreateInfo createInfo) { return pipelineCache->createPipeline(std::move(createInfo)); } -Gfx::PComputePipeline Graphics::createComputePipeline(Gfx::ComputePipelineCreateInfo createInfo) -{ +Gfx::PComputePipeline Graphics::createComputePipeline(Gfx::ComputePipelineCreateInfo createInfo) { return pipelineCache->createPipeline(std::move(createInfo)); } -Gfx::OSampler Graphics::createSampler(const SamplerCreateInfo& createInfo) -{ +Gfx::OSampler Graphics::createSampler(const SamplerCreateInfo& createInfo) { VkSamplerCreateInfo vkInfo = { .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .pNext = nullptr, @@ -243,87 +186,75 @@ Gfx::OSampler Graphics::createSampler(const SamplerCreateInfo& createInfo) return new Sampler(this, vkInfo); } -Gfx::ODescriptorLayout Graphics::createDescriptorLayout(const std::string& name) -{ - return new DescriptorLayout(this, name); -} +Gfx::ODescriptorLayout Graphics::createDescriptorLayout(const std::string& name) { return new DescriptorLayout(this, name); } -Gfx::OPipelineLayout Graphics::createPipelineLayout(const std::string& name, Gfx::PPipelineLayout baseLayout) -{ +Gfx::OPipelineLayout Graphics::createPipelineLayout(const std::string& name, Gfx::PPipelineLayout baseLayout) { return new PipelineLayout(this, name, baseLayout); } -Gfx::OVertexInput Graphics::createVertexInput(VertexInputStateCreateInfo createInfo) -{ - return new VertexInput(createInfo); -} +Gfx::OVertexInput Graphics::createVertexInput(VertexInputStateCreateInfo createInfo) { return new VertexInput(createInfo); } -void Graphics::resolveTexture(Gfx::PTexture source, Gfx::PTexture destination) -{ +void Graphics::resolveTexture(Gfx::PTexture source, Gfx::PTexture destination) { PTextureBase sourceTex = source.cast(); PTextureBase destinationTex = destination.cast(); VkImageResolve resolve = { - .srcSubresource = VkImageSubresourceLayers { - .aspectMask = sourceTex->getAspect(), - .mipLevel = 0, - .baseArrayLayer = 0, - .layerCount = 1, - }, - .srcOffset = VkOffset3D { - .x = 0, - .y = 0, - .z = 0, - }, - .dstSubresource = VkImageSubresourceLayers { - .aspectMask = sourceTex->getAspect(), - .mipLevel = 0, - .baseArrayLayer = 0, - .layerCount = 1, - }, - .dstOffset = VkOffset3D { - .x = 0, - .y = 0, - .z = 0, - }, - .extent = VkExtent3D { - .width = sourceTex->getWidth(), - .height = sourceTex->getHeight(), - .depth = sourceTex->getDepth(), - }, + .srcSubresource = + VkImageSubresourceLayers{ + .aspectMask = sourceTex->getAspect(), + .mipLevel = 0, + .baseArrayLayer = 0, + .layerCount = 1, + }, + .srcOffset = + VkOffset3D{ + .x = 0, + .y = 0, + .z = 0, + }, + .dstSubresource = + VkImageSubresourceLayers{ + .aspectMask = sourceTex->getAspect(), + .mipLevel = 0, + .baseArrayLayer = 0, + .layerCount = 1, + }, + .dstOffset = + VkOffset3D{ + .x = 0, + .y = 0, + .z = 0, + }, + .extent = + VkExtent3D{ + .width = sourceTex->getWidth(), + .height = sourceTex->getHeight(), + .depth = sourceTex->getDepth(), + }, }; - vkCmdResolveImage(getGraphicsCommands()->getCommands()->getHandle(), sourceTex->getImage(), cast(sourceTex->getLayout()), destinationTex->getImage(), cast(destinationTex->getLayout()), 1, &resolve); + vkCmdResolveImage(getGraphicsCommands()->getCommands()->getHandle(), sourceTex->getImage(), cast(sourceTex->getLayout()), + destinationTex->getImage(), cast(destinationTex->getLayout()), 1, &resolve); } -Gfx::OBottomLevelAS Graphics::createBottomLevelAccelerationStructure(const Gfx::BottomLevelASCreateInfo& createInfo) -{ +Gfx::OBottomLevelAS Graphics::createBottomLevelAccelerationStructure(const Gfx::BottomLevelASCreateInfo& createInfo) { return new BottomLevelAS(this, createInfo); } -Gfx::OTopLevelAS Graphics::createTopLevelAccelerationStructure(const Gfx::TopLevelASCreateInfo& createInfo) -{ +Gfx::OTopLevelAS Graphics::createTopLevelAccelerationStructure(const Gfx::TopLevelASCreateInfo& createInfo) { return new TopLevelAS(this, createInfo); } -void Graphics::vkCmdDrawMeshTasksEXT(VkCommandBuffer cmd, uint32 groupX, uint32 groupY, uint32 groupZ) -{ +void Graphics::vkCmdDrawMeshTasksEXT(VkCommandBuffer cmd, uint32 groupX, uint32 groupY, uint32 groupZ) { cmdDrawMeshTasks(cmd, groupX, groupY, groupZ); } -void Graphics::vkCmdDrawMeshTasksIndirectEXT(VkCommandBuffer cmd, VkBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) -{ +void Graphics::vkCmdDrawMeshTasksIndirectEXT(VkCommandBuffer cmd, VkBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) { cmdDrawMeshTasksIndirect(cmd, buffer, offset, drawCount, stride); } -void Graphics::vkSetDebugUtilsObjectNameEXT(VkDebugUtilsObjectNameInfoEXT* info) -{ - VK_CHECK(setDebugUtilsObjectName(handle, info)); -} +void Graphics::vkSetDebugUtilsObjectNameEXT(VkDebugUtilsObjectNameInfoEXT* info) { VK_CHECK(setDebugUtilsObjectName(handle, info)); } - -PCommandPool Graphics::getQueueCommands(Gfx::QueueType queueType) -{ - switch (queueType) - { +PCommandPool Graphics::getQueueCommands(Gfx::QueueType queueType) { + switch (queueType) { case Gfx::QueueType::GRAPHICS: return getGraphicsCommands(); case Gfx::QueueType::COMPUTE: @@ -334,41 +265,29 @@ PCommandPool Graphics::getQueueCommands(Gfx::QueueType queueType) throw new std::logic_error("invalid queue type"); } } -PCommandPool Graphics::getGraphicsCommands() -{ - if(graphicsCommands == nullptr) - { +PCommandPool Graphics::getGraphicsCommands() { + if (graphicsCommands == nullptr) { std::unique_lock l(poolLock); graphicsCommands = pools.add(new CommandPool(this, queues[graphicsQueue])); } return graphicsCommands; } -PCommandPool Graphics::getComputeCommands() -{ - if(computeCommands == nullptr) - { - if(graphicsQueue == computeQueue) - { +PCommandPool Graphics::getComputeCommands() { + if (computeCommands == nullptr) { + if (graphicsQueue == computeQueue) { computeCommands = getGraphicsCommands(); - } - else - { + } else { std::unique_lock l(poolLock); computeCommands = pools.add(new CommandPool(this, queues[computeQueue])); } } return computeCommands; } -PCommandPool Graphics::getTransferCommands() -{ - if(transferCommands == nullptr) - { - if(graphicsQueue == transferQueue) - { +PCommandPool Graphics::getTransferCommands() { + if (transferCommands == nullptr) { + if (graphicsQueue == transferQueue) { transferCommands = getGraphicsCommands(); - } - else - { + } else { std::unique_lock l(poolLock); transferCommands = pools.add(new CommandPool(this, queues[transferQueue])); } @@ -376,25 +295,17 @@ PCommandPool Graphics::getTransferCommands() return transferCommands; } -VmaAllocator Graphics::getAllocator() -{ - return allocator; -} +VmaAllocator Graphics::getAllocator() { return allocator; } -PDestructionManager Graphics::getDestructionManager() -{ - return destructionManager; -} +PDestructionManager Graphics::getDestructionManager() { return destructionManager; } -Array Graphics::getRequiredExtensions() -{ - Array extensions; +Array Graphics::getRequiredExtensions() { + Array extensions; unsigned int glfwExtensionCount = 0; - const char **glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); + const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); - for (unsigned int i = 0; i < glfwExtensionCount; i++) - { + for (unsigned int i = 0; i < glfwExtensionCount; i++) { extensions.add(glfwExtensions[i]); } #if ENABLE_VALIDATION @@ -402,8 +313,7 @@ Array Graphics::getRequiredExtensions() #endif // ENABLE_VALIDATION return extensions; } -void Graphics::initInstance(GraphicsInitializer initInfo) -{ +void Graphics::initInstance(GraphicsInitializer initInfo) { glfwInit(); assert(glfwVulkanSupported()); VkApplicationInfo appInfo = { @@ -415,10 +325,9 @@ void Graphics::initInstance(GraphicsInitializer initInfo) .engineVersion = VK_MAKE_VERSION(0, 0, 1), .apiVersion = VK_API_VERSION_1_3, }; - + Array extensions = getRequiredExtensions(); - for (uint32 i = 0; i < initInfo.instanceExtensions.size(); ++i) - { + for (uint32 i = 0; i < initInfo.instanceExtensions.size(); ++i) { extensions.add(initInfo.instanceExtensions[i]); } #ifdef __APPLE__ @@ -441,22 +350,21 @@ void Graphics::initInstance(GraphicsInitializer initInfo) }; VK_CHECK(vkCreateInstance(&info, nullptr, &instance)); } -void Graphics::setupDebugCallback() -{ +void Graphics::setupDebugCallback() { VkDebugUtilsMessengerCreateInfoEXT createInfo = { .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, .pNext = nullptr, .flags = 0, - .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT| VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT, - .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT, + .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT, + .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT, .pfnUserCallback = &debugCallback, .pUserData = nullptr, }; VK_CHECK(CreateDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &callback)); } -void Graphics::pickPhysicalDevice() -{ +void Graphics::pickPhysicalDevice() { uint32 physicalDeviceCount; vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, nullptr); Array physicalDevices(physicalDeviceCount); @@ -474,26 +382,21 @@ void Graphics::pickPhysicalDevice() features12.pNext = &features13; features13.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES; features13.pNext = nullptr; - for (auto dev : physicalDevices) - { + for (auto dev : physicalDevices) { uint32 currentRating = 0; vkGetPhysicalDeviceProperties(dev, &props); vkGetPhysicalDeviceFeatures2(dev, &features); - if (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) - { + if (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) { std::cout << "found dedicated gpu " << props.deviceName << std::endl; currentRating += 100; - } - else if (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) - { + } else if (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) { std::cout << "found integrated gpu " << props.deviceName << std::endl; currentRating += 10; } - if (currentRating > deviceRating) - { + if (currentRating > deviceRating) { deviceRating = currentRating; bestDevice = dev; - std::cout << "bestDevice: " << props.deviceName << std::endl; + std::cout << "bestDevice: " << props.deviceName << std::endl; } } physicalDevice = bestDevice; @@ -501,16 +404,13 @@ void Graphics::pickPhysicalDevice() vkGetPhysicalDeviceProperties(physicalDevice, &props); vkGetPhysicalDeviceFeatures2(physicalDevice, &features); features.features.robustBufferAccess = 0; - if (Gfx::useMeshShading) - { + if (Gfx::useMeshShading) { uint32 count = 0; vkEnumerateDeviceExtensionProperties(physicalDevice, NULL, &count, nullptr); Array extensionProps(count); vkEnumerateDeviceExtensionProperties(physicalDevice, NULL, &count, extensionProps.data()); - for (size_t i = 0; i < count; ++i) - { - if (std::strcmp(VK_EXT_MESH_SHADER_EXTENSION_NAME, extensionProps[i].extensionName) == 0) - { + for (size_t i = 0; i < count; ++i) { + if (std::strcmp(VK_EXT_MESH_SHADER_EXTENSION_NAME, extensionProps[i].extensionName) == 0) { meshShadingEnabled = true; break; } @@ -518,16 +418,14 @@ void Graphics::pickPhysicalDevice() } } -void Graphics::createDevice(GraphicsInitializer initializer) -{ +void Graphics::createDevice(GraphicsInitializer initializer) { uint32_t numQueueFamilies = 0; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &numQueueFamilies, nullptr); Array queueProperties(numQueueFamilies); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &numQueueFamilies, queueProperties.data()); Array queueInfos; - struct QueueCreateInfo - { + struct QueueCreateInfo { int32 familyIndex = -1; int32 queueIndex = -1; }; @@ -535,42 +433,35 @@ void Graphics::createDevice(GraphicsInitializer initializer) QueueCreateInfo transferQueueInfo; QueueCreateInfo computeQueueInfo; uint32 numPriorities = 0; - auto checkFamilyProperty = [](VkQueueFamilyProperties currProps, uint32 checkBit){ + auto checkFamilyProperty = [](VkQueueFamilyProperties currProps, uint32 checkBit) { return (currProps.queueFlags & checkBit) == checkBit; }; auto updateQueueInfo = [&queueProperties](uint32 familyIndex, QueueCreateInfo& info, uint32& numQueues) { - if(info.familyIndex == -1) { - if(queueProperties[familyIndex].queueCount == numQueues) - { + if (info.familyIndex == -1) { + if (queueProperties[familyIndex].queueCount == numQueues) { return; } info.familyIndex = familyIndex; info.queueIndex = numQueues++; } }; - for (uint32 familyIndex = 0; familyIndex < queueProperties.size(); ++familyIndex) - { + for (uint32 familyIndex = 0; familyIndex < queueProperties.size(); ++familyIndex) { uint32 numQueuesForFamily = 0; VkQueueFamilyProperties currProps = queueProperties[familyIndex]; - if (checkFamilyProperty(currProps, VK_QUEUE_GRAPHICS_BIT)) - { + if (checkFamilyProperty(currProps, VK_QUEUE_GRAPHICS_BIT)) { updateQueueInfo(familyIndex, graphicsQueueInfo, numQueuesForFamily); } - if(Gfx::useAsyncCompute) - { - if(checkFamilyProperty(currProps, VK_QUEUE_COMPUTE_BIT)) - { + if (Gfx::useAsyncCompute) { + if (checkFamilyProperty(currProps, VK_QUEUE_COMPUTE_BIT)) { updateQueueInfo(familyIndex, computeQueueInfo, numQueuesForFamily); } } - if ((currProps.queueFlags ^ VK_QUEUE_TRANSFER_BIT) == 0) - { + if ((currProps.queueFlags ^ VK_QUEUE_TRANSFER_BIT) == 0) { updateQueueInfo(familyIndex, transferQueueInfo, numQueuesForFamily); } - - if (numQueuesForFamily > 0) - { + + if (numQueuesForFamily > 0) { VkDeviceQueueCreateInfo info = { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, .pNext = nullptr, @@ -585,14 +476,12 @@ void Graphics::createDevice(GraphicsInitializer initializer) } Array queuePriorities; queuePriorities.resize(numPriorities); - float *currentPriority = queuePriorities.data(); - for (uint32 index = 0; index < queueInfos.size(); ++index) - { - VkDeviceQueueCreateInfo &currQueue = queueInfos[index]; + float* currentPriority = queuePriorities.data(); + for (uint32 index = 0; index < queueInfos.size(); ++index) { + VkDeviceQueueCreateInfo& currQueue = queueInfos[index]; currQueue.pQueuePriorities = currentPriority; - for (int32_t queueIndex = 0; queueIndex < (int32_t)currQueue.queueCount; ++queueIndex) - { + for (int32_t queueIndex = 0; queueIndex < (int32_t)currQueue.queueCount; ++queueIndex) { *currentPriority++ = 1.0f; } } @@ -602,8 +491,7 @@ void Graphics::createDevice(GraphicsInitializer initializer) .taskShader = VK_TRUE, .meshShader = VK_TRUE, }; - if (supportMeshShading()) - { + if (supportMeshShading()) { features12.pNext = &enabledMeshShaderFeatures; initializer.deviceExtensions.add(VK_EXT_MESH_SHADER_EXTENSION_NAME); } @@ -621,7 +509,7 @@ void Graphics::createDevice(GraphicsInitializer initializer) }; VK_CHECK(vkCreateDevice(physicalDevice, &deviceInfo, nullptr, &handle)); - //std::cout << "Vulkan handle: " << handle << std::endl; + // std::cout << "Vulkan handle: " << handle << std::endl; cmdDrawMeshTasks = (PFN_vkCmdDrawMeshTasksEXT)vkGetDeviceProcAddr(handle, "vkCmdDrawMeshTasksEXT"); @@ -629,20 +517,17 @@ void Graphics::createDevice(GraphicsInitializer initializer) computeQueue = 0; transferQueue = 0; queues.add(new Queue(this, graphicsQueueInfo.familyIndex, graphicsQueueInfo.queueIndex)); - if(computeQueueInfo.familyIndex != -1) - { + if (computeQueueInfo.familyIndex != -1) { computeQueue = queues.size(); queues.add(new Queue(this, computeQueueInfo.familyIndex, computeQueueInfo.queueIndex)); } - if(transferQueueInfo.familyIndex != -1) - { + if (transferQueueInfo.familyIndex != -1) { transferQueue = queues.size(); queues.add(new Queue(this, transferQueueInfo.familyIndex, transferQueueInfo.queueIndex)); } - + queueMapping.graphicsFamily = queues[graphicsQueue]->getFamilyIndex(); queueMapping.computeFamily = queues[computeQueue]->getFamilyIndex(); queueMapping.transferFamily = queues[transferQueue]->getFamilyIndex(); setDebugUtilsObjectName = (PFN_vkSetDebugUtilsObjectNameEXT)vkGetInstanceProcAddr(instance, "vkSetDebugUtilsObjectNameEXT"); - } diff --git a/src/Engine/Graphics/Vulkan/Graphics.h b/src/Engine/Graphics/Vulkan/Graphics.h index 9b9e7e7..361e3c0 100644 --- a/src/Engine/Graphics/Vulkan/Graphics.h +++ b/src/Engine/Graphics/Vulkan/Graphics.h @@ -2,18 +2,15 @@ #include "Graphics/Graphics.h" #include -namespace Seele -{ -namespace Vulkan -{ +namespace Seele { +namespace Vulkan { DECLARE_REF(DestructionManager) DECLARE_REF(CommandPool) DECLARE_REF(Queue) DECLARE_REF(PipelineCache) DECLARE_REF(Framebuffer) -class Graphics : public Gfx::Graphics -{ -public: +class Graphics : public Gfx::Graphics { + public: Graphics(); virtual ~Graphics(); constexpr VkInstance getInstance() const { return instance; }; @@ -30,10 +27,11 @@ public: // Inherited via Graphics virtual void init(GraphicsInitializer initializer) override; - virtual Gfx::OWindow createWindow(const WindowCreateInfo &createInfo) override; - virtual Gfx::OViewport createViewport(Gfx::PWindow owner, const ViewportCreateInfo &createInfo) override; + virtual Gfx::OWindow createWindow(const WindowCreateInfo& createInfo) override; + virtual Gfx::OViewport createViewport(Gfx::PWindow owner, const ViewportCreateInfo& createInfo) override; - virtual Gfx::ORenderPass createRenderPass(Gfx::RenderTargetLayout layout, Array dependencies, Gfx::PViewport renderArea) override; + virtual Gfx::ORenderPass createRenderPass(Gfx::RenderTargetLayout layout, Array dependencies, + Gfx::PViewport renderArea) override; virtual void beginRenderPass(Gfx::PRenderPass renderPass) override; virtual void endRenderPass() override; virtual void waitDeviceIdle() override; @@ -41,17 +39,17 @@ public: virtual void executeCommands(Array commands) override; virtual void executeCommands(Array commands) override; - virtual Gfx::OTexture2D createTexture2D(const TextureCreateInfo &createInfo) override; - virtual Gfx::OTexture3D createTexture3D(const TextureCreateInfo &createInfo) override; - virtual Gfx::OTextureCube createTextureCube(const TextureCreateInfo &createInfo) override; - virtual Gfx::OUniformBuffer createUniformBuffer(const UniformBufferCreateInfo &bulkData) override; - virtual Gfx::OShaderBuffer createShaderBuffer(const ShaderBufferCreateInfo &bulkData) override; - virtual Gfx::OVertexBuffer createVertexBuffer(const VertexBufferCreateInfo &bulkData) override; - virtual Gfx::OIndexBuffer createIndexBuffer(const IndexBufferCreateInfo &bulkData) override; - + virtual Gfx::OTexture2D createTexture2D(const TextureCreateInfo& createInfo) override; + virtual Gfx::OTexture3D createTexture3D(const TextureCreateInfo& createInfo) override; + virtual Gfx::OTextureCube createTextureCube(const TextureCreateInfo& createInfo) override; + virtual Gfx::OUniformBuffer createUniformBuffer(const UniformBufferCreateInfo& bulkData) override; + virtual Gfx::OShaderBuffer createShaderBuffer(const ShaderBufferCreateInfo& bulkData) override; + virtual Gfx::OVertexBuffer createVertexBuffer(const VertexBufferCreateInfo& bulkData) override; + virtual Gfx::OIndexBuffer createIndexBuffer(const IndexBufferCreateInfo& bulkData) override; + virtual Gfx::ORenderCommand createRenderCommand(const std::string& name) override; virtual Gfx::OComputeCommand createComputeCommand(const std::string& name) override; - + virtual Gfx::OVertexShader createVertexShader(const ShaderCreateInfo& createInfo) override; virtual Gfx::OFragmentShader createFragmentShader(const ShaderCreateInfo& createInfo) override; virtual Gfx::OComputeShader createComputeShader(const ShaderCreateInfo& createInfo) override; @@ -77,11 +75,11 @@ public: void vkCmdDrawMeshTasksIndirectEXT(VkCommandBuffer handle, VkBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride); void vkSetDebugUtilsObjectNameEXT(VkDebugUtilsObjectNameInfoEXT* info); -protected: + protected: PFN_vkCmdDrawMeshTasksEXT cmdDrawMeshTasks; PFN_vkCmdDrawMeshTasksIndirectEXT cmdDrawMeshTasksIndirect; PFN_vkSetDebugUtilsObjectNameEXT setDebugUtilsObjectName; - Array getRequiredExtensions(); + Array getRequiredExtensions(); void initInstance(GraphicsInitializer initInfo); void setupDebugCallback(); void pickPhysicalDevice(); diff --git a/src/Engine/Graphics/Vulkan/Pipeline.cpp b/src/Engine/Graphics/Vulkan/Pipeline.cpp index 1c079a7..ea1748a 100644 --- a/src/Engine/Graphics/Vulkan/Pipeline.cpp +++ b/src/Engine/Graphics/Vulkan/Pipeline.cpp @@ -5,54 +5,24 @@ using namespace Seele; using namespace Seele::Vulkan; -VertexInput::VertexInput(VertexInputStateCreateInfo createInfo) - : Gfx::VertexInput(createInfo) -{ -} +VertexInput::VertexInput(VertexInputStateCreateInfo createInfo) : Gfx::VertexInput(createInfo) {} -VertexInput::~VertexInput() -{ -} +VertexInput::~VertexInput() {} GraphicsPipeline::GraphicsPipeline(PGraphics graphics, VkPipeline handle, Gfx::PPipelineLayout pipelineLayout) - : Gfx::GraphicsPipeline(std::move(pipelineLayout)) - , graphics(graphics) - , pipeline(handle) -{ -} + : Gfx::GraphicsPipeline(std::move(pipelineLayout)), graphics(graphics), pipeline(handle) {} -GraphicsPipeline::~GraphicsPipeline() -{ -} +GraphicsPipeline::~GraphicsPipeline() {} -void GraphicsPipeline::bind(VkCommandBuffer handle) -{ - vkCmdBindPipeline(handle, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); -} +void GraphicsPipeline::bind(VkCommandBuffer handle) { vkCmdBindPipeline(handle, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); } -VkPipelineLayout GraphicsPipeline::getLayout() const -{ - return Gfx::PPipelineLayout(layout).cast()->getHandle(); -} +VkPipelineLayout GraphicsPipeline::getLayout() const { return Gfx::PPipelineLayout(layout).cast()->getHandle(); } -ComputePipeline::ComputePipeline(PGraphics graphics, VkPipeline handle, Gfx::PPipelineLayout pipelineLayout) - : Gfx::ComputePipeline(std::move(pipelineLayout)) - , graphics(graphics) - , pipeline(handle) -{ - -} +ComputePipeline::ComputePipeline(PGraphics graphics, VkPipeline handle, Gfx::PPipelineLayout pipelineLayout) + : Gfx::ComputePipeline(std::move(pipelineLayout)), graphics(graphics), pipeline(handle) {} -ComputePipeline::~ComputePipeline() -{ -} +ComputePipeline::~ComputePipeline() {} -void ComputePipeline::bind(VkCommandBuffer handle) -{ - vkCmdBindPipeline(handle, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); -} +void ComputePipeline::bind(VkCommandBuffer handle) { vkCmdBindPipeline(handle, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); } -VkPipelineLayout ComputePipeline::getLayout() const -{ - return Gfx::PPipelineLayout(layout).cast()->getHandle(); -} \ No newline at end of file +VkPipelineLayout ComputePipeline::getLayout() const { return Gfx::PPipelineLayout(layout).cast()->getHandle(); } \ No newline at end of file diff --git a/src/Engine/Graphics/Vulkan/Pipeline.h b/src/Engine/Graphics/Vulkan/Pipeline.h index 8cc07f7..702f716 100644 --- a/src/Engine/Graphics/Vulkan/Pipeline.h +++ b/src/Engine/Graphics/Vulkan/Pipeline.h @@ -2,39 +2,37 @@ #include "Enums.h" #include "Graphics/Pipeline.h" -namespace Seele -{ -namespace Vulkan -{ -class VertexInput : public Gfx::VertexInput -{ -public: +namespace Seele { +namespace Vulkan { +class VertexInput : public Gfx::VertexInput { + public: VertexInput(VertexInputStateCreateInfo createInfo); virtual ~VertexInput(); -private: + + private: }; DECLARE_REF(PipelineLayout) DECLARE_REF(Graphics) -class GraphicsPipeline : public Gfx::GraphicsPipeline -{ -public: +class GraphicsPipeline : public Gfx::GraphicsPipeline { + public: GraphicsPipeline(PGraphics graphics, VkPipeline handle, Gfx::PPipelineLayout pipelineLayout); virtual ~GraphicsPipeline(); void bind(VkCommandBuffer handle); VkPipelineLayout getLayout() const; -private: + + private: PGraphics graphics; VkPipeline pipeline; }; DEFINE_REF(GraphicsPipeline) -class ComputePipeline : public Gfx::ComputePipeline -{ -public: +class ComputePipeline : public Gfx::ComputePipeline { + public: ComputePipeline(PGraphics graphics, VkPipeline handle, Gfx::PPipelineLayout pipelineLayout); virtual ~ComputePipeline(); void bind(VkCommandBuffer handle); VkPipelineLayout getLayout() const; -private: + + private: PGraphics graphics; VkPipeline pipeline; }; diff --git a/src/Engine/Graphics/Vulkan/PipelineCache.cpp b/src/Engine/Graphics/Vulkan/PipelineCache.cpp index f942773..6cd64fc 100644 --- a/src/Engine/Graphics/Vulkan/PipelineCache.cpp +++ b/src/Engine/Graphics/Vulkan/PipelineCache.cpp @@ -1,18 +1,16 @@ #include "PipelineCache.h" -#include "Graphics.h" -#include "Enums.h" -#include "RenderPass.h" #include "Descriptor.h" +#include "Enums.h" +#include "Graphics.h" +#include "RenderPass.h" #include "Shader.h" #include + using namespace Seele; using namespace Seele::Vulkan; -PipelineCache::PipelineCache(PGraphics graphics, const std::string& cacheFilePath) - : graphics(graphics) - , cacheFile(cacheFilePath) -{ +PipelineCache::PipelineCache(PGraphics graphics, const std::string& cacheFilePath) : graphics(graphics), cacheFile(cacheFilePath) { std::ifstream stream(cacheFilePath, std::ios::binary | std::ios::ate); VkPipelineCacheCreateInfo cacheCreateInfo = { .sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, @@ -20,8 +18,7 @@ PipelineCache::PipelineCache(PGraphics graphics, const std::string& cacheFilePat .flags = 0, .initialDataSize = 0, }; - if(stream.good()) - { + if (stream.good()) { Array cacheData; uint32 fileSize = static_cast(stream.tellg()); cacheData.resize(fileSize); @@ -34,8 +31,7 @@ PipelineCache::PipelineCache(PGraphics graphics, const std::string& cacheFilePat VK_CHECK(vkCreatePipelineCache(graphics->getDevice(), &cacheCreateInfo, nullptr, &cache)); } -PipelineCache::~PipelineCache() -{ +PipelineCache::~PipelineCache() { size_t cacheSize; VK_CHECK(vkGetPipelineCacheData(graphics->getDevice(), cache, &cacheSize, nullptr)); Array cacheData(cacheSize); @@ -48,29 +44,24 @@ PipelineCache::~PipelineCache() std::cout << "Written " << cacheSize << " bytes to cache" << std::endl; } -PGraphicsPipeline PipelineCache::createPipeline(Gfx::LegacyPipelineCreateInfo gfxInfo) -{ +PGraphicsPipeline PipelineCache::createPipeline(Gfx::LegacyPipelineCreateInfo gfxInfo) { uint32 hash = CRC::Calculate(&gfxInfo, sizeof(Gfx::LegacyPipelineCreateInfo), CRC::CRC_32()); - if (graphicsPipelines.contains(hash)) - { + if (graphicsPipelines.contains(hash)) { return graphicsPipelines[hash]; } PPipelineLayout layout = Gfx::PPipelineLayout(gfxInfo.pipelineLayout).cast(); Array bindings; Array attributes; - if (gfxInfo.vertexInput != nullptr) - { + if (gfxInfo.vertexInput != nullptr) { const VertexInputStateCreateInfo& vertexInputDesc = gfxInfo.vertexInput->getInfo(); - for (const auto& b : vertexInputDesc.bindings) - { + for (const auto& b : vertexInputDesc.bindings) { bindings.add() = { .binding = b.binding, .stride = b.stride, .inputRate = VkVertexInputRate(b.inputRate), }; } - for (const auto& a : vertexInputDesc.attributes) - { + for (const auto& a : vertexInputDesc.attributes) { attributes.add() = { .location = a.location, .binding = a.binding, @@ -104,8 +95,7 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::LegacyPipelineCreateInfo gf .pSpecializationInfo = nullptr, }; - if (gfxInfo.fragmentShader != nullptr) - { + if (gfxInfo.fragmentShader != nullptr) { PFragmentShader fragment = gfxInfo.fragmentShader.cast(); stageInfos[stageCount++] = { @@ -173,8 +163,7 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::LegacyPipelineCreateInfo gf .maxDepthBounds = gfxInfo.depthStencilState.maxDepthBounds, }; Array blendAttachments; - for(uint32 i = 0; i < gfxInfo.colorBlend.attachmentCount; ++i) - { + for (uint32 i = 0; i < gfxInfo.colorBlend.attachmentCount; ++i) { const Gfx::ColorBlendState::BlendAttachment& attachment = gfxInfo.colorBlend.blendAttachments[i]; blendAttachments.add() = { .blendEnable = attachment.blendEnable, @@ -235,31 +224,26 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::LegacyPipelineCreateInfo gf auto endTime = std::chrono::high_resolution_clock::now(); int64 delta = std::chrono::duration_cast(endTime - beginTime).count(); std::cout << "Gfx creation time: " << delta << std::endl; - + OGraphicsPipeline pipeline = new GraphicsPipeline(graphics, pipelineHandle, gfxInfo.pipelineLayout); PGraphicsPipeline result = pipeline; graphicsPipelines[hash] = std::move(pipeline); return result; } - -PGraphicsPipeline PipelineCache::createPipeline(Gfx::MeshPipelineCreateInfo gfxInfo) -{ +PGraphicsPipeline PipelineCache::createPipeline(Gfx::MeshPipelineCreateInfo gfxInfo) { uint32 hash = CRC::Calculate(&gfxInfo, sizeof(Gfx::MeshPipelineCreateInfo), CRC::CRC_32()); - if (graphicsPipelines.contains(hash)) - { + if (graphicsPipelines.contains(hash)) { return graphicsPipelines[hash]; } PPipelineLayout layout = Gfx::PPipelineLayout(gfxInfo.pipelineLayout).cast(); - //uint32 hash = layout->getHash(); + // uint32 hash = layout->getHash(); uint32 stageCount = 0; - VkPipelineShaderStageCreateInfo stageInfos[3]; std::memset(stageInfos, 0, sizeof(stageInfos)); - if (gfxInfo.taskShader != nullptr) - { + if (gfxInfo.taskShader != nullptr) { PTaskShader taskShader = gfxInfo.taskShader.cast(); stageInfos[stageCount++] = { .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, @@ -283,8 +267,7 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::MeshPipelineCreateInfo gfxI .pSpecializationInfo = nullptr, }; - if (gfxInfo.fragmentShader != nullptr) - { + if (gfxInfo.fragmentShader != nullptr) { PFragmentShader fragment = gfxInfo.fragmentShader.cast(); stageInfos[stageCount++] = { @@ -297,7 +280,7 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::MeshPipelineCreateInfo gfxI .pSpecializationInfo = nullptr, }; } - //hash = CRC::Calculate(stageInfos, sizeof(stageInfos), CRC::CRC_32(), hash); + // hash = CRC::Calculate(stageInfos, sizeof(stageInfos), CRC::CRC_32(), hash); VkPipelineViewportStateCreateInfo viewportInfo = { .sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, @@ -308,7 +291,7 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::MeshPipelineCreateInfo gfxI .scissorCount = 1, .pScissors = nullptr, }; - //hash = CRC::Calculate(&viewportInfo, sizeof(VkPipelineViewportStateCreateInfo), CRC::CRC_32(), hash); + // hash = CRC::Calculate(&viewportInfo, sizeof(VkPipelineViewportStateCreateInfo), CRC::CRC_32(), hash); VkPipelineRasterizationStateCreateInfo rasterizationState = { .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, .pNext = nullptr, @@ -324,7 +307,7 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::MeshPipelineCreateInfo gfxI .depthBiasSlopeFactor = gfxInfo.rasterizationState.depthBiasSlopeFactor, .lineWidth = 0, }; - //hash = CRC::Calculate(&rasterizationState, sizeof(VkPipelineRasterizationStateCreateInfo), CRC::CRC_32(), hash); + // hash = CRC::Calculate(&rasterizationState, sizeof(VkPipelineRasterizationStateCreateInfo), CRC::CRC_32(), hash); VkPipelineMultisampleStateCreateInfo multisampleState = { .sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, @@ -337,7 +320,7 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::MeshPipelineCreateInfo gfxI .alphaToCoverageEnable = gfxInfo.multisampleState.alphaCoverageEnable, .alphaToOneEnable = gfxInfo.multisampleState.alphaToOneEnable, }; - //hash = CRC::Calculate(&multisampleState, sizeof(VkPipelineMultisampleStateCreateInfo), CRC::CRC_32(), hash); + // hash = CRC::Calculate(&multisampleState, sizeof(VkPipelineMultisampleStateCreateInfo), CRC::CRC_32(), hash); VkPipelineDepthStencilStateCreateInfo depthStencilState = { .sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, @@ -348,32 +331,33 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::MeshPipelineCreateInfo gfxI .depthCompareOp = cast(gfxInfo.depthStencilState.depthCompareOp), .depthBoundsTestEnable = gfxInfo.depthStencilState.depthBoundsTestEnable, .stencilTestEnable = gfxInfo.depthStencilState.stencilTestEnable, - .front = VkStencilOpState{ - .failOp = VK_STENCIL_OP_ZERO, - .passOp = (VkStencilOp)gfxInfo.depthStencilState.front, - .depthFailOp = VK_STENCIL_OP_ZERO, - .compareOp = VK_COMPARE_OP_ALWAYS, - .compareMask = 0, - .writeMask = 0, - .reference = 0, - }, - .back = VkStencilOpState{ - .failOp = VK_STENCIL_OP_ZERO, - .passOp = (VkStencilOp)gfxInfo.depthStencilState.back, - .depthFailOp = VK_STENCIL_OP_ZERO, - .compareOp = VK_COMPARE_OP_ALWAYS, - .compareMask = 0, - .writeMask = 0, - .reference = 0, - }, + .front = + VkStencilOpState{ + .failOp = VK_STENCIL_OP_ZERO, + .passOp = (VkStencilOp)gfxInfo.depthStencilState.front, + .depthFailOp = VK_STENCIL_OP_ZERO, + .compareOp = VK_COMPARE_OP_ALWAYS, + .compareMask = 0, + .writeMask = 0, + .reference = 0, + }, + .back = + VkStencilOpState{ + .failOp = VK_STENCIL_OP_ZERO, + .passOp = (VkStencilOp)gfxInfo.depthStencilState.back, + .depthFailOp = VK_STENCIL_OP_ZERO, + .compareOp = VK_COMPARE_OP_ALWAYS, + .compareMask = 0, + .writeMask = 0, + .reference = 0, + }, .minDepthBounds = gfxInfo.depthStencilState.minDepthBounds, .maxDepthBounds = gfxInfo.depthStencilState.maxDepthBounds, }; - //hash = CRC::Calculate(&depthStencilState, sizeof(VkPipelineDepthStencilStateCreateInfo), CRC::CRC_32(), hash); + // hash = CRC::Calculate(&depthStencilState, sizeof(VkPipelineDepthStencilStateCreateInfo), CRC::CRC_32(), hash); Array blendAttachments; - for (uint32 i = 0; i < gfxInfo.colorBlend.attachmentCount; ++i) - { + for (uint32 i = 0; i < gfxInfo.colorBlend.attachmentCount; ++i) { const Gfx::ColorBlendState::BlendAttachment& attachment = gfxInfo.colorBlend.blendAttachments[i]; blendAttachments.add() = { .blendEnable = attachment.blendEnable, @@ -386,7 +370,8 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::MeshPipelineCreateInfo gfxI .colorWriteMask = attachment.colorWriteMask, }; } - //hash = CRC::Calculate(blendAttachments.data(), blendAttachments.size() * sizeof(VkPipelineColorBlendAttachmentState), CRC::CRC_32(), hash); + // hash = CRC::Calculate(blendAttachments.data(), blendAttachments.size() * sizeof(VkPipelineColorBlendAttachmentState), CRC::CRC_32(), + // hash); VkPipelineColorBlendStateCreateInfo blendState = { .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, @@ -403,7 +388,7 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::MeshPipelineCreateInfo gfxI StaticArray dynamicEnabled; dynamicEnabled[numDynamicEnabled++] = VK_DYNAMIC_STATE_VIEWPORT; dynamicEnabled[numDynamicEnabled++] = VK_DYNAMIC_STATE_SCISSOR; - //hash = CRC::Calculate(dynamicEnabled.data(), sizeof(dynamicEnabled), CRC::CRC_32(), hash); + // hash = CRC::Calculate(dynamicEnabled.data(), sizeof(dynamicEnabled), CRC::CRC_32(), hash); VkPipelineDynamicStateCreateInfo dynamicState = { .sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, @@ -443,9 +428,7 @@ PGraphicsPipeline PipelineCache::createPipeline(Gfx::MeshPipelineCreateInfo gfxI return result; } - -PComputePipeline PipelineCache::createPipeline(Gfx::ComputePipelineCreateInfo computeInfo) -{ +PComputePipeline PipelineCache::createPipeline(Gfx::ComputePipelineCreateInfo computeInfo) { PPipelineLayout layout = Gfx::PPipelineLayout(computeInfo.pipelineLayout).cast(); auto computeStage = computeInfo.computeShader.cast(); @@ -455,20 +438,21 @@ PComputePipeline PipelineCache::createPipeline(Gfx::ComputePipelineCreateInfo co .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, .pNext = 0, .flags = 0, - .stage = { - .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .stage = VK_SHADER_STAGE_COMPUTE_BIT, - .module = computeStage->getModuleHandle(), - .pName = computeStage->getEntryPointName(), - }, + .stage = + { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .stage = VK_SHADER_STAGE_COMPUTE_BIT, + .module = computeStage->getModuleHandle(), + .pName = computeStage->getEntryPointName(), + }, .layout = layout->getHandle(), .basePipelineHandle = VK_NULL_HANDLE, .basePipelineIndex = 0, }; hash = CRC::Calculate(&createInfo, sizeof(createInfo), CRC::CRC_32(), hash); - + VkPipeline pipelineHandle; auto beginTime = std::chrono::high_resolution_clock::now(); VK_CHECK(vkCreateComputePipelines(graphics->getDevice(), cache, 1, &createInfo, nullptr, &pipelineHandle)); diff --git a/src/Engine/Graphics/Vulkan/PipelineCache.h b/src/Engine/Graphics/Vulkan/PipelineCache.h index e6bbfc0..88a1a42 100644 --- a/src/Engine/Graphics/Vulkan/PipelineCache.h +++ b/src/Engine/Graphics/Vulkan/PipelineCache.h @@ -1,19 +1,17 @@ #pragma once #include "Pipeline.h" -namespace Seele -{ -namespace Vulkan -{ -class PipelineCache -{ -public: +namespace Seele { +namespace Vulkan { +class PipelineCache { + public: PipelineCache(PGraphics graphics, const std::string& cacheFilePath); ~PipelineCache(); PGraphicsPipeline createPipeline(Gfx::LegacyPipelineCreateInfo createInfo); PGraphicsPipeline createPipeline(Gfx::MeshPipelineCreateInfo createInfo); PComputePipeline createPipeline(Gfx::ComputePipelineCreateInfo createInfo); -private: + + private: Map graphicsPipelines; Map computePipelines; std::mutex cacheLock; diff --git a/src/Engine/Graphics/Vulkan/Queue.cpp b/src/Engine/Graphics/Vulkan/Queue.cpp index 3fc51c3..0f5cb4b 100644 --- a/src/Engine/Graphics/Vulkan/Queue.cpp +++ b/src/Engine/Graphics/Vulkan/Queue.cpp @@ -1,27 +1,22 @@ #include "Queue.h" -#include "Graphics.h" #include "Allocator.h" #include "Command.h" #include "Enums.h" +#include "Graphics.h" + using namespace Seele; using namespace Seele::Vulkan; static constexpr bool waitIdleOnSubmit = false; -Queue::Queue(PGraphics graphics, uint32 familyIndex, uint32 queueIndex) - : graphics(graphics) - , familyIndex(familyIndex) -{ +Queue::Queue(PGraphics graphics, uint32 familyIndex, uint32 queueIndex) : graphics(graphics), familyIndex(familyIndex) { vkGetDeviceQueue(graphics->getDevice(), familyIndex, queueIndex, &queue); } -Queue::~Queue() -{ -} +Queue::~Queue() {} -void Queue::submitCommandBuffer(PCommand command, const Array& signalSemaphores) -{ +void Queue::submitCommandBuffer(PCommand command, const Array& signalSemaphores) { std::unique_lock lock(queueLock); assert(command->state == Command::State::End); @@ -30,11 +25,10 @@ void Queue::submitCommandBuffer(PCommand command, const Array& sign VkCommandBuffer cmdHandle = command->handle; Array waitSemaphores; - for (PSemaphore semaphore : command->waitSemaphores) - { + for (PSemaphore semaphore : command->waitSemaphores) { waitSemaphores.add(semaphore->getHandle()); } - + VkSubmitInfo submitInfo = { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .pNext = nullptr, @@ -46,15 +40,14 @@ void Queue::submitCommandBuffer(PCommand command, const Array& sign .signalSemaphoreCount = static_cast(signalSemaphores.size()), .pSignalSemaphores = signalSemaphores.data(), }; - + VK_CHECK(vkQueueSubmit(queue, 1, &submitInfo, command->fence->getHandle())); command->fence->submit(); command->state = Command::State::Submit; command->waitFlags.clear(); command->waitSemaphores.clear(); - if (waitIdleOnSubmit) - { + if (waitIdleOnSubmit) { command->fence->wait(1000 * 1000ull); } diff --git a/src/Engine/Graphics/Vulkan/Queue.h b/src/Engine/Graphics/Vulkan/Queue.h index e175de2..c480536 100644 --- a/src/Engine/Graphics/Vulkan/Queue.h +++ b/src/Engine/Graphics/Vulkan/Queue.h @@ -1,28 +1,19 @@ #pragma once #include "Resources.h" -namespace Seele -{ -namespace Vulkan -{ +namespace Seele { +namespace Vulkan { DECLARE_REF(Command) DECLARE_REF(Graphics) -class Queue -{ -public: +class Queue { + public: Queue(PGraphics graphics, uint32 familyIndex, uint32 queueIndex); virtual ~Queue(); void submitCommandBuffer(PCommand command, const Array& signalSemaphore); - constexpr uint32 getFamilyIndex() const - { - return familyIndex; - } - constexpr VkQueue getHandle() const - { - return queue; - } + constexpr uint32 getFamilyIndex() const { return familyIndex; } + constexpr VkQueue getHandle() const { return queue; } -private: + private: std::mutex queueLock; PGraphics graphics; VkQueue queue; diff --git a/src/Engine/Graphics/Vulkan/RayTracing.cpp b/src/Engine/Graphics/Vulkan/RayTracing.cpp index 8f7d3da..0e3e017 100644 --- a/src/Engine/Graphics/Vulkan/RayTracing.cpp +++ b/src/Engine/Graphics/Vulkan/RayTracing.cpp @@ -1,41 +1,45 @@ #include "RayTracing.h" #include "Buffer.h" +#include "Graphics/Buffer.h" #include "Graphics/Initializer.h" +#include "Graphics/Mesh.h" +#include "Graphics/VertexData.h" #include using namespace Seele::Vulkan; -BottomLevelAS::BottomLevelAS(PGraphics graphics, const Gfx::BottomLevelASCreateInfo& createInfo) -{ +BottomLevelAS::BottomLevelAS(PGraphics graphics, const Gfx::BottomLevelASCreateInfo& createInfo) : graphics(graphics) { + VertexData* vertexData = createInfo.mesh->vertexData; + Gfx::PShaderBuffer positionBuffer = vertexData->getPositionBuffer(); + Gfx::PIndexBuffer indexBuffer = vertexData->getIndexBuffer(); VkDeviceOrHostAddressConstKHR vertexDataDeviceAddress = { - .deviceAddress = createInfo.positionBuffer.cast()->getDeviceAddress() + createInfo.verticesOffset, + .deviceAddress = positionBuffer.cast()->getDeviceAddress(), }; VkDeviceOrHostAddressConstKHR indexDataDeviceAddress = { - .deviceAddress = createInfo.indexBuffer.cast()->getDeviceAddress() + createInfo.indicesOffset, + .deviceAddress = indexBuffer.cast()->getDeviceAddress(), }; VkAccelerationStructureGeometryKHR accelerationStructureGeometry = { .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR, .pNext = nullptr, .geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR, - .geometry = {.triangles = { - .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR, - .pNext = nullptr, - .vertexFormat = VK_FORMAT_R32G32B32_SFLOAT, - .vertexData = vertexDataDeviceAddress, - .vertexStride = sizeof(Vector), - .maxVertex = createInfo.positionBuffer->getNumElements(), - .indexType = VK_INDEX_TYPE_UINT32, - .indexData = indexDataDeviceAddress, - }}, + .geometry = {.triangles = + { + .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR, + .pNext = nullptr, + .vertexFormat = VK_FORMAT_R32G32B32_SFLOAT, + .vertexData = vertexDataDeviceAddress, + .vertexStride = sizeof(Vector), + .maxVertex = static_cast(createInfo.mesh->vertexCount), + .indexType = VK_INDEX_TYPE_UINT32, + .indexData = indexDataDeviceAddress, + }}, .flags = VK_GEOMETRY_OPAQUE_BIT_KHR, }; - - VkAccelerationStructureBuildRangeInfoKHR buildRangeInfo = { - .primitiveCount = createInfo.meshData.numIndices / 3, - .primitiveOffset = 0, - .firstVertex = 0, - .transformOffset = 0 - }; + + VkAccelerationStructureBuildRangeInfoKHR buildRangeInfo = {.primitiveCount = static_cast(createInfo.mesh->indices.size()), + .primitiveOffset = 0, + .firstVertex = 0, + .transformOffset = 0}; VkAccelerationStructureBuildGeometryInfoKHR buildGeometry = { .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR, @@ -51,17 +55,8 @@ BottomLevelAS::BottomLevelAS(PGraphics graphics, const Gfx::BottomLevelASCreateI }; } -BottomLevelAS::~BottomLevelAS() -{ +BottomLevelAS::~BottomLevelAS() {} -} +TopLevelAS::TopLevelAS(PGraphics graphics, const Gfx::TopLevelASCreateInfo& createInfo) {} -TopLevelAS::TopLevelAS(PGraphics graphics, const Gfx::TopLevelASCreateInfo& createInfo) -{ - -} - -TopLevelAS::~TopLevelAS() -{ - -} \ No newline at end of file +TopLevelAS::~TopLevelAS() {} \ No newline at end of file diff --git a/src/Engine/Graphics/Vulkan/RayTracing.h b/src/Engine/Graphics/Vulkan/RayTracing.h index fad71b0..e0709ba 100644 --- a/src/Engine/Graphics/Vulkan/RayTracing.h +++ b/src/Engine/Graphics/Vulkan/RayTracing.h @@ -1,32 +1,31 @@ #pragma once -#include "Graphics/Initializer.h" #include "Graphics.h" +#include "Graphics/Initializer.h" #include "Graphics/RayTracing.h" #include -namespace Seele -{ -namespace Vulkan -{ -class BottomLevelAS : public Gfx::BottomLevelAS -{ -public: + +namespace Seele { +namespace Vulkan { +class BottomLevelAS : public Gfx::BottomLevelAS { + public: BottomLevelAS(PGraphics graphics, const Gfx::BottomLevelASCreateInfo& createInfo); ~BottomLevelAS(); -private: + + private: PGraphics graphics; VkAccelerationStructureKHR handle; }; DEFINE_REF(BottomLevelAS) -class TopLevelAS : public Gfx::TopLevelAS -{ -public: +class TopLevelAS : public Gfx::TopLevelAS { + public: TopLevelAS(PGraphics graphics, const Gfx::TopLevelASCreateInfo& createInfo); ~TopLevelAS(); -private: + + private: PGraphics graphics; VkAccelerationStructureKHR handle; }; DEFINE_REF(TopLevelAS) -} -} \ No newline at end of file +} // namespace Vulkan +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/Vulkan/RenderPass.cpp b/src/Engine/Graphics/Vulkan/RenderPass.cpp index 52736cb..6cb45c8 100644 --- a/src/Engine/Graphics/Vulkan/RenderPass.cpp +++ b/src/Engine/Graphics/Vulkan/RenderPass.cpp @@ -1,18 +1,18 @@ #include "RenderPass.h" -#include "Graphics.h" -#include "Framebuffer.h" -#include "Texture.h" -#include "Resources.h" -#include "Command.h" #include "CRC.h" +#include "Command.h" +#include "Framebuffer.h" +#include "Graphics.h" +#include "Resources.h" +#include "Texture.h" + using namespace Seele; using namespace Seele::Vulkan; -RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout _layout, Array _dependencies, Gfx::PViewport viewport) - : Gfx::RenderPass(std::move(_layout), std::move(_dependencies)) - , graphics(graphics) -{ +RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout _layout, Array _dependencies, + Gfx::PViewport viewport) + : Gfx::RenderPass(std::move(_layout), std::move(_dependencies)), graphics(graphics) { renderArea.extent.width = viewport->getWidth(); renderArea.extent.height = viewport->getHeight(); renderArea.offset.x = viewport->getOffsetX(); @@ -26,8 +26,7 @@ RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout _layout, Arra VkAttachmentReference2 depthResolveRef; uint32 attachmentCounter = 0; - for (auto& inputAttachment : layout.inputAttachments) - { + for (auto& inputAttachment : layout.inputAttachments) { PTexture2D image = inputAttachment.getTexture().cast(); VkAttachmentDescription2& desc = attachments.add() = { .sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2, @@ -41,14 +40,13 @@ RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout _layout, Arra .initialLayout = cast(inputAttachment.getInitialLayout()), .finalLayout = cast(inputAttachment.getFinalLayout()), }; - + inputRefs.add() = { .attachment = attachmentCounter++, .layout = desc.initialLayout, }; } - for (auto& colorAttachment : layout.colorAttachments) - { + for (auto& colorAttachment : layout.colorAttachments) { attachments.add() = { .sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2, .pNext = nullptr, @@ -62,10 +60,9 @@ RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout _layout, Arra .initialLayout = cast(colorAttachment.getInitialLayout()), .finalLayout = cast(colorAttachment.getFinalLayout()), }; - + VkClearValue& clearValue = clearValues.add(); - if(attachments.back().loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) - { + if (attachments.back().loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) { clearValue = cast(colorAttachment.clear); } @@ -76,8 +73,7 @@ RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout _layout, Arra .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, }; } - for (auto& resolveAttachment : layout.resolveAttachments) - { + for (auto& resolveAttachment : layout.resolveAttachments) { attachments.add() = { .sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2, .pNext = nullptr, @@ -93,8 +89,7 @@ RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout _layout, Arra }; VkClearValue& clearValue = clearValues.add(); - if (attachments.back().loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) - { + if (attachments.back().loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) { clearValue = cast(resolveAttachment.clear); } @@ -105,8 +100,7 @@ RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout _layout, Arra .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, }; } - if (layout.depthAttachment.getTexture() != nullptr) - { + if (layout.depthAttachment.getTexture() != nullptr) { PTexture2D image = layout.depthAttachment.getTexture().cast(); attachments.add() = { .sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2, @@ -123,8 +117,7 @@ RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout _layout, Arra }; VkClearValue& clearValue = clearValues.add(); - if (attachments.back().loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) - { + if (attachments.back().loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) { clearValue = cast(layout.depthAttachment.clear); } @@ -135,8 +128,7 @@ RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout _layout, Arra .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, }; } - if (layout.depthResolveAttachment.getTexture() != nullptr) - { + if (layout.depthResolveAttachment.getTexture() != nullptr) { PTexture2D image = layout.depthResolveAttachment.getTexture().cast(); attachments.add() = { .sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2, @@ -158,7 +150,7 @@ RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout _layout, Arra .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, }; } - + VkSubpassDescriptionDepthStencilResolve depthResolve = { .sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE, .pNext = nullptr, @@ -179,7 +171,7 @@ RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout _layout, Arra .pDepthStencilAttachment = &depthRef, }; Array dep; - for(const auto& d : dependencies) { + for (const auto& d : dependencies) { dep.add() = { .sType = VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, .pNext = nullptr, @@ -206,48 +198,39 @@ RenderPass::RenderPass(PGraphics graphics, Gfx::RenderTargetLayout _layout, Arra VK_CHECK(vkCreateRenderPass2(graphics->getDevice(), &info, nullptr, &renderPass)); } -RenderPass::~RenderPass() -{ +RenderPass::~RenderPass() { vkDestroyRenderPass(graphics->getDevice(), renderPass, nullptr); - //graphics->getDestructionManager()->queueRenderPass(graphics->getGraphicsCommands()->getCommands(), renderPass); + // graphics->getDestructionManager()->queueRenderPass(graphics->getGraphicsCommands()->getCommands(), renderPass); } -uint32 RenderPass::getFramebufferHash() -{ +uint32 RenderPass::getFramebufferHash() { FramebufferDescription description; std::memset(&description, 0, sizeof(FramebufferDescription)); - for (auto& inputAttachment : layout.inputAttachments) - { + for (auto& inputAttachment : layout.inputAttachments) { PTexture2D tex = inputAttachment.getTexture().cast(); description.inputAttachments[description.numInputAttachments++] = tex->getView(); } - for (auto& colorAttachment : layout.colorAttachments) - { + for (auto& colorAttachment : layout.colorAttachments) { PTexture2D tex = colorAttachment.getTexture().cast(); description.colorAttachments[description.numColorAttachments++] = tex->getView(); } - if (layout.depthAttachment.getTexture() != nullptr) - { + if (layout.depthAttachment.getTexture() != nullptr) { PTexture2D tex = layout.depthAttachment.getTexture().cast(); description.depthAttachment = tex->getView(); } return CRC::Calculate(&description, sizeof(FramebufferDescription), CRC::CRC_32()); } -void Vulkan::RenderPass::endRenderPass() -{ - for (auto& inputAttachment : layout.inputAttachments) - { +void Vulkan::RenderPass::endRenderPass() { + for (auto& inputAttachment : layout.inputAttachments) { PTexture2D tex = inputAttachment.getTexture().cast(); tex->setLayout(inputAttachment.getFinalLayout()); } - for (auto& colorAttachment : layout.colorAttachments) - { + for (auto& colorAttachment : layout.colorAttachments) { PTexture2D tex = colorAttachment.getTexture().cast(); tex->setLayout(colorAttachment.getFinalLayout()); } - if (layout.depthAttachment.getTexture() != nullptr) - { + if (layout.depthAttachment.getTexture() != nullptr) { PTexture2D tex = layout.depthAttachment.getTexture().cast(); tex->setLayout(layout.depthAttachment.getFinalLayout()); } diff --git a/src/Engine/Graphics/Vulkan/RenderPass.h b/src/Engine/Graphics/Vulkan/RenderPass.h index 0377a18..2e81e2b 100644 --- a/src/Engine/Graphics/Vulkan/RenderPass.h +++ b/src/Engine/Graphics/Vulkan/RenderPass.h @@ -1,39 +1,23 @@ #pragma once -#include "Graphics/RenderTarget.h" #include "Graphics.h" +#include "Graphics/RenderTarget.h" -namespace Seele -{ -namespace Vulkan -{ -class RenderPass : public Gfx::RenderPass -{ -public: + +namespace Seele { +namespace Vulkan { +class RenderPass : public Gfx::RenderPass { + public: RenderPass(PGraphics graphics, Gfx::RenderTargetLayout layout, Array dependencies, Gfx::PViewport viewport); virtual ~RenderPass(); uint32 getFramebufferHash(); void endRenderPass(); - constexpr VkRenderPass getHandle() const - { - return renderPass; - } - constexpr size_t getClearValueCount() const - { - return clearValues.size(); - } - constexpr VkClearValue *getClearValues() const - { - return clearValues.data(); - } - constexpr VkRect2D getRenderArea() const - { - return renderArea; - } - constexpr VkSubpassContents getSubpassContents() const - { - return subpassContents; - } -private: + constexpr VkRenderPass getHandle() const { return renderPass; } + constexpr size_t getClearValueCount() const { return clearValues.size(); } + constexpr VkClearValue* getClearValues() const { return clearValues.data(); } + constexpr VkRect2D getRenderArea() const { return renderArea; } + constexpr VkSubpassContents getSubpassContents() const { return subpassContents; } + + private: PGraphics graphics; VkRenderPass renderPass; Array clearValues; diff --git a/src/Engine/Graphics/Vulkan/Resources.cpp b/src/Engine/Graphics/Vulkan/Resources.cpp index b160425..bc583dc 100644 --- a/src/Engine/Graphics/Vulkan/Resources.cpp +++ b/src/Engine/Graphics/Vulkan/Resources.cpp @@ -1,15 +1,14 @@ #include "Resources.h" +#include "Command.h" #include "Enums.h" #include "Graphics.h" -#include "Command.h" #include "Window.h" + using namespace Seele; using namespace Seele::Vulkan; -Semaphore::Semaphore(PGraphics graphics) - : graphics(graphics) -{ +Semaphore::Semaphore(PGraphics graphics) : graphics(graphics) { VkSemaphoreCreateInfo info = { .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, .pNext = nullptr, @@ -18,129 +17,83 @@ Semaphore::Semaphore(PGraphics graphics) VK_CHECK(vkCreateSemaphore(graphics->getDevice(), &info, nullptr, &handle)); } -Semaphore::~Semaphore() -{ +Semaphore::~Semaphore() { // graphics->getDestructionManager()->queueSemaphore(graphics->getGraphicsCommands()->getCommands(), handle); } -Fence::Fence(PGraphics graphics) - : graphics(graphics), status(Status::Ready) -{ - VkFenceCreateInfo info = { - .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, - .pNext = nullptr, - .flags = 0}; +Fence::Fence(PGraphics graphics) : graphics(graphics), status(Status::Ready) { + VkFenceCreateInfo info = {.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = nullptr, .flags = 0}; VK_CHECK(vkCreateFence(graphics->getDevice(), &info, nullptr, &fence)); } -Fence::~Fence() -{ +Fence::~Fence() { vkWaitForFences(graphics->getDevice(), 1, &fence, true, 10000000); vkDestroyFence(graphics->getDevice(), fence, nullptr); } -void Fence::submit() -{ - status = Status::InUse; -} +void Fence::submit() { status = Status::InUse; } -bool Fence::isSignaled() -{ - if (status == Status::Signalled) - { +bool Fence::isSignaled() { + if (status == Status::Signalled) { return true; } VkResult r = vkGetFenceStatus(graphics->getDevice(), fence); - if (r == VK_SUCCESS) - { + if (r == VK_SUCCESS) { status = Status::Signalled; return true; } - if (r == VK_NOT_READY) - { + if (r == VK_NOT_READY) { return false; - } - else - { + } else { VK_CHECK(r); return false; } } -void Fence::reset() -{ - while (status == Status::InUse) - { +void Fence::reset() { + while (status == Status::InUse) { wait(1000000); } - if (status == Status::Signalled) - { + if (status == Status::Signalled) { VK_CHECK(vkResetFences(graphics->getDevice(), 1, &fence)); status = Status::Ready; } } -void Fence::wait(uint64 timeout) -{ +void Fence::wait(uint64 timeout) { VkFence fences[] = {fence}; VkResult r = vkWaitForFences(graphics->getDevice(), 1, fences, true, timeout); - if (r == VK_SUCCESS) - { + if (r == VK_SUCCESS) { status = Status::Signalled; - } - else if (r == VK_TIMEOUT) - { + } else if (r == VK_TIMEOUT) { return; - } - else if (r != VK_NOT_READY) - { + } else if (r != VK_NOT_READY) { VK_CHECK(r); } } -DestructionManager::DestructionManager(PGraphics graphics) - : graphics(graphics) -{ -} +DestructionManager::DestructionManager(PGraphics graphics) : graphics(graphics) {} -DestructionManager::~DestructionManager() -{ -} +DestructionManager::~DestructionManager() {} -void DestructionManager::queueResourceForDestruction(OCommandBoundResource resource) -{ - resources.add(std::move(resource)); -} +void DestructionManager::queueResourceForDestruction(OCommandBoundResource resource) { resources.add(std::move(resource)); } -void DestructionManager::notifyCommandComplete() -{ - for (size_t i = 0; i < resources.size(); ++i) - { - if (!resources[i]->isCurrentlyBound()) - { +void DestructionManager::notifyCommandComplete() { + for (size_t i = 0; i < resources.size(); ++i) { + if (!resources[i]->isCurrentlyBound()) { resources.removeAt(i, false); i--; } } } -SamplerHandle::SamplerHandle(PGraphics graphics, VkSamplerCreateInfo createInfo) - : CommandBoundResource(graphics) -{ +SamplerHandle::SamplerHandle(PGraphics graphics, VkSamplerCreateInfo createInfo) : CommandBoundResource(graphics) { vkCreateSampler(graphics->getDevice(), &createInfo, nullptr, &sampler); } -SamplerHandle::~SamplerHandle() -{ - vkDestroySampler(graphics->getDevice(), sampler, nullptr); -} +SamplerHandle::~SamplerHandle() { vkDestroySampler(graphics->getDevice(), sampler, nullptr); } Sampler::Sampler(PGraphics graphics, VkSamplerCreateInfo createInfo) - : graphics(graphics), handle(new SamplerHandle(graphics, createInfo)) -{ -} + : graphics(graphics), handle(new SamplerHandle(graphics, createInfo)) {} -Sampler::~Sampler() -{ - graphics->getDestructionManager()->queueResourceForDestruction(std::move(handle)); -} +Sampler::~Sampler() { graphics->getDestructionManager()->queueResourceForDestruction(std::move(handle)); } diff --git a/src/Engine/Graphics/Vulkan/Resources.h b/src/Engine/Graphics/Vulkan/Resources.h index 63d0960..c8523d3 100644 --- a/src/Engine/Graphics/Vulkan/Resources.h +++ b/src/Engine/Graphics/Vulkan/Resources.h @@ -1,114 +1,97 @@ #pragma once -#include -#include #include "Containers/List.h" #include "Graphics/Resources.h" +#include +#include -namespace Seele -{ -namespace Vulkan -{ + +namespace Seele { +namespace Vulkan { DECLARE_REF(DescriptorPool) DECLARE_REF(CommandPool) DECLARE_REF(Command) DECLARE_REF(Graphics) -class Semaphore -{ -public: +class Semaphore { + public: Semaphore(PGraphics graphics); virtual ~Semaphore(); - constexpr VkSemaphore getHandle() const - { - return handle; - } -private: + constexpr VkSemaphore getHandle() const { return handle; } + + private: VkSemaphore handle; PGraphics graphics; }; DEFINE_REF(Semaphore) -class Fence -{ -public: +class Fence { + public: Fence(PGraphics graphics); ~Fence(); void submit(); bool isSignaled(); void reset(); - constexpr VkFence getHandle() const - { - return fence; - } + constexpr VkFence getHandle() const { return fence; } void wait(uint64 timeout); - bool operator<(const Fence &other) const - { - return fence < other.fence; - } + bool operator<(const Fence& other) const { return fence < other.fence; } -private: + private: PGraphics graphics; - enum class Status - { - Ready, - InUse, - Signalled, + enum class Status { + Ready, + InUse, + Signalled, }; Status status; VkFence fence; }; DEFINE_REF(Fence) DECLARE_REF(CommandBoundResource) -class DestructionManager -{ -public: +class DestructionManager { + public: DestructionManager(PGraphics graphics); ~DestructionManager(); void queueResourceForDestruction(OCommandBoundResource resource); void notifyCommandComplete(); -private: + + private: PGraphics graphics; Array resources; }; DEFINE_REF(DestructionManager) -class CommandBoundResource -{ -public: - CommandBoundResource(PGraphics graphics) - : graphics(graphics) - { - } - virtual ~CommandBoundResource() - { +class CommandBoundResource { + public: + CommandBoundResource(PGraphics graphics) : graphics(graphics) {} + virtual ~CommandBoundResource() { if (isCurrentlyBound()) abort(); } constexpr bool isCurrentlyBound() const { return bindCount > 0; } constexpr void bind() { bindCount++; } constexpr void unbind() { bindCount--; } -protected: + + protected: PGraphics graphics; uint64 bindCount = 0; }; DEFINE_REF(CommandBoundResource) -class SamplerHandle : public CommandBoundResource -{ -public: +class SamplerHandle : public CommandBoundResource { + public: SamplerHandle(PGraphics graphics, VkSamplerCreateInfo createInfo); virtual ~SamplerHandle(); VkSampler sampler; }; DEFINE_REF(SamplerHandle) -class Sampler : public Gfx::Sampler -{ -public: +class Sampler : public Gfx::Sampler { + public: Sampler(PGraphics graphics, VkSamplerCreateInfo createInfo); virtual ~Sampler(); PSamplerHandle getHandle() const { return handle; } VkSampler getSampler() const { return handle->sampler; } -private: + + private: PGraphics graphics; OSamplerHandle handle; }; diff --git a/src/Engine/Graphics/Vulkan/Shader.cpp b/src/Engine/Graphics/Vulkan/Shader.cpp index 35156de..7a96257 100644 --- a/src/Engine/Graphics/Vulkan/Shader.cpp +++ b/src/Engine/Graphics/Vulkan/Shader.cpp @@ -1,40 +1,30 @@ #include "Shader.h" #include "Graphics.h" #include "Graphics/slang-compile.h" -#include "slang.h" #include "slang-com-ptr.h" +#include "slang.h" #include "stdlib.h" #include + using namespace Seele; using namespace Seele::Vulkan; -Shader::Shader(PGraphics graphics, VkShaderStageFlags stage) - : graphics(graphics) - , stage(stage) -{ -} +Shader::Shader(PGraphics graphics, VkShaderStageFlags stage) : graphics(graphics), stage(stage) {} -Shader::~Shader() -{ - if (module != VK_NULL_HANDLE) - { +Shader::~Shader() { + if (module != VK_NULL_HANDLE) { vkDestroyShaderModule(graphics->getDevice(), module, nullptr); } } -uint32 Seele::Vulkan::Shader::getShaderHash() const -{ - return hash; -} +uint32 Seele::Vulkan::Shader::getShaderHash() const { return hash; } -void Shader::create(ShaderCreateInfo createInfo) -{ +void Shader::create(ShaderCreateInfo createInfo) { Map paramMapping; Slang::ComPtr kernelBlob = generateShader(createInfo, SLANG_SPIRV, paramMapping); createInfo.rootSignature->addMapping(paramMapping); - VkShaderModuleCreateInfo moduleInfo = - { + VkShaderModuleCreateInfo moduleInfo = { .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .pNext = nullptr, .flags = 0, diff --git a/src/Engine/Graphics/Vulkan/Shader.h b/src/Engine/Graphics/Vulkan/Shader.h index e0e1ba5..8eaf3dc 100644 --- a/src/Engine/Graphics/Vulkan/Shader.h +++ b/src/Engine/Graphics/Vulkan/Shader.h @@ -1,37 +1,29 @@ #pragma once -#include "Resources.h" #include "Enums.h" #include "Graphics/Shader.h" +#include "Resources.h" -namespace Seele -{ -namespace Vulkan -{ + +namespace Seele { +namespace Vulkan { DECLARE_REF(Graphics) DECLARE_REF(DescriptorLayout) -class Shader -{ -public: +class Shader { + public: Shader(PGraphics graphics, VkShaderStageFlags stage); virtual ~Shader(); void create(ShaderCreateInfo createInfo); - constexpr VkShaderModule getModuleHandle() const - { - return module; - } - constexpr const char* getEntryPointName() const - { - //SLang renames all entry points to main, so we dont need that - return "main";//entryPointName.c_str(); - } - constexpr VkShaderStageFlags getStage() const - { - return stage; + constexpr VkShaderModule getModuleHandle() const { return module; } + constexpr const char* getEntryPointName() const { + // SLang renames all entry points to main, so we dont need that + return "main"; // entryPointName.c_str(); } + constexpr VkShaderStageFlags getStage() const { return stage; } uint32 getShaderHash() const; -private: + + private: PGraphics graphics; VkShaderModule module; VkShaderStageFlags stage; @@ -39,17 +31,10 @@ private: }; DEFINE_REF(Shader) -template -class ShaderBase : public Base, public Shader -{ -public: - ShaderBase(PGraphics graphics) - : Shader(graphics, stageFlags) - { - } - virtual ~ShaderBase() - { - } +template class ShaderBase : public Base, public Shader { + public: + ShaderBase(PGraphics graphics) : Shader(graphics, stageFlags) {} + virtual ~ShaderBase() {} }; using VertexShader = ShaderBase; using FragmentShader = ShaderBase; @@ -63,4 +48,4 @@ DEFINE_REF(ComputeShader) DEFINE_REF(TaskShader) DEFINE_REF(MeshShader) } // namespace Vulkan -} \ No newline at end of file +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/Vulkan/Texture.cpp b/src/Engine/Graphics/Vulkan/Texture.cpp index 59c384b..42ca79c 100644 --- a/src/Engine/Graphics/Vulkan/Texture.cpp +++ b/src/Engine/Graphics/Vulkan/Texture.cpp @@ -6,10 +6,8 @@ using namespace Seele; using namespace Seele::Vulkan; -VkImageAspectFlags getAspectFromFormat(Gfx::SeFormat format) -{ - switch (format) - { +VkImageAspectFlags getAspectFromFormat(Gfx::SeFormat format) { + switch (format) { case Gfx::SE_FORMAT_D16_UNORM: return VK_IMAGE_ASPECT_DEPTH_BIT; case Gfx::SE_FORMAT_D32_SFLOAT: @@ -26,47 +24,28 @@ VkImageAspectFlags getAspectFromFormat(Gfx::SeFormat format) } } +TextureHandle::TextureHandle(PGraphics graphics) : CommandBoundResource(graphics) {} -TextureHandle::TextureHandle(PGraphics graphics) - : CommandBoundResource(graphics) -{ -} - -TextureHandle::~TextureHandle() -{ +TextureHandle::~TextureHandle() { vkDestroyImageView(graphics->getDevice(), imageView, nullptr); - if (ownsImage) - { + if (ownsImage) { vmaDestroyImage(graphics->getAllocator(), image, allocation); } } -TextureBase::TextureBase(PGraphics graphics, VkImageViewType viewType, - const TextureCreateInfo& createInfo, Gfx::QueueType& owner, VkImage existingImage) - : currentOwner(owner) - , graphics(graphics) - , width(createInfo.width) - , height(createInfo.height) - , depth(createInfo.depth) - , arrayCount(createInfo.elements) - , layerCount(createInfo.layers) - , mipLevels(createInfo.mipLevels) - , samples(createInfo.samples) - , format(createInfo.format) - , usage(createInfo.usage) - , handle(new TextureHandle(graphics)) - , aspect(getAspectFromFormat(createInfo.format)) - , layout(Gfx::SE_IMAGE_LAYOUT_UNDEFINED) -{ +TextureBase::TextureBase(PGraphics graphics, VkImageViewType viewType, const TextureCreateInfo& createInfo, Gfx::QueueType& owner, + VkImage existingImage) + : currentOwner(owner), graphics(graphics), width(createInfo.width), height(createInfo.height), depth(createInfo.depth), + arrayCount(createInfo.elements), layerCount(createInfo.layers), mipLevels(createInfo.mipLevels), samples(createInfo.samples), + format(createInfo.format), usage(createInfo.usage), handle(new TextureHandle(graphics)), + aspect(getAspectFromFormat(createInfo.format)), layout(Gfx::SE_IMAGE_LAYOUT_UNDEFINED) { handle->image = existingImage; handle->ownsImage = false; - if (existingImage == VK_NULL_HANDLE) - { + if (existingImage == VK_NULL_HANDLE) { handle->ownsImage = true; VkImageType type = VK_IMAGE_TYPE_MAX_ENUM; VkImageCreateFlags flags = 0; - switch (viewType) - { + switch (viewType) { case VK_IMAGE_VIEW_TYPE_1D: case VK_IMAGE_VIEW_TYPE_1D_ARRAY: type = VK_IMAGE_TYPE_1D; @@ -87,12 +66,8 @@ TextureBase::TextureBase(PGraphics graphics, VkImageViewType viewType, default: break; } - if ((usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) == 0) - { - usage = usage - | VK_IMAGE_USAGE_TRANSFER_DST_BIT - | VK_IMAGE_USAGE_TRANSFER_SRC_BIT - | VK_IMAGE_USAGE_SAMPLED_BIT; + if ((usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) == 0) { + usage = usage | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; } VkImageCreateInfo info = { .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, @@ -100,11 +75,12 @@ TextureBase::TextureBase(PGraphics graphics, VkImageViewType viewType, .flags = flags, .imageType = type, .format = cast(format), - .extent = { - .width = width, - .height = height, - .depth = depth, - }, + .extent = + { + .width = width, + .height = height, + .depth = depth, + }, .mipLevels = mipLevels, .arrayLayers = arrayCount * layerCount, .samples = (VkSampleCountFlagBits)samples, @@ -120,11 +96,9 @@ TextureBase::TextureBase(PGraphics graphics, VkImageViewType viewType, } const DataSource& sourceData = createInfo.sourceData; - if (sourceData.size > 0) - { - changeLayout(Gfx::SE_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - VK_ACCESS_NONE, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); + if (sourceData.size > 0) { + changeLayout(Gfx::SE_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_NONE, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); void* data; OBufferAllocation stagingAlloc = new BufferAllocation(graphics); VkBufferCreateInfo stagingInfo = { @@ -139,7 +113,8 @@ TextureBase::TextureBase(PGraphics graphics, VkImageViewType viewType, .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT, .usage = VMA_MEMORY_USAGE_AUTO, }; - VK_CHECK(vmaCreateBuffer(graphics->getAllocator(), &stagingInfo, &alloc, &stagingAlloc->buffer, &stagingAlloc->allocation, nullptr)); + VK_CHECK( + vmaCreateBuffer(graphics->getAllocator(), &stagingInfo, &alloc, &stagingAlloc->buffer, &stagingAlloc->allocation, nullptr)); vmaMapMemory(graphics->getAllocator(), stagingAlloc->allocation, &data); vmaSetAllocationName(graphics->getAllocator(), stagingAlloc->allocation, "TextureStaging"); @@ -151,53 +126,40 @@ TextureBase::TextureBase(PGraphics graphics, VkImageViewType viewType, .bufferOffset = 0, .bufferRowLength = 0, .bufferImageHeight = 0, - .imageSubresource = { - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .mipLevel = 0, - .baseArrayLayer = 0, - .layerCount = arrayCount * layerCount, - }, - .imageOffset = { - .x = 0, - .y = 0, - .z = 0, - }, - .imageExtent = { - .width = width, - .height = height, - .depth = depth - }, + .imageSubresource = + { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .mipLevel = 0, + .baseArrayLayer = 0, + .layerCount = arrayCount * layerCount, + }, + .imageOffset = + { + .x = 0, + .y = 0, + .z = 0, + }, + .imageExtent = {.width = width, .height = height, .depth = depth}, }; - vkCmdCopyBufferToImage(commandPool->getCommands()->getHandle(), - stagingAlloc->buffer, handle->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion); + vkCmdCopyBufferToImage(commandPool->getCommands()->getHandle(), stagingAlloc->buffer, handle->image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion); commandPool->getCommands()->bindResource(PBufferAllocation(stagingAlloc)); // When loading a texture from a file, we will almost always use it as a texture map for fragment shaders - changeLayout(Gfx::SE_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + changeLayout(Gfx::SE_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); graphics->getDestructionManager()->queueResourceForDestruction(std::move(stagingAlloc)); - } - else - { - if (usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) - { - changeLayout(Gfx::SE_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, - VK_ACCESS_NONE, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT); - } - else if (usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) - { - changeLayout(Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - VK_ACCESS_NONE, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); - } - else - { - changeLayout(Gfx::SE_IMAGE_LAYOUT_GENERAL, - VK_ACCESS_NONE, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT); + } else { + if (usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { + changeLayout(Gfx::SE_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_ACCESS_NONE, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT); + } else if (usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) { + changeLayout(Gfx::SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_ACCESS_NONE, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); + } else { + changeLayout(Gfx::SE_IMAGE_LAYOUT_GENERAL, VK_ACCESS_NONE, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_ACCESS_MEMORY_WRITE_BIT, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT); } } VkImageViewCreateInfo viewInfo = { @@ -207,35 +169,25 @@ TextureBase::TextureBase(PGraphics graphics, VkImageViewType viewType, .image = handle->image, .viewType = viewType, .format = cast(format), - .subresourceRange = { - .aspectMask = aspect, - .levelCount = mipLevels, - .layerCount = layerCount, - }, + .subresourceRange = + { + .aspectMask = aspect, + .levelCount = mipLevels, + .layerCount = layerCount, + }, }; - + VK_CHECK(vkCreateImageView(graphics->getDevice(), &viewInfo, nullptr, &handle->imageView)); } -TextureBase::~TextureBase() -{ - graphics->getDestructionManager()->queueResourceForDestruction(std::move(handle)); -} +TextureBase::~TextureBase() { graphics->getDestructionManager()->queueResourceForDestruction(std::move(handle)); } -VkImage TextureBase::getImage() const -{ - return handle->image; -} +VkImage TextureBase::getImage() const { return handle->image; } -VkImageView TextureBase::getView() const -{ - return handle->imageView; -} +VkImageView TextureBase::getView() const { return handle->imageView; } -void TextureBase::changeLayout(Gfx::SeImageLayout newLayout, - VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, VkPipelineStageFlags dstStage) -{ +void TextureBase::changeLayout(Gfx::SeImageLayout newLayout, VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, + VkAccessFlags dstAccess, VkPipelineStageFlags dstStage) { VkImageMemoryBarrier barrier = { .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .pNext = nullptr, @@ -246,31 +198,28 @@ void TextureBase::changeLayout(Gfx::SeImageLayout newLayout, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = handle->image, - .subresourceRange = { - .aspectMask = aspect, - .baseMipLevel = 0, - .levelCount = mipLevels, - .baseArrayLayer = 0, - .layerCount = layerCount, - }, + .subresourceRange = + { + .aspectMask = aspect, + .baseMipLevel = 0, + .levelCount = mipLevels, + .baseArrayLayer = 0, + .layerCount = layerCount, + }, }; PCommandPool commandPool = graphics->getQueueCommands(currentOwner); - vkCmdPipelineBarrier(commandPool->getCommands()->getHandle(), - srcStage, dstStage, - 0, 0, nullptr, 0, nullptr, 1, &barrier); + vkCmdPipelineBarrier(commandPool->getCommands()->getHandle(), srcStage, dstStage, 0, 0, nullptr, 0, nullptr, 1, &barrier); commandPool->getCommands()->bindResource(PTextureHandle(handle)); commandPool->submitCommands(); layout = newLayout; } -void TextureBase::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) -{ +void TextureBase::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) { uint64 imageSize = width * height * depth * Gfx::getFormatInfo(format).blockSize; auto prevLayout = layout; - changeLayout(Gfx::SE_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); + changeLayout(Gfx::SE_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); void* data; OBufferAllocation stagingAlloc = new BufferAllocation(graphics); // always create a staging buffer since we do buffer -> image copy and the image may be in any tiling format @@ -290,33 +239,30 @@ void TextureBase::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Arra vmaSetAllocationName(graphics->getAllocator(), stagingAlloc->allocation, "DownloadBuffer"); PCommand cmdBuffer = graphics->getQueueCommands(currentOwner)->getCommands(); - //Gfx::FormatCompatibilityInfo formatInfo = Gfx::getFormatInfo(format); + // Gfx::FormatCompatibilityInfo formatInfo = Gfx::getFormatInfo(format); VkBufferImageCopy region = { .bufferOffset = 0, .bufferRowLength = 0, .bufferImageHeight = 0, - .imageSubresource = { - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .mipLevel = mipLevel, - .baseArrayLayer = arrayLayer * layerCount + face, - .layerCount = 1, - }, - .imageOffset = { - .x = 0, - .y = 0, - .z = 0, - }, - .imageExtent = { - .width = width, - .height = height, - .depth = depth - }, + .imageSubresource = + { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .mipLevel = mipLevel, + .baseArrayLayer = arrayLayer * layerCount + face, + .layerCount = 1, + }, + .imageOffset = + { + .x = 0, + .y = 0, + .z = 0, + }, + .imageExtent = {.width = width, .height = height, .depth = depth}, }; vkCmdCopyImageToBuffer(cmdBuffer->getHandle(), handle->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, stagingAlloc->buffer, 1, ®ion); cmdBuffer->bindResource(PBufferAllocation(stagingAlloc)); - changeLayout(prevLayout, - VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT); + changeLayout(prevLayout, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_MEMORY_READ_BIT, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT); VK_CHECK(vmaMapMemory(graphics->getAllocator(), stagingAlloc->allocation, &data)); buffer.resize(imageSize); std::memcpy(buffer.data(), data, buffer.size()); @@ -324,8 +270,7 @@ void TextureBase::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Arra graphics->getDestructionManager()->queueResourceForDestruction(std::move(stagingAlloc)); } -void TextureBase::executeOwnershipBarrier(Gfx::QueueType newOwner) -{ +void TextureBase::executeOwnershipBarrier(Gfx::QueueType newOwner) { Gfx::QueueFamilyMapping mapping = graphics->getFamilyMapping(); VkImageMemoryBarrier imageBarrier = { .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, @@ -335,52 +280,43 @@ void TextureBase::executeOwnershipBarrier(Gfx::QueueType newOwner) .srcQueueFamilyIndex = mapping.getQueueTypeFamilyIndex(currentOwner), .dstQueueFamilyIndex = mapping.getQueueTypeFamilyIndex(newOwner), .image = handle->image, - .subresourceRange = { - .aspectMask = aspect, - .baseMipLevel = 0, - .levelCount = mipLevels, - .baseArrayLayer = 0, - .layerCount = arrayCount, - }, + .subresourceRange = + { + .aspectMask = aspect, + .baseMipLevel = 0, + .levelCount = mipLevels, + .baseArrayLayer = 0, + .layerCount = arrayCount, + }, }; PCommandPool sourcePool = graphics->getQueueCommands(currentOwner); PCommandPool dstPool = nullptr; VkPipelineStageFlags srcStage = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; VkPipelineStageFlags dstStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - if (currentOwner == Gfx::QueueType::TRANSFER) - { + if (currentOwner == Gfx::QueueType::TRANSFER) { imageBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT; - } - else if (currentOwner == Gfx::QueueType::COMPUTE) - { + } else if (currentOwner == Gfx::QueueType::COMPUTE) { imageBarrier.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; srcStage = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - } - else if (currentOwner == Gfx::QueueType::GRAPHICS) - { + } else if (currentOwner == Gfx::QueueType::GRAPHICS) { imageBarrier.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; srcStage = VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT; } - if (newOwner == Gfx::QueueType::TRANSFER) - { + if (newOwner == Gfx::QueueType::TRANSFER) { imageBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT; dstPool = graphics->getTransferCommands(); - } - else if (newOwner == Gfx::QueueType::COMPUTE) - { + } else if (newOwner == Gfx::QueueType::COMPUTE) { imageBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; dstStage = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; dstPool = graphics->getComputeCommands(); - } - else if (newOwner == Gfx::QueueType::GRAPHICS) - { + } else if (newOwner == Gfx::QueueType::GRAPHICS) { imageBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; dstStage = VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT; dstPool = graphics->getGraphicsCommands(); } - + VkCommandBuffer sourceCmd = sourcePool->getCommands()->getHandle(); VkCommandBuffer destCmd = dstPool->getCommands()->getHandle(); sourcePool->getCommands()->bindResource(PTextureHandle(handle)); @@ -391,9 +327,8 @@ void TextureBase::executeOwnershipBarrier(Gfx::QueueType newOwner) sourcePool->submitCommands(); } -void TextureBase::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, VkPipelineStageFlags dstStage) -{ +void TextureBase::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, VkAccessFlags dstAccess, + VkPipelineStageFlags dstStage) { VkImageMemoryBarrier barrier = { .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .pNext = nullptr, @@ -404,13 +339,14 @@ void TextureBase::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStag .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = handle->image, - .subresourceRange = { - .aspectMask = aspect, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, + .subresourceRange = + { + .aspectMask = aspect, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, }; PCommand command = graphics->getQueueCommands(currentOwner)->getCommands(); vkCmdPipelineBarrier(command->getHandle(), srcStage, dstStage, 0, 0, nullptr, 0, nullptr, 1, &barrier); @@ -418,101 +354,67 @@ void TextureBase::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStag } Texture2D::Texture2D(PGraphics graphics, const TextureCreateInfo& createInfo, VkImage existingImage) - : Gfx::Texture2D(graphics->getFamilyMapping(), createInfo.sourceData.owner) - , TextureBase(graphics, createInfo.elements > 1 ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D, - createInfo, Gfx::Texture2D::currentOwner, existingImage) -{ -} + : Gfx::Texture2D(graphics->getFamilyMapping(), createInfo.sourceData.owner), + TextureBase(graphics, createInfo.elements > 1 ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D, createInfo, + Gfx::Texture2D::currentOwner, existingImage) {} -Texture2D::~Texture2D() -{ -} +Texture2D::~Texture2D() {} -void Texture2D::changeLayout(Gfx::SeImageLayout newLayout, - Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) -{ +void Texture2D::changeLayout(Gfx::SeImageLayout newLayout, Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) { TextureBase::changeLayout(newLayout, srcAccess, srcStage, dstAccess, dstStage); } -void Texture2D::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) -{ +void Texture2D::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) { TextureBase::download(mipLevel, arrayLayer, face, buffer); } -void Texture2D::executeOwnershipBarrier(Gfx::QueueType newOwner) -{ - TextureBase::executeOwnershipBarrier(newOwner); -} +void Texture2D::executeOwnershipBarrier(Gfx::QueueType newOwner) { TextureBase::executeOwnershipBarrier(newOwner); } -void Texture2D::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, VkPipelineStageFlags dstStage) -{ +void Texture2D::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, VkAccessFlags dstAccess, + VkPipelineStageFlags dstStage) { TextureBase::executePipelineBarrier(srcAccess, srcStage, dstAccess, dstStage); } Texture3D::Texture3D(PGraphics graphics, const TextureCreateInfo& createInfo, VkImage existingImage) - : Gfx::Texture3D(graphics->getFamilyMapping(), createInfo.sourceData.owner) - , TextureBase(graphics, VK_IMAGE_VIEW_TYPE_3D, - createInfo, Gfx::Texture3D::currentOwner, existingImage) -{ -} + : Gfx::Texture3D(graphics->getFamilyMapping(), createInfo.sourceData.owner), + TextureBase(graphics, VK_IMAGE_VIEW_TYPE_3D, createInfo, Gfx::Texture3D::currentOwner, existingImage) {} -Texture3D::~Texture3D() -{ -} +Texture3D::~Texture3D() {} -void Texture3D::changeLayout(Gfx::SeImageLayout newLayout, - Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) -{ +void Texture3D::changeLayout(Gfx::SeImageLayout newLayout, Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) { TextureBase::changeLayout(newLayout, srcAccess, srcStage, dstAccess, dstStage); } -void Texture3D::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) -{ +void Texture3D::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) { TextureBase::download(mipLevel, arrayLayer, face, buffer); } -void Texture3D::executeOwnershipBarrier(Gfx::QueueType newOwner) -{ - TextureBase::executeOwnershipBarrier(newOwner); -} +void Texture3D::executeOwnershipBarrier(Gfx::QueueType newOwner) { TextureBase::executeOwnershipBarrier(newOwner); } -void Texture3D::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, VkPipelineStageFlags dstStage) -{ +void Texture3D::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, VkAccessFlags dstAccess, + VkPipelineStageFlags dstStage) { TextureBase::executePipelineBarrier(srcAccess, srcStage, dstAccess, dstStage); } TextureCube::TextureCube(PGraphics graphics, const TextureCreateInfo& createInfo, VkImage existingImage) - : Gfx::TextureCube(graphics->getFamilyMapping(), createInfo.sourceData.owner) - , TextureBase(graphics, createInfo.elements > 1? VK_IMAGE_VIEW_TYPE_CUBE_ARRAY : VK_IMAGE_VIEW_TYPE_CUBE, - createInfo, Gfx::TextureCube::currentOwner, existingImage) -{ -} + : Gfx::TextureCube(graphics->getFamilyMapping(), createInfo.sourceData.owner), + TextureBase(graphics, createInfo.elements > 1 ? VK_IMAGE_VIEW_TYPE_CUBE_ARRAY : VK_IMAGE_VIEW_TYPE_CUBE, createInfo, + Gfx::TextureCube::currentOwner, existingImage) {} -TextureCube::~TextureCube() -{ -} +TextureCube::~TextureCube() {} -void TextureCube::changeLayout(Gfx::SeImageLayout newLayout, - Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) -{ +void TextureCube::changeLayout(Gfx::SeImageLayout newLayout, Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) { TextureBase::changeLayout(newLayout, srcAccess, srcStage, dstAccess, dstStage); } -void TextureCube::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) -{ +void TextureCube::download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) { TextureBase::download(mipLevel, arrayLayer, face, buffer); } -void TextureCube::executeOwnershipBarrier(Gfx::QueueType newOwner) -{ - TextureBase::executeOwnershipBarrier(newOwner); -} +void TextureCube::executeOwnershipBarrier(Gfx::QueueType newOwner) { TextureBase::executeOwnershipBarrier(newOwner); } -void TextureCube::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, VkPipelineStageFlags dstStage) -{ +void TextureCube::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, VkAccessFlags dstAccess, + VkPipelineStageFlags dstStage) { TextureBase::executePipelineBarrier(srcAccess, srcStage, dstAccess, dstStage); } diff --git a/src/Engine/Graphics/Vulkan/Texture.h b/src/Engine/Graphics/Vulkan/Texture.h index 8633cd0..22eef14 100644 --- a/src/Engine/Graphics/Vulkan/Texture.h +++ b/src/Engine/Graphics/Vulkan/Texture.h @@ -1,15 +1,13 @@ #pragma once -#include "Graphics/Texture.h" #include "Graphics.h" +#include "Graphics/Texture.h" #include "Resources.h" -namespace Seele -{ -namespace Vulkan -{ -class TextureHandle : public CommandBoundResource -{ -public: + +namespace Seele { +namespace Vulkan { +class TextureHandle : public CommandBoundResource { + public: TextureHandle(PGraphics graphics); virtual ~TextureHandle(); VkImage image; @@ -18,73 +16,35 @@ public: uint8 ownsImage; }; DECLARE_REF(TextureHandle) -class TextureBase -{ -public: - TextureBase(PGraphics graphics, VkImageViewType viewType, - const TextureCreateInfo& createInfo, Gfx::QueueType& owner, VkImage existingImage = VK_NULL_HANDLE); +class TextureBase { + public: + TextureBase(PGraphics graphics, VkImageViewType viewType, const TextureCreateInfo& createInfo, Gfx::QueueType& owner, + VkImage existingImage = VK_NULL_HANDLE); virtual ~TextureBase(); - uint32 getWidth() const - { - return width; - } - uint32 getHeight() const - { - return height; - } - uint32 getDepth() const - { - return depth; - } - PTextureHandle getHandle() const - { - return handle; - } + uint32 getWidth() const { return width; } + uint32 getHeight() const { return height; } + uint32 getDepth() const { return depth; } + PTextureHandle getHandle() const { return handle; } VkImage getImage() const; VkImageView getView() const; - constexpr Gfx::SeImageLayout getLayout() const - { - return layout; - } - void setLayout(Gfx::SeImageLayout val) - { - layout = val; - } - constexpr VkImageAspectFlags getAspect() const - { - return aspect; - } - constexpr VkImageUsageFlags getUsage() const - { - return usage; - } - constexpr Gfx::SeFormat getFormat() const - { - return format; - } - constexpr Gfx::SeSampleCountFlags getNumSamples() const - { - return samples; - } - constexpr uint32 getMipLevels() const - { - return mipLevels; - } - constexpr bool isDepthStencil() const - { - return aspect & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT); - } + constexpr Gfx::SeImageLayout getLayout() const { return layout; } + void setLayout(Gfx::SeImageLayout val) { layout = val; } + constexpr VkImageAspectFlags getAspect() const { return aspect; } + constexpr VkImageUsageFlags getUsage() const { return usage; } + constexpr Gfx::SeFormat getFormat() const { return format; } + constexpr Gfx::SeSampleCountFlags getNumSamples() const { return samples; } + constexpr uint32 getMipLevels() const { return mipLevels; } + constexpr bool isDepthStencil() const { return aspect & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT); } void executeOwnershipBarrier(Gfx::QueueType newOwner); - void executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, VkPipelineStageFlags dstStage); - void changeLayout(Gfx::SeImageLayout newLayout, - VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, VkPipelineStageFlags dstStage); + void executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, VkAccessFlags dstAccess, + VkPipelineStageFlags dstStage); + void changeLayout(Gfx::SeImageLayout newLayout, VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, VkAccessFlags dstAccess, + VkPipelineStageFlags dstStage); void download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer); -protected: + protected: OTextureHandle handle; - //Updates via reference + // Updates via reference Gfx::QueueType& currentOwner; PGraphics graphics; uint32 width; @@ -102,131 +62,70 @@ protected: }; DEFINE_REF(TextureBase) -class Texture2D : public Gfx::Texture2D, public TextureBase -{ -public: +class Texture2D : public Gfx::Texture2D, public TextureBase { + public: Texture2D(PGraphics graphics, const TextureCreateInfo& createInfo, VkImage existingImage = VK_NULL_HANDLE); virtual ~Texture2D(); - virtual uint32 getWidth() const override - { - return width; - } - virtual uint32 getHeight() const override - { - return height; - } - virtual uint32 getDepth() const override - { - return depth; - } - virtual Gfx::SeFormat getFormat() const override - { - return format; - } - virtual Gfx::SeSampleCountFlags getNumSamples() const override - { - return samples; - } - virtual uint32 getMipLevels() const override - { - return mipLevels; - } - virtual void changeLayout(Gfx::SeImageLayout newLayout, - Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; + virtual uint32 getWidth() const override { return width; } + virtual uint32 getHeight() const override { return height; } + virtual uint32 getDepth() const override { return depth; } + virtual Gfx::SeFormat getFormat() const override { return format; } + virtual Gfx::SeSampleCountFlags getNumSamples() const override { return samples; } + virtual uint32 getMipLevels() const override { return mipLevels; } + virtual void changeLayout(Gfx::SeImageLayout newLayout, Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; virtual void download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) override; -protected: + protected: // Inherited via QueueOwnedResource virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; - virtual void executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, VkPipelineStageFlags dstStage) override; - + virtual void executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, VkAccessFlags dstAccess, + VkPipelineStageFlags dstStage) override; }; DEFINE_REF(Texture2D) -class Texture3D : public Gfx::Texture3D, public TextureBase -{ -public: +class Texture3D : public Gfx::Texture3D, public TextureBase { + public: Texture3D(PGraphics graphics, const TextureCreateInfo& createInfo, VkImage existingImage = VK_NULL_HANDLE); virtual ~Texture3D(); - virtual uint32 getWidth() const override - { - return width; - } - virtual uint32 getHeight() const override - { - return height; - } - virtual uint32 getDepth() const override - { - return depth; - } - virtual Gfx::SeFormat getFormat() const override - { - return format; - } - virtual Gfx::SeSampleCountFlags getNumSamples() const override - { - return samples; - } - virtual uint32 getMipLevels() const override - { - return mipLevels; - } - virtual void changeLayout(Gfx::SeImageLayout newLayout, - Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; + virtual uint32 getWidth() const override { return width; } + virtual uint32 getHeight() const override { return height; } + virtual uint32 getDepth() const override { return depth; } + virtual Gfx::SeFormat getFormat() const override { return format; } + virtual Gfx::SeSampleCountFlags getNumSamples() const override { return samples; } + virtual uint32 getMipLevels() const override { return mipLevels; } + virtual void changeLayout(Gfx::SeImageLayout newLayout, Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; virtual void download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) override; -protected: + protected: // Inherited via QueueOwnedResource virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; - virtual void executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, VkPipelineStageFlags dstStage) override; - + virtual void executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, VkAccessFlags dstAccess, + VkPipelineStageFlags dstStage) override; }; DEFINE_REF(Texture3D) -class TextureCube : public Gfx::TextureCube, public TextureBase -{ -public: +class TextureCube : public Gfx::TextureCube, public TextureBase { + public: TextureCube(PGraphics graphics, const TextureCreateInfo& createInfo, VkImage existingImage = VK_NULL_HANDLE); virtual ~TextureCube(); - virtual uint32 getWidth() const override - { - return width; - } - virtual uint32 getHeight() const override - { - return height; - } - virtual uint32 getDepth() const override - { - return depth; - } - virtual Gfx::SeFormat getFormat() const override - { - return format; - } - virtual Gfx::SeSampleCountFlags getNumSamples() const override - { - return samples; - } - virtual uint32 getMipLevels() const override - { - return mipLevels; - } - virtual void changeLayout(Gfx::SeImageLayout newLayout, - Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, - Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; + virtual uint32 getWidth() const override { return width; } + virtual uint32 getHeight() const override { return height; } + virtual uint32 getDepth() const override { return depth; } + virtual Gfx::SeFormat getFormat() const override { return format; } + virtual Gfx::SeSampleCountFlags getNumSamples() const override { return samples; } + virtual uint32 getMipLevels() const override { return mipLevels; } + virtual void changeLayout(Gfx::SeImageLayout newLayout, Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, + Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; virtual void download(uint32 mipLevel, uint32 arrayLayer, uint32 face, Array& buffer) override; -protected: + + protected: // Inherited via QueueOwnedResource virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; - virtual void executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, - VkAccessFlags dstAccess, VkPipelineStageFlags dstStage) override; + virtual void executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, VkAccessFlags dstAccess, + VkPipelineStageFlags dstStage) override; }; DEFINE_REF(TextureCube) -} -} \ No newline at end of file +} // namespace Vulkan +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/Vulkan/Window.cpp b/src/Engine/Graphics/Vulkan/Window.cpp index 4b5b702..28cbf7d 100644 --- a/src/Engine/Graphics/Vulkan/Window.cpp +++ b/src/Engine/Graphics/Vulkan/Window.cpp @@ -1,81 +1,64 @@ #include "Window.h" -#include "Resources.h" -#include "Graphics.h" -#include "Enums.h" #include "Command.h" +#include "Enums.h" +#include "Graphics.h" +#include "Resources.h" #include + using namespace Seele; using namespace Seele::Vulkan; double currentFrameDelta = 0; -double Gfx::getCurrentFrameDelta() -{ - return currentFrameDelta; -} +double Gfx::getCurrentFrameDelta() { return currentFrameDelta; } uint32 currentFrameIndex = 0; -uint32 Gfx::getCurrentFrameIndex() -{ - return currentFrameIndex; -} +uint32 Gfx::getCurrentFrameIndex() { return currentFrameIndex; } -void glfwKeyCallback(GLFWwindow* handle, int key, int, int action, int modifier) -{ - if (key == -1) - { +void glfwKeyCallback(GLFWwindow* handle, int key, int, int action, int modifier) { + if (key == -1) { return; } Window* window = (Window*)glfwGetWindowUserPointer(handle); window->keyPress((KeyCode)key, (InputAction)action, (KeyModifier)modifier); } -void glfwMouseMoveCallback(GLFWwindow* handle, double xpos, double ypos) -{ +void glfwMouseMoveCallback(GLFWwindow* handle, double xpos, double ypos) { Window* window = (Window*)glfwGetWindowUserPointer(handle); window->mouseMove(xpos, ypos); } -void glfwMouseButtonCallback(GLFWwindow* handle, int button, int action, int modifier) -{ +void glfwMouseButtonCallback(GLFWwindow* handle, int button, int action, int modifier) { Window* window = (Window*)glfwGetWindowUserPointer(handle); window->mouseButton((MouseButton)button, (InputAction)action, (KeyModifier)modifier); } -void glfwScrollCallback(GLFWwindow* handle, double xoffset, double yoffset) -{ +void glfwScrollCallback(GLFWwindow* handle, double xoffset, double yoffset) { Window* window = (Window*)glfwGetWindowUserPointer(handle); window->scroll(xoffset, yoffset); } -void glfwFileCallback(GLFWwindow* handle, int count, const char** paths) -{ +void glfwFileCallback(GLFWwindow* handle, int count, const char** paths) { Window* window = (Window*)glfwGetWindowUserPointer(handle); window->fileDrop(count, paths); } -void glfwCloseCallback(GLFWwindow* handle) -{ +void glfwCloseCallback(GLFWwindow* handle) { Window* window = (Window*)glfwGetWindowUserPointer(handle); window->close(); } -void glfwFramebufferResizeCallback(GLFWwindow* handle, int width, int height) -{ +void glfwFramebufferResizeCallback(GLFWwindow* handle, int width, int height) { Window* window = (Window*)glfwGetWindowUserPointer(handle); window->resize(width, height); } -Window::Window(PGraphics graphics, const WindowCreateInfo &createInfo) - : graphics(graphics) - , preferences(createInfo) - , instance(graphics->getInstance()) - , swapchain(VK_NULL_HANDLE) -{ +Window::Window(PGraphics graphics, const WindowCreateInfo& createInfo) + : graphics(graphics), preferences(createInfo), instance(graphics->getInstance()), swapchain(VK_NULL_HANDLE) { float xscale, yscale; glfwGetMonitorContentScale(glfwGetPrimaryMonitor(), &xscale, &yscale); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - GLFWwindow *handle = glfwCreateWindow(createInfo.width / xscale, createInfo.height / yscale, createInfo.title, nullptr, nullptr); + GLFWwindow* handle = glfwCreateWindow(createInfo.width / xscale, createInfo.height / yscale, createInfo.title, nullptr, nullptr); windowHandle = handle; glfwSetWindowUserPointer(handle, this); @@ -86,10 +69,10 @@ Window::Window(PGraphics graphics, const WindowCreateInfo &createInfo) glfwSetDropCallback(handle, &glfwFileCallback); glfwSetWindowCloseCallback(handle, &glfwCloseCallback); glfwSetFramebufferSizeCallback(handle, &glfwFramebufferResizeCallback); - //glfwSetWindowSizeCallback(handle, &glfwResizeCallback); + // glfwSetWindowSizeCallback(handle, &glfwResizeCallback); glfwCreateWindowSurface(instance, handle, nullptr, &surface); - + querySurface(); chooseSwapSurfaceFormat(); framebufferFormat = cast(format.format); @@ -100,31 +83,28 @@ Window::Window(PGraphics graphics, const WindowCreateInfo &createInfo) createSwapChain(); } -Window::~Window() -{ +Window::~Window() { vkDestroySwapchainKHR(graphics->getDevice(), swapchain, nullptr); vkDestroySurfaceKHR(instance, surface, nullptr); - glfwDestroyWindow(static_cast(windowHandle)); + glfwDestroyWindow(static_cast(windowHandle)); } -void Window::pollInput() -{ - glfwPollEvents(); -} +void Window::pollInput() { glfwPollEvents(); } -void Window::beginFrame() -{ +void Window::beginFrame() { imageAvailableFences[currentSemaphoreIndex]->reset(); - vkAcquireNextImageKHR(graphics->getDevice(), swapchain, std::numeric_limits::max(), imageAvailableSemaphores[currentSemaphoreIndex]->getHandle(), imageAvailableFences[currentSemaphoreIndex]->getHandle(), ¤tImageIndex); + vkAcquireNextImageKHR(graphics->getDevice(), swapchain, std::numeric_limits::max(), + imageAvailableSemaphores[currentSemaphoreIndex]->getHandle(), + imageAvailableFences[currentSemaphoreIndex]->getHandle(), ¤tImageIndex); imageAvailableFences[currentSemaphoreIndex]->submit(); - graphics->getGraphicsCommands()->getCommands()->waitForSemaphore(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, imageAvailableSemaphores[currentSemaphoreIndex]); + graphics->getGraphicsCommands()->getCommands()->waitForSemaphore(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + imageAvailableSemaphores[currentSemaphoreIndex]); } -void Window::endFrame() -{ - swapChainTextures[currentImageIndex]->changeLayout(Gfx::SE_IMAGE_LAYOUT_PRESENT_SRC_KHR, - Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - Gfx::SE_ACCESS_MEMORY_READ_BIT, Gfx::SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT); +void Window::endFrame() { + swapChainTextures[currentImageIndex]->changeLayout(Gfx::SE_IMAGE_LAYOUT_PRESENT_SRC_KHR, Gfx::SE_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + Gfx::SE_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, Gfx::SE_ACCESS_MEMORY_READ_BIT, + Gfx::SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT); graphics->getGraphicsCommands()->submitCommands(renderingDoneSemaphores[currentSemaphoreIndex]); VkSemaphore renderDoneHandle = renderingDoneSemaphores[currentSemaphoreIndex]->getHandle(); VkPresentInfoKHR presentInfo = { @@ -138,99 +118,49 @@ void Window::endFrame() .pResults = nullptr, }; VkResult r = vkQueuePresentKHR(graphics->getGraphicsCommands()->getQueue()->getHandle(), &presentInfo); - if(r == VK_SUCCESS) - { } - else if (r == VK_ERROR_OUT_OF_DATE_KHR || r == VK_SUBOPTIMAL_KHR) - { + if (r == VK_SUCCESS) { + } else if (r == VK_ERROR_OUT_OF_DATE_KHR || r == VK_SUBOPTIMAL_KHR) { createSwapChain(); - } - else - { + } else { VK_CHECK(r); } currentSemaphoreIndex = (currentSemaphoreIndex + 1) % Gfx::numFramesBuffered; currentFrameIndex = currentSemaphoreIndex; - //graphics->waitDeviceIdle(); + // graphics->waitDeviceIdle(); } -void Window::onWindowCloseEvent() -{ -} +void Window::onWindowCloseEvent() {} -Gfx::PTexture2D Window::getBackBuffer() const -{ - return PTexture2D(swapChainTextures[currentImageIndex]); -} +Gfx::PTexture2D Window::getBackBuffer() const { return PTexture2D(swapChainTextures[currentImageIndex]); } -void Window::setKeyCallback(std::function callback) -{ - keyCallback = callback; -} +void Window::setKeyCallback(std::function callback) { keyCallback = callback; } -void Window::setMouseMoveCallback(std::function callback) -{ - mouseMoveCallback = callback; -} +void Window::setMouseMoveCallback(std::function callback) { mouseMoveCallback = callback; } -void Window::setMouseButtonCallback(std::function callback) -{ - mouseButtonCallback = callback; -} +void Window::setMouseButtonCallback(std::function callback) { mouseButtonCallback = callback; } -void Window::setScrollCallback(std::function callback) -{ - scrollCallback = callback; -} +void Window::setScrollCallback(std::function callback) { scrollCallback = callback; } -void Window::setFileCallback(std::function callback) -{ - fileCallback = callback; -} +void Window::setFileCallback(std::function callback) { fileCallback = callback; } -void Window::setCloseCallback(std::function callback) -{ - closeCallback = callback; -} +void Window::setCloseCallback(std::function callback) { closeCallback = callback; } -void Window::setResizeCallback(std::function callback) -{ - resizeCallback = callback; -} +void Window::setResizeCallback(std::function callback) { resizeCallback = callback; } -void Window::keyPress(KeyCode code, InputAction action, KeyModifier modifier) -{ - keyCallback(code, action, modifier); -} +void Window::keyPress(KeyCode code, InputAction action, KeyModifier modifier) { keyCallback(code, action, modifier); } -void Window::mouseMove(double x, double y) -{ - mouseMoveCallback(x, y); -} +void Window::mouseMove(double x, double y) { mouseMoveCallback(x, y); } -void Window::mouseButton(MouseButton button, InputAction action, KeyModifier modifier) -{ - mouseButtonCallback(button, action, modifier); -} +void Window::mouseButton(MouseButton button, InputAction action, KeyModifier modifier) { mouseButtonCallback(button, action, modifier); } -void Window::scroll(double x, double y) -{ - scrollCallback(x, y); -} +void Window::scroll(double x, double y) { scrollCallback(x, y); } -void Window::fileDrop(int num, const char** files) -{ - fileCallback(num, files); -} +void Window::fileDrop(int num, const char** files) { fileCallback(num, files); } -void Window::close() -{ - closeCallback(); -} +void Window::close() { closeCallback(); } -void Window::resize(int width, int height) -{ - if (width == 0 || height == 0) - { +void Window::resize(int width, int height) { + if (width == 0 || height == 0) { paused = true; return; } @@ -246,8 +176,7 @@ void Window::resize(int width, int height) resizeCallback(width, height); } -void Window::querySurface() -{ +void Window::querySurface() { vkGetPhysicalDeviceSurfaceCapabilitiesKHR(graphics->getPhysicalDevice(), surface, &capabilities); uint32 numFormats; @@ -261,20 +190,15 @@ void Window::querySurface() vkGetPhysicalDeviceSurfacePresentModesKHR(graphics->getPhysicalDevice(), surface, &numPresentModes, supportedPresentModes.data()); } -void Window::chooseSwapSurfaceFormat() -{ - for (const auto& supportedFormat : supportedFormats) - { - if (supportedFormat.format == cast(preferences.preferredFormat)) - { +void Window::chooseSwapSurfaceFormat() { + for (const auto& supportedFormat : supportedFormats) { + if (supportedFormat.format == cast(preferences.preferredFormat)) { format = supportedFormat; return; } } - for (const auto& supportedFormat : supportedFormats) - { - if (supportedFormat.format == VK_FORMAT_R8G8B8A8_SRGB && supportedFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) - { + for (const auto& supportedFormat : supportedFormats) { + if (supportedFormat.format == VK_FORMAT_R8G8B8A8_SRGB && supportedFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { format = supportedFormat; return; } @@ -282,12 +206,9 @@ void Window::chooseSwapSurfaceFormat() format = supportedFormats[0]; } -void Window::chooseSwapPresentMode() -{ - for (const auto& supportedPresentMode : supportedPresentModes) - { - if (supportedPresentMode == VK_PRESENT_MODE_MAILBOX_KHR) - { +void Window::chooseSwapPresentMode() { + for (const auto& supportedPresentMode : supportedPresentModes) { + if (supportedPresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { presentMode = supportedPresentMode; return; } @@ -295,8 +216,7 @@ void Window::chooseSwapPresentMode() presentMode = VK_PRESENT_MODE_FIFO_KHR; } -void Window::chooseSwapExtent() -{ +void Window::chooseSwapExtent() { if (capabilities.currentExtent.width != std::numeric_limits::max()) { extent = capabilities.currentExtent; return; @@ -312,8 +232,7 @@ void Window::chooseSwapExtent() extent.height = std::clamp(extent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height); } -void Window::createSwapChain() -{ +void Window::createSwapChain() { uint32 imageCount = Gfx::numFramesBuffered; VkSwapchainCreateInfoKHR createInfo = { .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, @@ -336,21 +255,21 @@ void Window::createSwapChain() VK_CHECK(vkGetSwapchainImagesKHR(graphics->getDevice(), swapchain, &imageCount, swapChainImages.data())); - for (uint32 i = 0; i < imageCount; ++i) - { - swapChainTextures[i] = new Texture2D(graphics, TextureCreateInfo{ - .format = cast(format.format), - .width = extent.width, - .height = extent.height, - .depth = 1, - .mipLevels = 1, - .layers = 1, - .elements = 1, - .samples = 1, - .usage = Gfx::SE_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | Gfx::SE_IMAGE_USAGE_TRANSFER_DST_BIT, - }, swapChainImages[i]); - if(imageAvailableFences[i] != nullptr) - { + for (uint32 i = 0; i < imageCount; ++i) { + swapChainTextures[i] = new Texture2D(graphics, + TextureCreateInfo{ + .format = cast(format.format), + .width = extent.width, + .height = extent.height, + .depth = 1, + .mipLevels = 1, + .layers = 1, + .elements = 1, + .samples = 1, + .usage = Gfx::SE_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | Gfx::SE_IMAGE_USAGE_TRANSFER_DST_BIT, + }, + swapChainImages[i]); + if (imageAvailableFences[i] != nullptr) { imageAvailableFences[i]->wait(100000); imageAvailableFences[i]->reset(); } @@ -360,24 +279,19 @@ void Window::createSwapChain() } } -Viewport::Viewport(PWindow owner, const ViewportCreateInfo &viewportInfo) - : Gfx::Viewport(owner, viewportInfo) -{ +Viewport::Viewport(PWindow owner, const ViewportCreateInfo& viewportInfo) : Gfx::Viewport(owner, viewportInfo) { handle.width = static_cast(sizeX); handle.height = static_cast(sizeY); handle.x = static_cast(offsetX); handle.y = static_cast(offsetY) + handle.height; handle.height = -handle.height; - handle.minDepth = 1.f; - handle.maxDepth = 0.f; + handle.minDepth = 1.f; + handle.maxDepth = 0.f; } -Viewport::~Viewport() -{ -} +Viewport::~Viewport() {} -void Viewport::resize(uint32 newX, uint32 newY) -{ +void Viewport::resize(uint32 newX, uint32 newY) { sizeX = newX; sizeY = newY; handle.width = static_cast(sizeX); @@ -385,8 +299,7 @@ void Viewport::resize(uint32 newX, uint32 newY) handle.height = -static_cast(sizeY); } -void Viewport::move(uint32 newOffsetX, uint32 newOffsetY) -{ +void Viewport::move(uint32 newOffsetX, uint32 newOffsetY) { offsetX = newOffsetX; offsetY = newOffsetY; handle.x = static_cast(offsetX); diff --git a/src/Engine/Graphics/Vulkan/Window.h b/src/Engine/Graphics/Vulkan/Window.h index ec3ddd1..db81e82 100644 --- a/src/Engine/Graphics/Vulkan/Window.h +++ b/src/Engine/Graphics/Vulkan/Window.h @@ -1,17 +1,15 @@ #pragma once -#include "Graphics/RenderTarget.h" #include "Graphics.h" -#include "Texture.h" +#include "Graphics/RenderTarget.h" #include "Resources.h" +#include "Texture.h" -namespace Seele -{ -namespace Vulkan -{ -class Window : public Gfx::Window -{ -public: - Window(PGraphics graphics, const WindowCreateInfo &createInfo); + +namespace Seele { +namespace Vulkan { +class Window : public Gfx::Window { + public: + Window(PGraphics graphics, const WindowCreateInfo& createInfo); virtual ~Window(); virtual void pollInput() override; virtual void beginFrame() override; @@ -25,7 +23,7 @@ public: virtual void setFileCallback(std::function callback) override; virtual void setCloseCallback(std::function callback) override; virtual void setResizeCallback(std::function callback) override; - + void keyPress(KeyCode code, InputAction action, KeyModifier modifier); void mouseMove(double x, double y); void mouseButton(MouseButton button, InputAction action, KeyModifier modifier); @@ -33,7 +31,8 @@ public: void fileDrop(int num, const char** files); void close(); void resize(int width, int height); -protected: + + protected: void querySurface(); void chooseSwapSurfaceFormat(); void chooseSwapPresentMode(); @@ -52,7 +51,7 @@ protected: VkSurfaceFormatKHR format; VkPresentModeKHR presentMode; VkExtent2D extent; - void *windowHandle; + void* windowHandle; StaticArray swapChainImages; StaticArray swapChainTextures; StaticArray imageAvailableFences; @@ -71,17 +70,17 @@ protected: }; DEFINE_REF(Window) -class Viewport : public Gfx::Viewport -{ -public: - Viewport(PWindow owner, const ViewportCreateInfo &createInfo); +class Viewport : public Gfx::Viewport { + public: + Viewport(PWindow owner, const ViewportCreateInfo& createInfo); virtual ~Viewport(); virtual void resize(uint32 newX, uint32 newY); virtual void move(uint32 newOffsetX, uint32 newOffsetY); VkViewport getHandle() const { return handle; } -private: + + private: VkViewport handle; }; DECLARE_REF(Viewport) -} -} \ No newline at end of file +} // namespace Vulkan +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/Window.cpp b/src/Engine/Graphics/Window.cpp index e39c73c..029cb15 100644 --- a/src/Engine/Graphics/Window.cpp +++ b/src/Engine/Graphics/Window.cpp @@ -3,50 +3,33 @@ using namespace Seele; using namespace Seele::Gfx; +Window::Window() {} -Window::Window() -{ -} - -Window::~Window() -{ -} +Window::~Window() {} Viewport::Viewport(PWindow owner, const ViewportCreateInfo& viewportInfo) - : sizeX(std::min(owner->getFramebufferWidth(), viewportInfo.dimensions.size.x)) - , sizeY(std::min(owner->getFramebufferHeight(), viewportInfo.dimensions.size.y)) - , offsetX(viewportInfo.dimensions.offset.x) - , offsetY(viewportInfo.dimensions.offset.y) - , fieldOfView(viewportInfo.fieldOfView) - , samples(viewportInfo.numSamples) - , owner(owner) -{ -} + : sizeX(std::min(owner->getFramebufferWidth(), viewportInfo.dimensions.size.x)), + sizeY(std::min(owner->getFramebufferHeight(), viewportInfo.dimensions.size.y)), offsetX(viewportInfo.dimensions.offset.x), + offsetY(viewportInfo.dimensions.offset.y), fieldOfView(viewportInfo.fieldOfView), samples(viewportInfo.numSamples), owner(owner) {} -Viewport::~Viewport() -{ -} +Viewport::~Viewport() {} -Matrix4 Viewport::getProjectionMatrix() const -{ - if (fieldOfView > 0.0f) - { - //float h = 1.0 / tan(fieldOfView * 0.5); - //float w = h / (sizeX / static_cast(sizeY)); - //float zFar = 1000.0f; - //float zNear = 0.1f; - //float a = -zNear / (zFar - zNear); - //float b = (zNear * zFar) / (zFar - zNear); - //return Matrix4( - // w, 0, 0, 0, - // 0, -h, 0, 0, - // 0, 0, a, b, - // 0, 0, 1, 0 - //); - return glm::perspective(fieldOfView, sizeX / static_cast(sizeY), 0.1f, 10000.0f); - } - else - { - return glm::ortho(0.0f, (float)sizeX, (float)sizeY, 0.0f); - } +Matrix4 Viewport::getProjectionMatrix() const { + if (fieldOfView > 0.0f) { + // float h = 1.0 / tan(fieldOfView * 0.5); + // float w = h / (sizeX / static_cast(sizeY)); + // float zFar = 1000.0f; + // float zNear = 0.1f; + // float a = -zNear / (zFar - zNear); + // float b = (zNear * zFar) / (zFar - zNear); + // return Matrix4( + // w, 0, 0, 0, + // 0, -h, 0, 0, + // 0, 0, a, b, + // 0, 0, 1, 0 + //); + return glm::perspective(fieldOfView, sizeX / static_cast(sizeY), 0.1f, 10000.0f); + } else { + return glm::ortho(0.0f, (float)sizeX, (float)sizeY, 0.0f); + } } \ No newline at end of file diff --git a/src/Engine/Graphics/Window.h b/src/Engine/Graphics/Window.h index e3dcf73..cde88dd 100644 --- a/src/Engine/Graphics/Window.h +++ b/src/Engine/Graphics/Window.h @@ -3,13 +3,10 @@ #include "Texture.h" #include -namespace Seele -{ -namespace Gfx -{ -class Window -{ -public: +namespace Seele { +namespace Gfx { +class Window { + public: Window(); virtual ~Window(); virtual void pollInput() = 0; @@ -24,23 +21,12 @@ public: virtual void setFileCallback(std::function callback) = 0; virtual void setCloseCallback(std::function callback) = 0; virtual void setResizeCallback(std::function callback) = 0; - constexpr SeFormat getSwapchainFormat() const - { - return framebufferFormat; - } - constexpr uint32 getFramebufferWidth() const - { - return framebufferWidth; - } - constexpr uint32 getFramebufferHeight() const - { - return framebufferHeight; - } - constexpr bool isPaused() const - { - return paused; - } -protected: + constexpr SeFormat getSwapchainFormat() const { return framebufferFormat; } + constexpr uint32 getFramebufferWidth() const { return framebufferWidth; } + constexpr uint32 getFramebufferHeight() const { return framebufferHeight; } + constexpr bool isPaused() const { return paused; } + + protected: SeFormat framebufferFormat; uint32 framebufferWidth; uint32 framebufferHeight; @@ -48,9 +34,8 @@ protected: }; DEFINE_REF(Window) -class Viewport -{ -public: +class Viewport { + public: Viewport(PWindow owner, const ViewportCreateInfo& createInfo); virtual ~Viewport(); virtual void resize(uint32 newX, uint32 newY) = 0; @@ -62,7 +47,8 @@ public: constexpr uint32 getOffsetY() const { return offsetY; } constexpr Gfx::SeSampleCountFlags getSamples() const { return samples; } Matrix4 getProjectionMatrix() const; -protected: + + protected: uint32 sizeX; uint32 sizeY; uint32 offsetX; @@ -73,5 +59,5 @@ protected: }; DEFINE_REF(Viewport) -} -} \ No newline at end of file +} // namespace Gfx +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Graphics/slang-compile.cpp b/src/Engine/Graphics/slang-compile.cpp index 0501fbd..5a37d3b 100644 --- a/src/Engine/Graphics/slang-compile.cpp +++ b/src/Engine/Graphics/slang-compile.cpp @@ -1,17 +1,29 @@ #include "slang-compile.h" -#include #include "Containers/Array.h" #include #include +#include -#define CHECK_RESULT(x) {SlangResult r = x; if(r != 0) {throw std::runtime_error(fmt::format("Error: {0}", r));}} -#define CHECK_DIAGNOSTICS() {if(diagnostics) {std::cout << (const char*)diagnostics->getBufferPointer() << std::endl; assert(false);}} -Slang::ComPtr Seele::generateShader(const ShaderCreateInfo& createInfo, SlangCompileTarget target, Map& paramMapping) -{ +#define CHECK_RESULT(x) \ + { \ + SlangResult r = x; \ + if (r != 0) { \ + throw std::runtime_error(fmt::format("Error: {0}", r)); \ + } \ + } +#define CHECK_DIAGNOSTICS() \ + { \ + if (diagnostics) { \ + std::cout << (const char*)diagnostics->getBufferPointer() << std::endl; \ + assert(false); \ + } \ + } + +Slang::ComPtr Seele::generateShader(const ShaderCreateInfo& createInfo, SlangCompileTarget target, + Map& paramMapping) { thread_local Slang::ComPtr globalSession; - if(!globalSession) - { + if (!globalSession) { slang::createGlobalSession(globalSession.writeRef()); } slang::SessionDesc sessionDesc; @@ -34,8 +46,7 @@ Slang::ComPtr Seele::generateShader(const ShaderCreateInfo& create sessionDesc.compilerOptionEntryCount = option.size(); sessionDesc.defaultMatrixLayoutMode = SLANG_MATRIX_LAYOUT_COLUMN_MAJOR; Array macros; - for(const auto& [key, val] : createInfo.defines) - { + for (const auto& [key, val] : createInfo.defines) { macros.add(slang::PreprocessorMacroDesc{ .name = key, .value = val, @@ -57,8 +68,7 @@ Slang::ComPtr Seele::generateShader(const ShaderCreateInfo& create Slang::ComPtr diagnostics; Array modules; Slang::ComPtr entrypoint; - for (const auto& moduleName : createInfo.additionalModules) - { + for (const auto& moduleName : createInfo.additionalModules) { modules.add(session->loadModule(moduleName.c_str(), diagnostics.writeRef())); CHECK_DIAGNOSTICS(); } @@ -73,7 +83,7 @@ Slang::ComPtr Seele::generateShader(const ShaderCreateInfo& create session->createCompositeComponentType(modules.data(), modules.size(), moduleComposition.writeRef(), diagnostics.writeRef()); CHECK_DIAGNOSTICS(); - + Slang::ComPtr linkedProgram; moduleComposition->link(linkedProgram.writeRef(), diagnostics.writeRef()); @@ -84,38 +94,26 @@ Slang::ComPtr Seele::generateShader(const ShaderCreateInfo& create CHECK_DIAGNOSTICS(); Array specialization; - for(const auto& [key, value] : createInfo.typeParameter) - { + for (const auto& [key, value] : createInfo.typeParameter) { specialization.add(slang::SpecializationArg::fromType(reflection->findTypeByName(value))); } Slang::ComPtr specializedComponent; linkedProgram->specialize(specialization.data(), specialization.size(), specializedComponent.writeRef(), diagnostics.writeRef()); CHECK_DIAGNOSTICS(); - + Slang::ComPtr kernelBlob; - specializedComponent->getEntryPointCode( - 0, - 0, - kernelBlob.writeRef(), - diagnostics.writeRef() - ); + specializedComponent->getEntryPointCode(0, 0, kernelBlob.writeRef(), diagnostics.writeRef()); CHECK_DIAGNOSTICS(); slang::ProgramLayout* signature = specializedComponent->getLayout(0, diagnostics.writeRef()); CHECK_DIAGNOSTICS(); - for(size_t i = 0; i < signature->getParameterCount(); ++i) - { + for (size_t i = 0; i < signature->getParameterCount(); ++i) { auto param = signature->getParameterByIndex(i); // workaround - if (std::strcmp(param->getName(), "pVertexData") == 0) - { + if (std::strcmp(param->getName(), "pVertexData") == 0) { paramMapping[param->getName()] = 1; - } - else if (std::strcmp(param->getName(), "pMaterial") == 0) - { + } else if (std::strcmp(param->getName(), "pMaterial") == 0) { paramMapping[param->getName()] = 4; - } - else - { + } else { paramMapping[param->getName()] = param->getBindingIndex(); } } diff --git a/src/Engine/Graphics/slang-compile.h b/src/Engine/Graphics/slang-compile.h index 7a9989e..89f9a2f 100644 --- a/src/Engine/Graphics/slang-compile.h +++ b/src/Engine/Graphics/slang-compile.h @@ -4,5 +4,6 @@ #include namespace Seele { -Slang::ComPtr generateShader(const ShaderCreateInfo& createInfo, SlangCompileTarget target, Map& paramMapping); +Slang::ComPtr generateShader(const ShaderCreateInfo& createInfo, SlangCompileTarget target, + Map& paramMapping); } diff --git a/src/Engine/Material/Material.cpp b/src/Engine/Material/Material.cpp index fa6f294..5be1a2d 100644 --- a/src/Engine/Material/Material.cpp +++ b/src/Engine/Material/Material.cpp @@ -1,60 +1,35 @@ #include "Material.h" #include "Graphics/Enums.h" -#include "Serialization/Serialization.h" -#include "Window/WindowManager.h" -#include "MaterialInstance.h" #include "Graphics/Graphics.h" #include "Graphics/Shader.h" +#include "MaterialInstance.h" +#include "Serialization/Serialization.h" +#include "Window/WindowManager.h" #include + using namespace Seele; std::atomic_uint64_t Material::materialIdCounter = 0; Array Material::materials; -Material::Material() -{ -} +Material::Material() {} -Material::Material(Gfx::PGraphics graphics, - Gfx::ODescriptorLayout layout, - uint32 uniformDataSize, - uint32 uniformBinding, - std::string materialName, - Array expressions, - Array parameter, - MaterialNode brdf) - : graphics(graphics) - , uniformDataSize(uniformDataSize) - , uniformBinding(uniformBinding) - , instanceId(0) - , layout(std::move(layout)) - , materialName(materialName) - , codeExpressions(std::move(expressions)) - , parameters(std::move(parameter)) - , brdf(std::move(brdf)) - , materialId(materialIdCounter++) -{ +Material::Material(Gfx::PGraphics graphics, Gfx::ODescriptorLayout layout, uint32 uniformDataSize, uint32 uniformBinding, + std::string materialName, Array expressions, Array parameter, MaterialNode brdf) + : graphics(graphics), uniformDataSize(uniformDataSize), uniformBinding(uniformBinding), instanceId(0), layout(std::move(layout)), + materialName(materialName), codeExpressions(std::move(expressions)), parameters(std::move(parameter)), brdf(std::move(brdf)), + materialId(materialIdCounter++) { materials.add(this); } -Material::~Material() -{ +Material::~Material() {} + +OMaterialInstance Material::instantiate() { + return new MaterialInstance(instanceId++, graphics, codeExpressions, parameters, uniformBinding, uniformDataSize); } -OMaterialInstance Material::instantiate() -{ - return new MaterialInstance( - instanceId++, - graphics, - codeExpressions, - parameters, - uniformBinding, - uniformDataSize); -} - -void Material::save(ArchiveBuffer& buffer) const -{ +void Material::save(ArchiveBuffer& buffer) const { Serialization::save(buffer, uniformDataSize); Serialization::save(buffer, uniformBinding); Serialization::save(buffer, instanceId); @@ -65,8 +40,7 @@ void Material::save(ArchiveBuffer& buffer) const Serialization::save(buffer, layout->getName()); const auto& bindings = layout->getBindings(); Serialization::save(buffer, bindings.size()); - for (const auto& binding : bindings) - { + for (const auto& binding : bindings) { Serialization::save(buffer, binding.binding); Serialization::save(buffer, binding.descriptorType); Serialization::save(buffer, binding.textureType); @@ -76,8 +50,7 @@ void Material::save(ArchiveBuffer& buffer) const } } -void Material::load(ArchiveBuffer& buffer) -{ +void Material::load(ArchiveBuffer& buffer) { graphics = buffer.getGraphics(); Serialization::load(buffer, uniformDataSize); Serialization::load(buffer, uniformBinding); @@ -91,8 +64,7 @@ void Material::load(ArchiveBuffer& buffer) uint64 numBindings; Serialization::load(buffer, numBindings); layout = graphics->createDescriptorLayout(descriptorName); - for (uint64 i = 0; i < numBindings; ++i) - { + for (uint64 i = 0; i < numBindings; ++i) { uint32 binding; Serialization::load(buffer, binding); @@ -111,21 +83,27 @@ void Material::load(ArchiveBuffer& buffer) Gfx::SeShaderStageFlags shaderStages; Serialization::load(buffer, shaderStages); - layout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = binding, .descriptorType = descriptorType, .textureType = textureType, .descriptorCount = descriptorCount, .bindingFlags = bindingFlags, .shaderStages = shaderStages,}); + layout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = binding, + .descriptorType = descriptorType, + .textureType = textureType, + .descriptorCount = descriptorCount, + .bindingFlags = bindingFlags, + .shaderStages = shaderStages, + }); } layout->create(); materialId = materialIdCounter++; } -void Material::compile() -{ - std::ofstream codeStream("./shaders/generated/"+materialName+".slang"); +void Material::compile() { + std::ofstream codeStream("./shaders/generated/" + materialName + ".slang"); codeStream << "import BRDF;\n"; codeStream << "import MaterialParameter;\n"; codeStream << "struct " << materialName << "{\n"; - for(const auto& parameter : parameters) - { - PShaderParameter handle = PShaderExpression(*codeExpressions.find([¶meter](const OShaderExpression& exp) {return exp->key == parameter; })); + for (const auto& parameter : parameters) { + PShaderParameter handle = + PShaderExpression(*codeExpressions.find([¶meter](const OShaderExpression& exp) { return exp->key == parameter; })); handle->generateDeclaration(codeStream); } codeStream << "\ttypedef " << brdf.profile << " BRDF;\n"; @@ -133,12 +111,10 @@ void Material::compile() codeStream << "\t\t" << brdf.profile << " result;\n"; Map varState; // initialize variable state - for(const auto& expr :codeExpressions) - { + for (const auto& expr : codeExpressions) { codeStream << "\t\t" << expr->evaluate(varState); } - for(const auto& [name, exp] : brdf.variables) - { + for (const auto& [name, exp] : brdf.variables) { codeStream << "\t\tresult." << name << " = " << varState[exp] << ";" << std::endl; } codeStream << "\t\treturn result;\n"; diff --git a/src/Engine/Material/Material.h b/src/Engine/Material/Material.h index c4893d9..660a4ca 100644 --- a/src/Engine/Material/Material.h +++ b/src/Engine/Material/Material.h @@ -1,22 +1,15 @@ #pragma once -#include "ShaderExpression.h" #include "Graphics/Descriptor.h" +#include "ShaderExpression.h" -namespace Seele -{ + +namespace Seele { DECLARE_REF(MaterialInstance) -class Material -{ -public: +class Material { + public: Material(); - Material(Gfx::PGraphics graphics, - Gfx::ODescriptorLayout layout, - uint32 uniformDataSize, - uint32 uniformBinding, - std::string materialName, - Array expressions, - Array parameter, - MaterialNode brdf); + Material(Gfx::PGraphics graphics, Gfx::ODescriptorLayout layout, uint32 uniformDataSize, uint32 uniformBinding, + std::string materialName, Array expressions, Array parameter, MaterialNode brdf); ~Material(); const Gfx::PDescriptorLayout getDescriptorLayout() const { return layout; } Gfx::PDescriptorLayout getDescriptorLayout() { return layout; } @@ -30,7 +23,7 @@ public: void compile(); -private: + private: Gfx::PGraphics graphics; uint32 uniformDataSize; uint32 uniformBinding; diff --git a/src/Engine/Material/MaterialInstance.cpp b/src/Engine/Material/MaterialInstance.cpp index 99cd494..913e989 100644 --- a/src/Engine/Material/MaterialInstance.cpp +++ b/src/Engine/Material/MaterialInstance.cpp @@ -1,40 +1,30 @@ #include "MaterialInstance.h" -#include "Material.h" #include "Graphics/Graphics.h" +#include "Material.h" + using namespace Seele; -MaterialInstance::MaterialInstance() -{ -} +MaterialInstance::MaterialInstance() {} -MaterialInstance::MaterialInstance(uint64 id, - Gfx::PGraphics graphics, - Array& expressions, - Array params, - uint32 uniformBinding, - uint32 uniformSize) - : graphics(graphics) - , uniformBinding(uniformBinding) - , id(id) -{ - if(uniformSize > 0) - { +MaterialInstance::MaterialInstance(uint64 id, Gfx::PGraphics graphics, Array& expressions, Array params, + uint32 uniformBinding, uint32 uniformSize) + : graphics(graphics), uniformBinding(uniformBinding), id(id) { + if (uniformSize > 0) { uniformBuffer = graphics->createUniformBuffer(UniformBufferCreateInfo{ - .sourceData = { + .sourceData = + { .size = uniformSize, }, - .dynamic = true, - } - ); + .dynamic = true, + }); } uniformData.resize(uniformSize); ArchiveBuffer buffer(graphics); parameters.reserve(params.size()); - for (size_t i = 0; i < params.size(); ++i) - { + for (size_t i = 0; i < params.size(); ++i) { const std::string& name = params[i]; - Serialization::save(buffer, *expressions.find([&name](const OShaderExpression& p) {return p->key == name; })); + Serialization::save(buffer, *expressions.find([&name](const OShaderExpression& p) { return p->key == name; })); buffer.rewind(); OShaderParameter param; Serialization::load(buffer, param); @@ -43,21 +33,15 @@ MaterialInstance::MaterialInstance(uint64 id, } } -MaterialInstance::~MaterialInstance() -{ - -} +MaterialInstance::~MaterialInstance() {} -void MaterialInstance::updateDescriptor() -{ +void MaterialInstance::updateDescriptor() { Gfx::PDescriptorLayout layout = baseMaterial->getMaterial()->getDescriptorLayout(); descriptor = layout->allocateDescriptorSet(); - for (auto& param : parameters) - { + for (auto& param : parameters) { param->updateDescriptorSet(descriptor, uniformData.data()); } - if(uniformData.size() > 0) - { + if (uniformData.size() > 0) { uniformBuffer->updateContents(DataSource{ .size = uniformData.size(), .data = uniformData.data(), @@ -67,36 +51,29 @@ void MaterialInstance::updateDescriptor() descriptor->writeChanges(); } -Gfx::PDescriptorSet MaterialInstance::getDescriptorSet() const -{ - return descriptor; -} +Gfx::PDescriptorSet MaterialInstance::getDescriptorSet() const { return descriptor; } -void MaterialInstance::setBaseMaterial(PMaterialAsset asset) -{ - if(uniformData.size() > 0) - { +void MaterialInstance::setBaseMaterial(PMaterialAsset asset) { + if (uniformData.size() > 0) { uniformBuffer = graphics->createUniformBuffer(UniformBufferCreateInfo{ - .sourceData = { + .sourceData = + { .size = uniformData.size(), }, - .dynamic = true, - } - ); + .dynamic = true, + }); } baseMaterial = asset; } -void MaterialInstance::save(ArchiveBuffer& buffer) const -{ +void MaterialInstance::save(ArchiveBuffer& buffer) const { Serialization::save(buffer, uniformData); Serialization::save(buffer, uniformBinding); Serialization::save(buffer, parameters); Serialization::save(buffer, id); } -void MaterialInstance::load(ArchiveBuffer& buffer) -{ +void MaterialInstance::load(ArchiveBuffer& buffer) { graphics = buffer.getGraphics(); Serialization::load(buffer, uniformData); Serialization::load(buffer, uniformBinding); diff --git a/src/Engine/Material/MaterialInstance.h b/src/Engine/Material/MaterialInstance.h index 578ce6e..7ea01c2 100644 --- a/src/Engine/Material/MaterialInstance.h +++ b/src/Engine/Material/MaterialInstance.h @@ -1,20 +1,15 @@ #pragma once -#include "Material.h" -#include "Graphics/Buffer.h" #include "Asset/MaterialAsset.h" +#include "Graphics/Buffer.h" +#include "Material.h" -namespace Seele -{ -class MaterialInstance -{ -public: + +namespace Seele { +class MaterialInstance { + public: MaterialInstance(); - MaterialInstance(uint64 id, - Gfx::PGraphics graphics, - Array& expressions, - Array params, - uint32 uniformBinding, - uint32 uniformSize); + MaterialInstance(uint64 id, Gfx::PGraphics graphics, Array& expressions, Array params, + uint32 uniformBinding, uint32 uniformSize); ~MaterialInstance(); void updateDescriptor(); Gfx::PDescriptorSet getDescriptorSet() const; @@ -26,7 +21,7 @@ public: void save(ArchiveBuffer& buffer) const; void load(ArchiveBuffer& buffer); -private: + private: Gfx::PGraphics graphics; Array uniformData; uint32 uniformBinding; diff --git a/src/Engine/Material/ShaderExpression.cpp b/src/Engine/Material/ShaderExpression.cpp index 3876433..31281bc 100644 --- a/src/Engine/Material/ShaderExpression.cpp +++ b/src/Engine/Material/ShaderExpression.cpp @@ -1,195 +1,139 @@ #include "ShaderExpression.h" -#include "Graphics/Resources.h" -#include "Asset/TextureAsset.h" #include "Asset/AssetRegistry.h" -#include "Graphics/Graphics.h" +#include "Asset/TextureAsset.h" #include "Graphics/Descriptor.h" -#include +#include "Graphics/Graphics.h" +#include "Graphics/Resources.h" #include +#include + using namespace Seele; -void ExpressionInput::save(ArchiveBuffer& buffer) const -{ +void ExpressionInput::save(ArchiveBuffer& buffer) const { Serialization::save(buffer, source); Serialization::save(buffer, type); } -void ExpressionInput::load(ArchiveBuffer& buffer) -{ +void ExpressionInput::load(ArchiveBuffer& buffer) { Serialization::load(buffer, source); Serialization::load(buffer, type); } -void ExpressionOutput::save(ArchiveBuffer& buffer) const -{ +void ExpressionOutput::save(ArchiveBuffer& buffer) const { Serialization::save(buffer, name); Serialization::save(buffer, type); } -void ExpressionOutput::load(ArchiveBuffer& buffer) -{ +void ExpressionOutput::load(ArchiveBuffer& buffer) { Serialization::load(buffer, name); Serialization::load(buffer, type); } -ShaderExpression::ShaderExpression() -{ -} +ShaderExpression::ShaderExpression() {} -ShaderExpression::ShaderExpression(std::string key) - : key(key) -{ -} +ShaderExpression::ShaderExpression(std::string key) : key(key) {} -ShaderExpression::~ShaderExpression() -{ -} +ShaderExpression::~ShaderExpression() {} -void ShaderExpression::save(ArchiveBuffer& buffer) const -{ +void ShaderExpression::save(ArchiveBuffer& buffer) const { Serialization::save(buffer, inputs); Serialization::save(buffer, output); Serialization::save(buffer, key); } -void ShaderExpression::load(ArchiveBuffer& buffer) -{ +void ShaderExpression::load(ArchiveBuffer& buffer) { Serialization::load(buffer, inputs); Serialization::load(buffer, output); Serialization::load(buffer, key); } -ShaderParameter::ShaderParameter(std::string name, uint32 byteOffset, uint32 binding) - : ShaderExpression(name) - , byteOffset(byteOffset) - , binding(binding) -{ -} +ShaderParameter::ShaderParameter(std::string name, uint32 byteOffset, uint32 binding) + : ShaderExpression(name), byteOffset(byteOffset), binding(binding) {} -ShaderParameter::~ShaderParameter() -{ -} +ShaderParameter::~ShaderParameter() {} -std::string ShaderParameter::evaluate(Map& varState) const -{ +std::string ShaderParameter::evaluate(Map& varState) const { varState[key] = key; return ""; } -void ShaderParameter::save(ArchiveBuffer& buffer) const -{ +void ShaderParameter::save(ArchiveBuffer& buffer) const { ShaderExpression::save(buffer); Serialization::save(buffer, byteOffset); Serialization::save(buffer, binding); } -void ShaderParameter::load(ArchiveBuffer& buffer) -{ +void ShaderParameter::load(ArchiveBuffer& buffer) { ShaderExpression::load(buffer); Serialization::load(buffer, byteOffset); Serialization::load(buffer, binding); } -FloatParameter::FloatParameter(std::string name, float data, uint32 byteOffset, uint32 binding) - : ShaderParameter(name, byteOffset, binding) - , data(data) -{ +FloatParameter::FloatParameter(std::string name, float data, uint32 byteOffset, uint32 binding) + : ShaderParameter(name, byteOffset, binding), data(data) { output.name = name; output.type = ExpressionType::FLOAT; } -FloatParameter::~FloatParameter() -{ -} +FloatParameter::~FloatParameter() {} -void FloatParameter::save(ArchiveBuffer& buffer) const -{ +void FloatParameter::save(ArchiveBuffer& buffer) const { ShaderParameter::save(buffer); Serialization::save(buffer, data); } -void FloatParameter::load(ArchiveBuffer& buffer) -{ +void FloatParameter::load(ArchiveBuffer& buffer) { ShaderParameter::load(buffer); Serialization::load(buffer, data); } -void FloatParameter::updateDescriptorSet(Gfx::PDescriptorSet, uint8* dst) -{ - std::memcpy(dst + byteOffset, &data, sizeof(float)); -} +void FloatParameter::updateDescriptorSet(Gfx::PDescriptorSet, uint8* dst) { std::memcpy(dst + byteOffset, &data, sizeof(float)); } -void FloatParameter::generateDeclaration(std::ofstream& stream) const -{ - stream << "\tfloat " << key << ";\n"; -} +void FloatParameter::generateDeclaration(std::ofstream& stream) const { stream << "\tfloat " << key << ";\n"; } -VectorParameter::VectorParameter(std::string name, Vector data, uint32 byteOffset, uint32 binding) - : ShaderParameter(name, byteOffset, binding) - , data(data) -{ +VectorParameter::VectorParameter(std::string name, Vector data, uint32 byteOffset, uint32 binding) + : ShaderParameter(name, byteOffset, binding), data(data) { output.name = name; output.type = ExpressionType::FLOAT3; } -VectorParameter::~VectorParameter() -{ -} +VectorParameter::~VectorParameter() {} -void VectorParameter::updateDescriptorSet(Gfx::PDescriptorSet, uint8* dst) -{ - std::memcpy(dst + byteOffset, &data, sizeof(Vector)); -} +void VectorParameter::updateDescriptorSet(Gfx::PDescriptorSet, uint8* dst) { std::memcpy(dst + byteOffset, &data, sizeof(Vector)); } -void VectorParameter::generateDeclaration(std::ofstream& stream) const -{ - stream << "\tfloat3 " << key << ";\n"; -} +void VectorParameter::generateDeclaration(std::ofstream& stream) const { stream << "\tfloat3 " << key << ";\n"; } -void VectorParameter::save(ArchiveBuffer& buffer) const -{ +void VectorParameter::save(ArchiveBuffer& buffer) const { ShaderParameter::save(buffer); Serialization::save(buffer, data); } -void VectorParameter::load(ArchiveBuffer& buffer) -{ +void VectorParameter::load(ArchiveBuffer& buffer) { ShaderParameter::load(buffer); Serialization::load(buffer, data); } -TextureParameter::TextureParameter(std::string name, PTextureAsset asset, uint32 binding) - : ShaderParameter(name, 0, binding) - , data(asset) -{ +TextureParameter::TextureParameter(std::string name, PTextureAsset asset, uint32 binding) : ShaderParameter(name, 0, binding), data(asset) { output.name = name; output.type = ExpressionType::TEXTURE; } -TextureParameter::~TextureParameter() -{ -} +TextureParameter::~TextureParameter() {} -void TextureParameter::updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, uint8*) -{ +void TextureParameter::updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, uint8*) { descriptorSet->updateTexture(binding, data->getTexture()); } -void TextureParameter::generateDeclaration(std::ofstream& stream) const -{ - stream << "\tTexture2D " << key << ";\n"; -} +void TextureParameter::generateDeclaration(std::ofstream& stream) const { stream << "\tTexture2D " << key << ";\n"; } -void TextureParameter::save(ArchiveBuffer& buffer) const -{ +void TextureParameter::save(ArchiveBuffer& buffer) const { ShaderParameter::save(buffer); Serialization::save(buffer, data->getFolderPath()); Serialization::save(buffer, data->getName()); } -void TextureParameter::load(ArchiveBuffer& buffer) -{ +void TextureParameter::load(ArchiveBuffer& buffer) { ShaderParameter::load(buffer); std::string folder; Serialization::load(buffer, folder); @@ -198,73 +142,46 @@ void TextureParameter::load(ArchiveBuffer& buffer) data = AssetRegistry::findTexture(folder, filename); } -SamplerParameter::SamplerParameter(std::string name, Gfx::OSampler sampler, uint32 binding) - : ShaderParameter(name, 0, binding) - , data(std::move(sampler)) -{ +SamplerParameter::SamplerParameter(std::string name, Gfx::OSampler sampler, uint32 binding) + : ShaderParameter(name, 0, binding), data(std::move(sampler)) { output.name = name; output.type = ExpressionType::SAMPLER; } -SamplerParameter::~SamplerParameter() -{ - -} +SamplerParameter::~SamplerParameter() {} -void SamplerParameter::updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, uint8*) -{ - descriptorSet->updateSampler(binding, data); -} +void SamplerParameter::updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, uint8*) { descriptorSet->updateSampler(binding, data); } -void SamplerParameter::generateDeclaration(std::ofstream& stream) const -{ - stream << "\tSamplerState " << key << ";\n"; -} +void SamplerParameter::generateDeclaration(std::ofstream& stream) const { stream << "\tSamplerState " << key << ";\n"; } -void SamplerParameter::save(ArchiveBuffer& buffer) const -{ - ShaderParameter::save(buffer); -} +void SamplerParameter::save(ArchiveBuffer& buffer) const { ShaderParameter::save(buffer); } -void SamplerParameter::load(ArchiveBuffer& buffer) -{ +void SamplerParameter::load(ArchiveBuffer& buffer) { ShaderParameter::load(buffer); data = buffer.getGraphics()->createSampler(SamplerCreateInfo{}); } -CombinedTextureParameter::CombinedTextureParameter(std::string name, PTextureAsset data, Gfx::OSampler sampler, uint32 binding) - : ShaderParameter(name, 0, binding) - , data(data) - , sampler(std::move(sampler)) -{ +CombinedTextureParameter::CombinedTextureParameter(std::string name, PTextureAsset data, Gfx::OSampler sampler, uint32 binding) + : ShaderParameter(name, 0, binding), data(data), sampler(std::move(sampler)) { output.name = name; output.type = ExpressionType::TEXTURE; } -CombinedTextureParameter::~CombinedTextureParameter() -{ - -} +CombinedTextureParameter::~CombinedTextureParameter() {} -void CombinedTextureParameter::updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, uint8*) -{ +void CombinedTextureParameter::updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, uint8*) { descriptorSet->updateTexture(binding, data->getTexture(), sampler); } -void CombinedTextureParameter::generateDeclaration(std::ofstream& stream) const -{ - stream << "\tSampler2D " << key << ";\n"; -} +void CombinedTextureParameter::generateDeclaration(std::ofstream& stream) const { stream << "\tSampler2D " << key << ";\n"; } -void CombinedTextureParameter::save(ArchiveBuffer& buffer) const -{ +void CombinedTextureParameter::save(ArchiveBuffer& buffer) const { ShaderParameter::save(buffer); Serialization::save(buffer, data->getFolderPath()); Serialization::save(buffer, data->getName()); } -void CombinedTextureParameter::load(ArchiveBuffer& buffer) -{ +void CombinedTextureParameter::load(ArchiveBuffer& buffer) { ShaderParameter::load(buffer); std::string folder; Serialization::load(buffer, folder); @@ -274,146 +191,99 @@ void CombinedTextureParameter::load(ArchiveBuffer& buffer) sampler = buffer.getGraphics()->createSampler({}); } -ConstantExpression::ConstantExpression() -{ -} +ConstantExpression::ConstantExpression() {} -ConstantExpression::ConstantExpression(std::string expr, ExpressionType type) - : expr(expr) -{ +ConstantExpression::ConstantExpression(std::string expr, ExpressionType type) : expr(expr) { output.name = "cexpr"; output.type = type; } -ConstantExpression::~ConstantExpression() -{ - -} +ConstantExpression::~ConstantExpression() {} -std::string ConstantExpression::evaluate(Map& varState) const -{ +std::string ConstantExpression::evaluate(Map& varState) const { std::string varName = fmt::format("const_exp_{}", key); varState[key] = varName; return fmt::format("let {} = {};\n", varName, expr); } -void ConstantExpression::save(ArchiveBuffer& buffer) const -{ +void ConstantExpression::save(ArchiveBuffer& buffer) const { ShaderExpression::save(buffer); Serialization::save(buffer, expr); } -void ConstantExpression::load(ArchiveBuffer& buffer) -{ +void ConstantExpression::load(ArchiveBuffer& buffer) { ShaderExpression::load(buffer); Serialization::load(buffer, expr); } -AddExpression::AddExpression() -{ +AddExpression::AddExpression() {} -} +AddExpression::~AddExpression() {} -AddExpression::~AddExpression() -{ - -} - -std::string AddExpression::evaluate(Map& varState) const -{ +std::string AddExpression::evaluate(Map& varState) const { std::string varName = fmt::format("exp_{}", key); varState[key] = varName; std::string lhs = inputs.at("lhs").source; - if (varState.contains(lhs)) - { + if (varState.contains(lhs)) { lhs = varState[lhs]; } std::string rhs = inputs.at("rhs").source; - if (varState.contains(rhs)) - { + if (varState.contains(rhs)) { rhs = varState[rhs]; } return fmt::format("let {} = {} + {};\n", varName, lhs, rhs); } -void AddExpression::save(ArchiveBuffer& buffer) const -{ - ShaderExpression::save(buffer); -} +void AddExpression::save(ArchiveBuffer& buffer) const { ShaderExpression::save(buffer); } -void AddExpression::load(ArchiveBuffer& buffer) -{ - ShaderExpression::load(buffer); -} +void AddExpression::load(ArchiveBuffer& buffer) { ShaderExpression::load(buffer); } -std::string SubExpression::evaluate(Map& varState) const -{ +std::string SubExpression::evaluate(Map& varState) const { std::string varName = fmt::format("exp_{}", key); varState[key] = varName; std::string lhs = inputs.at("lhs").source; - if (varState.contains(lhs)) - { + if (varState.contains(lhs)) { lhs = varState[lhs]; } std::string rhs = inputs.at("rhs").source; - if (varState.contains(rhs)) - { + if (varState.contains(rhs)) { rhs = varState[rhs]; } return fmt::format("let {} = {} - {};\n", varName, lhs, rhs); } -void SubExpression::save(ArchiveBuffer& buffer) const -{ - ShaderExpression::save(buffer); -} +void SubExpression::save(ArchiveBuffer& buffer) const { ShaderExpression::save(buffer); } -void SubExpression::load(ArchiveBuffer& buffer) -{ - ShaderExpression::load(buffer); -} +void SubExpression::load(ArchiveBuffer& buffer) { ShaderExpression::load(buffer); } -std::string MulExpression::evaluate(Map& varState) const -{ +std::string MulExpression::evaluate(Map& varState) const { std::string varName = fmt::format("exp_{}", key); varState[key] = varName; std::string lhs = inputs.at("lhs").source; - if (varState.contains(lhs)) - { + if (varState.contains(lhs)) { lhs = varState[lhs]; } std::string rhs = inputs.at("rhs").source; - if (varState.contains(rhs)) - { + if (varState.contains(rhs)) { rhs = varState[rhs]; } return fmt::format("let {} = {} * {};\n", varName, lhs, rhs); } -void MulExpression::save(ArchiveBuffer& buffer) const -{ - ShaderExpression::save(buffer); -} +void MulExpression::save(ArchiveBuffer& buffer) const { ShaderExpression::save(buffer); } -void MulExpression::load(ArchiveBuffer& buffer) -{ - ShaderExpression::load(buffer); -} +void MulExpression::load(ArchiveBuffer& buffer) { ShaderExpression::load(buffer); } -std::string SwizzleExpression::evaluate(Map& varState) const -{ +std::string SwizzleExpression::evaluate(Map& varState) const { std::string varName = fmt::format("exp_{}", key); std::string swizzle = ""; - for(uint32 i = 0; i < 4; ++i) - { - if(comp[i] == -1) - { + for (uint32 i = 0; i < 4; ++i) { + if (comp[i] == -1) { break; } - switch (comp[i]) - { + switch (comp[i]) { case 0: swizzle += "x"; break; @@ -434,54 +304,40 @@ std::string SwizzleExpression::evaluate(Map& varState) return fmt::format("let {} = {}.{};\n", varName, varState[inputs.at("target").source], swizzle); } -void SwizzleExpression::save(ArchiveBuffer& buffer) const -{ +void SwizzleExpression::save(ArchiveBuffer& buffer) const { ShaderExpression::save(buffer); Serialization::save(buffer, comp); } -void SwizzleExpression::load(ArchiveBuffer& buffer) -{ +void SwizzleExpression::load(ArchiveBuffer& buffer) { ShaderExpression::load(buffer); Serialization::load(buffer, comp); } -std::string SampleExpression::evaluate(Map& varState) const -{ +std::string SampleExpression::evaluate(Map& varState) const { std::string varName = fmt::format("exp_{}", key); varState[key] = varName; std::string texCoords = inputs.at("coords").source; - if (varState.contains(inputs.at("coords").source)) - { + if (varState.contains(inputs.at("coords").source)) { texCoords = varState[inputs.at("coords").source]; } - if (inputs.contains("texture")) - { - return fmt::format("let {} = {}.Sample({}, {});\n", varName, varState[inputs.at("texture").source], varState[inputs.at("sampler").source], texCoords); - } - else - { + if (inputs.contains("texture")) { + return fmt::format("let {} = {}.Sample({}, {});\n", varName, varState[inputs.at("texture").source], + varState[inputs.at("sampler").source], texCoords); + } else { return fmt::format("let {} = {}.Sample({});\n", varName, varState[inputs.at("sampler").source], texCoords); } } -void SampleExpression::save(ArchiveBuffer& buffer) const -{ - ShaderExpression::save(buffer); -} +void SampleExpression::save(ArchiveBuffer& buffer) const { ShaderExpression::save(buffer); } -void SampleExpression::load(ArchiveBuffer& buffer) -{ - ShaderExpression::load(buffer); -} +void SampleExpression::load(ArchiveBuffer& buffer) { ShaderExpression::load(buffer); } -void MaterialNode::save(ArchiveBuffer& buffer) const -{ +void MaterialNode::save(ArchiveBuffer& buffer) const { Serialization::save(buffer, profile); Serialization::save(buffer, variables); } -void MaterialNode::load(ArchiveBuffer& buffer) -{ +void MaterialNode::load(ArchiveBuffer& buffer) { Serialization::load(buffer, profile); Serialization::load(buffer, variables); } \ No newline at end of file diff --git a/src/Engine/Material/ShaderExpression.h b/src/Engine/Material/ShaderExpression.h index 0866a39..a70dd23 100644 --- a/src/Engine/Material/ShaderExpression.h +++ b/src/Engine/Material/ShaderExpression.h @@ -1,13 +1,12 @@ #pragma once -#include "MinimalEngine.h" +#include "Asset/TextureAsset.h" #include "Containers/Map.h" #include "Math/Math.h" -#include "Asset/TextureAsset.h" +#include "MinimalEngine.h" -namespace Seele -{ -enum class ExpressionType -{ + +namespace Seele { +enum class ExpressionType { UNKNOWN, FLOAT, FLOAT2, @@ -16,24 +15,21 @@ enum class ExpressionType TEXTURE, SAMPLER, }; -struct ExpressionInput -{ +struct ExpressionInput { std::string source; ExpressionType type = ExpressionType::UNKNOWN; void save(ArchiveBuffer& buffer) const; void load(ArchiveBuffer& buffer); }; -struct ExpressionOutput -{ +struct ExpressionOutput { std::string name; ExpressionType type = ExpressionType::UNKNOWN; void save(ArchiveBuffer& buffer) const; void load(ArchiveBuffer& buffer); }; DECLARE_REF(ShaderExpression); -class ShaderExpression -{ -public: +class ShaderExpression { + public: Map inputs; ExpressionOutput output; std::string key; @@ -48,8 +44,7 @@ public: DEFINE_REF(ShaderExpression) DECLARE_NAME_REF(Gfx, DescriptorSet) -struct ShaderParameter : public ShaderExpression -{ +struct ShaderParameter : public ShaderExpression { uint32 byteOffset = 0; uint32 binding = 0; ShaderParameter() {} @@ -64,8 +59,7 @@ struct ShaderParameter : public ShaderExpression virtual void load(ArchiveBuffer& buffer) override; }; DEFINE_REF(ShaderParameter) -struct FloatParameter : public ShaderParameter -{ +struct FloatParameter : public ShaderParameter { static constexpr uint64 IDENTIFIER = 0x01; float data = 0.0f; FloatParameter() {} @@ -78,8 +72,7 @@ struct FloatParameter : public ShaderParameter virtual void load(ArchiveBuffer& buffer) override; }; DEFINE_REF(FloatParameter) -struct VectorParameter : public ShaderParameter -{ +struct VectorParameter : public ShaderParameter { static constexpr uint64 IDENTIFIER = 0x02; Vector data = Vector(); VectorParameter() {} @@ -92,8 +85,7 @@ struct VectorParameter : public ShaderParameter virtual void load(ArchiveBuffer& buffer) override; }; DEFINE_REF(VectorParameter) -struct TextureParameter : public ShaderParameter -{ +struct TextureParameter : public ShaderParameter { static constexpr uint64 IDENTIFIER = 0x04; PTextureAsset data = nullptr; TextureParameter() {} @@ -107,8 +99,7 @@ struct TextureParameter : public ShaderParameter }; DEFINE_REF(TextureParameter) DECLARE_NAME_REF(Gfx, Sampler) -struct SamplerParameter : public ShaderParameter -{ +struct SamplerParameter : public ShaderParameter { static constexpr uint64 IDENTIFIER = 0x08; Gfx::OSampler data = nullptr; SamplerParameter() {} @@ -121,8 +112,7 @@ struct SamplerParameter : public ShaderParameter virtual void load(ArchiveBuffer& buffer) override; }; DEFINE_REF(SamplerParameter) -struct CombinedTextureParameter : public ShaderParameter -{ +struct CombinedTextureParameter : public ShaderParameter { static constexpr uint64 IDENTIFIER = 0x10; PTextureAsset data = nullptr; Gfx::OSampler sampler = nullptr; @@ -137,9 +127,7 @@ struct CombinedTextureParameter : public ShaderParameter }; DEFINE_REF(CombinedTextureParameter) - -struct ConstantExpression : public ShaderExpression -{ +struct ConstantExpression : public ShaderExpression { static constexpr uint64 IDENTIFIER = 0x11; std::string expr; ConstantExpression(); @@ -151,8 +139,7 @@ struct ConstantExpression : public ShaderExpression virtual void load(ArchiveBuffer& buffer) override; }; DEFINE_REF(ConstantExpression) -struct AddExpression : public ShaderExpression -{ +struct AddExpression : public ShaderExpression { static constexpr uint64 IDENTIFIER = 0x12; AddExpression(); virtual ~AddExpression(); @@ -162,8 +149,7 @@ struct AddExpression : public ShaderExpression virtual void load(ArchiveBuffer& buffer) override; }; DEFINE_REF(AddExpression) -struct SubExpression : public ShaderExpression -{ +struct SubExpression : public ShaderExpression { static constexpr uint64 IDENTIFIER = 0x13; SubExpression() {} virtual ~SubExpression() {} @@ -173,8 +159,7 @@ struct SubExpression : public ShaderExpression virtual void load(ArchiveBuffer& buffer) override; }; DEFINE_REF(SubExpression) -struct MulExpression : public ShaderExpression -{ +struct MulExpression : public ShaderExpression { static constexpr uint64 IDENTIFIER = 0x14; MulExpression() {} virtual ~MulExpression() {} @@ -184,12 +169,11 @@ struct MulExpression : public ShaderExpression virtual void load(ArchiveBuffer& buffer) override; }; DEFINE_REF(MulExpression) -struct SwizzleExpression : public ShaderExpression -{ +struct SwizzleExpression : public ShaderExpression { static constexpr uint64 IDENTIFIER = 0x15; StaticArray comp = {-1, -1, -1, -1}; SwizzleExpression() {} - SwizzleExpression(StaticArray comp) : comp(std::move(comp)) {} + SwizzleExpression(StaticArray comp) : comp(std::move(comp)) {} virtual ~SwizzleExpression() {} virtual uint64 getIdentifier() const override { return IDENTIFIER; } virtual std::string evaluate(Map& varState) const override; @@ -197,8 +181,7 @@ struct SwizzleExpression : public ShaderExpression virtual void load(ArchiveBuffer& buffer) override; }; DEFINE_REF(SwizzleExpression) -struct SampleExpression : public ShaderExpression -{ +struct SampleExpression : public ShaderExpression { static constexpr uint64 IDENTIFIER = 0x16; SampleExpression() {} virtual ~SampleExpression() {} @@ -209,8 +192,7 @@ struct SampleExpression : public ShaderExpression }; DEFINE_REF(SampleExpression) -struct MaterialNode -{ +struct MaterialNode { std::string profile; Map variables; MaterialNode() {} @@ -218,20 +200,15 @@ struct MaterialNode void save(ArchiveBuffer& buffer) const; void load(ArchiveBuffer& buffer); }; -template<> -void Serialization::save(ArchiveBuffer& buffer, const OShaderExpression& parameter) -{ +template <> void Serialization::save(ArchiveBuffer& buffer, const OShaderExpression& parameter) { Serialization::save(buffer, parameter->getIdentifier()); parameter->save(buffer); } -template<> -void Serialization::load(ArchiveBuffer& buffer, OShaderExpression& parameter) -{ +template <> void Serialization::load(ArchiveBuffer& buffer, OShaderExpression& parameter) { uint64 identifier = 0; Serialization::load(buffer, identifier); - switch (identifier) - { + switch (identifier) { case FloatParameter::IDENTIFIER: parameter = new FloatParameter(); break; @@ -271,20 +248,15 @@ void Serialization::load(ArchiveBuffer& buffer, OShaderExpression& parameter) parameter->load(buffer); } -template<> -void Serialization::save(ArchiveBuffer& buffer, const OShaderParameter& parameter) -{ +template <> void Serialization::save(ArchiveBuffer& buffer, const OShaderParameter& parameter) { Serialization::save(buffer, parameter->getIdentifier()); parameter->save(buffer); } -template<> -void Serialization::load(ArchiveBuffer& buffer, OShaderParameter& parameter) -{ +template <> void Serialization::load(ArchiveBuffer& buffer, OShaderParameter& parameter) { uint64 identifier = 0; Serialization::load(buffer, identifier); - switch (identifier) - { + switch (identifier) { case FloatParameter::IDENTIFIER: parameter = new FloatParameter(); break; diff --git a/src/Engine/Math/AABB.h b/src/Engine/Math/AABB.h index 7cb005d..8a36fe8 100644 --- a/src/Engine/Math/AABB.h +++ b/src/Engine/Math/AABB.h @@ -1,23 +1,20 @@ #pragma once -#include "Vector.h" -#include "Matrix.h" #include "Containers/Array.h" #include "Graphics/DebugVertex.h" -namespace Seele -{ -struct BoundingSphere -{ +#include "Matrix.h" +#include "Vector.h" + +namespace Seele { +struct BoundingSphere { Vector center; float radius; }; -struct AABB -{ +struct AABB { Vector min = Vector(std::numeric_limits::max()); - float pad0; // So that it can be used directly in shaders - Vector max = Vector(std::numeric_limits::lowest());// cause of reasons + float pad0; // So that it can be used directly in shaders + Vector max = Vector(std::numeric_limits::lowest()); // cause of reasons float pad1; - BoundingSphere toSphere() const - { + BoundingSphere toSphere() const { Vector center = (min + max) / 2.f; StaticArray corners; corners[0] = Vector(min.x, min.y, min.z); @@ -29,8 +26,7 @@ struct AABB corners[6] = Vector(max.x, max.y, min.z); corners[7] = Vector(max.x, max.y, max.z); float radius = 0; - for (const auto& corner : corners) - { + for (const auto& corner : corners) { radius = std::max(radius, glm::length(center - corner)); } return BoundingSphere{ @@ -38,17 +34,16 @@ struct AABB .radius = radius, }; } - void visualize(Array& vertices) const - { + void visualize(Array& vertices) const { StaticArray corners; - corners[0] = DebugVertex { .position = Vector(min.x, min.y, min.z), .color = Vector(0, 1, 0) }; - corners[1] = DebugVertex { .position = Vector(min.x, min.y, max.z), .color = Vector(0, 1, 0) }; - corners[2] = DebugVertex { .position = Vector(min.x, max.y, min.z), .color = Vector(0, 1, 0) }; - corners[3] = DebugVertex { .position = Vector(min.x, max.y, max.z), .color = Vector(0, 1, 0) }; - corners[4] = DebugVertex { .position = Vector(max.x, min.y, min.z), .color = Vector(0, 1, 0) }; - corners[5] = DebugVertex { .position = Vector(max.x, min.y, max.z), .color = Vector(0, 1, 0) }; - corners[6] = DebugVertex { .position = Vector(max.x, max.y, min.z), .color = Vector(0, 1, 0) }; - corners[7] = DebugVertex { .position = Vector(max.x, max.y, max.z), .color = Vector(0, 1, 0) }; + corners[0] = DebugVertex{.position = Vector(min.x, min.y, min.z), .color = Vector(0, 1, 0)}; + corners[1] = DebugVertex{.position = Vector(min.x, min.y, max.z), .color = Vector(0, 1, 0)}; + corners[2] = DebugVertex{.position = Vector(min.x, max.y, min.z), .color = Vector(0, 1, 0)}; + corners[3] = DebugVertex{.position = Vector(min.x, max.y, max.z), .color = Vector(0, 1, 0)}; + corners[4] = DebugVertex{.position = Vector(max.x, min.y, min.z), .color = Vector(0, 1, 0)}; + corners[5] = DebugVertex{.position = Vector(max.x, min.y, max.z), .color = Vector(0, 1, 0)}; + corners[6] = DebugVertex{.position = Vector(max.x, max.y, min.z), .color = Vector(0, 1, 0)}; + corners[7] = DebugVertex{.position = Vector(max.x, max.y, max.z), .color = Vector(0, 1, 0)}; vertices.add(corners[0]); vertices.add(corners[1]); @@ -61,7 +56,7 @@ struct AABB vertices.add(corners[0]); vertices.add(corners[2]); - + vertices.add(corners[0]); vertices.add(corners[4]); @@ -73,7 +68,7 @@ struct AABB vertices.add(corners[3]); vertices.add(corners[7]); - + vertices.add(corners[4]); vertices.add(corners[5]); @@ -86,51 +81,35 @@ struct AABB vertices.add(corners[4]); vertices.add(corners[6]); } - float surfaceArea() const - { + float surfaceArea() const { Vector d = max - min; return 2.0f * (d.x * d.y + d.y * d.z + d.z * d.x); } - bool intersects(const AABB& other) const - { - if (min.x > other.max.x - || max.x < other.min.x) - { + bool intersects(const AABB& other) const { + if (min.x > other.max.x || max.x < other.min.x) { return false; } - if (min.y > other.max.y - || max.y < other.min.y) - { + if (min.y > other.max.y || max.y < other.min.y) { return false; } - if (min.z > other.max.z - || max.z < other.min.z) - { + if (min.z > other.max.z || max.z < other.min.z) { return false; } return true; } - bool contains(const AABB& other) const - { - if (min.x > other.min.x - || max.x < other.max.x) - { + bool contains(const AABB& other) const { + if (min.x > other.min.x || max.x < other.max.x) { return false; } - if (min.y > other.min.y - || max.y < other.max.y) - { + if (min.y > other.min.y || max.y < other.max.y) { return false; } - if (min.z > other.min.z - || max.z < other.max.z) - { + if (min.z > other.min.z || max.z < other.max.z) { return false; } return true; } - AABB getTransformedBox(const Matrix4& matrix) const - { + AABB getTransformedBox(const Matrix4& matrix) const { StaticArray corners; corners[0] = Vector(min.x, min.y, min.z); corners[1] = Vector(min.x, min.y, max.z); @@ -142,40 +121,29 @@ struct AABB corners[7] = Vector(max.x, max.y, max.z); Vector tmin = Vector(std::numeric_limits::max()); Vector tmax = Vector(std::numeric_limits::lowest()); - for(int i = 0; i < 8; ++i) - { + for (int i = 0; i < 8; ++i) { Vector transformed = matrix * Vector4(corners[i], 1.0f); tmin = Vector(std::min(tmin.x, transformed.x), std::min(tmin.y, transformed.y), std::min(tmin.z, transformed.z)); tmax = Vector(std::max(tmax.x, transformed.x), std::max(tmax.y, transformed.y), std::max(tmax.z, transformed.z)); } - return AABB { + return AABB{ .min = tmin, .max = tmax, }; } - void adjust(const Vector vertex) - { + void adjust(const Vector vertex) { min.x = std::min(min.x, vertex.x); min.y = std::min(min.y, vertex.y); min.z = std::min(min.z, vertex.z); - + max.x = std::max(max.x, vertex.x); max.y = std::max(max.y, vertex.y); max.z = std::max(max.z, vertex.z); } - AABB combine(const AABB& other) const - { - return AABB { - .min = Vector( - std::min(min.x, other.min.x), - std::min(min.y, other.min.y), - std::min(min.z, other.min.z) - ), - .max = Vector ( - std::max(max.x, other.max.x), - std::max(max.y, other.max.y), - std::max(max.z, other.max.z) - ), + AABB combine(const AABB& other) const { + return AABB{ + .min = Vector(std::min(min.x, other.min.x), std::min(min.y, other.min.y), std::min(min.z, other.min.z)), + .max = Vector(std::max(max.x, other.max.x), std::max(max.y, other.max.y), std::max(max.z, other.max.z)), }; } }; diff --git a/src/Engine/Math/Math.h b/src/Engine/Math/Math.h index fd1bbc6..11b6834 100644 --- a/src/Engine/Math/Math.h +++ b/src/Engine/Math/Math.h @@ -1,28 +1,22 @@ #pragma once -#include "Vector.h" -#include "Matrix.h" #include "EngineTypes.h" +#include "Matrix.h" +#include "Vector.h" -namespace Seele -{ -struct Rect -{ - bool isEmpty() const - { - return size.x == 0 || size.y == 0; - } - Vector2 size; - Vector2 offset; + +namespace Seele { +struct Rect { + bool isEmpty() const { return size.x == 0 || size.y == 0; } + Vector2 size; + Vector2 offset; }; -//Unsigned int -struct URect -{ - UVector2 size = UVector2(0); - UVector2 offset = UVector2(0); +// Unsigned int +struct URect { + UVector2 size = UVector2(0); + UVector2 offset = UVector2(0); }; -struct Rect3D -{ - Vector size = Vector(0); - Vector offset = Vector(0); +struct Rect3D { + Vector size = Vector(0); + Vector offset = Vector(0); }; } // namespace Seele \ No newline at end of file diff --git a/src/Engine/Math/Matrix.h b/src/Engine/Math/Matrix.h index b1f68bb..5ed0a7c 100644 --- a/src/Engine/Math/Matrix.h +++ b/src/Engine/Math/Matrix.h @@ -3,8 +3,7 @@ #include #include #include -namespace Seele -{ +namespace Seele { typedef glm::mat2 Matrix2; typedef glm::mat3 Matrix3; typedef glm::mat4 Matrix4; diff --git a/src/Engine/Math/Transform.cpp b/src/Engine/Math/Transform.cpp index 3f8da1e..1b4e49b 100644 --- a/src/Engine/Math/Transform.cpp +++ b/src/Engine/Math/Transform.cpp @@ -1,50 +1,30 @@ #include "Transform.h" #define GLM_ENABLE_EXPERIMENTAL -#include #include "Transform.h" +#include + using namespace Seele; using namespace Seele::Math; -Transform::Transform() - : position(Vector4(0, 0, 0, 0)), rotation(Quaternion(1, 0, 0, 0)), scale(Vector4(1, 1, 1, 0)) -{ -} +Transform::Transform() : position(Vector4(0, 0, 0, 0)), rotation(Quaternion(1, 0, 0, 0)), scale(Vector4(1, 1, 1, 0)) {} -Transform::Transform(Transform &&other) - : position(other.position), rotation(other.rotation), scale(other.scale) -{ +Transform::Transform(Transform&& other) : position(other.position), rotation(other.rotation), scale(other.scale) { other.position = Vector4(0, 0, 0, 0); other.rotation = Quaternion(1, 0, 0, 0); other.scale = Vector4(0, 0, 0, 0); } -Transform::Transform(const Transform &other) - : position(other.position), rotation(other.rotation), scale(other.scale) -{ -} +Transform::Transform(const Transform& other) : position(other.position), rotation(other.rotation), scale(other.scale) {} -Transform::Transform(Vector position) - : position(Vector4(position, 0)), rotation(Quaternion(1, 0, 0, 0)), scale(Vector4(1, 1, 1, 0)) -{ -} +Transform::Transform(Vector position) : position(Vector4(position, 0)), rotation(Quaternion(1, 0, 0, 0)), scale(Vector4(1, 1, 1, 0)) {} Transform::Transform(Vector position, Quaternion rotation) - : position(Vector4(position, 0)), rotation(rotation), scale(Vector4(1, 1, 1, 0)) -{ -} + : position(Vector4(position, 0)), rotation(rotation), scale(Vector4(1, 1, 1, 0)) {} Transform::Transform(Vector position, Quaternion rotation, Vector scale) - : position(Vector4(position, 0)), rotation(rotation), scale(Vector4(scale, 0)) -{ -} -Transform::Transform(Quaternion rotation, Vector scale) - : position(Vector4(0, 0, 0, 0)), rotation(rotation), scale(Vector4(scale, 0)) -{ -} -Transform::~Transform() -{ -} -Matrix4 Transform::toMatrix() const -{ + : position(Vector4(position, 0)), rotation(rotation), scale(Vector4(scale, 0)) {} +Transform::Transform(Quaternion rotation, Vector scale) : position(Vector4(0, 0, 0, 0)), rotation(rotation), scale(Vector4(scale, 0)) {} +Transform::~Transform() {} +Matrix4 Transform::toMatrix() const { // TODO: actual calculations, SIMD Matrix4 result = Matrix4(1); result = glm::scale(result, Vector(scale)); @@ -55,98 +35,55 @@ Matrix4 Transform::toMatrix() const return result; } -Vector Transform::transformPosition(const Vector &v) const -{ - return Vector(glm::toMat4(rotation) * Vector4(v, 1)); -} +Vector Transform::transformPosition(const Vector& v) const { return Vector(glm::toMat4(rotation) * Vector4(v, 1)); } -Vector Transform::getPosition() const -{ - return Vector(position); -} +Vector Transform::getPosition() const { return Vector(position); } -Quaternion Transform::getRotation() const -{ - return rotation; -} +Quaternion Transform::getRotation() const { return rotation; } -Vector Transform::getScale() const -{ - return Vector(scale); -} +Vector Transform::getScale() const { return Vector(scale); } -void Transform::setPosition(Vector pos) -{ - position = Vector4(pos, 0); -} +void Transform::setPosition(Vector pos) { position = Vector4(pos, 0); } -void Transform::setRotation(Quaternion quat) -{ - rotation = quat; -} +void Transform::setRotation(Quaternion quat) { rotation = quat; } -void Transform::setScale(Vector s) -{ - scale = Vector4(s, 0); -} +void Transform::setScale(Vector s) { scale = Vector4(s, 0); } -Vector Transform::getForward() const -{ - return glm::normalize(Vector(0, 0, 1) * rotation); -} +Vector Transform::getForward() const { return glm::normalize(Vector(0, 0, 1) * rotation); } -Vector Transform::getRight() const -{ - return glm::normalize(Vector(1, 0, 0) * rotation); -} +Vector Transform::getRight() const { return glm::normalize(Vector(1, 0, 0) * rotation); } -Vector Transform::getUp() const -{ - return glm::normalize(Vector(0, 1, 0) * rotation); -} +Vector Transform::getUp() const { return glm::normalize(Vector(0, 1, 0) * rotation); } -bool Transform::equals(const Transform &other, float tolerance) -{ - if (abs(position - other.position).length() > tolerance) - { +bool Transform::equals(const Transform& other, float tolerance) { + if (abs(position - other.position).length() > tolerance) { return false; } - if ((abs(rotation.x - other.rotation.x) <= tolerance - && abs(rotation.y - other.rotation.y) <= tolerance - && abs(rotation.z - other.rotation.z) <= tolerance - && abs(rotation.w - other.rotation.w) <= tolerance) - || (abs(rotation.x + other.rotation.x) <= tolerance - && abs(rotation.y + other.rotation.y) <= tolerance - && abs(rotation.z + other.rotation.z) <= tolerance - && abs(rotation.w + other.rotation.w) <= tolerance)) - { + if ((abs(rotation.x - other.rotation.x) <= tolerance && abs(rotation.y - other.rotation.y) <= tolerance && + abs(rotation.z - other.rotation.z) <= tolerance && abs(rotation.w - other.rotation.w) <= tolerance) || + (abs(rotation.x + other.rotation.x) <= tolerance && abs(rotation.y + other.rotation.y) <= tolerance && + abs(rotation.z + other.rotation.z) <= tolerance && abs(rotation.w + other.rotation.w) <= tolerance)) { return false; } - if (abs(scale - other.scale).length() > tolerance) - { + if (abs(scale - other.scale).length() > tolerance) { return false; } return true; } -void Transform::multiply(Transform *outTransform, const Transform *a, const Transform *b) -{ +void Transform::multiply(Transform* outTransform, const Transform* a, const Transform* b) { outTransform->rotation = b->rotation * a->rotation; outTransform->position = b->rotation * (b->scale * a->position) + b->position; outTransform->scale = b->scale * a->scale; } -void Transform::add(Transform *outTransform, const Transform *a, const Transform *b) -{ +void Transform::add(Transform* outTransform, const Transform* a, const Transform* b) { outTransform->position = a->position + b->position; outTransform->rotation = a->rotation + b->rotation; outTransform->scale = a->scale + b->scale; } - -Transform &Transform::operator=(const Transform &other) -{ - if(&other != this) - { +Transform& Transform::operator=(const Transform& other) { + if (&other != this) { position = other.position; rotation = other.rotation; scale = other.scale; @@ -154,10 +91,8 @@ Transform &Transform::operator=(const Transform &other) return *this; } -Transform &Transform::operator=(Transform &&other) -{ - if(&other != this) - { +Transform& Transform::operator=(Transform&& other) { + if (&other != this) { position = other.position; rotation = other.rotation; scale = other.scale; @@ -168,15 +103,13 @@ Transform &Transform::operator=(Transform &&other) return *this; } -Transform Transform::operator+(const Transform & other) const -{ +Transform Transform::operator+(const Transform& other) const { Transform outTransform; add(&outTransform, this, &other); return outTransform; } -Transform Transform::operator*(const Transform &other) const -{ +Transform Transform::operator*(const Transform& other) const { Transform outTransform; multiply(&outTransform, this, &other); return outTransform; diff --git a/src/Engine/Math/Transform.h b/src/Engine/Math/Transform.h index 1a6bb2e..77989e5 100644 --- a/src/Engine/Math/Transform.h +++ b/src/Engine/Math/Transform.h @@ -1,24 +1,22 @@ #pragma once -#include "Math/Vector.h" #include "Math/Matrix.h" +#include "Math/Vector.h" -namespace Seele -{ -namespace Math -{ -class Transform -{ -public: + +namespace Seele { +namespace Math { +class Transform { + public: Transform(); - Transform(const Transform &other); - Transform(Transform &&other); + Transform(const Transform& other); + Transform(Transform&& other); explicit Transform(Vector position); Transform(Vector position, Quaternion rotation); Transform(Vector position, Quaternion rotation, Vector scale); Transform(Quaternion rotation, Vector scale); ~Transform(); Matrix4 toMatrix() const; - Vector transformPosition(const Vector &v) const; + Vector transformPosition(const Vector& v) const; Vector getPosition() const; Quaternion getRotation() const; @@ -32,16 +30,16 @@ public: Vector getRight() const; Vector getUp() const; - bool equals(const Transform &other, float tolerance = 0.000000001f); - static void multiply(Transform *outTransform, const Transform *a, const Transform *b); - static void add(Transform *outTransform, const Transform *a, const Transform *b); + bool equals(const Transform& other, float tolerance = 0.000000001f); + static void multiply(Transform* outTransform, const Transform* a, const Transform* b); + static void add(Transform* outTransform, const Transform* a, const Transform* b); - Transform &operator=(const Transform &other); - Transform &operator=(Transform &&other); + Transform& operator=(const Transform& other); + Transform& operator=(Transform&& other); Transform operator+(const Transform& other) const; - Transform operator*(const Transform &other) const; + Transform operator*(const Transform& other) const; -private: + private: Vector4 position; Quaternion rotation; Vector4 scale; diff --git a/src/Engine/Math/Vector.cpp b/src/Engine/Math/Vector.cpp index fdf1d92..63d30f4 100644 --- a/src/Engine/Math/Vector.cpp +++ b/src/Engine/Math/Vector.cpp @@ -1,19 +1,16 @@ #include "Vector.h" -#include -#include -#include -#include #include "Serialization/ArchiveBuffer.h" +#include +#include +#include +#include + using namespace Seele; -void to_json(nlohmann::json& j, const Vector& vec) -{ - j = nlohmann::json{fmt::format("({}, {}, {})", vec.x, vec.y, vec.z)}; -} +void to_json(nlohmann::json& j, const Vector& vec) { j = nlohmann::json{fmt::format("({}, {}, {})", vec.x, vec.y, vec.z)}; } -void from_json(const nlohmann::json& j, Vector& vec) -{ +void from_json(const nlohmann::json& j, Vector& vec) { std::string str; j.get_to(str); auto newEnd = std::remove(str.begin(), str.end(), ' '); @@ -28,29 +25,25 @@ void from_json(const nlohmann::json& j, Vector& vec) vec.z = std::stof(temp); } -std::ostream& operator<<(std::ostream& stream, const Vector2& vector) -{ +std::ostream& operator<<(std::ostream& stream, const Vector2& vector) { stream << "(" << vector.x << ", " << vector.y << ")"; return stream; } -std::ostream& operator<<(std::ostream& stream, const Vector& vector) -{ +std::ostream& operator<<(std::ostream& stream, const Vector& vector) { stream << "(" << vector.x << ", " << vector.y << ", " << vector.z << ")"; return stream; } -std::ostream& operator<<(std::ostream& stream, const Vector4& vector) -{ +std::ostream& operator<<(std::ostream& stream, const Vector4& vector) { stream << "(" << vector.x << ", " << vector.y << ", " << vector.z << ", " << vector.w << ")"; return stream; } -Vector Seele::parseVector(const char* str) -{ - //regex pattern consisting of 'float3(xComp, yComp, zComp)', more also matches for invalid floats, but that will throw later +Vector Seele::parseVector(const char* str) { + // regex pattern consisting of 'float3(xComp, yComp, zComp)', more also matches for invalid floats, but that will throw later std::regex pattern("float3\\(\\s*([0-9.]+f?)\\s*,\\s*([0-9.]+f?)\\s*,\\s*([0-9.]+f?)\\s*\\)"); std::cmatch base_match; std::regex_match(str, base_match, pattern); - //match 0 is the whole expression + // match 0 is the whole expression float x = std::stof(base_match[1].str()); float y = std::stof(base_match[2].str()); float z = std::stof(base_match[3].str()); diff --git a/src/Engine/Math/Vector.h b/src/Engine/Math/Vector.h index 739180a..ca45b66 100644 --- a/src/Engine/Math/Vector.h +++ b/src/Engine/Math/Vector.h @@ -1,7 +1,7 @@ #pragma once #ifdef WIN32 #pragma warning(push) -#pragma warning(disable: 4201) +#pragma warning(disable : 4201) #endif #include #include @@ -13,8 +13,7 @@ #endif #include -namespace Seele -{ +namespace Seele { typedef glm::vec2 Vector2; typedef glm::vec3 Vector; typedef glm::vec4 Vector4; diff --git a/src/Engine/MinimalEngine.h b/src/Engine/MinimalEngine.h index cc2316b..08e70bf 100644 --- a/src/Engine/MinimalEngine.h +++ b/src/Engine/MinimalEngine.h @@ -2,176 +2,98 @@ #include "EngineTypes.h" #include #include -#include #include +#include -#define DEFINE_REF(x) \ - typedef ::Seele::RefPtr P##x; \ - typedef ::Seele::UniquePtr UP##x; \ + +#define DEFINE_REF(x) \ + typedef ::Seele::RefPtr P##x; \ + typedef ::Seele::UniquePtr UP##x; \ typedef ::Seele::OwningPtr O##x; -#define DECLARE_REF(x) \ - class x; \ - typedef ::Seele::RefPtr P##x; \ - typedef ::Seele::UniquePtr UP##x; \ +#define DECLARE_REF(x) \ + class x; \ + typedef ::Seele::RefPtr P##x; \ + typedef ::Seele::UniquePtr UP##x; \ typedef ::Seele::OwningPtr O##x; - -#define DECLARE_NAME_REF(nmsp, x) \ - namespace nmsp \ - { \ - class x; \ - typedef RefPtr P##x; \ - typedef UniquePtr UP##x; \ - typedef OwningPtr O##x; \ +#define DECLARE_NAME_REF(nmsp, x) \ + namespace nmsp { \ + class x; \ + typedef RefPtr P##x; \ + typedef UniquePtr UP##x; \ + typedef OwningPtr O##x; \ } -namespace Seele -{ -template -class RefPtr -{ -public: - constexpr RefPtr() noexcept - : object(nullptr) - { - } - constexpr RefPtr(std::nullptr_t) noexcept - : object(nullptr) - { - } - RefPtr(T* ptr) - : object(ptr) - { - } - constexpr RefPtr(const RefPtr& other) noexcept - : object(other.object) - { - } - constexpr RefPtr(RefPtr&& rhs) noexcept - : object(std::move(rhs.object)) - { - rhs.object = nullptr; - } - template - constexpr RefPtr cast() - { +namespace Seele { +template class RefPtr { + public: + constexpr RefPtr() noexcept : object(nullptr) {} + constexpr RefPtr(std::nullptr_t) noexcept : object(nullptr) {} + RefPtr(T* ptr) : object(ptr) {} + constexpr RefPtr(const RefPtr& other) noexcept : object(other.object) {} + constexpr RefPtr(RefPtr&& rhs) noexcept : object(std::move(rhs.object)) { rhs.object = nullptr; } + template constexpr RefPtr cast() { T* t = object; F* f = dynamic_cast(t); - if (f == nullptr) - { + if (f == nullptr) { return nullptr; } return RefPtr(f); } - template - constexpr const RefPtr cast() const - { + template constexpr const RefPtr cast() const { T* t = object; F* f = dynamic_cast(t); - if (f == nullptr) - { + if (f == nullptr) { return nullptr; } return RefPtr(f); } - constexpr RefPtr& operator=(const RefPtr& other) - { - if (this != &other) - { + constexpr RefPtr& operator=(const RefPtr& other) { + if (this != &other) { object = other.object; } return *this; } - constexpr RefPtr& operator=(RefPtr&& rhs) noexcept - { - if (this != &rhs) - { + constexpr RefPtr& operator=(RefPtr&& rhs) noexcept { + if (this != &rhs) { object = std::move(rhs.object); rhs.object = nullptr; } return *this; } - constexpr ~RefPtr() - { - } - constexpr bool operator==(const RefPtr& rhs) const noexcept - { - return object == rhs.object; - } - constexpr auto operator<=>(const RefPtr& rhs) const noexcept - { - return object <=> rhs.object; - } - template - constexpr bool operator==(const RefPtr& rhs) const noexcept - { - return object == rhs.getHandle(); - } - template - constexpr auto operator<=>(const RefPtr& rhs) const noexcept - { - return object <=> rhs.getHandle(); - } - template - constexpr operator RefPtr() - { - return RefPtr(static_cast(object)); - } - template - constexpr operator RefPtr() const - { - return RefPtr(static_cast(object)); - } - constexpr T* operator->() - { - return object; - } - constexpr const T* operator->() const - { - return object; - } - constexpr T* getHandle() - { - return object; - } - constexpr const T* getHandle() const - { - return object; - } -private: + constexpr ~RefPtr() {} + constexpr bool operator==(const RefPtr& rhs) const noexcept { return object == rhs.object; } + constexpr auto operator<=>(const RefPtr& rhs) const noexcept { return object <=> rhs.object; } + template constexpr bool operator==(const RefPtr& rhs) const noexcept { return object == rhs.getHandle(); } + template constexpr auto operator<=>(const RefPtr& rhs) const noexcept { return object <=> rhs.getHandle(); } + template constexpr operator RefPtr() { return RefPtr(static_cast(object)); } + template constexpr operator RefPtr() const { return RefPtr(static_cast(object)); } + constexpr T* operator->() { return object; } + constexpr const T* operator->() const { return object; } + constexpr T* getHandle() { return object; } + constexpr const T* getHandle() const { return object; } + + private: T* object; }; -template > -class OwningPtr -{ -public: - OwningPtr() - : pointer(nullptr) - { - } - OwningPtr(T* ptr) - : pointer(ptr) - {} - template - OwningPtr(OwningPtr&& other) - { +template > class OwningPtr { + public: + OwningPtr() : pointer(nullptr) {} + OwningPtr(T* ptr) : pointer(ptr) {} + template OwningPtr(OwningPtr&& other) { pointer = dynamic_cast(*other); other.clear(); } OwningPtr(const OwningPtr& other) = delete; - OwningPtr(OwningPtr&& other) noexcept - { + OwningPtr(OwningPtr&& other) noexcept { pointer = other.pointer; other.pointer = nullptr; } OwningPtr& operator=(const OwningPtr& other) = delete; - OwningPtr& operator=(OwningPtr&& other) noexcept - { - if (this != &other) - { - if(pointer != nullptr) - { + OwningPtr& operator=(OwningPtr&& other) noexcept { + if (this != &other) { + if (pointer != nullptr) { Deleter()(pointer); } pointer = other.pointer; @@ -179,109 +101,45 @@ public: } return *this; } - ~OwningPtr() - { - Deleter()(pointer); - } - operator RefPtr() - { - return RefPtr(pointer); - } - operator RefPtr() const - { - return RefPtr(pointer); - } - constexpr T* operator->() - { - return pointer; - } - constexpr const T* operator->() const - { - return pointer; - } - constexpr T* operator*() - { - return pointer; - } - constexpr const T* operator*() const - { - return pointer; - } - constexpr bool operator==(std::nullptr_t) const noexcept - { - return pointer == nullptr; - } - constexpr auto operator<=>(const OwningPtr& rhs) const noexcept - { - return pointer <=> rhs.pointer; - } + ~OwningPtr() { Deleter()(pointer); } + operator RefPtr() { return RefPtr(pointer); } + operator RefPtr() const { return RefPtr(pointer); } + constexpr T* operator->() { return pointer; } + constexpr const T* operator->() const { return pointer; } + constexpr T* operator*() { return pointer; } + constexpr const T* operator*() const { return pointer; } + constexpr bool operator==(std::nullptr_t) const noexcept { return pointer == nullptr; } + constexpr auto operator<=>(const OwningPtr& rhs) const noexcept { return pointer <=> rhs.pointer; } // INTERNAL USE - constexpr void clear() - { - pointer = nullptr; - } -private: + constexpr void clear() { pointer = nullptr; } + + private: friend class RefPtr; T* pointer; }; -template -class UniquePtr -{ -public: - UniquePtr() - : handle(nullptr) - { - } - UniquePtr(std::nullptr_t) - : handle(nullptr) - { - } - UniquePtr(T *ptr) - : handle(ptr) - { - } - UniquePtr(const UniquePtr &rhs) = delete; - UniquePtr(UniquePtr &&rhs) noexcept - : handle(rhs.handle) - { - rhs.handle = nullptr; - } - UniquePtr &operator=(const UniquePtr &rhs) = delete; - UniquePtr &operator=(UniquePtr &&rhs) - { - if (this != &rhs) - { +template class UniquePtr { + public: + UniquePtr() : handle(nullptr) {} + UniquePtr(std::nullptr_t) : handle(nullptr) {} + UniquePtr(T* ptr) : handle(ptr) {} + UniquePtr(const UniquePtr& rhs) = delete; + UniquePtr(UniquePtr&& rhs) noexcept : handle(rhs.handle) { rhs.handle = nullptr; } + UniquePtr& operator=(const UniquePtr& rhs) = delete; + UniquePtr& operator=(UniquePtr&& rhs) { + if (this != &rhs) { handle = rhs.handle; rhs.handle = nullptr; } return *this; } - ~UniquePtr() - { - delete handle; - } - inline bool operator==(const UniquePtr &other) const - { - return handle == other.handle; - } - inline bool operator!=(const UniquePtr &other) const - { - return handle != other.handle; - } - inline T *operator->() - { - return handle; - } - inline T* getHandle() - { - return handle; - } - bool isValid() - { - return handle != nullptr; - } + ~UniquePtr() { delete handle; } + inline bool operator==(const UniquePtr& other) const { return handle == other.handle; } + inline bool operator!=(const UniquePtr& other) const { return handle != other.handle; } + inline T* operator->() { return handle; } + inline T* getHandle() { return handle; } + bool isValid() { return handle != nullptr; } -private: - T *handle; + private: + T* handle; }; } // namespace Seele diff --git a/src/Engine/Physics/BVH.cpp b/src/Engine/Physics/BVH.cpp index a70302b..eca8b9e 100644 --- a/src/Engine/Physics/BVH.cpp +++ b/src/Engine/Physics/BVH.cpp @@ -2,13 +2,10 @@ using namespace Seele; -void BVH::findOverlaps(Array>& overlaps) -{ +void BVH::findOverlaps(Array>& overlaps) { overlaps.clear(); - for(const auto& node : dynamicNodes) - { - if(!node.isLeaf) - { + for (const auto& node : dynamicNodes) { + if (!node.isLeaf) { continue; } traverseStaticTree(node.box, node.owner, staticRoot, overlaps); @@ -16,60 +13,46 @@ void BVH::findOverlaps(Array>& overlaps) } } -void BVH::updateDynamicCollider(entt::entity entity, AABB aabb) -{ - - for(auto& node : dynamicNodes) - { - if(node.owner == entity) - { - if(!node.box.contains(aabb)) - { +void BVH::updateDynamicCollider(entt::entity entity, AABB aabb) { + + for (auto& node : dynamicNodes) { + if (node.owner == entity) { + if (!node.box.contains(aabb)) { // moved out of extended bounds reinsertCollider(entity, aabb); - } return; } } // new collider addDynamicCollider(entity, aabb); - } -void BVH::colliderCallback(entt::registry& registry, entt::entity entity) -{ +void BVH::colliderCallback(entt::registry& registry, entt::entity entity) { Component::Collider& collider = registry.get(entity); Component::Transform& transform = registry.get(entity); - if(collider.type == Component::ColliderType::STATIC) - { + if (collider.type == Component::ColliderType::STATIC) { addStaticCollider(entity, collider.boundingbox.getTransformedBox(transform.toMatrix())); } } -void BVH::visualize() -{ +void BVH::visualize() { Array verts; - for (const auto& node : staticNodes) - { + for (const auto& node : staticNodes) { node.box.visualize(verts); } - for (const auto& node : dynamicNodes) - { + for (const auto& node : dynamicNodes) { node.box.visualize(verts); } addDebugVertices(verts); } -void BVH::traverseStaticTree(const AABB& aabb, entt::entity source, int32 nodeIndex, Array>& overlaps) -{ +void BVH::traverseStaticTree(const AABB& aabb, entt::entity source, int32 nodeIndex, Array>& overlaps) { const Node& node = staticNodes[nodeIndex]; - if(!aabb.intersects(node.box)) - { + if (!aabb.intersects(node.box)) { return; } - if(node.isLeaf && node.owner != source) - { + if (node.isLeaf && node.owner != source) { overlaps.add(Pair(source, node.owner)); return; } @@ -77,19 +60,15 @@ void BVH::traverseStaticTree(const AABB& aabb, entt::entity source, int32 nodeIn traverseStaticTree(aabb, source, node.right, overlaps); } -void BVH::traverseDynamicTree(const AABB& aabb, entt::entity source, int32 nodeIndex, Array>& overlaps) -{ - if(nodeIndex == -1) - { +void BVH::traverseDynamicTree(const AABB& aabb, entt::entity source, int32 nodeIndex, Array>& overlaps) { + if (nodeIndex == -1) { return; } const Node& node = dynamicNodes[nodeIndex]; - if(!aabb.intersects(node.box)) - { + if (!aabb.intersects(node.box)) { return; } - if(node.isLeaf && node.owner != source) - { + if (node.isLeaf && node.owner != source) { overlaps.add(Pair(source, node.owner)); return; } @@ -97,147 +76,117 @@ void BVH::traverseDynamicTree(const AABB& aabb, entt::entity source, int32 nodeI traverseDynamicTree(aabb, source, node.right, overlaps); } -void BVH::reinsertCollider(entt::entity entity, AABB aabb) -{ - +void BVH::reinsertCollider(entt::entity entity, AABB aabb) { + removeCollider(entity); - + addDynamicCollider(entity, aabb); - } -void BVH::removeCollider(entt::entity entity) -{ +void BVH::removeCollider(entt::entity entity) { int32 nodeIndex = -1; - for (size_t i = 0; i < dynamicNodes.size(); i++) - { - if(dynamicNodes[i].isLeaf && dynamicNodes[i].owner == entity) - { + for (size_t i = 0; i < dynamicNodes.size(); i++) { + if (dynamicNodes[i].isLeaf && dynamicNodes[i].owner == entity) { nodeIndex = i; break; } } - if(nodeIndex == -1) - { + if (nodeIndex == -1) { return; } int32 parentIndex = dynamicNodes[nodeIndex].parentIndex; - if(parentIndex == -1) - { + if (parentIndex == -1) { // its the root node dynamicRoot = -1; freeNode(nodeIndex); - + return; } const Node& parent = dynamicNodes[parentIndex]; int32 siblingIndex; - - if(parent.left == nodeIndex) - { + + if (parent.left == nodeIndex) { siblingIndex = parent.right; - } - else - { + } else { siblingIndex = parent.left; } - + // the node to remove and their sibling share a parent // now that the node is removed, the parent is also useless // so the grandparent should point to the sibling directly instead of the parent - if(parent.parentIndex != -1) - { + if (parent.parentIndex != -1) { Node& grandParent = dynamicNodes[parent.parentIndex]; - if(grandParent.left == parentIndex) - { + if (grandParent.left == parentIndex) { grandParent.left = siblingIndex; - } - else - { + } else { grandParent.right = siblingIndex; } dynamicNodes[siblingIndex].parentIndex = parent.parentIndex; - } - else - { + } else { // if the shared parent was the root, we need a new root, which is the remaining sibling dynamicRoot = siblingIndex; dynamicNodes[siblingIndex].parentIndex = -1; } - + freeNode(nodeIndex); - + freeNode(parentIndex); - } -void BVH::addDynamicCollider(entt::entity entity, AABB aabb) -{ +void BVH::addDynamicCollider(entt::entity entity, AABB aabb) { auto center = (aabb.max + aabb.min) / 2.0f; // enlarge box slightly to buffer movement - aabb = AABB { + aabb = AABB{ .min = center + (aabb.min - center) * 1.1f, .max = center + (aabb.max - center) * 1.1f, }; int32 leafIndex = allocateNode(); - Node newNode = Node { + Node newNode = Node{ .box = aabb, .isLeaf = true, .isValid = true, .owner = entity, }; dynamicNodes[leafIndex] = newNode; - - if (dynamicRoot == -1) - { + if (dynamicRoot == -1) { dynamicRoot = leafIndex; return; } - + int32 bestSibling; float bestCost = std::numeric_limits::max(); findSibling(newNode, dynamicRoot, bestCost, bestSibling); - int32 oldParent = dynamicNodes[bestSibling].parentIndex; int32 newParent = allocateNode(); - dynamicNodes[newParent] = Node { + dynamicNodes[newParent] = Node{ .box = aabb.combine(dynamicNodes[bestSibling].box), .parentIndex = oldParent, .isLeaf = false, .isValid = true, }; - - if(oldParent != -1) - { - if(dynamicNodes[oldParent].left == bestSibling) - { + if (oldParent != -1) { + if (dynamicNodes[oldParent].left == bestSibling) { dynamicNodes[oldParent].left = newParent; - } - else - { + } else { dynamicNodes[oldParent].right = newParent; } dynamicNodes[newParent].left = bestSibling; dynamicNodes[newParent].right = leafIndex; dynamicNodes[bestSibling].parentIndex = newParent; dynamicNodes[leafIndex].parentIndex = newParent; - - } - else - { + + } else { dynamicNodes[newParent].left = bestSibling; dynamicNodes[newParent].right = leafIndex; dynamicNodes[bestSibling].parentIndex = newParent; dynamicNodes[leafIndex].parentIndex = newParent; dynamicRoot = newParent; - } int32 index = dynamicNodes[leafIndex].parentIndex; - while(index != -1) - { + while (index != -1) { int32 left = dynamicNodes[index].left; int32 right = dynamicNodes[index].right; @@ -246,9 +195,8 @@ void BVH::addDynamicCollider(entt::entity entity, AABB aabb) } } -void BVH::addStaticCollider(entt::entity entity, AABB boundingBox) -{ - staticCollider.add(AABBCenter { +void BVH::addStaticCollider(entt::entity entity, AABB boundingBox) { + staticCollider.add(AABBCenter{ .bb = boundingBox, .center = (boundingBox.min + boundingBox.max) / 2.0f, .id = entity, @@ -257,18 +205,14 @@ void BVH::addStaticCollider(entt::entity entity, AABB boundingBox) staticRoot = splitNode(staticCollider); } -void BVH::findSibling(Node newNode, int32 nodeIndex, float& bestCost, int32& result) -{ - if(nodeIndex == -1) - { +void BVH::findSibling(Node newNode, int32 nodeIndex, float& bestCost, int32& result) { + if (nodeIndex == -1) { return; } float lowerBound = lowerBoundCost(newNode, nodeIndex); - if(lowerBound < bestCost) - { + if (lowerBound < bestCost) { float cost = siblingCost(newNode, nodeIndex); - if(cost < bestCost) - { + if (cost < bestCost) { bestCost = cost; result = nodeIndex; } @@ -277,14 +221,12 @@ void BVH::findSibling(Node newNode, int32 nodeIndex, float& bestCost, int32& res } } -float BVH::siblingCost(Node newNode, int32 siblingIndex) -{ +float BVH::siblingCost(Node newNode, int32 siblingIndex) { const Node& sibling = dynamicNodes[siblingIndex]; AABB newBox = sibling.box.combine(newNode.box); float cost = newBox.surfaceArea(); int32 parentIndex = sibling.parentIndex; - while(parentIndex != -1) - { + while (parentIndex != -1) { AABB parentBox = dynamicNodes[parentIndex].box; cost += parentBox.combine(newBox).surfaceArea() - parentBox.surfaceArea(); parentIndex = dynamicNodes[parentIndex].parentIndex; @@ -292,11 +234,9 @@ float BVH::siblingCost(Node newNode, int32 siblingIndex) return cost; } -float BVH::lowerBoundCost(Node newNode, int32 branchIndex) -{ +float BVH::lowerBoundCost(Node newNode, int32 branchIndex) { float cost = newNode.box.surfaceArea(); - while(branchIndex != -1) - { + while (branchIndex != -1) { AABB box = dynamicNodes[branchIndex].box; cost += box.combine(newNode.box).surfaceArea() - box.surfaceArea(); branchIndex = dynamicNodes[branchIndex].parentIndex; @@ -304,10 +244,8 @@ float BVH::lowerBoundCost(Node newNode, int32 branchIndex) return cost; } -int32 BVH::splitNode(Array aabbs) -{ - if(aabbs.size() == 1) - { +int32 BVH::splitNode(Array aabbs) { + if (aabbs.size() == 1) { int32 leafIndex = static_cast(staticNodes.size()); Node& leaf = staticNodes.add(); leaf.isLeaf = true; @@ -318,8 +256,7 @@ int32 BVH::splitNode(Array aabbs) return leafIndex; } AABB rootBox; - for(size_t i = 0; i < aabbs.size(); ++i) - { + for (size_t i = 0; i < aabbs.size(); ++i) { rootBox.adjust(aabbs[i].bb.min); rootBox.adjust(aabbs[i].bb.max); } @@ -327,32 +264,25 @@ int32 BVH::splitNode(Array aabbs) float ylen = rootBox.max.y - rootBox.min.y; float zlen = rootBox.max.z - rootBox.min.z; int32 longestAxis; - if(xlen >= ylen && xlen >= zlen) - { + if (xlen >= ylen && xlen >= zlen) { longestAxis = 0; } - if(ylen >= xlen && ylen >= zlen) - { + if (ylen >= xlen && ylen >= zlen) { longestAxis = 1; } - if(zlen >= xlen && zlen >= ylen) - { + if (zlen >= xlen && zlen >= ylen) { longestAxis = 2; } - struct - { - bool operator()(const AABBCenter& lhs, const AABBCenter& rhs) - { - return lhs.center[longestAxis] < rhs.center[longestAxis]; - } + struct { + bool operator()(const AABBCenter& lhs, const AABBCenter& rhs) { return lhs.center[longestAxis] < rhs.center[longestAxis]; } int32 longestAxis; } compare = {longestAxis}; - + std::sort(aabbs.begin(), aabbs.end(), compare); - Array left((aabbs.size()+1)/2); - Array right(aabbs.size()/2); - std::copy(aabbs.begin(), aabbs.begin()+left.size(), left.begin()); - std::copy(aabbs.begin()+left.size(), aabbs.end(), right.begin()); + Array left((aabbs.size() + 1) / 2); + Array right(aabbs.size() / 2); + std::copy(aabbs.begin(), aabbs.begin() + left.size(), left.begin()); + std::copy(aabbs.begin() + left.size(), aabbs.end(), right.begin()); int32 rootIndex = static_cast(staticNodes.size()); Node& rootNode = staticNodes.add(); rootNode.box = rootBox; @@ -360,12 +290,9 @@ int32 BVH::splitNode(Array aabbs) rootNode.right = splitNode(std::move(right)); return rootIndex; } -int32 BVH::allocateNode() -{ - for (size_t i = 0; i < dynamicNodes.size(); i++) - { - if(!dynamicNodes[i].isValid) - { +int32 BVH::allocateNode() { + for (size_t i = 0; i < dynamicNodes.size(); i++) { + if (!dynamicNodes[i].isValid) { return i; } } @@ -373,26 +300,21 @@ int32 BVH::allocateNode() dynamicNodes.add(); return newLeaf; } -void BVH::freeNode(int32 nodeIndex) -{ +void BVH::freeNode(int32 nodeIndex) { dynamicNodes[nodeIndex].isValid = false; dynamicNodes[nodeIndex].parentIndex = -1; } -void BVH::validateBVH() const -{ - if(dynamicRoot != -1) - { +void BVH::validateBVH() const { + if (dynamicRoot != -1) { assert(dynamicNodes[dynamicRoot].parentIndex == -1); } - for(size_t i = 0; i < dynamicNodes.size(); ++i) - { + for (size_t i = 0; i < dynamicNodes.size(); ++i) { int32 nodeIdx = i; size_t counter = dynamicNodes.size(); - if(!dynamicNodes[nodeIdx].isValid) + if (!dynamicNodes[nodeIdx].isValid) continue; - while(dynamicNodes[nodeIdx].parentIndex != -1) - { + while (dynamicNodes[nodeIdx].parentIndex != -1) { nodeIdx = dynamicNodes[nodeIdx].parentIndex; assert(counter-- > 0 && dynamicNodes[nodeIdx].isValid); } diff --git a/src/Engine/Physics/BVH.h b/src/Engine/Physics/BVH.h index ed7d78f..705d105 100644 --- a/src/Engine/Physics/BVH.h +++ b/src/Engine/Physics/BVH.h @@ -1,28 +1,26 @@ #pragma once -#include -#include "Containers/Array.h" -#include "Math/AABB.h" #include "Component/Collider.h" +#include "Containers/Array.h" #include "Containers/Pair.h" +#include "Math/AABB.h" +#include -namespace Seele -{ -class BVH -{ -public: + +namespace Seele { +class BVH { + public: void findOverlaps(Array>& overlaps); void updateDynamicCollider(entt::entity entity, AABB aabb); void colliderCallback(entt::registry& registry, entt::entity entity); void visualize(); -private: - struct AABBCenter - { + + private: + struct AABBCenter { AABB bb; Vector center; entt::entity id; }; - struct Node - { + struct Node { AABB box; int32 parentIndex = -1; int32 left = -1; diff --git a/src/Engine/Physics/CollisionSystem.cpp b/src/Engine/Physics/CollisionSystem.cpp index 06d160f..6b5f8c1 100644 --- a/src/Engine/Physics/CollisionSystem.cpp +++ b/src/Engine/Physics/CollisionSystem.cpp @@ -3,25 +3,17 @@ using namespace Seele; using namespace Seele::Component; -CollisionSystem::CollisionSystem(entt::registry& registry) - : registry(registry) -{ +CollisionSystem::CollisionSystem(entt::registry& registry) : registry(registry) { registry.on_construct().connect<&BVH::colliderCallback>(bvh); } -CollisionSystem::~CollisionSystem() -{ - -} +CollisionSystem::~CollisionSystem() {} -void CollisionSystem::detectCollisions(Array& collisions) -{ +void CollisionSystem::detectCollisions(Array& collisions) { collisions.clear(); auto view = registry.view(); - for(auto && [entity, collider, transform] : view.each()) - { - if(collider.type == ColliderType::DYNAMIC) - { + for (auto&& [entity, collider, transform] : view.each()) { + if (collider.type == ColliderType::DYNAMIC) { bvh.updateDynamicCollider(entity, collider.boundingbox.getTransformedBox(transform.toMatrix())); } collider.physicsMesh.transform(transform).visualize(); @@ -29,11 +21,9 @@ void CollisionSystem::detectCollisions(Array& collisions) bvh.visualize(); Array> overlaps; bvh.findOverlaps(overlaps); - for(auto pair : overlaps) - { - if(checkCollision(pair)) - { - collisions.add(Collision { + for (auto pair : overlaps) { + if (checkCollision(pair)) { + collisions.add(Collision{ .a = pair.key, .b = pair.value, }); @@ -41,42 +31,36 @@ void CollisionSystem::detectCollisions(Array& collisions) } } -bool CollisionSystem::checkCollision(Pair pair) -{ - const auto&[collider1, transform1] = registry.get(pair.key); - const auto&[collider2, transform2] = registry.get(pair.value); +bool CollisionSystem::checkCollision(Pair pair) { + const auto& [collider1, transform1] = registry.get(pair.key); + const auto& [collider2, transform2] = registry.get(pair.value); ShapeBase shape1 = collider1.physicsMesh.transform(transform1); ShapeBase shape2 = collider2.physicsMesh.transform(transform2); Witness witness; - if(cachedWitness.exists(pair)) - { + if (cachedWitness.exists(pair)) { witness = cachedWitness[pair]; } - if(witnessValid(witness, shape1, shape2)) - { + if (witnessValid(witness, shape1, shape2)) { return false; } return createWitness(witness, shape1, shape2); } -void CollisionSystem::updateWitness(Witness& result, const glm::vec3& point, const glm::vec3& v1, const glm::vec3& v2) -{ +void CollisionSystem::updateWitness(Witness& result, const glm::vec3& point, const glm::vec3& v1, const glm::vec3& v2) { const glm::vec3 faceNormal = glm::normalize(glm::cross(v1, v2)); result.n = faceNormal; result.p = point; } -bool CollisionSystem::createWitness(Witness& result, const ShapeBase& source, const ShapeBase& other) -{ - for (size_t i = 0; i < source.indices.size(); i += 3) - { +bool CollisionSystem::createWitness(Witness& result, const ShapeBase& source, const ShapeBase& other) { + for (size_t i = 0; i < source.indices.size(); i += 3) { const glm::vec3 point1 = source.vertices[source.indices[i + 0]]; const glm::vec3 point2 = source.vertices[source.indices[i + 1]]; const glm::vec3 point3 = source.vertices[source.indices[i + 2]]; const glm::vec3 v1 = point2 - point1; const glm::vec3 v2 = point3 - point1; - + updateWitness(result, point1, v1, v2); result.point1Index = source.indices[i + 0]; result.point2Index = source.indices[i + 1]; @@ -84,48 +68,39 @@ bool CollisionSystem::createWitness(Witness& result, const ShapeBase& source, co result.point4Index = UINT32_MAX; bool valid = witnessValid(result, source, other); // if not, it is a valid separating plane, so no collision - if (valid) - { + if (valid) { return false; } } - for (size_t i = 0; i < source.indices.size(); i += 3) - { - auto findEdgePlane = [this, &source, &other, &result](uint32_t point1Index, uint32_t point2Index) - { + for (size_t i = 0; i < source.indices.size(); i += 3) { + auto findEdgePlane = [this, &source, &other, &result](uint32_t point1Index, uint32_t point2Index) { const glm::vec3 point1 = source.vertices[point1Index]; const glm::vec3 point2 = source.vertices[point2Index]; result.point1Index = point1Index; result.point2Index = point2Index; const glm::vec3 d1 = point2 - point1; - for (size_t j = 0; j < other.indices.size(); j += 3) - { - for (const auto& [point3Index, point4Index] : { std::pair(j+1, j), std::pair(j+2, j+1), std::pair(j, j+2) }) - { + for (size_t j = 0; j < other.indices.size(); j += 3) { + for (const auto& [point3Index, point4Index] : {std::pair(j + 1, j), std::pair(j + 2, j + 1), std::pair(j, j + 2)}) { result.point3Index = other.indices[point3Index]; result.point4Index = other.indices[point4Index]; const glm::vec3 point3 = other.vertices[result.point3Index]; const glm::vec3 point4 = other.vertices[result.point4Index]; const glm::vec3 d2 = point3 - point4; updateWitness(result, point1, d2, d1); - if (witnessValid(result, source, other)) - { + if (witnessValid(result, source, other)) { return true; } } } return false; }; - if(findEdgePlane(source.indices[i], source.indices[i+1])) - { + if (findEdgePlane(source.indices[i], source.indices[i + 1])) { return false; } - if(findEdgePlane(source.indices[i+1], source.indices[i+2])) - { + if (findEdgePlane(source.indices[i + 1], source.indices[i + 2])) { return false; } - if(findEdgePlane(source.indices[i+2], source.indices[i])) - { + if (findEdgePlane(source.indices[i + 2], source.indices[i])) { return false; } } @@ -133,23 +108,18 @@ bool CollisionSystem::createWitness(Witness& result, const ShapeBase& source, co return true; } -bool CollisionSystem::witnessValid(const Witness& witness, const Component::ShapeBase& shape1, const Component::ShapeBase& shape2) -{ +bool CollisionSystem::witnessValid(const Witness& witness, const Component::ShapeBase& shape1, const Component::ShapeBase& shape2) { const float e = 0.0001f; - for (size_t i = 0; i < shape1.vertices.size(); i++) - { - if(glm::dot(witness.n, shape1.vertices[i] - witness.p) > e) - { + for (size_t i = 0; i < shape1.vertices.size(); i++) { + if (glm::dot(witness.n, shape1.vertices[i] - witness.p) > e) { // something intersecting the separating plane // it is not valid anymore return false; } } - for (size_t i = 0; i < shape2.vertices.size(); i++) - { - if(glm::dot(witness.n, shape2.vertices[i] - witness.p) < -e) - { + for (size_t i = 0; i < shape2.vertices.size(); i++) { + if (glm::dot(witness.n, shape2.vertices[i] - witness.p) < -e) { // something intersecting the separating plane // it is not valid anymore return false; @@ -157,4 +127,3 @@ bool CollisionSystem::witnessValid(const Witness& witness, const Component::Shap } return true; } - diff --git a/src/Engine/Physics/CollisionSystem.h b/src/Engine/Physics/CollisionSystem.h index 6974ef5..17006dd 100644 --- a/src/Engine/Physics/CollisionSystem.h +++ b/src/Engine/Physics/CollisionSystem.h @@ -1,26 +1,24 @@ #pragma once -#include #include "BVH.h" -#include "Containers/Map.h" -#include "Containers/Array.h" #include "Component/Collider.h" #include "Component/Transform.h" +#include "Containers/Array.h" +#include "Containers/Map.h" +#include -namespace Seele -{ -struct Collision -{ + +namespace Seele { +struct Collision { entt::entity a, b; }; -class CollisionSystem -{ -public: +class CollisionSystem { + public: CollisionSystem(entt::registry& registry); virtual ~CollisionSystem(); void detectCollisions(Array& collisions); -private: - struct Witness - { + + private: + struct Witness { Vector p; Vector n; // for finding p diff --git a/src/Engine/Physics/PhysicsSystem.cpp b/src/Engine/Physics/PhysicsSystem.cpp index 9ec4e0b..538fede 100644 --- a/src/Engine/Physics/PhysicsSystem.cpp +++ b/src/Engine/Physics/PhysicsSystem.cpp @@ -1,47 +1,36 @@ #include "PhysicsSystem.h" -#include #include +#include + using namespace Seele; using namespace Seele::Component; -PhysicsSystem::PhysicsSystem(entt::registry& registry) - : registry(registry) - , collisionSystem(registry) -{ +PhysicsSystem::PhysicsSystem(entt::registry& registry) : registry(registry), collisionSystem(registry) {} -} +PhysicsSystem::~PhysicsSystem() {} -PhysicsSystem::~PhysicsSystem() -{ - -} - -void PhysicsSystem::update(float deltaTime) -{ +void PhysicsSystem::update(float deltaTime) { Array initialBodies; readRigidBodies(initialBodies); - //std::cout << "Updating " << initialBodies.size() << " bodies" << std::endl; + // std::cout << "Updating " << initialBodies.size() << " bodies" << std::endl; Array bodies = integratePhysics(initialBodies, 0, deltaTime); writeRigidBodies(bodies); Array collisions; collisionSystem.detectCollisions(collisions); - - if(!collisions.empty()) - { + + if (!collisions.empty()) { constexpr size_t numSteps = 2; - for (float t = 0; t < deltaTime; t += deltaTime / numSteps) - { + for (float t = 0; t < deltaTime; t += deltaTime / numSteps) { rewindCollisions(initialBodies, t, t + (deltaTime / numSteps), 10); readRigidBodies(initialBodies); } } } -void PhysicsSystem::serializeRB(const Body& rb, float* y) const -{ +void PhysicsSystem::serializeRB(const Body& rb, float* y) const { *y++ = rb.x.x; *y++ = rb.x.y; *y++ = rb.x.z; @@ -60,8 +49,7 @@ void PhysicsSystem::serializeRB(const Body& rb, float* y) const *y++ = rb.L.z; } -void PhysicsSystem::deserializeRB(Body& rb, const float* y) const -{ +void PhysicsSystem::deserializeRB(Body& rb, const float* y) const { rb.x.x = *y++; rb.x.y = *y++; rb.x.z = *y++; @@ -85,49 +73,37 @@ void PhysicsSystem::deserializeRB(Body& rb, const float* y) const rb.omega = rb.iInv * rb.L; } -void PhysicsSystem::serializeArray(const Array& bodies, Array& x) const -{ +void PhysicsSystem::serializeArray(const Array& bodies, Array& x) const { x.resize(bodies.size() * FLOATS_PER_RB); - for(uint32_t i = 0; i < bodies.size(); ++i) - { - serializeRB(bodies[i], x.data()+(i*FLOATS_PER_RB)); + for (uint32_t i = 0; i < bodies.size(); ++i) { + serializeRB(bodies[i], x.data() + (i * FLOATS_PER_RB)); } } -void PhysicsSystem::deserializeArray(Array& bodies, const Array& x) const -{ +void PhysicsSystem::deserializeArray(Array& bodies, const Array& x) const { bodies.resize(x.size() / FLOATS_PER_RB); - for(uint32_t i = 0; i < bodies.size(); ++i) - { - deserializeRB(bodies[i], x.data()+(i*FLOATS_PER_RB)); + for (uint32_t i = 0; i < bodies.size(); ++i) { + deserializeRB(bodies[i], x.data() + (i * FLOATS_PER_RB)); } } -void PhysicsSystem::readRigidBodies(Array& bodies) const -{ +void PhysicsSystem::readRigidBodies(Array& bodies) const { auto view = registry.view(); bodies.clear(); bodies.reserve(view.size_hint()); - view - .each([&bodies](entt::entity id, RigidBody& rb, Transform& transform, Collider& collider) - { + view.each([&bodies](entt::entity id, RigidBody& rb, Transform& transform, Collider& collider) { Body& rigidBody = bodies.add(Body(id, rb, collider, transform)); rigidBody.updateMatrix(); }); - registry.view(entt::exclude) - .each([&bodies](entt::entity id, Collider& collider, Transform& transform) - { + registry.view(entt::exclude).each([&bodies](entt::entity id, Collider& collider, Transform& transform) { Body& rigidBody = bodies.add(Body(id, collider, transform)); rigidBody.updateMatrix(); }); } -void PhysicsSystem::writeRigidBodies(const Array& bodies) const -{ - for(auto& body : bodies) - { - if(registry.all_of(body.id)) - { +void PhysicsSystem::writeRigidBodies(const Array& bodies) const { + for (auto& body : bodies) { + if (registry.all_of(body.id)) { auto [physics, transform] = registry.get(body.id); transform.setPosition(body.x); transform.setRotation(body.q); @@ -139,16 +115,12 @@ void PhysicsSystem::writeRigidBodies(const Array& bodies) const } } -PhysicsSystem::Body PhysicsSystem::readRigidBody(entt::entity entity) const -{ +PhysicsSystem::Body PhysicsSystem::readRigidBody(entt::entity entity) const { Body rigidBody; - if(registry.all_of(entity)) - { + if (registry.all_of(entity)) { const auto& [physics, collider, transform] = registry.get(entity); rigidBody = Body(entity, physics, collider, transform); - } - else - { + } else { const auto& [collider, transform] = registry.get(entity); rigidBody = Body(entity, collider, transform); } @@ -156,11 +128,8 @@ PhysicsSystem::Body PhysicsSystem::readRigidBody(entt::entity entity) const return rigidBody; } - -void PhysicsSystem::writeRigidBody(const Body& body) const -{ - if(registry.all_of(body.id)) - { +void PhysicsSystem::writeRigidBody(const Body& body) const { + if (registry.all_of(body.id)) { const auto& [physics, transform] = registry.get(body.id); transform.setPosition(body.x); transform.setRotation(body.q); @@ -168,34 +137,29 @@ void PhysicsSystem::writeRigidBody(const Body& body) const physics.angularMomentum = body.L; physics.force = body.force; physics.torque = body.torque; - } - else - { + } else { auto& transform = registry.get(body.id); assert(transform.getPosition() == body.x); assert(transform.getRotation() == body.q); } } -Array PhysicsSystem::integratePhysics(const Array& bodies, const float t0, const float tdelta) const -{ +Array PhysicsSystem::integratePhysics(const Array& bodies, const float t0, const float tdelta) const { Array result; Array buffer; result.resize(bodies.size()); buffer.resize(bodies.size() * FLOATS_PER_RB); std::memcpy(result.data(), bodies.data(), result.size() * sizeof(Body)); serializeArray(bodies, buffer); - auto dxdt = [this, &result](const Array& x, Array& x2, const float) - { + auto dxdt = [this, &result](const Array& x, Array& x2, const float) { deserializeArray(result, x); float* xdot = x2.data(); - for (size_t i = 0; i < result.size(); i++) - { + for (size_t i = 0; i < result.size(); i++) { // x(t)' = v(t) *xdot++ = result[i].v.x; *xdot++ = result[i].v.y; *xdot++ = result[i].v.z; - + // R(t)' = omega(t)*R(t) Quaternion qdot = 0.5f * (Quaternion(0, result[i].omega) * result[i].q); *xdot++ = qdot.w; @@ -214,54 +178,48 @@ Array PhysicsSystem::integratePhysics(const Array& bo *xdot++ = result[i].torque.z; } }; - //TODO - //boost::numeric::odeint::runge_kutta4, float> stepper; - //boost::numeric::odeint::integrate_const(stepper, dxdt, buffer, t0, tdelta, tdelta); + // TODO + // boost::numeric::odeint::runge_kutta4, float> stepper; + // boost::numeric::odeint::integrate_const(stepper, dxdt, buffer, t0, tdelta, tdelta); deserializeArray(result, buffer); return result; } - - -void PhysicsSystem::rewindCollisions(const Array& t0Bodies, const float t0, const float t1, size_t remainingRecursionDepth) -{ - if(remainingRecursionDepth == 0) - { - //std::cout << "reached max recursion depth" << std::endl; +void PhysicsSystem::rewindCollisions(const Array& t0Bodies, const float t0, const float t1, size_t remainingRecursionDepth) { + if (remainingRecursionDepth == 0) { + // std::cout << "reached max recursion depth" << std::endl; } // there are collisions happening between t0 and t1 // we integrate until tc and see if they have already occured then Array collisions; writeRigidBodies(integratePhysics(t0Bodies, t0, t1)); collisionSystem.detectCollisions(collisions); - - //std::cout << "detected " << collisions.size() << " at " << tc << std::endl; - // now we check if there has been a contact at tc + + // std::cout << "detected " << collisions.size() << " at " << tc << std::endl; + // now we check if there has been a contact at tc Array contacts; // collision occured at [tc; t1] - for (auto &&collision : collisions) - { - const auto&[collider1, transform1] = registry.get(collision.a); - const auto&[collider2, transform2] = registry.get(collision.b); - calculateContacts(collision.a, collider1.physicsMesh.transform(transform1), collision.b, collider2.physicsMesh.transform(transform2), contacts); - calculateContacts(collision.b, collider2.physicsMesh.transform(transform2), collision.a, collider1.physicsMesh.transform(transform1), contacts); + for (auto&& collision : collisions) { + const auto& [collider1, transform1] = registry.get(collision.a); + const auto& [collider2, transform2] = registry.get(collision.b); + calculateContacts(collision.a, collider1.physicsMesh.transform(transform1), collision.b, + collider2.physicsMesh.transform(transform2), contacts); + calculateContacts(collision.b, collider2.physicsMesh.transform(transform2), collision.a, + collider1.physicsMesh.transform(transform1), contacts); } // we then apply forces in order to counteract interpenetration Array restingContacts; - for(const auto& contact : contacts) - { + for (const auto& contact : contacts) { Body a = readRigidBody(contact.a); Body b = readRigidBody(contact.b); Vector paDot = a.ptVelocity(contact.p); Vector pbDot = b.ptVelocity(contact.p); float vrel = glm::dot(contact.n, paDot - pbDot); - if(vrel > 0.001f) - { + if (vrel > 0.001f) { continue; } - if(vrel > -0.001f) - { + if (vrel > -0.001f) { restingContacts.add(contact); continue; } @@ -274,10 +232,9 @@ void PhysicsSystem::rewindCollisions(const Array& t0Bodies, const float t0 resolveRestingContacts(restingContacts); } -void PhysicsSystem::calculateContacts(entt::entity id1, const ShapeBase& shape1, entt::entity id2, const ShapeBase& shape2, Array& contacts) const -{ - for(size_t i = 0; i < shape1.indices.size(); i += 3) - { +void PhysicsSystem::calculateContacts(entt::entity id1, const ShapeBase& shape1, entt::entity id2, const ShapeBase& shape2, + Array& contacts) const { + for (size_t i = 0; i < shape1.indices.size(); i += 3) { // face - vertex contacts const Vector point1 = shape1.vertices[shape1.indices[i + 0]]; const Vector point2 = shape1.vertices[shape1.indices[i + 1]]; @@ -285,24 +242,14 @@ void PhysicsSystem::calculateContacts(entt::entity id1, const ShapeBase& shape1, const Vector v1 = point2 - point1; const Vector v2 = point3 - point1; const Vector faceNormal = glm::normalize(glm::cross(v1, v2)); - addDebugVertex(DebugVertex{ - .position = (point1 + point2 + point3) / 3.f, - .color = Vector(1, 0, 0) - }); - addDebugVertex(DebugVertex{ - .position = faceNormal + (point1 + point2 + point3) / 3.f, - .color = Vector(1, 0, 0) - }); - auto area = [](Vector ab, Vector ac){ - return glm::length(glm::cross(ab, ac)) / 2.0f; - }; + addDebugVertex(DebugVertex{.position = (point1 + point2 + point3) / 3.f, .color = Vector(1, 0, 0)}); + addDebugVertex(DebugVertex{.position = faceNormal + (point1 + point2 + point3) / 3.f, .color = Vector(1, 0, 0)}); + auto area = [](Vector ab, Vector ac) { return glm::length(glm::cross(ab, ac)) / 2.0f; }; float faceArea = area(v1, v2); - for(size_t j = 0; j < shape2.vertices.size(); j++) - { + for (size_t j = 0; j < shape2.vertices.size(); j++) { Vector worldPos = shape2.vertices[j]; float dot = glm::dot(faceNormal, worldPos - point1); - if(std::abs(dot) < 0.2f) - { + if (std::abs(dot) < 0.2f) { Vector pa = point1 - worldPos; Vector pb = point2 - worldPos; Vector pc = point3 - worldPos; @@ -310,27 +257,19 @@ void PhysicsSystem::calculateContacts(entt::entity id1, const ShapeBase& shape1, float a2 = area(pb, pc); float a3 = area(pc, pa); - if(std::abs(a1 + a2 + a3 - faceArea) > 0.2f) - { + if (std::abs(a1 + a2 + a3 - faceArea) > 0.2f) { continue; } - Contact c = { - .a = id2, - .b = id1, - .p = worldPos, - .n = faceNormal, - .vf = true - }; + Contact c = {.a = id2, .b = id1, .p = worldPos, .n = faceNormal, .vf = true}; contacts.add(c); } } - //std::cout << minTemp << std::endl; - // edge - edge contacts - auto lineLineContact = [=, &contacts](Vector p1, Vector p2, Vector p3, Vector p4) - { - //L1 = p1 + t * p2 - p1; - //L2 = p3 + u * p4 - p3; + // std::cout << minTemp << std::endl; + // edge - edge contacts + auto lineLineContact = [=, &contacts](Vector p1, Vector p2, Vector p3, Vector p4) { + // L1 = p1 + t * p2 - p1; + // L2 = p3 + u * p4 - p3; Vector a = p1; Vector c = p3; Vector ab = p2 - p1; @@ -341,12 +280,7 @@ void PhysicsSystem::calculateContacts(entt::entity id1, const ShapeBase& shape1, float ty = (c.x * ab.z - a.x * ab.z - c.z * ab.x + a.z * ab.x) / ty_den; float tz_den = cd.y * ab.x - cd.x * ab.y; float tz = (c.x * ab.y - a.x * ab.y - c.y * ab.x + a.y * ab.x) / tz_den; - if (std::abs(tx - ty) < 0.1f - && std::abs(ty - tz) < 0.1f - && std::abs(tz - tx) < 0.1f - && tx >= 0.f - && tx <= 1.f) - { + if (std::abs(tx - ty) < 0.1f && std::abs(ty - tz) < 0.1f && std::abs(tz - tx) < 0.1f && tx >= 0.f && tx <= 1.f) { // Vector p = p1 + tx * (p2 - p1); // Vector ea = p2 - p1; // Vector eb = p4 - p3; @@ -362,8 +296,7 @@ void PhysicsSystem::calculateContacts(entt::entity id1, const ShapeBase& shape1, // }; } }; - for(size_t j = 0; j < shape2.indices.size(); j+=3) - { + for (size_t j = 0; j < shape2.indices.size(); j += 3) { const Vector point4 = shape2.vertices[shape2.indices[j + 0]]; const Vector point5 = shape2.vertices[shape2.indices[j + 1]]; const Vector point6 = shape2.vertices[shape2.indices[j + 2]]; @@ -383,11 +316,9 @@ void PhysicsSystem::calculateContacts(entt::entity id1, const ShapeBase& shape1, } } -void PhysicsSystem::resolveRestingContacts(const Array& contacts) const -{ +void PhysicsSystem::resolveRestingContacts(const Array& contacts) const { Array> amat(contacts.size()); - for(size_t i = 0; i < contacts.size(); ++i) - { + for (size_t i = 0; i < contacts.size(); ++i) { amat[i] = Array(contacts.size()); } Array bvec(contacts.size()); @@ -398,8 +329,7 @@ void PhysicsSystem::resolveRestingContacts(const Array& contacts) const Array fvec(bvec); solveQP(amat, bvec, fvec); - for(size_t y = 0; y < contacts.size(); ++y) - { + for (size_t y = 0; y < contacts.size(); ++y) { std::cout << "resting contact force: " << fvec[y] << std::endl; float f = fvec[y]; Vector n = contacts[y].n; @@ -415,8 +345,7 @@ void PhysicsSystem::resolveRestingContacts(const Array& contacts) const } } -void PhysicsSystem::resolvePenetratingContact(const Contact& contact, Body& a, Body& b) const -{ +void PhysicsSystem::resolvePenetratingContact(const Contact& contact, Body& a, Body& b) const { Vector paDot = a.ptVelocity(contact.p); Vector pbDot = b.ptVelocity(contact.p); float vrel = glm::dot(contact.n, paDot - pbDot); @@ -445,14 +374,10 @@ void PhysicsSystem::resolvePenetratingContact(const Contact& contact, Body& a, B b.omega = b.iInv * b.L; } -Vector PhysicsSystem::computeNdot(const Contact& c, const Body& a, const Body& b) const -{ - if(c.vf) - { +Vector PhysicsSystem::computeNdot(const Contact& c, const Body& a, const Body& b) const { + if (c.vf) { return glm::cross(b.omega, c.n); - } - else - { + } else { Vector eadot = glm::cross(a.omega, c.ea); Vector ebdot = glm::cross(b.omega, c.eb); Vector n1 = glm::cross(c.ea, c.eb); @@ -464,10 +389,8 @@ Vector PhysicsSystem::computeNdot(const Contact& c, const Body& a, const Body& b } } -float PhysicsSystem::computeAij(const Contact& ci, const Contact& cj) const -{ - if((ci.a != cj.a) && (ci.b != cj.b) && - (ci.a != cj.b) && (ci.b != cj.a)) +float PhysicsSystem::computeAij(const Contact& ci, const Contact& cj) const { + if ((ci.a != cj.a) && (ci.b != cj.b) && (ci.a != cj.b) && (ci.b != cj.a)) return 0.0f; Body a = readRigidBody(ci.a); @@ -481,25 +404,19 @@ float PhysicsSystem::computeAij(const Contact& ci, const Contact& cj) const Vector forceOnA = Vector(0); Vector torqueOnA = Vector(0); - if(cj.a == ci.a) - { + if (cj.a == ci.a) { forceOnA = nj; torqueOnA = glm::cross((pj - a.x + a.centerOfMass), nj); - } - else if(cj.b == ci.a) - { + } else if (cj.b == ci.a) { forceOnA = -nj; torqueOnA = glm::cross((pj - a.x + a.centerOfMass), nj); } Vector forceOnB = Vector(0); Vector torqueOnB = Vector(0); - if(cj.a == ci.b) - { + if (cj.a == ci.b) { forceOnB = nj; torqueOnB = glm::cross((pj - b.x + b.centerOfMass), nj); - } - else if(cj.b == ci.b) - { + } else if (cj.b == ci.b) { forceOnB = -nj; torqueOnB = glm::cross((pj - b.x + b.centerOfMass), nj); } @@ -513,21 +430,16 @@ float PhysicsSystem::computeAij(const Contact& ci, const Contact& cj) const return glm::dot(ni, ((aLinear + aAngular) - (bLinear + bAngular))); } -void PhysicsSystem::computeAMatrix(const Array& contacts, Array>& amat) const -{ - for(size_t x = 0; x < contacts.size(); ++x) - { - for(size_t y = 0; y < contacts.size(); ++y) - { +void PhysicsSystem::computeAMatrix(const Array& contacts, Array>& amat) const { + for (size_t x = 0; x < contacts.size(); ++x) { + for (size_t y = 0; y < contacts.size(); ++y) { amat[x][y] = computeAij(contacts[x], contacts[y]); } } } -void PhysicsSystem::computeBVector(const Array& contacts, Array& bvec) const -{ - for(size_t y = 0; y < contacts.size(); ++y) - { +void PhysicsSystem::computeBVector(const Array& contacts, Array& bvec) const { + for (size_t y = 0; y < contacts.size(); ++y) { Contact c = contacts[y]; Body a = readRigidBody(c.a); Body b = readRigidBody(c.b); @@ -539,7 +451,7 @@ void PhysicsSystem::computeBVector(const Array& contacts, Array& Vector fExtB = b.force; Vector tExtA = a.torque; Vector tExtB = b.torque; - + Vector aExtPart = fExtA * a.inverseMass + glm::cross(a.iInv * tExtA, ra); Vector bExtPart = fExtB * b.inverseMass + glm::cross(b.iInv * tExtB, rb); @@ -554,28 +466,22 @@ void PhysicsSystem::computeBVector(const Array& contacts, Array& } } -void PhysicsSystem::solveQP(const Array>& CI, const Array& ci0, Array& sol) const -{ +void PhysicsSystem::solveQP(const Array>& CI, const Array& ci0, Array& sol) const { static std::mt19937_64 generator; static std::uniform_real_distribution dist(0.01f, 0.1f); sol.resize(CI.size()); bool solved = false; - while(!solved) - { - for(size_t i = 0; i < sol.size(); ++i) - { + while (!solved) { + for (size_t i = 0; i < sol.size(); ++i) { sol[i] = dist(generator); } solved = true; - for(size_t i = 0; i < sol.size(); ++i) - { + for (size_t i = 0; i < sol.size(); ++i) { float res = 0; - for(size_t j = 0; j < sol.size(); ++j) - { + for (size_t j = 0; j < sol.size(); ++j) { res += CI[i][j] * sol[j] + ci0[i]; } - if(res < 0) - { + if (res < 0) { solved = false; std::cout << "failed to solve QP" << std::endl; continue; diff --git a/src/Engine/Physics/PhysicsSystem.h b/src/Engine/Physics/PhysicsSystem.h index d71ecab..12fa1e2 100644 --- a/src/Engine/Physics/PhysicsSystem.h +++ b/src/Engine/Physics/PhysicsSystem.h @@ -1,22 +1,21 @@ #pragma once -#include -#include "MinimalEngine.h" -#include "Component/Transform.h" -#include "Component/RigidBody.h" -#include "Component/Collider.h" #include "CollisionSystem.h" +#include "Component/Collider.h" +#include "Component/RigidBody.h" +#include "Component/Transform.h" +#include "MinimalEngine.h" +#include -namespace Seele -{ -class PhysicsSystem -{ -public: + +namespace Seele { +class PhysicsSystem { + public: PhysicsSystem(entt::registry& registry); ~PhysicsSystem(); void update(float deltaTime); -private: - struct Body - { + + private: + struct Body { entt::entity id = entt::entity(); float inverseMass = 0.0f; Vector centerOfMass = Vector(); @@ -35,63 +34,36 @@ private: Vector force = Vector(); Vector torque = Vector(); Matrix4 matrix = Matrix4(); - Vector ptVelocity(Vector p) const {return v + glm::cross(omega, p - x + centerOfMass);} + Vector ptVelocity(Vector p) const { return v + glm::cross(omega, p - x + centerOfMass); } void updateMatrix() { Matrix4 scaleMatrix = glm::scale(Matrix4(1), scale); Matrix4 rotationMatrix = glm::mat4_cast(q); Matrix4 translationMatrix = glm::translate(Matrix4(1), x); matrix = translationMatrix * rotationMatrix * scaleMatrix; } - Body() - {} - Body(entt::entity id, const Component::RigidBody& physics, const Component::Collider& collider, const Component::Transform& transform) - : id(id) - , inverseMass(1 / (physics.mass * glm::length(transform.getScale()))) - , centerOfMass(collider.physicsMesh.centerOfMass) - , iBody(collider.physicsMesh.bodyInertia) - , iBodyInv(glm::inverse(collider.physicsMesh.bodyInertia)) - , scale(transform.getScale()) - , x(transform.getPosition()) - , q(transform.getRotation()) - , P(physics.linearMomentum) - , L(physics.angularMomentum) - , iInv(glm::mat3()) - , R(glm::mat3()) - , v(Vector()) - , omega(Vector()) - , force(physics.force) - , torque(physics.torque) - { + Body() {} + Body(entt::entity id, const Component::RigidBody& physics, const Component::Collider& collider, + const Component::Transform& transform) + : id(id), inverseMass(1 / (physics.mass * glm::length(transform.getScale()))), centerOfMass(collider.physicsMesh.centerOfMass), + iBody(collider.physicsMesh.bodyInertia), iBodyInv(glm::inverse(collider.physicsMesh.bodyInertia)), + scale(transform.getScale()), x(transform.getPosition()), q(transform.getRotation()), P(physics.linearMomentum), + L(physics.angularMomentum), iInv(glm::mat3()), R(glm::mat3()), v(Vector()), omega(Vector()), force(physics.force), + torque(physics.torque) { v = P * inverseMass; R = glm::mat3_cast(glm::normalize(q)); iInv = R * iBodyInv * glm::transpose(R); omega = iInv * L; } Body(entt::entity id, const Component::Collider& collider, const Component::Transform& transform) - : id(id) - , inverseMass(0) - , centerOfMass(collider.physicsMesh.centerOfMass) - , iBody(glm::mat3(0)) - , iBodyInv(glm::mat3(0)) - , scale(transform.getScale()) - , x(transform.getPosition()) - , q(transform.getRotation()) - , P(Vector(0)) - , L(Vector(0)) - , iInv(glm::mat3()) - , R(glm::mat3()) - , v(Vector()) - , omega(Vector()) - , force(Vector(0)) - , torque(Vector(0)) - { + : id(id), inverseMass(0), centerOfMass(collider.physicsMesh.centerOfMass), iBody(glm::mat3(0)), iBodyInv(glm::mat3(0)), + scale(transform.getScale()), x(transform.getPosition()), q(transform.getRotation()), P(Vector(0)), L(Vector(0)), + iInv(glm::mat3()), R(glm::mat3()), v(Vector()), omega(Vector()), force(Vector(0)), torque(Vector(0)) { R = glm::mat3_cast(glm::normalize(q)); iInv = R * iBodyInv * glm::transpose(R); omega = iInv * L; } }; - struct Contact - { + struct Contact { entt::entity a, b; glm::vec3 p; glm::vec3 n; @@ -105,26 +77,27 @@ private: bool pause = false; void serializeRB(const Body& rb, float* y) const; - + void deserializeRB(Body& rb, const float* y) const; - + void serializeArray(const Array& bodies, Array& x) const; - + void deserializeArray(Array& bodies, const Array& x) const; - + void readRigidBodies(Array& bodies) const; - + void writeRigidBodies(const Array& bodies) const; - + Body readRigidBody(entt::entity entity) const; - + void writeRigidBody(const Body& body) const; - + Array integratePhysics(const Array& bodies, const float t0, const float tdelta) const; - + void rewindCollisions(const Array& t0Bodies, const float t0, const float t1, size_t remainingDepth); - - void calculateContacts(entt::entity id1, const Component::ShapeBase& shape1, entt::entity id2, const Component::ShapeBase& shape2, Array& contacts) const; + + void calculateContacts(entt::entity id1, const Component::ShapeBase& shape1, entt::entity id2, const Component::ShapeBase& shape2, + Array& contacts) const; void resolveRestingContacts(const Array& contacts) const; diff --git a/src/Engine/Platform/Linux/GameInterface.cpp b/src/Engine/Platform/Linux/GameInterface.cpp index dc09864..bb690a3 100644 --- a/src/Engine/Platform/Linux/GameInterface.cpp +++ b/src/Engine/Platform/Linux/GameInterface.cpp @@ -2,26 +2,14 @@ using namespace Seele; -GameInterface::GameInterface(std::string soPath) - : lib(NULL) - , soPath(soPath) -{ -} +GameInterface::GameInterface(std::string soPath) : lib(NULL), soPath(soPath) {} -GameInterface::~GameInterface() -{ - -} +GameInterface::~GameInterface() {} -Game* GameInterface::getGame() -{ - return game; -} +Game* GameInterface::getGame() { return game; } -void GameInterface::reload() -{ - if(lib != NULL) - { +void GameInterface::reload() { + if (lib != NULL) { destroyInstance(game); dlclose(lib); } diff --git a/src/Engine/Platform/Linux/GameInterface.h b/src/Engine/Platform/Linux/GameInterface.h index b9649c9..7b0a2d9 100644 --- a/src/Engine/Platform/Linux/GameInterface.h +++ b/src/Engine/Platform/Linux/GameInterface.h @@ -2,16 +2,15 @@ #include "Game.h" #include "dlfcn.h" -namespace Seele -{ -class GameInterface -{ -public: +namespace Seele { +class GameInterface { + public: GameInterface(std::string soPath); ~GameInterface(); Game* getGame(); void reload(); -private: + + private: void* lib; std::string soPath; Game* game; diff --git a/src/Engine/Platform/Mac/GameInterface.cpp b/src/Engine/Platform/Mac/GameInterface.cpp index dc09864..bb690a3 100644 --- a/src/Engine/Platform/Mac/GameInterface.cpp +++ b/src/Engine/Platform/Mac/GameInterface.cpp @@ -2,26 +2,14 @@ using namespace Seele; -GameInterface::GameInterface(std::string soPath) - : lib(NULL) - , soPath(soPath) -{ -} +GameInterface::GameInterface(std::string soPath) : lib(NULL), soPath(soPath) {} -GameInterface::~GameInterface() -{ - -} +GameInterface::~GameInterface() {} -Game* GameInterface::getGame() -{ - return game; -} +Game* GameInterface::getGame() { return game; } -void GameInterface::reload() -{ - if(lib != NULL) - { +void GameInterface::reload() { + if (lib != NULL) { destroyInstance(game); dlclose(lib); } diff --git a/src/Engine/Platform/Mac/GameInterface.h b/src/Engine/Platform/Mac/GameInterface.h index b9649c9..7b0a2d9 100644 --- a/src/Engine/Platform/Mac/GameInterface.h +++ b/src/Engine/Platform/Mac/GameInterface.h @@ -2,16 +2,15 @@ #include "Game.h" #include "dlfcn.h" -namespace Seele -{ -class GameInterface -{ -public: +namespace Seele { +class GameInterface { + public: GameInterface(std::string soPath); ~GameInterface(); Game* getGame(); void reload(); -private: + + private: void* lib; std::string soPath; Game* game; diff --git a/src/Engine/Platform/Windows/GameInterface.cpp b/src/Engine/Platform/Windows/GameInterface.cpp index 7ead9de..afdbd89 100644 --- a/src/Engine/Platform/Windows/GameInterface.cpp +++ b/src/Engine/Platform/Windows/GameInterface.cpp @@ -2,25 +2,14 @@ using namespace Seele; -GameInterface::GameInterface(std::string dllPath) - : dllPath(dllPath) -{ -} +GameInterface::GameInterface(std::string dllPath) : dllPath(dllPath) {} -GameInterface::~GameInterface() -{ - -} +GameInterface::~GameInterface() {} -Game* GameInterface::getGame() -{ - return game; -} +Game* GameInterface::getGame() { return game; } -void GameInterface::reload() -{ - if(lib != NULL) - { +void GameInterface::reload() { + if (lib != NULL) { destroyInstance(game); FreeLibrary(lib); } diff --git a/src/Engine/Platform/Windows/GameInterface.h b/src/Engine/Platform/Windows/GameInterface.h index ed0e447..6819f46 100644 --- a/src/Engine/Platform/Windows/GameInterface.h +++ b/src/Engine/Platform/Windows/GameInterface.h @@ -2,16 +2,15 @@ #include "Game.h" #include "Windows.h" -namespace Seele -{ -class GameInterface -{ -public: +namespace Seele { +class GameInterface { + public: GameInterface(std::string dllPath); ~GameInterface(); Game* getGame(); void reload(); -private: + + private: HMODULE lib = NULL; std::string dllPath; Game* game; diff --git a/src/Engine/Scene/EventManager.h b/src/Engine/Scene/EventManager.h index 6715b39..3b3f545 100644 --- a/src/Engine/Scene/EventManager.h +++ b/src/Engine/Scene/EventManager.h @@ -1,25 +1,13 @@ #pragma once #include -namespace Seele -{ -template -struct Event -{ -}; -class EventManager -{ -public: - template - void pushEvent(Event event) - { +namespace Seele { +template struct Event {}; +class EventManager { + public: + template void pushEvent(Event event) {} + template void subscribe() {} - } - template - void subscribe() - { - - } -private: + private: }; } // namespace Seele diff --git a/src/Engine/Scene/LightEnvironment.cpp b/src/Engine/Scene/LightEnvironment.cpp index 411719e..ddf6bd4 100644 --- a/src/Engine/Scene/LightEnvironment.cpp +++ b/src/Engine/Scene/LightEnvironment.cpp @@ -3,122 +3,102 @@ using namespace Seele; -LightEnvironment::LightEnvironment(Gfx::PGraphics graphics) - : graphics(graphics) -{ +LightEnvironment::LightEnvironment(Gfx::PGraphics graphics) : graphics(graphics) { layout = graphics->createDescriptorLayout("pLightEnv"); - layout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 0, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,}); - layout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 1, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,}); - layout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = 2, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,}); + layout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 0, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + }); + layout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 1, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, + }); + layout->addDescriptorBinding(Gfx::DescriptorBinding{ + .binding = 2, + .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, + }); layout->create(); lightEnvBuffer = graphics->createUniformBuffer(UniformBufferCreateInfo{ - .sourceData = { - .size = sizeof(LightEnv), - .data = (uint8*) &lightEnv, - }, + .sourceData = + { + .size = sizeof(LightEnv), + .data = (uint8*)&lightEnv, + }, .dynamic = true, }); directionalLights = graphics->createShaderBuffer(ShaderBufferCreateInfo{ - .sourceData = { - .size = sizeof(Component::DirectionalLight) * INIT_DIRECTIONAL_LIGHTS, - .data = nullptr, - }, + .sourceData = + { + .size = sizeof(Component::DirectionalLight) * INIT_DIRECTIONAL_LIGHTS, + .data = nullptr, + }, .numElements = INIT_DIRECTIONAL_LIGHTS, .dynamic = true, }); pointLights = graphics->createShaderBuffer(ShaderBufferCreateInfo{ - .sourceData = { - .size = sizeof(Component::PointLight) * INIT_POINT_LIGHTS, - .data = nullptr, - }, + .sourceData = + { + .size = sizeof(Component::PointLight) * INIT_POINT_LIGHTS, + .data = nullptr, + }, .numElements = INIT_POINT_LIGHTS, .dynamic = true, }); } -LightEnvironment::~LightEnvironment() -{ -} +LightEnvironment::~LightEnvironment() {} -void LightEnvironment::reset() -{ +void LightEnvironment::reset() { layout->reset(); set = layout->allocateDescriptorSet(); dirs.clear(); points.clear(); } -void LightEnvironment::addDirectionalLight(Component::DirectionalLight dirLight) -{ - dirs.add(dirLight); -} +void LightEnvironment::addDirectionalLight(Component::DirectionalLight dirLight) { dirs.add(dirLight); } -void LightEnvironment::addPointLight(Component::PointLight pointLight) -{ - points.add(pointLight); -} +void LightEnvironment::addPointLight(Component::PointLight pointLight) { points.add(pointLight); } -void LightEnvironment::commit() -{ - lightEnvBuffer->pipelineBarrier( - Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_ALL_COMMANDS_BIT, - Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT - ); - pointLights->pipelineBarrier( - Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_ALL_COMMANDS_BIT, - Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT - ); - directionalLights->pipelineBarrier( - Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_ALL_COMMANDS_BIT, - Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT - ); +void LightEnvironment::commit() { + lightEnvBuffer->pipelineBarrier(Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_ALL_COMMANDS_BIT, + Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT); + pointLights->pipelineBarrier(Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_ALL_COMMANDS_BIT, Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, + Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT); + directionalLights->pipelineBarrier(Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_ALL_COMMANDS_BIT, + Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT); lightEnv.numDirectionalLights = dirs.size(); lightEnv.numPointLights = points.size(); lightEnvBuffer->updateContents(DataSource{ .size = sizeof(LightEnv), - .data = (uint8*) & lightEnv, - }); + .data = (uint8*)&lightEnv, + }); directionalLights->rotateBuffer(sizeof(Component::DirectionalLight) * dirs.size()); directionalLights->updateContents({ - .sourceData = { - .size = sizeof(Component::DirectionalLight) * dirs.size(), - .data = (uint8*)dirs.data(), - }, + .sourceData = + { + .size = sizeof(Component::DirectionalLight) * dirs.size(), + .data = (uint8*)dirs.data(), + }, .numElements = dirs.size(), }); pointLights->rotateBuffer(sizeof(Component::PointLight) * points.size()); pointLights->updateContents({ - .sourceData = { - .size = sizeof(Component::PointLight) * points.size(), - .data = (uint8*)points.data() - }, + .sourceData = {.size = sizeof(Component::PointLight) * points.size(), .data = (uint8*)points.data()}, .numElements = points.size(), }); - - lightEnvBuffer->pipelineBarrier( - Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, - Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_ALL_COMMANDS_BIT - ); - pointLights->pipelineBarrier( - Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, - Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_ALL_COMMANDS_BIT - ); - directionalLights->pipelineBarrier( - Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, - Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_ALL_COMMANDS_BIT - ); + + lightEnvBuffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT, + Gfx::SE_PIPELINE_STAGE_ALL_COMMANDS_BIT); + pointLights->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT, + Gfx::SE_PIPELINE_STAGE_ALL_COMMANDS_BIT); + directionalLights->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, + Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_ALL_COMMANDS_BIT); set->updateBuffer(0, lightEnvBuffer); set->updateBuffer(1, directionalLights); set->updateBuffer(2, pointLights); set->writeChanges(); } -const Gfx::PDescriptorLayout LightEnvironment::getDescriptorLayout() const -{ - return layout; -} +const Gfx::PDescriptorLayout LightEnvironment::getDescriptorLayout() const { return layout; } -Gfx::PDescriptorSet LightEnvironment::getDescriptorSet() -{ - return set; -} +Gfx::PDescriptorSet LightEnvironment::getDescriptorSet() { return set; } diff --git a/src/Engine/Scene/LightEnvironment.h b/src/Engine/Scene/LightEnvironment.h index 3f32a45..f88f861 100644 --- a/src/Engine/Scene/LightEnvironment.h +++ b/src/Engine/Scene/LightEnvironment.h @@ -1,14 +1,13 @@ #pragma once -#include "Graphics/Descriptor.h" -#include "Graphics/Buffer.h" #include "Component/DirectionalLight.h" #include "Component/PointLight.h" +#include "Graphics/Buffer.h" +#include "Graphics/Descriptor.h" -namespace Seele -{ -class LightEnvironment -{ -public: + +namespace Seele { +class LightEnvironment { + public: LightEnvironment(Gfx::PGraphics graphics); ~LightEnvironment(); void reset(); @@ -17,11 +16,11 @@ public: void commit(); const Gfx::PDescriptorLayout getDescriptorLayout() const; Gfx::PDescriptorSet getDescriptorSet(); -private: - #define INIT_DIRECTIONAL_LIGHTS 4 - #define INIT_POINT_LIGHTS 256 - struct LightEnv - { + + private: +#define INIT_DIRECTIONAL_LIGHTS 4 +#define INIT_POINT_LIGHTS 256 + struct LightEnv { uint32 numDirectionalLights; uint32 numPointLights; } lightEnv; @@ -35,4 +34,4 @@ private: Gfx::PGraphics graphics; }; DEFINE_REF(LightEnvironment) -} \ No newline at end of file +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/Scene/Scene.cpp b/src/Engine/Scene/Scene.cpp index 2a1d9ca..2d1c67f 100644 --- a/src/Engine/Scene/Scene.cpp +++ b/src/Engine/Scene/Scene.cpp @@ -1,30 +1,20 @@ #include "Scene.h" +#include "Actor/PointLightActor.h" +#include "Asset/AssetRegistry.h" +#include "Asset/MaterialAsset.h" +#include "Asset/TextureAsset.h" +#include "Component/DirectionalLight.h" +#include "Component/Mesh.h" +#include "Component/PointLight.h" +#include "Component/Transform.h" #include "Graphics/Graphics.h" #include "Graphics/Mesh.h" -#include "Component/Mesh.h" -#include "Component/Transform.h" -#include "Asset/AssetRegistry.h" -#include "Asset/TextureAsset.h" -#include "Asset/MaterialAsset.h" -#include "Component/PointLight.h" -#include "Component/DirectionalLight.h" -#include "Actor/PointLightActor.h" + using namespace Seele; -Scene::Scene(Gfx::PGraphics graphics) - : graphics(graphics) - , lightEnv(new LightEnvironment(graphics)) - , physics(registry) -{ -} +Scene::Scene(Gfx::PGraphics graphics) : graphics(graphics), lightEnv(new LightEnvironment(graphics)), physics(registry) {} -Scene::~Scene() -{ -} - -void Scene::update(float deltaTime) -{ - physics.update(deltaTime); -} +Scene::~Scene() {} +void Scene::update(float deltaTime) { physics.update(deltaTime); } diff --git a/src/Engine/Scene/Scene.h b/src/Engine/Scene/Scene.h index dac8c30..b2deed0 100644 --- a/src/Engine/Scene/Scene.h +++ b/src/Engine/Scene/Scene.h @@ -1,64 +1,41 @@ #pragma once -#include -#include "MinimalEngine.h" -#include "Graphics/Graphics.h" -#include "Physics/PhysicsSystem.h" #include "Component/Skybox.h" +#include "Graphics/Graphics.h" #include "LightEnvironment.h" +#include "MinimalEngine.h" +#include "Physics/PhysicsSystem.h" +#include #include -namespace Seele -{ + +namespace Seele { DECLARE_REF(Material) DECLARE_REF(Entity) -class Scene -{ -public: +class Scene { + public: Scene(Gfx::PGraphics graphics); ~Scene(); void update(float deltaTime); - entt::entity createEntity() - { - return registry.create(); - } - void destroyEntity(entt::entity identifier) - { - registry.destroy(identifier); - } - template - Component& attachComponent(entt::entity entity, Args&&... args) - { + entt::entity createEntity() { return registry.create(); } + void destroyEntity(entt::entity identifier) { registry.destroy(identifier); } + template Component& attachComponent(entt::entity entity, Args&&... args) { return registry.emplace(entity, std::forward(args)...); } - template - Component& accessComponent(entt::entity entity) - { - return registry.get(entity); - } - template - const Component& accessComponent(entt::entity entity) const - { - return registry.get(entity); - } - template - void view(Func func) requires std::is_invocable_v || std::is_invocable_v + template Component& accessComponent(entt::entity entity) { return registry.get(entity); } + template const Component& accessComponent(entt::entity entity) const { return registry.get(entity); } + template + void view(Func func) + requires std::is_invocable_v || std::is_invocable_v { registry.view().each(func); } - template - auto constructCallback() - { - return registry.on_construct(); - } - template - auto destroyCallback() - { - return registry.on_destroy(); - } + template auto constructCallback() { return registry.on_construct(); } + template auto destroyCallback() { return registry.on_destroy(); } PLightEnvironment getLightEnvironment() { return lightEnv; } Gfx::PGraphics getGraphics() const { return graphics; } entt::registry registry; -private: + + private: Gfx::PGraphics graphics; OLightEnvironment lightEnv; PhysicsSystem physics; diff --git a/src/Engine/Scene/Util.h b/src/Engine/Scene/Util.h index cccc89a..388a8b9 100644 --- a/src/Engine/Scene/Util.h +++ b/src/Engine/Scene/Util.h @@ -1,136 +1,88 @@ #pragma once #include "MinimalEngine.h" -namespace Seele -{ -template -class Writable -{ -public: - Writable() - {} - Writable(T initialData) - : toBeWritten(initialData) - , data(initialData) - {} +namespace Seele { +template class Writable { + public: + Writable() {} + Writable(T initialData) : toBeWritten(initialData), data(initialData) {} Writable(const Writable& other) = delete; Writable(Writable&& other) = default; ~Writable() = default; Writable& operator=(const Writable& other) const = delete; Writable& operator=(Writable&& other) const = delete; - const Writable& operator=(const T& other) const - { + const Writable& operator=(const T& other) const { deferWrite(other); return *this; } - const Writable& operator=(T&& other) const - { + const Writable& operator=(T&& other) const { deferWrite(std::move(other)); return *this; } - template - const Writable& operator+(Other&& other) const - { + template const Writable& operator+(Other&& other) const { deferWrite(data + std::forward(other)); return *this; } - template - const Writable& operator-(Other&& other) const - { + template const Writable& operator-(Other&& other) const { deferWrite(data - std::forward(other)); return *this; } - template - const Writable& operator*(Other&& other) const - { + template const Writable& operator*(Other&& other) const { deferWrite(data * std::forward(other)); return *this; } - template - const Writable& operator/(Other&& other) const - { + template const Writable& operator/(Other&& other) const { deferWrite(data / std::forward(other)); return *this; } - template - const Writable& operator%(Other&& other) const - { + template const Writable& operator%(Other&& other) const { deferWrite(data % std::forward(other)); return *this; } - template - const Writable& operator^(Other&& other) const - { + template const Writable& operator^(Other&& other) const { deferWrite(data ^ std::forward(other)); return *this; } - template - const Writable& operator&(Other&& other) const - { + template const Writable& operator&(Other&& other) const { deferWrite(data & std::forward(other)); return *this; } - template - const Writable& operator|(Other&& other) const - { + template const Writable& operator|(Other&& other) const { deferWrite(data | std::forward(other)); return *this; } - template - bool operator==(Type other) const - { - return data == other.data; - } - template - bool operator<=>(Type other) const - { - return data <=> other.data; - } - const Writable& operator++() const - { - deferWrite(data+1); + template bool operator==(Type other) const { return data == other.data; } + template bool operator<=>(Type other) const { return data <=> other.data; } + const Writable& operator++() const { + deferWrite(data + 1); return *this; } - const Writable& operator--() const - { - deferWrite(data-1); + const Writable& operator--() const { + deferWrite(data - 1); return *this; } - Writable&& operator++(int) const - { + Writable&& operator++(int) const { Writable tmp(data); ++*this; return std::move(tmp); } - Writable&& operator--(int) const - { + Writable&& operator--(int) const { Writable tmp(data); --*this; return std::move(tmp); } - const T& operator*() const - { - return data; - } - const T& get() const - { - return data; - } - const T& operator->() const - { - return data; - } - void update() - { + const T& operator*() const { return data; } + const T& get() const { return data; } + const T& operator->() const { return data; } + void update() { // lock should not be necessary, but lets keep it for now - //std::scoped_lock lock(dataLock); + // std::scoped_lock lock(dataLock); data = toBeWritten; dirty = false; } -private: - template - void deferWrite(Type&& newValue) const - { + + private: + template void deferWrite(Type&& newValue) const { std::scoped_lock lock(dataLock); assert(!dirty); toBeWritten = std::forward(newValue); @@ -141,9 +93,6 @@ private: mutable T toBeWritten; T data; }; -template -concept writable = requires(A&& a) -{ - a.update(); -}; +template +concept writable = requires(A&& a) { a.update(); }; } // namespace Seele diff --git a/src/Engine/Serialization/ArchiveBuffer.cpp b/src/Engine/Serialization/ArchiveBuffer.cpp index 01b3257..953dbd0 100644 --- a/src/Engine/Serialization/ArchiveBuffer.cpp +++ b/src/Engine/Serialization/ArchiveBuffer.cpp @@ -1,44 +1,37 @@ #include "ArchiveBuffer.h" #include "Graphics/Graphics.h" -#include #include +#include + using namespace Seele; -ArchiveBuffer::ArchiveBuffer() -{} +ArchiveBuffer::ArchiveBuffer() {} -ArchiveBuffer::ArchiveBuffer(Gfx::PGraphics graphics) - : graphics(graphics) -{} +ArchiveBuffer::ArchiveBuffer(Gfx::PGraphics graphics) : graphics(graphics) {} -void ArchiveBuffer::writeBytes(const void* data, uint64 size) -{ - if (size + position >= memory.size()) - { +void ArchiveBuffer::writeBytes(const void* data, uint64 size) { + if (size + position >= memory.size()) { memory.resize(size + position); } std::memcpy(memory.data() + position, data, size); position += size; } -void ArchiveBuffer::readBytes(void* dest, uint64 size) -{ +void ArchiveBuffer::readBytes(void* dest, uint64 size) { assert(position + size <= memory.size()); std::memcpy(dest, memory.data() + position, size); position += size; } -void ArchiveBuffer::writeToStream(std::ostream& stream) -{ +void ArchiveBuffer::writeToStream(std::ostream& stream) { uint64 bufferLength = memory.size(); stream.write((char*)&version, sizeof(uint64)); stream.write((char*)&bufferLength, sizeof(uint64)); stream.write((char*)memory.data(), memory.size()); } -void ArchiveBuffer::readFromStream(std::istream& stream) -{ +void ArchiveBuffer::readFromStream(std::istream& stream) { stream.read((char*)&version, sizeof(uint64)); uint64 bufferLength = 0; stream.read((char*)&bufferLength, sizeof(uint64)); @@ -46,11 +39,9 @@ void ArchiveBuffer::readFromStream(std::istream& stream) stream.read((char*)memory.data(), bufferLength); } -void ArchiveBuffer::seek(int64 s, SeekOp op) -{ +void ArchiveBuffer::seek(int64 s, SeekOp op) { int64 newPos = position; - switch (op) - { + switch (op) { case SeekOp::BEGIN: newPos = s; break; @@ -65,22 +56,10 @@ void ArchiveBuffer::seek(int64 s, SeekOp op) newPos = position; } -bool ArchiveBuffer::eof() const -{ - return position == memory.size(); -} +bool ArchiveBuffer::eof() const { return position == memory.size(); } -size_t Seele::ArchiveBuffer::size() const -{ - return memory.size(); -} +size_t Seele::ArchiveBuffer::size() const { return memory.size(); } -void ArchiveBuffer::rewind() -{ - position = 0; -} +void ArchiveBuffer::rewind() { position = 0; } -Gfx::PGraphics& ArchiveBuffer::getGraphics() -{ - return graphics; -} +Gfx::PGraphics& ArchiveBuffer::getGraphics() { return graphics; } diff --git a/src/Engine/Serialization/ArchiveBuffer.h b/src/Engine/Serialization/ArchiveBuffer.h index 20ed243..9406aa0 100644 --- a/src/Engine/Serialization/ArchiveBuffer.h +++ b/src/Engine/Serialization/ArchiveBuffer.h @@ -1,23 +1,21 @@ #pragma once -#include "MinimalEngine.h" -#include "Containers/Array.h" #include "Concepts.h" +#include "Containers/Array.h" +#include "MinimalEngine.h" #include -namespace Seele -{ + +namespace Seele { DECLARE_NAME_REF(Gfx, Graphics) -class ArchiveBuffer -{ -public: +class ArchiveBuffer { + public: ArchiveBuffer(); ArchiveBuffer(Gfx::PGraphics graphics); void writeBytes(const void* data, uint64 size); void readBytes(void* dest, uint64 size); void writeToStream(std::ostream& stream); void readFromStream(std::istream& stream); - enum class SeekOp - { + enum class SeekOp { CURRENT, BEGIN, END, @@ -27,7 +25,8 @@ public: size_t size() const; void rewind(); Gfx::PGraphics& getGraphics(); -private: + + private: Gfx::PGraphics graphics; uint64 version = 0; uint64 position = 0; diff --git a/src/Engine/Serialization/Serialization.h b/src/Engine/Serialization/Serialization.h index 2e2162a..4342930 100644 --- a/src/Engine/Serialization/Serialization.h +++ b/src/Engine/Serialization/Serialization.h @@ -1,156 +1,115 @@ #pragma once #include "ArchiveBuffer.h" -#include "Math/Vector.h" #include "Math/Matrix.h" +#include "Math/Vector.h" -namespace Seele + +namespace Seele { +namespace Serialization { +template static void save(ArchiveBuffer& buffer, const T& type) { buffer.writeBytes(&type, sizeof(type)); } +template static void load(ArchiveBuffer& buffer, T& type) { buffer.readBytes(&type, sizeof(type)); } +template static void save(ArchiveBuffer& buffer, const T& type) { buffer.writeBytes(&type, sizeof(type)); } +template static void load(ArchiveBuffer& buffer, T& type) { buffer.readBytes(&type, sizeof(type)); } +static void save(ArchiveBuffer& buffer, const IVector2& vec) { + save(buffer, vec.x); + save(buffer, vec.y); +} +static void load(ArchiveBuffer& buffer, IVector2& vec) { + load(buffer, vec.x); + load(buffer, vec.y); +} +static void save(ArchiveBuffer& buffer, const Vector2& vec) { + save(buffer, vec.x); + save(buffer, vec.y); +} +static void load(ArchiveBuffer& buffer, Vector2& vec) { + load(buffer, vec.x); + load(buffer, vec.y); +} +static void save(ArchiveBuffer& buffer, const Vector& vec) { + save(buffer, vec.x); + save(buffer, vec.y); + save(buffer, vec.z); +} +static void load(ArchiveBuffer& buffer, Matrix4& mat) { buffer.readBytes(&mat, sizeof(Matrix4)); } +static void save(ArchiveBuffer& buffer, const Matrix4& mat) { buffer.writeBytes(&mat, sizeof(Matrix4)); } +static void load(ArchiveBuffer& buffer, Vector& vec) { + load(buffer, vec.x); + load(buffer, vec.y); + load(buffer, vec.z); +} +template static void save(ArchiveBuffer& buffer, const T& type) { buffer.writeBytes(&type, sizeof(type)); } +template static void load(ArchiveBuffer& buffer, T& type) { buffer.readBytes(&type, sizeof(type)); } +template +static void save(ArchiveBuffer& buffer, const T& type) + requires(serializable) { -namespace Serialization + type.save(buffer); +} +template +static void load(ArchiveBuffer& buffer, T& type) + requires(serializable) { - template - static void save(ArchiveBuffer& buffer, const T& type) - { - buffer.writeBytes(&type, sizeof(type)); + type.load(buffer); +} +template static void save(ArchiveBuffer& buffer, const OwningPtr& ptr); +template static void load(ArchiveBuffer& buffer, OwningPtr& ptr); +static void save(ArchiveBuffer& buffer, const std::string& type) { + uint64 length = type.size(); + buffer.writeBytes(&length, sizeof(uint64)); + buffer.writeBytes(type.data(), type.size() * sizeof(char)); +} +static void load(ArchiveBuffer& buffer, std::string& type) { + uint64 length = 0; + buffer.readBytes(&length, sizeof(uint64)); + type.resize(length); + buffer.readBytes(type.data(), length * sizeof(char)); +} +template +static void save(ArchiveBuffer& buffer, const Array& type) + requires(std::is_trivially_copyable_v) +{ + uint64 length = type.size(); + buffer.writeBytes(&length, sizeof(uint64)); + buffer.writeBytes(type.data(), sizeof(T) * type.size()); +} +template +static void load(ArchiveBuffer& buffer, Array& type) + requires(std::is_trivially_copyable_v) +{ + uint64 length = 0; + buffer.readBytes(&length, sizeof(uint64)); + type.resize(length); + buffer.readBytes(type.data(), sizeof(T) * type.size()); +} +template +static void save(ArchiveBuffer& buffer, const StaticArray& type) + requires(std::is_trivially_copyable_v) +{ + buffer.writeBytes(type.data(), sizeof(T) * N); +} +template +static void load(ArchiveBuffer& buffer, StaticArray& type) + requires(std::is_trivially_copyable_v) +{ + buffer.readBytes(type.data(), sizeof(T) * N); +} +template static void save(ArchiveBuffer& buffer, const Array& type) { + uint64 length = type.size(); + buffer.writeBytes(&length, sizeof(uint64)); + for (const T& x : type) { + save(buffer, x); } - template - static void load(ArchiveBuffer& buffer, T& type) - { - buffer.readBytes(&type, sizeof(type)); - } - template - static void save(ArchiveBuffer& buffer, const T& type) - { - buffer.writeBytes(&type, sizeof(type)); - } - template - static void load(ArchiveBuffer& buffer, T& type) - { - buffer.readBytes(&type, sizeof(type)); - } - static void save(ArchiveBuffer& buffer, const IVector2& vec) - { - save(buffer, vec.x); - save(buffer, vec.y); - } - static void load(ArchiveBuffer& buffer, IVector2& vec) - { - load(buffer, vec.x); - load(buffer, vec.y); - } - static void save(ArchiveBuffer& buffer, const Vector2& vec) - { - save(buffer, vec.x); - save(buffer, vec.y); - } - static void load(ArchiveBuffer& buffer, Vector2& vec) - { - load(buffer, vec.x); - load(buffer, vec.y); - } - static void save(ArchiveBuffer& buffer, const Vector& vec) - { - save(buffer, vec.x); - save(buffer, vec.y); - save(buffer, vec.z); - } - static void load(ArchiveBuffer& buffer, Matrix4& mat) - { - buffer.readBytes(&mat, sizeof(Matrix4)); - } - static void save(ArchiveBuffer& buffer, const Matrix4& mat) - { - buffer.writeBytes(&mat, sizeof(Matrix4)); - } - static void load(ArchiveBuffer& buffer, Vector& vec) - { - load(buffer, vec.x); - load(buffer, vec.y); - load(buffer, vec.z); - } - template - static void save(ArchiveBuffer& buffer, const T& type) - { - buffer.writeBytes(&type, sizeof(type)); - } - template - static void load(ArchiveBuffer& buffer, T& type) - { - buffer.readBytes(&type, sizeof(type)); - } - template - static void save(ArchiveBuffer& buffer, const T& type) requires(serializable) - { - type.save(buffer); - } - template - static void load(ArchiveBuffer& buffer, T& type) requires(serializable) - { - type.load(buffer); - } - template - static void save(ArchiveBuffer& buffer, const OwningPtr& ptr); - template - static void load(ArchiveBuffer& buffer, OwningPtr& ptr); - static void save(ArchiveBuffer& buffer, const std::string& type) - { - uint64 length = type.size(); - buffer.writeBytes(&length, sizeof(uint64)); - buffer.writeBytes(type.data(), type.size() * sizeof(char)); - } - static void load(ArchiveBuffer& buffer, std::string& type) - { - uint64 length = 0; - buffer.readBytes(&length, sizeof(uint64)); - type.resize(length); - buffer.readBytes(type.data(), length * sizeof(char)); - } - template - static void save(ArchiveBuffer& buffer, const Array& type) requires (std::is_trivially_copyable_v) - { - uint64 length = type.size(); - buffer.writeBytes(&length, sizeof(uint64)); - buffer.writeBytes(type.data(), sizeof(T) * type.size()); - } - template - static void load(ArchiveBuffer& buffer, Array& type) requires (std::is_trivially_copyable_v) - { - uint64 length = 0; - buffer.readBytes(&length, sizeof(uint64)); - type.resize(length); - buffer.readBytes(type.data(), sizeof(T) * type.size()); - } - template - static void save(ArchiveBuffer& buffer, const StaticArray& type) requires (std::is_trivially_copyable_v) - { - buffer.writeBytes(type.data(), sizeof(T) * N); - } - template - static void load(ArchiveBuffer& buffer, StaticArray& type) requires (std::is_trivially_copyable_v) - { - buffer.readBytes(type.data(), sizeof(T) * N); - } - template - static void save(ArchiveBuffer& buffer, const Array& type) - { - uint64 length = type.size(); - buffer.writeBytes(&length, sizeof(uint64)); - for (const T& x : type) - { - save(buffer, x); - } - } - template - static void load(ArchiveBuffer& buffer, Array& type) - { - uint64 length = 0; - buffer.readBytes(&length, sizeof(uint64)); - type.reserve(length); - for (uint32 i = 0; i < length; ++i) - { - T t = T(); - load(buffer, t); - type.add(std::move(t)); - } +} +template static void load(ArchiveBuffer& buffer, Array& type) { + uint64 length = 0; + buffer.readBytes(&length, sizeof(uint64)); + type.reserve(length); + for (uint32 i = 0; i < length; ++i) { + T t = T(); + load(buffer, t); + type.add(std::move(t)); } +} } // namespace Serialization } // namespace Seele \ No newline at end of file diff --git a/src/Engine/System/CameraUpdater.cpp b/src/Engine/System/CameraUpdater.cpp index 9bbbf6d..6730c63 100644 --- a/src/Engine/System/CameraUpdater.cpp +++ b/src/Engine/System/CameraUpdater.cpp @@ -3,16 +3,8 @@ using namespace Seele; using namespace Seele::System; -CameraUpdater::CameraUpdater(PScene scene) - : ComponentSystem(scene) -{ -} +CameraUpdater::CameraUpdater(PScene scene) : ComponentSystem(scene) {} -CameraUpdater::~CameraUpdater() -{ -} +CameraUpdater::~CameraUpdater() {} -void CameraUpdater::update(Component::Camera& camera) -{ - camera.buildViewMatrix(); -} +void CameraUpdater::update(Component::Camera& camera) { camera.buildViewMatrix(); } diff --git a/src/Engine/System/CameraUpdater.h b/src/Engine/System/CameraUpdater.h index 98ad461..4c32845 100644 --- a/src/Engine/System/CameraUpdater.h +++ b/src/Engine/System/CameraUpdater.h @@ -1,19 +1,17 @@ #pragma once -#include "ComponentSystem.h" #include "Component/Camera.h" +#include "ComponentSystem.h" -namespace Seele -{ -namespace System -{ -class CameraUpdater : public ComponentSystem -{ -public: +namespace Seele { +namespace System { +class CameraUpdater : public ComponentSystem { + public: CameraUpdater(PScene scene); virtual ~CameraUpdater(); virtual void update(Component::Camera& camera); -private: + + private: }; -} -} \ No newline at end of file +} // namespace System +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/System/ComponentSystem.h b/src/Engine/System/ComponentSystem.h index 844c8ed..266d0f5 100644 --- a/src/Engine/System/ComponentSystem.h +++ b/src/Engine/System/ComponentSystem.h @@ -1,43 +1,28 @@ #pragma once -#include "SystemBase.h" -#include "Component/Component.h" #include "Component/Camera.h" +#include "Component/Component.h" +#include "SystemBase.h" -namespace Seele -{ -namespace System -{ -template -class ComponentSystem : public SystemBase -{ -public: +namespace Seele { +namespace System { +template class ComponentSystem : public SystemBase { + public: ComponentSystem(PScene scene) : SystemBase(scene) {} virtual ~ComponentSystem() {} - template - auto getDependencies() - { - return Comp::dependencies; - } - template - Dependencies<> getDependencies() - { - return Dependencies<>(); - } - template - void setupView(Dependencies) - { - //List> work; - registry.view().each([&](entt::entity id, Components&... comp, Deps&... deps){ - //work.add([&]() { - (accessComponent(deps), ...); - update(comp...); - update(id, comp...); + template auto getDependencies() { return Comp::dependencies; } + template Dependencies<> getDependencies() { return Dependencies<>(); } + template void setupView(Dependencies) { + // List> work; + registry.view().each([&](entt::entity id, Components&... comp, Deps&... deps) { + // work.add([&]() { + (accessComponent(deps), ...); + update(comp...); + update(id, comp...); //}); }); - //getThreadPool().runAndWait(std::move(work)); + // getThreadPool().runAndWait(std::move(work)); } - virtual void run(double delta) override - { + virtual void run(double delta) override { SystemBase::run(delta); setupView((getDependencies() | ...)); } diff --git a/src/Engine/System/Executor.h b/src/Engine/System/Executor.h index 2e76d40..0f32ad3 100644 --- a/src/Engine/System/Executor.h +++ b/src/Engine/System/Executor.h @@ -2,13 +2,10 @@ #include "MinimalEngine.h" #include "SystemBase.h" -namespace Seele -{ -namespace System -{ -class Executor -{ -public: +namespace Seele { +namespace System { +class Executor { + public: Executor(); ~Executor(); }; diff --git a/src/Engine/System/KeyboardInput.cpp b/src/Engine/System/KeyboardInput.cpp index 141e43b..85ce322 100644 --- a/src/Engine/System/KeyboardInput.cpp +++ b/src/Engine/System/KeyboardInput.cpp @@ -3,18 +3,11 @@ using namespace Seele; using namespace Seele::System; -KeyboardInput::KeyboardInput(PScene scene) - : ComponentSystem(scene) -{ - std::memset(keys.data(), 0, sizeof(keys)); -} +KeyboardInput::KeyboardInput(PScene scene) : ComponentSystem(scene) { std::memset(keys.data(), 0, sizeof(keys)); } -KeyboardInput::~KeyboardInput() -{ -} +KeyboardInput::~KeyboardInput() {} -void KeyboardInput::update(Component::KeyboardInput& input) -{ +void KeyboardInput::update(Component::KeyboardInput& input) { std::memcpy(input.keys.data(), keys.data(), sizeof(keys)); input.deltaX = deltaX; input.deltaY = deltaY; @@ -32,31 +25,23 @@ void KeyboardInput::update(Component::KeyboardInput& input) scrollY = 0; } -void KeyboardInput::keyCallback(KeyCode code, InputAction action, KeyModifier) -{ - keys[code] = action != InputAction::RELEASE; -} +void KeyboardInput::keyCallback(KeyCode code, InputAction action, KeyModifier) { keys[code] = action != InputAction::RELEASE; } -void KeyboardInput::mouseCallback(double x, double y) -{ +void KeyboardInput::mouseCallback(double x, double y) { mouseX = x; mouseY = y; } -void KeyboardInput::mouseButtonCallback(MouseButton button, InputAction action, KeyModifier) -{ - if (button == MouseButton::MOUSE_BUTTON_1) - { +void KeyboardInput::mouseButtonCallback(MouseButton button, InputAction action, KeyModifier) { + if (button == MouseButton::MOUSE_BUTTON_1) { mouse1 = action != InputAction::RELEASE; } - if (button == MouseButton::MOUSE_BUTTON_2) - { + if (button == MouseButton::MOUSE_BUTTON_2) { mouse2 = action != InputAction::RELEASE; } } -void KeyboardInput::scrollCallback(double xScroll, double yScroll) -{ +void KeyboardInput::scrollCallback(double xScroll, double yScroll) { scrollX = xScroll; scrollY = yScroll; } diff --git a/src/Engine/System/KeyboardInput.h b/src/Engine/System/KeyboardInput.h index 934cd8b..3ec46ed 100644 --- a/src/Engine/System/KeyboardInput.h +++ b/src/Engine/System/KeyboardInput.h @@ -1,14 +1,11 @@ #pragma once -#include "ComponentSystem.h" #include "Component/KeyboardInput.h" +#include "ComponentSystem.h" -namespace Seele -{ -namespace System -{ -class KeyboardInput : public ComponentSystem -{ -public: +namespace Seele { +namespace System { +class KeyboardInput : public ComponentSystem { + public: KeyboardInput(PScene scene); virtual ~KeyboardInput(); virtual void update(Component::KeyboardInput& input) override; @@ -16,7 +13,8 @@ public: void mouseCallback(double xPos, double yPos); void mouseButtonCallback(MouseButton button, InputAction action, KeyModifier modifier); void scrollCallback(double xScroll, double yScroll); -private: + + private: Seele::StaticArray keys; bool mouse1 = false; bool mouse2 = false; @@ -30,5 +28,5 @@ private: float scrollY = 0; }; DEFINE_REF(KeyboardInput) -} -} \ No newline at end of file +} // namespace System +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/System/LightGather.cpp b/src/Engine/System/LightGather.cpp index fe0d905..c6fe2ed 100644 --- a/src/Engine/System/LightGather.cpp +++ b/src/Engine/System/LightGather.cpp @@ -3,23 +3,12 @@ using namespace Seele; using namespace Seele::System; -LightGather::LightGather(PScene scene) - : SystemBase(scene) - , lightEnv(scene->getLightEnvironment()) -{ -} +LightGather::LightGather(PScene scene) : SystemBase(scene), lightEnv(scene->getLightEnvironment()) {} -LightGather::~LightGather() -{ -} +LightGather::~LightGather() {} -void LightGather::update() -{ +void LightGather::update() { lightEnv->reset(); - scene->view([this](Component::PointLight& pointLight) { - lightEnv->addPointLight(pointLight); - }); - scene->view([this](Component::DirectionalLight& dirLight) { - lightEnv->addDirectionalLight(dirLight); - }); + scene->view([this](Component::PointLight& pointLight) { lightEnv->addPointLight(pointLight); }); + scene->view([this](Component::DirectionalLight& dirLight) { lightEnv->addDirectionalLight(dirLight); }); } diff --git a/src/Engine/System/LightGather.h b/src/Engine/System/LightGather.h index ca34c94..7c6679d 100644 --- a/src/Engine/System/LightGather.h +++ b/src/Engine/System/LightGather.h @@ -1,18 +1,16 @@ #pragma once #include "SystemBase.h" -namespace Seele -{ -namespace System -{ -class LightGather : public SystemBase -{ -public: +namespace Seele { +namespace System { +class LightGather : public SystemBase { + public: LightGather(PScene scene); virtual ~LightGather(); virtual void update() override; -private: + + private: PLightEnvironment lightEnv; }; -} -} \ No newline at end of file +} // namespace System +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/System/MeshUpdater.cpp b/src/Engine/System/MeshUpdater.cpp index 21eddac..c9e69e5 100644 --- a/src/Engine/System/MeshUpdater.cpp +++ b/src/Engine/System/MeshUpdater.cpp @@ -5,19 +5,12 @@ using namespace Seele; using namespace Seele::System; -MeshUpdater::MeshUpdater(PScene scene) - : ComponentSystem(scene) -{ -} +MeshUpdater::MeshUpdater(PScene scene) : ComponentSystem(scene) {} -MeshUpdater::~MeshUpdater() -{ -} +MeshUpdater::~MeshUpdater() {} -void MeshUpdater::update(entt::entity id, Component::Transform& transform, Component::Mesh& comp) -{ - for (uint32 i = 0; i < comp.asset->meshes.size(); ++i) - { +void MeshUpdater::update(entt::entity id, Component::Transform& transform, Component::Mesh& comp) { + for (uint32 i = 0; i < comp.asset->meshes.size(); ++i) { comp.asset->meshes[i]->vertexData->updateMesh(id, i, comp.asset->meshes[i], transform); } } diff --git a/src/Engine/System/MeshUpdater.h b/src/Engine/System/MeshUpdater.h index 44d52f9..53672a1 100644 --- a/src/Engine/System/MeshUpdater.h +++ b/src/Engine/System/MeshUpdater.h @@ -1,19 +1,17 @@ #pragma once -#include "ComponentSystem.h" -#include "Component/Transform.h" #include "Component/Mesh.h" +#include "Component/Transform.h" +#include "ComponentSystem.h" -namespace Seele -{ -namespace System -{ -class MeshUpdater : public ComponentSystem -{ -public: - MeshUpdater(PScene scene); - virtual ~MeshUpdater(); - virtual void update(entt::entity id, Component::Transform& transform, Component::Mesh& mesh) override; -private: +namespace Seele { +namespace System { +class MeshUpdater : public ComponentSystem { + public: + MeshUpdater(PScene scene); + virtual ~MeshUpdater(); + virtual void update(entt::entity id, Component::Transform& transform, Component::Mesh& mesh) override; + + private: }; } // namespace System } // namespace Seele \ No newline at end of file diff --git a/src/Engine/System/SystemBase.h b/src/Engine/System/SystemBase.h index a40ccee..09d86ff 100644 --- a/src/Engine/System/SystemBase.h +++ b/src/Engine/System/SystemBase.h @@ -1,24 +1,21 @@ #pragma once -#include -#include "ThreadPool.h" #include "Scene/Scene.h" +#include "ThreadPool.h" +#include -namespace Seele -{ -namespace System -{ -class SystemBase -{ -public: +namespace Seele { +namespace System { +class SystemBase { + public: SystemBase(PScene scene) : registry(scene->registry), scene(scene) {} virtual ~SystemBase() {} - virtual void run(double delta) - { + virtual void run(double delta) { deltaTime = delta; update(); } virtual void update() {} -protected: + + protected: double deltaTime; entt::registry& registry; PScene scene; diff --git a/src/Engine/System/SystemGraph.cpp b/src/Engine/System/SystemGraph.cpp index 6a7e02d..c41acaf 100644 --- a/src/Engine/System/SystemGraph.cpp +++ b/src/Engine/System/SystemGraph.cpp @@ -2,14 +2,10 @@ using namespace Seele; -void SystemGraph::addSystem(System::OSystemBase system) -{ - systems.add(std::move(system)); -} +void SystemGraph::addSystem(System::OSystemBase system) { systems.add(std::move(system)); } -void SystemGraph::run(float deltaTime) -{ - for(auto& system : systems) { +void SystemGraph::run(float deltaTime) { + for (auto& system : systems) { system->run(deltaTime); } } diff --git a/src/Engine/System/SystemGraph.h b/src/Engine/System/SystemGraph.h index 54a5a14..ec2e2a5 100644 --- a/src/Engine/System/SystemGraph.h +++ b/src/Engine/System/SystemGraph.h @@ -1,17 +1,16 @@ #pragma once -#include "ThreadPool.h" #include "Containers/Array.h" #include "SystemBase.h" +#include "ThreadPool.h" -namespace Seele -{ -class SystemGraph -{ -public: +namespace Seele { +class SystemGraph { + public: void addSystem(System::OSystemBase system); void run(float deltaTime); -private: + + private: Array systems; }; DEFINE_REF(SystemGraph) -} // namespace Seele; \ No newline at end of file +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/ThreadPool.cpp b/src/Engine/ThreadPool.cpp index 52cd6ab..d670570 100644 --- a/src/Engine/ThreadPool.cpp +++ b/src/Engine/ThreadPool.cpp @@ -2,50 +2,40 @@ using namespace Seele; -ThreadPool::ThreadPool(uint32 numWorkers) -{ - for (uint32 i = 0; i < numWorkers; ++i) - { +ThreadPool::ThreadPool(uint32 numWorkers) { + for (uint32 i = 0; i < numWorkers; ++i) { workers.add(std::thread(&ThreadPool::work, this)); } } -ThreadPool::~ThreadPool() -{ +ThreadPool::~ThreadPool() { { std::unique_lock l(taskLock); running = false; taskCV.notify_all(); } - for (auto& worker : workers) - { + for (auto& worker : workers) { worker.join(); } } -void ThreadPool::runAndWait(List> functions) -{ +void ThreadPool::runAndWait(List> functions) { std::unique_lock l(taskLock); currentTask.numRemaining = functions.size(); currentTask.functions = std::move(functions); taskCV.notify_all(); - - while (currentTask.numRemaining > 0) - { + + while (currentTask.numRemaining > 0) { completedCV.wait(l); } } -void ThreadPool::work() -{ - while (running) - { +void ThreadPool::work() { + while (running) { std::unique_lock l(taskLock); - while(currentTask.functions.empty()) - { + while (currentTask.functions.empty()) { taskCV.wait(l); - if (!running) - { + if (!running) { return; } } @@ -55,8 +45,7 @@ void ThreadPool::work() func(); l.lock(); currentTask.numRemaining--; - if (currentTask.numRemaining == 0) - { + if (currentTask.numRemaining == 0) { currentTask.functions.clear(); completedCV.notify_one(); } @@ -65,7 +54,4 @@ void ThreadPool::work() static ThreadPool threadPool; -ThreadPool& Seele::getThreadPool() -{ - return threadPool; -} +ThreadPool& Seele::getThreadPool() { return threadPool; } diff --git a/src/Engine/ThreadPool.h b/src/Engine/ThreadPool.h index 6871d46..48e27fd 100644 --- a/src/Engine/ThreadPool.h +++ b/src/Engine/ThreadPool.h @@ -1,20 +1,19 @@ #pragma once -#include -#include #include "Containers/Array.h" #include "Containers/List.h" +#include +#include -namespace Seele -{ -class ThreadPool -{ -public: + +namespace Seele { +class ThreadPool { + public: ThreadPool(uint32 numWorkers = std::thread::hardware_concurrency() - 2); ~ThreadPool(); void runAndWait(List> functions); -private: - struct Task - { + + private: + struct Task { uint64 numRemaining = 0; List> functions; }; @@ -27,4 +26,4 @@ private: bool running = true; }; ThreadPool& getThreadPool(); -} \ No newline at end of file +} // namespace Seele \ No newline at end of file diff --git a/src/Engine/UI/Elements/Button.h b/src/Engine/UI/Elements/Button.h index 6f77296..87c4e7a 100644 --- a/src/Engine/UI/Elements/Button.h +++ b/src/Engine/UI/Elements/Button.h @@ -1,13 +1,8 @@ #pragma once #include "Element.h" -namespace Seele -{ -namespace UI -{ -class Button : public Element -{ - -}; +namespace Seele { +namespace UI { +class Button : public Element {}; } // namespace UI } // namespace Seele diff --git a/src/Engine/UI/Elements/Element.cpp b/src/Engine/UI/Elements/Element.cpp index b0a9cb7..a838378 100644 --- a/src/Engine/UI/Elements/Element.cpp +++ b/src/Engine/UI/Elements/Element.cpp @@ -1,70 +1,35 @@ #include "Element.h" -#include "UI/System.h" #include "Graphics/Graphics.h" +#include "UI/System.h" using namespace Seele; using namespace Seele::UI; -Element::Element() - : dirty(false) - , enabled(false) -{ -} +Element::Element() : dirty(false), enabled(false) {} -Element::~Element() -{ -} +Element::~Element() {} -void Element::setParent(PElement element) -{ - if(parent != nullptr) - { +void Element::setParent(PElement element) { + if (parent != nullptr) { parent->removeChild(this); } parent = element; } -PElement Element::getParent() const -{ - return parent; -} +PElement Element::getParent() const { return parent; } -void Element::addChild(PElement element) -{ - children.add(element); -} +void Element::addChild(PElement element) { children.add(element); } -void Element::removeChild(PElement element) -{ - children.remove(element, false); -} +void Element::removeChild(PElement element) { children.remove(element, false); } -const Array Element::getChildren() -{ - return children; -} +const Array Element::getChildren() { return children; } -void Element::clear() -{ - children.clear(); -} +void Element::clear() { children.clear(); } -void Element::setEnabled(bool newEnabled) -{ - enabled = newEnabled; -} +void Element::setEnabled(bool newEnabled) { enabled = newEnabled; } -bool Element::isEnabled() const -{ - return enabled; -} +bool Element::isEnabled() const { return enabled; } -Rect& Element::getBoundingBox() -{ - return boundingBox; -} +Rect& Element::getBoundingBox() { return boundingBox; } -const Rect Element::getBoundingBox() const -{ - return boundingBox; -} \ No newline at end of file +const Rect Element::getBoundingBox() const { return boundingBox; } \ No newline at end of file diff --git a/src/Engine/UI/Elements/Element.h b/src/Engine/UI/Elements/Element.h index 1b9d883..ba0908f 100644 --- a/src/Engine/UI/Elements/Element.h +++ b/src/Engine/UI/Elements/Element.h @@ -1,18 +1,15 @@ #pragma once -#include "MinimalEngine.h" #include "Containers/Array.h" #include "Math/Math.h" +#include "MinimalEngine.h" -namespace Seele -{ -namespace UI -{ -//Element defines any part of the UI +namespace Seele { +namespace UI { +// Element defines any part of the UI DECLARE_REF(Element) DECLARE_REF(System) -class Element -{ -public: +class Element { + public: Element(); virtual ~Element(); void setParent(PElement element); @@ -30,10 +27,11 @@ public: // relative to the total view, meaning a bounding box of (0,0), (1,1) // would take up the entire view const Rect getBoundingBox() const; -protected: + + protected: Rect boundingBox; bool dirty; - + bool enabled; PSystem system; PElement parent; diff --git a/src/Engine/UI/Elements/Label.h b/src/Engine/UI/Elements/Label.h index 9102c5a..a9cda6e 100644 --- a/src/Engine/UI/Elements/Label.h +++ b/src/Engine/UI/Elements/Label.h @@ -1,17 +1,15 @@ #pragma once #include "Element.h" -namespace Seele -{ -namespace UI -{ -class Label : public Element -{ -public: +namespace Seele { +namespace UI { +class Label : public Element { + public: Label(); ~Label(); -private: + + private: std::string text; }; -} // namespace UI +} // namespace UI } // namespace Seele diff --git a/src/Engine/UI/Elements/Panel.cpp b/src/Engine/UI/Elements/Panel.cpp index ce5e965..3a0643c 100644 --- a/src/Engine/UI/Elements/Panel.cpp +++ b/src/Engine/UI/Elements/Panel.cpp @@ -4,12 +4,6 @@ using namespace Seele; using namespace Seele::UI; -Panel::Panel() -{ - -} +Panel::Panel() {} -Panel::~Panel() -{ - -} \ No newline at end of file +Panel::~Panel() {} \ No newline at end of file diff --git a/src/Engine/UI/Elements/Panel.h b/src/Engine/UI/Elements/Panel.h index 69b4f0d..834bc1f 100644 --- a/src/Engine/UI/Elements/Panel.h +++ b/src/Engine/UI/Elements/Panel.h @@ -1,17 +1,15 @@ #pragma once #include "Element.h" -namespace Seele -{ -namespace UI -{ +namespace Seele { +namespace UI { DECLARE_REF(Layout) -class Panel : Element -{ -public: +class Panel : Element { + public: Panel(); virtual ~Panel(); -private: + + private: PLayout activeLayout; }; diff --git a/src/Engine/UI/HorizontalLayout.cpp b/src/Engine/UI/HorizontalLayout.cpp index 3363ffa..58f62c5 100644 --- a/src/Engine/UI/HorizontalLayout.cpp +++ b/src/Engine/UI/HorizontalLayout.cpp @@ -4,27 +4,18 @@ using namespace Seele; using namespace Seele::UI; -HorizontalLayout::HorizontalLayout(PElement element) - : Layout(element) -{ - -} +HorizontalLayout::HorizontalLayout(PElement element) : Layout(element) {} -HorizontalLayout::~HorizontalLayout() -{ - -} +HorizontalLayout::~HorizontalLayout() {} -void HorizontalLayout::apply() -{ +void HorizontalLayout::apply() { Array children = element->getChildren(); const Rect parent = element->getBoundingBox(); float xOffset = parent.offset.x; float yOffset = parent.offset.y; float xSize = parent.size.x / children.size(); float ySize = parent.size.y; - for(uint32 index = 0; index < children.size(); ++index) - { + for (uint32 index = 0; index < children.size(); ++index) { Rect& child = children[index]->getBoundingBox(); child.offset.x = xOffset + (index * xSize); child.offset.y = yOffset; diff --git a/src/Engine/UI/HorizontalLayout.h b/src/Engine/UI/HorizontalLayout.h index 275d72c..b442e42 100644 --- a/src/Engine/UI/HorizontalLayout.h +++ b/src/Engine/UI/HorizontalLayout.h @@ -1,17 +1,15 @@ #pragma once #include "Layout.h" -namespace Seele -{ -namespace UI -{ -class HorizontalLayout : Layout -{ -public: +namespace Seele { +namespace UI { +class HorizontalLayout : Layout { + public: HorizontalLayout(PElement element); ~HorizontalLayout(); virtual void apply() override; -private: + + private: }; } // namespace UI } // namespace Seele \ No newline at end of file diff --git a/src/Engine/UI/Layout.cpp b/src/Engine/UI/Layout.cpp index b65d226..557412a 100644 --- a/src/Engine/UI/Layout.cpp +++ b/src/Engine/UI/Layout.cpp @@ -4,12 +4,6 @@ using namespace Seele; using namespace Seele::UI; -Layout::Layout(PElement element) - : element(element) -{ -} +Layout::Layout(PElement element) : element(element) {} -Layout::~Layout() -{ - -} \ No newline at end of file +Layout::~Layout() {} \ No newline at end of file diff --git a/src/Engine/UI/Layout.h b/src/Engine/UI/Layout.h index 46e8fe9..25cee6c 100644 --- a/src/Engine/UI/Layout.h +++ b/src/Engine/UI/Layout.h @@ -1,18 +1,16 @@ #pragma once #include "MinimalEngine.h" -namespace Seele -{ -namespace UI -{ +namespace Seele { +namespace UI { DECLARE_REF(Element); -class Layout -{ -public: +class Layout { + public: Layout(PElement element); virtual ~Layout(); virtual void apply() = 0; -protected: + + protected: PElement element; }; } // namespace UI diff --git a/src/Engine/UI/RenderHierarchy.cpp b/src/Engine/UI/RenderHierarchy.cpp index d9fc6a3..62e245c 100644 --- a/src/Engine/UI/RenderHierarchy.cpp +++ b/src/Engine/UI/RenderHierarchy.cpp @@ -3,22 +3,18 @@ using namespace Seele; using namespace Seele::UI; -void AddElementRenderHierarchyUpdate::apply(Array& elements) -{ - auto parentIt = elements.find([this](RenderElement e){return e.parent == parent;}); +void AddElementRenderHierarchyUpdate::apply(Array& elements) { + auto parentIt = elements.find([this](RenderElement e) { return e.parent == parent; }); parentIt->referencedElement->addChild(addedElement); addedElement->setParent(parentIt->referencedElement); elements.emplace(parentIt->referencedElement, addedElement); } -void RemoveElementRenderHierarchyUpdate::apply(Array& elements) -{ - auto elementIt = elements.find([this](RenderElement e){return e.referencedElement == element;}); - if(!removeChildren) - { - for(auto child : elementIt->referencedElement->getChildren()) - { +void RemoveElementRenderHierarchyUpdate::apply(Array& elements) { + auto elementIt = elements.find([this](RenderElement e) { return e.referencedElement == element; }); + if (!removeChildren) { + for (auto child : elementIt->referencedElement->getChildren()) { child->setParent(elementIt->referencedElement->getParent()); } } @@ -27,55 +23,36 @@ void RemoveElementRenderHierarchyUpdate::apply(Array& elements) elements.remove(elementIt); } -RenderHierarchy::RenderHierarchy() -{ - -} +RenderHierarchy::RenderHierarchy() {} -RenderHierarchy::~RenderHierarchy() -{ - -} +RenderHierarchy::~RenderHierarchy() {} -void RenderHierarchy::addElement(PElement addedElement) -{ +void RenderHierarchy::addElement(PElement addedElement) { std::scoped_lock lock(updateLock); - updates.add(new AddElementRenderHierarchyUpdate{ - addedElement.getHandle(), - addedElement->getParent().getHandle() - }); + updates.add(new AddElementRenderHierarchyUpdate{addedElement.getHandle(), addedElement->getParent().getHandle()}); } -void RenderHierarchy::removeElement(PElement elementToRemove) -{ +void RenderHierarchy::removeElement(PElement elementToRemove) { std::scoped_lock lock(updateLock); updates.add(new RemoveElementRenderHierarchyUpdate{ elementToRemove.getHandle(), }); } -void RenderHierarchy::moveElement(PElement elementToMove, PElement newParent) -{ +void RenderHierarchy::moveElement(PElement elementToMove, PElement newParent) { std::scoped_lock lock(updateLock); - updates.add(new AddElementRenderHierarchyUpdate{ - elementToMove.getHandle(), - newParent.getHandle() - }); - updates.add(new RemoveElementRenderHierarchyUpdate{ - elementToMove.getHandle() - }); + updates.add(new AddElementRenderHierarchyUpdate{elementToMove.getHandle(), newParent.getHandle()}); + updates.add(new RemoveElementRenderHierarchyUpdate{elementToMove.getHandle()}); } -void RenderHierarchy::updateHierarchy() -{ +void RenderHierarchy::updateHierarchy() { List localUpdates; { // make a local copy of the updates so we dont hold the lock for too long std::scoped_lock lock(updateLock); localUpdates = updates; updates.clear(); } - for(auto update : localUpdates) - { + for (auto update : localUpdates) { update->apply(drawElements); } } diff --git a/src/Engine/UI/RenderHierarchy.h b/src/Engine/UI/RenderHierarchy.h index 2016a54..9cb47c9 100644 --- a/src/Engine/UI/RenderHierarchy.h +++ b/src/Engine/UI/RenderHierarchy.h @@ -1,71 +1,56 @@ #pragma once -#include "Elements/Element.h" #include "Containers/List.h" +#include "Elements/Element.h" #include "Graphics/Resources.h" #include "Graphics/Texture.h" -namespace Seele -{ -namespace UI -{ -struct RenderElementStyle -{ + +namespace Seele { +namespace UI { +struct RenderElementStyle { Vector position = Vector(0, 0, 0); uint32 backgroundImageIndex = UINT32_MAX; Vector backgroundColor = Vector(1, 1, 1); float opacity = 1.0f; - //Vector4 borderBottomColor = Vector4(1, 1, 1, 1); - //Vector4 borderLeftColor = Vector4(1, 1, 1, 1); - //Vector4 borderRightColor = Vector4(1, 1, 1, 1); - //Vector4 borderTopColor = Vector4(1, 1, 1, 1); - //float borderBottomLeftRadius = 0; - //float borderBottomRightRadius = 0; - //float borderTopLeftRadius = 0; - //float borderTopRightRadius = 0; + // Vector4 borderBottomColor = Vector4(1, 1, 1, 1); + // Vector4 borderLeftColor = Vector4(1, 1, 1, 1); + // Vector4 borderRightColor = Vector4(1, 1, 1, 1); + // Vector4 borderTopColor = Vector4(1, 1, 1, 1); + // float borderBottomLeftRadius = 0; + // float borderBottomRightRadius = 0; + // float borderTopLeftRadius = 0; + // float borderTopRightRadius = 0; Vector2 dimensions = Vector2(1, 1); }; -class RenderElement -{ -public: +class RenderElement { + public: RenderElement() = default; - RenderElement(Element* parent, Element* referencedElement) - : parent(parent) - , referencedElement(referencedElement) - {} + RenderElement(Element* parent, Element* referencedElement) : parent(parent), referencedElement(referencedElement) {} ~RenderElement() = default; Element* parent; Element* referencedElement; }; -struct RenderHierarchyUpdate -{ +struct RenderHierarchyUpdate { virtual void apply(Array& elements) = 0; }; -struct AddElementRenderHierarchyUpdate : public RenderHierarchyUpdate -{ +struct AddElementRenderHierarchyUpdate : public RenderHierarchyUpdate { Element* addedElement; Element* parent; - AddElementRenderHierarchyUpdate(Element* addedElement, Element* parent) - : addedElement(addedElement) - , parent(parent) - {} + AddElementRenderHierarchyUpdate(Element* addedElement, Element* parent) : addedElement(addedElement), parent(parent) {} virtual void apply(Array& elements) override; }; -struct RemoveElementRenderHierarchyUpdate : public RenderHierarchyUpdate -{ +struct RemoveElementRenderHierarchyUpdate : public RenderHierarchyUpdate { Element* element; bool removeChildren; RemoveElementRenderHierarchyUpdate(Element* elementToRemove, bool removeChildren = false) - : element(elementToRemove) - , removeChildren(removeChildren) - {} + : element(elementToRemove), removeChildren(removeChildren) {} virtual void apply(Array& elements) override; }; -class RenderHierarchy -{ -public: +class RenderHierarchy { + public: RenderHierarchy(); ~RenderHierarchy(); // logic thread interface, queue hierarchy changes @@ -75,7 +60,8 @@ public: // render thread interface, apply changes void updateHierarchy(); -private: + + private: static_assert(std::is_trivially_copyable_v); // List of all drawable elements in draw order Array drawElements; diff --git a/src/Engine/UI/System.cpp b/src/Engine/UI/System.cpp index b59a8db..3f5573c 100644 --- a/src/Engine/UI/System.cpp +++ b/src/Engine/UI/System.cpp @@ -1,33 +1,21 @@ #include "System.h" -#include "Elements/Panel.h" -#include "Graphics/Graphics.h" #include "Asset/AssetRegistry.h" #include "Asset/TextureAsset.h" +#include "Elements/Panel.h" +#include "Graphics/Graphics.h" + using namespace Seele; using namespace Seele::UI; -System::System() -{ - +System::System() {} + +System::~System() {} + +void System::update() {} + +void System::updateViewport(Gfx::PViewport) { + // TODO set viewport FoV to 0 } -System::~System() -{ - -} - -void System::update() -{ - -} - -void System::updateViewport(Gfx::PViewport) -{ - //TODO set viewport FoV to 0 -} - -Component::Camera System::getVirtualCamera() const -{ - return virtualCamera; -} +Component::Camera System::getVirtualCamera() const { return virtualCamera; } diff --git a/src/Engine/UI/System.h b/src/Engine/UI/System.h index 580a9e6..785400d 100644 --- a/src/Engine/UI/System.h +++ b/src/Engine/UI/System.h @@ -1,23 +1,22 @@ #pragma once +#include "Graphics/RenderPass/TextPass.h" +#include "Graphics/RenderPass/UIPass.h" #include "MinimalEngine.h" #include "RenderHierarchy.h" -#include "Graphics/RenderPass/UIPass.h" -#include "Graphics/RenderPass/TextPass.h" -namespace Seele -{ -namespace UI -{ + +namespace Seele { +namespace UI { DECLARE_REF(Panel) -class System -{ -public: +class System { + public: System(); virtual ~System(); void update(); void updateViewport(Gfx::PViewport viewport); Component::Camera getVirtualCamera() const; -private: + + private: Component::Camera virtualCamera; PPanel rootPanel; RenderHierarchy hierarchy; diff --git a/src/Engine/UI/VerticalLayout.cpp b/src/Engine/UI/VerticalLayout.cpp index 76de71d..298aed0 100644 --- a/src/Engine/UI/VerticalLayout.cpp +++ b/src/Engine/UI/VerticalLayout.cpp @@ -4,27 +4,18 @@ using namespace Seele; using namespace Seele::UI; -VerticalLayout::VerticalLayout(PElement element) - : Layout(element) -{ - -} +VerticalLayout::VerticalLayout(PElement element) : Layout(element) {} -VerticalLayout::~VerticalLayout() -{ - -} +VerticalLayout::~VerticalLayout() {} -void VerticalLayout::apply() -{ +void VerticalLayout::apply() { Array children = element->getChildren(); const Rect parent = element->getBoundingBox(); float xOffset = parent.offset.x; float yOffset = parent.offset.y; float xSize = parent.size.x; float ySize = parent.size.y / children.size(); - for(uint32 index = 0; index < children.size(); ++index) - { + for (uint32 index = 0; index < children.size(); ++index) { Rect& child = children[index]->getBoundingBox(); child.offset.x = xOffset; child.offset.y = yOffset + (index * ySize); diff --git a/src/Engine/UI/VerticalLayout.h b/src/Engine/UI/VerticalLayout.h index 445a1c1..07b557e 100644 --- a/src/Engine/UI/VerticalLayout.h +++ b/src/Engine/UI/VerticalLayout.h @@ -1,17 +1,15 @@ #pragma once #include "Layout.h" -namespace Seele -{ -namespace UI -{ -class VerticalLayout : Layout -{ -public: +namespace Seele { +namespace UI { +class VerticalLayout : Layout { + public: VerticalLayout(PElement element); ~VerticalLayout(); virtual void apply() override; -private: + + private: }; } // namespace UI } // namespace Seele \ No newline at end of file diff --git a/src/Engine/Window/GameView.cpp b/src/Engine/Window/GameView.cpp index a4d38b9..67d358e 100644 --- a/src/Engine/Window/GameView.cpp +++ b/src/Engine/Window/GameView.cpp @@ -1,19 +1,19 @@ #include "GameView.h" -#include "Graphics/Graphics.h" -#include "Window/Window.h" -#include "Component/KeyboardInput.h" #include "Actor/CameraActor.h" #include "Asset/AssetRegistry.h" +#include "Component/KeyboardInput.h" +#include "Graphics/Graphics.h" +#include "Graphics/RenderPass/BasePass.h" +#include "Graphics/RenderPass/CachedDepthPass.h" +#include "Graphics/RenderPass/DebugPass.h" +#include "Graphics/RenderPass/DepthPrepass.h" +#include "Graphics/RenderPass/LightCullingPass.h" +#include "Graphics/RenderPass/SkyboxRenderPass.h" +#include "Graphics/RenderPass/VisibilityPass.h" +#include "System/CameraUpdater.h" #include "System/LightGather.h" #include "System/MeshUpdater.h" -#include "System/CameraUpdater.h" -#include "Graphics/RenderPass/CachedDepthPass.h" -#include "Graphics/RenderPass/DepthPrepass.h" -#include "Graphics/RenderPass/VisibilityPass.h" -#include "Graphics/RenderPass/LightCullingPass.h" -#include "Graphics/RenderPass/BasePass.h" -#include "Graphics/RenderPass/SkyboxRenderPass.h" -#include "Graphics/RenderPass/DebugPass.h" +#include "Window/Window.h" using namespace Seele; @@ -22,12 +22,8 @@ bool useViewCulling = false; bool useLightCulling = false; bool resetVisibility = false; - -GameView::GameView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo &createInfo, std::string dllPath) - : View(graphics, window, createInfo, "Game") - , scene(new Scene(graphics)) - , gameInterface(dllPath) -{ +GameView::GameView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::string dllPath) + : View(graphics, window, createInfo, "Game"), scene(new Scene(graphics)), gameInterface(dllPath) { reloadGame(); renderGraph.addPass(new CachedDepthPass(graphics, scene)); renderGraph.addPass(new DepthPrepass(graphics, scene)); @@ -35,31 +31,23 @@ GameView::GameView(Gfx::PGraphics graphics, PWindow window, const ViewportCreate renderGraph.addPass(new LightCullingPass(graphics, scene)); renderGraph.addPass(new BasePass(graphics, scene)); renderGraph.addPass(new DebugPass(graphics, scene)); - //renderGraph.addPass(new SkyboxRenderPass(graphics, scene)); + // renderGraph.addPass(new SkyboxRenderPass(graphics, scene)); renderGraph.setViewport(viewport); renderGraph.createRenderPass(); } -GameView::~GameView() -{ - -} +GameView::~GameView() {} -void GameView::beginUpdate() -{ -} +void GameView::beginUpdate() {} -void GameView::update() -{ +void GameView::update() { static auto startTime = std::chrono::high_resolution_clock::now(); - for (VertexData* vd : VertexData::getList()) - { + for (VertexData* vd : VertexData::getList()) { vd->resetMeshData(); } systemGraph->run(updateTime); scene->update(updateTime); - for (VertexData* vd : VertexData::getList()) - { + for (VertexData* vd : VertexData::getList()) { vd->createDescriptors(); } scene->getLightEnvironment()->commit(); @@ -69,33 +57,24 @@ void GameView::update() startTime = endTime; } -void GameView::commitUpdate() -{ -} +void GameView::commitUpdate() {} -void GameView::prepareRender() -{ -} +void GameView::prepareRender() {} -void GameView::render() -{ +void GameView::render() { Component::Camera cam; scene->view([&cam](Component::Camera& c) { - if (c.mainCamera) + if (c.mainCamera) cam = c; }); renderGraph.render(cam); } -void GameView::applyArea(URect) -{ - renderGraph.setViewport(viewport); -} +void GameView::applyArea(URect) { renderGraph.setViewport(viewport); } -void GameView::reloadGame() -{ +void GameView::reloadGame() { gameInterface.reload(); - + systemGraph = new SystemGraph(); gameInterface.getGame()->setupScene(scene, systemGraph); System::OKeyboardInput keyInput = new System::KeyboardInput(scene); @@ -106,45 +85,31 @@ void GameView::reloadGame() systemGraph->addSystem(new System::CameraUpdater(scene)); } -void GameView::keyCallback(KeyCode code, InputAction action, KeyModifier modifier) -{ +void GameView::keyCallback(KeyCode code, InputAction action, KeyModifier modifier) { keyboardSystem->keyCallback(code, action, modifier); - if (code == KeyCode::KEY_P && action == InputAction::RELEASE) - { + if (code == KeyCode::KEY_P && action == InputAction::RELEASE) { usePositionOnly = !usePositionOnly; std::cout << "Use Pos only " << usePositionOnly << std::endl; } - if (code == KeyCode::KEY_O && action == InputAction::RELEASE) - { + if (code == KeyCode::KEY_O && action == InputAction::RELEASE) { useViewCulling = !useViewCulling; std::cout << "Use View Culling " << useViewCulling << std::endl; } - if (code == KeyCode::KEY_L && action == InputAction::RELEASE) - { + if (code == KeyCode::KEY_L && action == InputAction::RELEASE) { useLightCulling = !useLightCulling; std::cout << "Use Light Culling " << useLightCulling << std::endl; } - if (code == KeyCode::KEY_R && action == InputAction::RELEASE) - { + if (code == KeyCode::KEY_R && action == InputAction::RELEASE) { resetVisibility = true; } } -void GameView::mouseMoveCallback(double xPos, double yPos) -{ - keyboardSystem->mouseCallback(xPos, yPos); -} +void GameView::mouseMoveCallback(double xPos, double yPos) { keyboardSystem->mouseCallback(xPos, yPos); } -void GameView::mouseButtonCallback(MouseButton button, InputAction action, KeyModifier modifier) -{ +void GameView::mouseButtonCallback(MouseButton button, InputAction action, KeyModifier modifier) { keyboardSystem->mouseButtonCallback(button, action, modifier); } -void GameView::scrollCallback(double xScroll, double yScroll) -{ - keyboardSystem->scrollCallback(xScroll, yScroll); -} +void GameView::scrollCallback(double xScroll, double yScroll) { keyboardSystem->scrollCallback(xScroll, yScroll); } -void GameView::fileCallback(int, const char**) -{ -} +void GameView::fileCallback(int, const char**) {} diff --git a/src/Engine/Window/GameView.h b/src/Engine/Window/GameView.h index 3545854..7fb949d 100644 --- a/src/Engine/Window/GameView.h +++ b/src/Engine/Window/GameView.h @@ -1,19 +1,18 @@ #pragma once -#include "Window/View.h" #include "Scene/Scene.h" #include "System/KeyboardInput.h" +#include "Window/View.h" + #ifdef WIN32 #include "Platform/Windows/GameInterface.h" // TODO #else #include "Platform/Linux/GameInterface.h" #endif -namespace Seele -{ - class GameView : public View - { +namespace Seele { +class GameView : public View { public: - GameView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo &createInfo, std::string dllPath); + GameView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::string dllPath); virtual ~GameView(); virtual void beginUpdate() override; virtual void update() override; @@ -38,7 +37,7 @@ namespace Seele virtual void mouseMoveCallback(double xPos, double yPos) override; virtual void mouseButtonCallback(Seele::MouseButton button, Seele::InputAction action, Seele::KeyModifier modifier) override; virtual void scrollCallback(double xOffset, double yOffset) override; - virtual void fileCallback(int count, const char **paths) override; - }; - DEFINE_REF(GameView) + virtual void fileCallback(int count, const char** paths) override; +}; +DEFINE_REF(GameView) } // namespace Seele diff --git a/src/Engine/Window/View.cpp b/src/Engine/Window/View.cpp index 9c45117..251fbcc 100644 --- a/src/Engine/Window/View.cpp +++ b/src/Engine/Window/View.cpp @@ -1,37 +1,24 @@ #include "View.h" -#include "Window.h" #include "Graphics/Graphics.h" +#include "Window.h" using namespace Seele; -View::View(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo &viewportInfo, std::string name) - : graphics(graphics) - , createInfo(viewportInfo) - , owner(window) - , name(name) -{ - viewport = graphics->createViewport(owner->getGfxHandle(), viewportInfo); - owner->addView(this); - setFocused(); +View::View(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& viewportInfo, std::string name) + : graphics(graphics), createInfo(viewportInfo), owner(window), name(name) { + viewport = graphics->createViewport(owner->getGfxHandle(), viewportInfo); + owner->addView(this); + setFocused(); } -View::~View() -{ +View::~View() {} + +void View::resize(URect area) { + createInfo.dimensions = area; + viewport = graphics->createViewport(owner->getGfxHandle(), createInfo); + applyArea(area); } -void View::resize(URect area) -{ - createInfo.dimensions = area; - viewport = graphics->createViewport(owner->getGfxHandle(), createInfo); - applyArea(area); -} +void View::setFocused() { owner->setFocused(this); } -void View::setFocused() -{ - owner->setFocused(this); -} - -const std::string& View::getName() -{ - return name; -} +const std::string& View::getName() { return name; } diff --git a/src/Engine/Window/View.h b/src/Engine/Window/View.h index d81280b..f157b3c 100644 --- a/src/Engine/Window/View.h +++ b/src/Engine/Window/View.h @@ -1,41 +1,39 @@ #pragma once #include "Graphics/RenderPass/RenderGraph.h" -namespace Seele -{ +namespace Seele { DECLARE_REF(Window) // A view is a part of the window, which can be anything from a scene viewport to an inspector -class View -{ -public: - View(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo &createInfo, std::string name); - virtual ~View(); - - virtual void beginUpdate() = 0; - virtual void update() = 0; - virtual void commitUpdate() = 0; +class View { + public: + View(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::string name); + virtual ~View(); - virtual void prepareRender() = 0; - virtual void render() = 0; - void resize(URect area); - void setFocused(); + virtual void beginUpdate() = 0; + virtual void update() = 0; + virtual void commitUpdate() = 0; - const std::string& getName(); + virtual void prepareRender() = 0; + virtual void render() = 0; + void resize(URect area); + void setFocused(); -protected: - virtual void applyArea(URect area) = 0; - Gfx::PGraphics graphics; - Gfx::OViewport viewport; - ViewportCreateInfo createInfo; - PWindow owner; - std::string name; - - virtual void keyCallback(KeyCode code, InputAction action, KeyModifier modifier) = 0; - virtual void mouseMoveCallback(double xPos, double yPos) = 0; - virtual void mouseButtonCallback(MouseButton button, InputAction action, KeyModifier modifier) = 0; - virtual void scrollCallback(double xOffset, double yOffset) = 0; - virtual void fileCallback(int count, const char** paths) = 0; - friend class Window; + const std::string& getName(); + + protected: + virtual void applyArea(URect area) = 0; + Gfx::PGraphics graphics; + Gfx::OViewport viewport; + ViewportCreateInfo createInfo; + PWindow owner; + std::string name; + + virtual void keyCallback(KeyCode code, InputAction action, KeyModifier modifier) = 0; + virtual void mouseMoveCallback(double xPos, double yPos) = 0; + virtual void mouseButtonCallback(MouseButton button, InputAction action, KeyModifier modifier) = 0; + virtual void scrollCallback(double xOffset, double yOffset) = 0; + virtual void fileCallback(int count, const char** paths) = 0; + friend class Window; }; DEFINE_REF(View) diff --git a/src/Engine/Window/Window.cpp b/src/Engine/Window/Window.cpp index fb9b730..ab5bd56 100644 --- a/src/Engine/Window/Window.cpp +++ b/src/Engine/Window/Window.cpp @@ -4,32 +4,19 @@ using namespace Seele; -Window::Window(PWindowManager owner, Gfx::OWindow handle) - : owner(owner) - , gfxHandle(std::move(handle)) -{ - gfxHandle->setResizeCallback([this](uint32 w, uint32 h) {onResize(w, h); }); +Window::Window(PWindowManager owner, Gfx::OWindow handle) : owner(owner), gfxHandle(std::move(handle)) { + gfxHandle->setResizeCallback([this](uint32 w, uint32 h) { onResize(w, h); }); } -Window::~Window() -{ -} +Window::~Window() {} -void Window::addView(PView view) -{ - views.add(view); -} +void Window::addView(PView view) { views.add(view); } -void Window::pollInputs() -{ - gfxHandle->pollInput(); -} +void Window::pollInputs() { gfxHandle->pollInput(); } -void Window::render() -{ +void Window::render() { gfxHandle->beginFrame(); - for(auto& view : views) - { + for (auto& view : views) { view->beginUpdate(); view->update(); view->commitUpdate(); @@ -39,16 +26,13 @@ void Window::render() gfxHandle->endFrame(); } -Gfx::PWindow Window::getGfxHandle() -{ - return gfxHandle; -} - -void Window::setFocused(PView view) -{ +Gfx::PWindow Window::getGfxHandle() { return gfxHandle; } + +void Window::setFocused(PView view) { auto keyFunction = std::bind(&View::keyCallback, view.getHandle(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); auto mouseMoveFunction = std::bind(&View::mouseMoveCallback, view.getHandle(), std::placeholders::_1, std::placeholders::_2); - auto mouseButtonFunction = std::bind(&View::mouseButtonCallback, view.getHandle() , std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); + auto mouseButtonFunction = + std::bind(&View::mouseButtonCallback, view.getHandle(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); auto scrollFunction = std::bind(&View::scrollCallback, view.getHandle(), std::placeholders::_1, std::placeholders::_2); auto fileFunction = std::bind(&View::fileCallback, view.getHandle(), std::placeholders::_1, std::placeholders::_2); gfxHandle->setKeyCallback(keyFunction); @@ -56,19 +40,15 @@ void Window::setFocused(PView view) gfxHandle->setMouseButtonCallback(mouseButtonFunction); gfxHandle->setScrollCallback(scrollFunction); gfxHandle->setFileCallback(fileFunction); - gfxHandle->setCloseCallback([this](){ - owner->notifyWindowClosed(this); - }); + gfxHandle->setCloseCallback([this]() { owner->notifyWindowClosed(this); }); } -void Window::onResize(uint32 width, uint32 height) -{ - for (auto& view : views) - { +void Window::onResize(uint32 width, uint32 height) { + for (auto& view : views) { // TODO: some sort of layouting algorithm should do this view->resize(URect{ .size = UVector2(width, height), .offset = UVector2(0, 0), - }); + }); } } diff --git a/src/Engine/Window/Window.h b/src/Engine/Window/Window.h index 6736087..2f9902a 100644 --- a/src/Engine/Window/Window.h +++ b/src/Engine/Window/Window.h @@ -1,14 +1,12 @@ #pragma once -#include "View.h" #include "Graphics/RenderTarget.h" +#include "View.h" -namespace Seele -{ +namespace Seele { DECLARE_REF(WindowManager) // The logical window, with the graphics proxy -class Window -{ -public: +class Window { + public: Window(PWindowManager owner, Gfx::OWindow handle); ~Window(); void addView(PView view); @@ -17,11 +15,9 @@ public: Gfx::PWindow getGfxHandle(); void setFocused(PView view); void onResize(uint32 width, uint32 height); - constexpr bool isPaused() const - { - return gfxHandle->isPaused(); - } -protected: + constexpr bool isPaused() const { return gfxHandle->isPaused(); } + + protected: PWindowManager owner; Array views; Gfx::OWindow gfxHandle; diff --git a/src/Engine/Window/WindowManager.cpp b/src/Engine/Window/WindowManager.cpp index d609154..5ffd37a 100644 --- a/src/Engine/Window/WindowManager.cpp +++ b/src/Engine/Window/WindowManager.cpp @@ -3,25 +3,18 @@ using namespace Seele; -WindowManager::WindowManager() -{ -} +WindowManager::WindowManager() {} -WindowManager::~WindowManager() -{ -} +WindowManager::~WindowManager() {} -OWindow WindowManager::addWindow(Gfx::PGraphics graphics, const WindowCreateInfo &createInfo) -{ +OWindow WindowManager::addWindow(Gfx::PGraphics graphics, const WindowCreateInfo& createInfo) { OWindow window = new Window(this, graphics->createWindow(createInfo)); windows.add(window); return window; } -void WindowManager::render() -{ - for (auto& window : windows) - { +void WindowManager::render() { + for (auto& window : windows) { window->pollInputs(); if (window->isPaused()) continue; @@ -29,7 +22,4 @@ void WindowManager::render() } } -void WindowManager::notifyWindowClosed(PWindow window) -{ - windows.remove(window); -} +void WindowManager::notifyWindowClosed(PWindow window) { windows.remove(window); } diff --git a/src/Engine/Window/WindowManager.h b/src/Engine/Window/WindowManager.h index 263e524..c447d47 100644 --- a/src/Engine/Window/WindowManager.h +++ b/src/Engine/Window/WindowManager.h @@ -2,24 +2,19 @@ #include "Containers/Array.h" #include "Window.h" -namespace Seele -{ +namespace Seele { DECLARE_NAME_REF(Gfx, Graphics) -class WindowManager -{ -public: - WindowManager(); - ~WindowManager(); - OWindow addWindow(Gfx::PGraphics graphics, const WindowCreateInfo &createInfo); - void render(); - void notifyWindowClosed(PWindow window); - bool isActive() const - { - return windows.size(); - } +class WindowManager { + public: + WindowManager(); + ~WindowManager(); + OWindow addWindow(Gfx::PGraphics graphics, const WindowCreateInfo& createInfo); + void render(); + void notifyWindowClosed(PWindow window); + bool isActive() const { return windows.size(); } -private: - Array windows; + private: + Array windows; }; DEFINE_REF(WindowManager) } // namespace Seele \ No newline at end of file