diff --git a/CMakeLists.txt b/CMakeLists.txt index e7e6331..c3be367 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -80,7 +80,6 @@ target_link_libraries(Engine PUBLIC dp::thread-pool) target_link_libraries(Engine PUBLIC crcpp) target_link_libraries(Engine PUBLIC odeint) target_link_libraries(Engine PUBLIC zlib) -target_link_libraries(Engine PUBLIC zlibstatic) if(UNIX) target_link_libraries(Engine PUBLIC Threads::Threads) target_link_libraries(Engine PUBLIC dl) @@ -89,7 +88,7 @@ endif() add_executable(Editor "") target_link_libraries(Editor PRIVATE Engine) target_include_directories(Editor PRIVATE src/Editor) -#target_compile_definitions(Editor PRIVATE EDITOR) +target_compile_definitions(Editor PRIVATE EDITOR=1) add_executable(AssetViewer "") target_link_libraries(AssetViewer PRIVATE Engine) @@ -149,7 +148,6 @@ install( nlohmann_json ThreadPool zlib - zlibstatic IrrXML odeint EXPORT diff --git a/cmake/SuperBuild.cmake b/cmake/SuperBuild.cmake index 3312bdf..6e2062a 100644 --- a/cmake/SuperBuild.cmake +++ b/cmake/SuperBuild.cmake @@ -14,7 +14,7 @@ set(ASSIMP_BUILD_ASSIMP_TOOLS OFF CACHE INTERNAL "") add_subdirectory(${ASSIMP_ROOT}) target_compile_definitions(assimp PRIVATE _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING) if(WIN32) - target_compile_options(assimp PRIVATE /WX-) + target_compile_options(assimp PRIVATE /WX- /MP14) else() target_compile_options(assimp PRIVATE -Wno-error -fPIC) target_compile_options(IrrXML PRIVATE -fPIC) diff --git a/res/cmake/CMakeLists.txt.in b/res/cmake/CMakeLists.txt.in new file mode 100644 index 0000000..440ffaf --- /dev/null +++ b/res/cmake/CMakeLists.txt.in @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 3.7...3.23) + +if(${CMAKE_VERSION} VERSION_LESS 3.12) + cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}) +endif() +set(CMAKE_CXX_STANDARD 20) + +project(${GAME_TITLE}) + +add_executable(${GAME_TITLE} main.cpp ) \ No newline at end of file diff --git a/res/cmake/main.cpp.in b/res/cmake/main.cpp.in index f4d6a54..61954d3 100644 --- a/res/cmake/main.cpp.in +++ b/res/cmake/main.cpp.in @@ -1,4 +1,5 @@ #include "Window/WindowManager.h" +#include "" #include "Asset/AssetRegistry.h" int main() @@ -22,7 +23,7 @@ int main() }, }, }; - new GameView(windowManager->getGraphics(), window, gameViewInfo); + new GameView(windowManager->getGraphics(), window, gameViewInfo, ${DLL_PATH}); window->render(); return 0; } \ No newline at end of file diff --git a/res/shaders/DepthPrepass.slang b/res/shaders/DepthPrepass.slang index 602d90a..1728996 100644 --- a/res/shaders/DepthPrepass.slang +++ b/res/shaders/DepthPrepass.slang @@ -14,7 +14,7 @@ VertexStageOutput vertexMain(PositionOnlyVertexShaderInput input) VertexStageOutput output; float3 worldPosition = input.getWorldPosition(); - worldPosition += gMaterial.getWorldOffset(); + //worldPosition += gMaterial.getWorldOffset(); float4 clipSpacePosition; float4 viewSpacePosition = mul(gViewParams.viewMatrix, float4(worldPosition, 1)); diff --git a/res/shaders/ForwardPlus.slang b/res/shaders/ForwardPlus.slang index 33f0d3c..76f4db7 100644 --- a/res/shaders/ForwardPlus.slang +++ b/res/shaders/ForwardPlus.slang @@ -26,7 +26,7 @@ VertexStageOutput vertexMain( VertexStageOutput output; VertexValueCache cache = input.getVertexCache(); float3 worldPosition = input.getWorldPosition(); - worldPosition += gMaterial.getWorldOffset(); + //worldPosition += gMaterial.getWorldOffset(); float4 clipSpacePosition; float3x3 tangentToLocal = cache.getTangentToLocal(); diff --git a/res/shaders/Placeholder.asset b/res/shaders/Placeholder.asset index 3e9eb74..859cc18 100644 --- a/res/shaders/Placeholder.asset +++ b/res/shaders/Placeholder.asset @@ -35,27 +35,24 @@ "type": "SamplerState" } }, - "code": { - "baseColor": [ - "return diffuseTexture.Sample(textureSampler, input.texCoords[0] * uvScale).xyz;" - ], - "metallic": [ - "return metallic;" - ], - "normal": [ - "return normalTexture.Sample(textureSampler, input.texCoords[0] * uvScale).xyz;" - ], - "specular": [ - "return specularTexture.Sample(textureSampler, input.texCoords[0] * uvScale).x;" - ], - "roughness": [ - "return roughness;" - ], - "sheen": [ - "return sheen;" - ], - "worldOffset": [ - "return worldOffset;" - ] - } + "code": [ + { + "exp": "Sample", + "texture": "diffuseTexture", + "sampler": "textureSampler", + "coords": "input.texCoords[0]" + }, + { + "exp": "Swizzle", + "target": 0, + "comp": [0, 1, 2] + }, + { + "exp": "BRDF", + "profile": "BlinnPhong", + "values": { + "baseColor": 1 + } + } + ] } \ No newline at end of file diff --git a/res/shaders/lib/BRDF.slang b/res/shaders/lib/BRDF.slang index 2db0e3b..e79d12d 100644 --- a/res/shaders/lib/BRDF.slang +++ b/res/shaders/lib/BRDF.slang @@ -20,7 +20,7 @@ struct BlinnPhong : IBRDF float3 h = normalize(light + view); float nDotH = saturate(dot(normal, h)); - return baseColor * nDotL + lightColor * specular * pow(nDotH, sheen); + return baseColor; } }; diff --git a/res/shaders/lib/Material.slang b/res/shaders/lib/Material.slang index 52e82ea..b531cf3 100644 --- a/res/shaders/lib/Material.slang +++ b/res/shaders/lib/Material.slang @@ -6,15 +6,6 @@ interface IMaterial { associatedtype BRDF : IBRDF; BRDF prepare(MaterialFragmentParameter input); - - float3 getWorldOffset(); - - float3 getBaseColor(MaterialFragmentParameter input); - float getMetallic(MaterialFragmentParameter input); - float3 getNormal(MaterialFragmentParameter input); - float getSpecular(MaterialFragmentParameter input); - float getRoughness(MaterialFragmentParameter input); - float getSheen(MaterialFragmentParameter input); }; layout(set = INDEX_MATERIAL, binding = 0, std430) diff --git a/src/Editor/Asset/AssetImporter.cpp b/src/Editor/Asset/AssetImporter.cpp new file mode 100644 index 0000000..5075d3b --- /dev/null +++ b/src/Editor/Asset/AssetImporter.cpp @@ -0,0 +1,64 @@ +#include "AssetImporter.h" +#include "FontLoader.h" +#include "TextureLoader.h" +#include "MaterialLoader.h" +#include "MeshLoader.h" +#include "Graphics/Graphics.h" + +using namespace Seele; + +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())) + { + // 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())) + { + // 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())) + { + // skip importing duplicates + return; + } + get().materialLoader->importAsset(args); +} + +void AssetImporter::init(Gfx::PGraphics graphics, AssetRegistry* registry) +{ + get().registry = registry; + get().meshLoader = new MeshLoader(graphics); + get().textureLoader = new TextureLoader(graphics); + get().materialLoader = new MaterialLoader(graphics); + get().fontLoader = new FontLoader(graphics); +} + +AssetImporter& AssetImporter::get() +{ + static AssetImporter instance; + return instance; +} + diff --git a/src/Editor/Asset/AssetImporter.h b/src/Editor/Asset/AssetImporter.h new file mode 100644 index 0000000..5c60218 --- /dev/null +++ b/src/Editor/Asset/AssetImporter.h @@ -0,0 +1,27 @@ +#pragma once +#include "MinimalEngine.h" +#include "Asset/AssetRegistry.h" + +namespace Seele +{ +DECLARE_REF(TextureLoader) +DECLARE_REF(FontLoader) +DECLARE_REF(MeshLoader) +DECLARE_REF(MaterialLoader) +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, AssetRegistry* registry); +private: + static AssetImporter& get(); + UPTextureLoader textureLoader; + UPFontLoader fontLoader; + UPMeshLoader meshLoader; + UPMaterialLoader materialLoader; + AssetRegistry* registry; +}; +} // namespace Seele \ No newline at end of file diff --git a/src/Editor/Asset/CMakeLists.txt b/src/Editor/Asset/CMakeLists.txt new file mode 100644 index 0000000..616e629 --- /dev/null +++ b/src/Editor/Asset/CMakeLists.txt @@ -0,0 +1,12 @@ +target_sources(Editor + PRIVATE + AssetImporter.h + AssetImporter.cpp + FontLoader.h + FontLoader.cpp + MaterialLoader.h + MaterialLoader.cpp + MeshLoader.h + MeshLoader.cpp + TextureLoader.h + TextureLoader.cpp) \ No newline at end of file diff --git a/src/Engine/Asset/FontLoader.cpp b/src/Editor/Asset/FontLoader.cpp similarity index 97% rename from src/Engine/Asset/FontLoader.cpp rename to src/Editor/Asset/FontLoader.cpp index 666f343..56e3bef 100644 --- a/src/Engine/Asset/FontLoader.cpp +++ b/src/Editor/Asset/FontLoader.cpp @@ -1,7 +1,7 @@ #include "FontLoader.h" #include "Graphics/Graphics.h" -#include "FontAsset.h" -#include "AssetRegistry.h" +#include "Asset/FontAsset.h" +#include "Asset/AssetRegistry.h" #include "Graphics/GraphicsResources.h" #include #include FT_FREETYPE_H diff --git a/src/Engine/Asset/FontLoader.h b/src/Editor/Asset/FontLoader.h similarity index 100% rename from src/Engine/Asset/FontLoader.h rename to src/Editor/Asset/FontLoader.h diff --git a/src/Engine/Asset/MaterialLoader.cpp b/src/Editor/Asset/MaterialLoader.cpp similarity index 53% rename from src/Engine/Asset/MaterialLoader.cpp rename to src/Editor/Asset/MaterialLoader.cpp index a8169d4..3d2536a 100644 --- a/src/Engine/Asset/MaterialLoader.cpp +++ b/src/Editor/Asset/MaterialLoader.cpp @@ -1,12 +1,11 @@ #include "MaterialLoader.h" #include "Graphics/Graphics.h" -#include "MaterialAsset.h" -#include "AssetRegistry.h" +#include "Asset/MaterialAsset.h" +#include "Asset/AssetRegistry.h" #include "Material/Material.h" -#include "Material/BRDF.h" #include "Window/WindowManager.h" #include "Material/ShaderExpression.h" -#include "TextureAsset.h" +#include "Asset/TextureAsset.h" #include using namespace Seele; @@ -15,10 +14,12 @@ using json = nlohmann::json; MaterialLoader::MaterialLoader(Gfx::PGraphics graphics) : graphics(graphics) { - importAsset(MaterialImportArgs{ + PMaterialAsset placeholderAsset = new MaterialAsset(); + import(MaterialImportArgs{ .filePath = std::filesystem::absolute("./shaders/Placeholder.asset"), .importPath = "", - }); + }, placeholderAsset); + AssetRegistry::get().assetRoot->materials[""] = placeholderAsset; } MaterialLoader::~MaterialLoader() @@ -45,18 +46,14 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) //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()); - std::ofstream codeStream("./shaders/generated/"+materialName+".slang"); - std::string profile = j["profile"].get(); - - codeStream << "import Material;" << std::endl; - codeStream << "import BRDF;" << std::endl; - codeStream << "import MaterialParameter;" << std::endl << std::endl; - - codeStream << "struct " << materialName << " : IMaterial {" << std::endl; + uint32 uniformBufferOffset = 0; uint32 bindingCounter = 0; // Uniform buffers are always binding 0 uint32 uniformBinding = -1; - Array parameters; + Map expressions; + int32 key = 0; + int32 auxKey = -1; + Map parameters; for(auto param : j["params"].items()) { std::string type = param.value()["type"].get(); @@ -65,7 +62,7 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) if(type.compare("float") == 0) { PFloatParameter p = new FloatParameter(param.key(), uniformBufferOffset, 0); - codeStream << "\tlayout(offset = " << uniformBufferOffset << ")"; + p->key = auxKey; if(uniformBinding == -1) { layout->addDescriptorBinding(bindingCounter, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER); @@ -76,13 +73,14 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) { p->data = std::stof(defaultValue.value().get()); } - parameters.add(p); + expressions[auxKey--] = p; + parameters[param.key()] = p; } // TODO: ALIGNMENT RULES else if(type.compare("float3") == 0) { PVectorParameter p = new VectorParameter(param.key(), uniformBufferOffset, 0); - codeStream << "\tlayout(offset = " << uniformBufferOffset << ")"; + p->key = auxKey; if(uniformBinding == -1) { layout->addDescriptorBinding(bindingCounter, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER); @@ -93,11 +91,13 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) { p->data = parseVector(defaultValue.value().get().c_str()); } - parameters.add(p); + expressions[auxKey--] = p; + parameters[param.key()] = p; } else if(type.compare("Texture2D") == 0) { PTextureParameter p = new TextureParameter(param.key(), 0, bindingCounter); + p->key = auxKey; layout->addDescriptorBinding(bindingCounter++, Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE); if(defaultValue != param.value().end()) { @@ -108,36 +108,120 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) { p->data = AssetRegistry::findTexture(""); // this will return placeholder texture } - parameters.add(p); + expressions[auxKey--] = p; + parameters[param.key()] = p; } else if(type.compare("SamplerState") == 0) { PSamplerParameter p = new SamplerParameter(param.key(), 0, bindingCounter); + p->key = auxKey; layout->addDescriptorBinding(bindingCounter++, Gfx::SE_DESCRIPTOR_TYPE_SAMPLER); p->data = graphics->createSamplerState({}); - parameters.add(p); + expressions[auxKey--] = p; + parameters[param.key()] = p; } else { std::cout << "Error unsupported parameter type" << std::endl; } - codeStream << "\t" << type << " " << param.key() << ";\n"; } uint32 uniformDataSize = uniformBufferOffset; - - BRDF* brdf = BRDF::getBRDFByName(profile); - brdf->generateMaterialCode(codeStream, j["code"]); - codeStream << "};"; - codeStream.close(); + auto referenceExpression = [&auxKey, &expressions](json obj) -> PShaderExpression + { + if(obj.is_string()) + { + PConstantExpression c = new ConstantExpression(obj.get(), ExpressionType::UNKNOWN); + c->key = auxKey; + expressions[auxKey--] = c; + return c; + } + else + { + return expressions[obj.get()]; + } + }; + MaterialNode mat; + + for(auto param : j["code"].items()) + { + auto obj = param.value(); + std::string exp = obj["exp"].get(); + if(exp.compare("Add") == 0) + { + PAddExpression p = new AddExpression(); + p->key = key; + p->inputs["lhs"].source = referenceExpression(obj["lhs"])->key; + p->inputs["rhs"].source = referenceExpression(obj["rhs"])->key; + expressions[key++] = p; + } + if(exp.compare("Sub") == 0) + { + PSubExpression p = new SubExpression(); + p->key = key; + p->inputs["lhs"].source = referenceExpression(obj["lhs"])->key; + p->inputs["rhs"].source = referenceExpression(obj["rhs"])->key; + expressions[key++] = p; + } + if(exp.compare("Mul") == 0) + { + PMulExpression p = new MulExpression(); + p->key = key; + p->inputs["lhs"].source = referenceExpression(obj["lhs"])->key; + p->inputs["rhs"].source = referenceExpression(obj["rhs"])->key; + expressions[key++] = p; + } + if(exp.compare("Swizzle") == 0) + { + PSwizzleExpression p = new SwizzleExpression(); + p->key = key; + p->inputs["target"].source = referenceExpression(obj["target"])->key; + int32 i = 0; + for(auto c : obj["comp"].items()) + { + p->comp[i++] = c.value().get(); + } + expressions[key++] = p; + } + if(exp.compare("Sample") == 0) + { + PSampleExpression p = new SampleExpression(); + p->key = key; + p->inputs["texture"].source = parameters[obj["texture"].get()]->key; + p->inputs["sampler"].source = parameters[obj["sampler"].get()]->key; + p->inputs["coords"].source = referenceExpression(obj["coords"])->key; + expressions[key++] = p; + } + if(exp.compare("BRDF") == 0) + { + mat.profile = obj["profile"].get(); + for(auto val : obj["values"].items()) + { + mat.variables[val.key()] = referenceExpression(val.value()); + } + } + } layout->create(); + Array codeExp; + for(const auto& [_, e] : expressions) + { + codeExp.add(e); + } + Array params; + for(const auto& [_, p] : parameters) + { + params.add(p); + } asset->material = new Material( graphics, - std::move(parameters), + std::move(params), std::move(layout), uniformDataSize, uniformBinding, - materialName + materialName, + std::move(codeExp), + std::move(mat) ); + asset->material->compile(); graphics->getShaderCompiler()->registerMaterial(asset->material); asset->setStatus(Asset::Status::Ready); ////co_return; diff --git a/src/Engine/Asset/MaterialLoader.h b/src/Editor/Asset/MaterialLoader.h similarity index 100% rename from src/Engine/Asset/MaterialLoader.h rename to src/Editor/Asset/MaterialLoader.h diff --git a/src/Engine/Asset/MeshLoader.cpp b/src/Editor/Asset/MeshLoader.cpp similarity index 90% rename from src/Engine/Asset/MeshLoader.cpp rename to src/Editor/Asset/MeshLoader.cpp index 4405822..76d47d5 100644 --- a/src/Engine/Asset/MeshLoader.cpp +++ b/src/Editor/Asset/MeshLoader.cpp @@ -1,11 +1,11 @@ #include "MeshLoader.h" #include "Graphics/GraphicsResources.h" #include "Graphics/Graphics.h" -#include "MeshAsset.h" +#include "Asset/MeshAsset.h" #include "Graphics/Mesh.h" #include "Graphics/StaticMeshVertexInput.h" -#include "AssetRegistry.h" -#include "MaterialAsset.h" +#include "Asset/AssetImporter.h" +#include "Asset/MaterialAsset.h" #include #include #include @@ -62,31 +62,48 @@ void MeshLoader::loadMaterials(const aiScene* scene, const std::string& baseName {"type", "Texture2D"}, {"default", texFilename} }; - matCode["code"]["baseColor"] = "return diffuseTexture.Sample(textureSampler, input.texCoords[0]).xyz;"; + matCode["code"].push_back( + { + { "exp", "Sample" }, + { "texture", "diffuseTexture" }, + { "sampler", "textureSampler" }, + { "coords", "input.texCoords[0]"} + } + ); + matCode["code"].push_back( + { + { "exp", "Swizzle" }, + { "target", 0 }, + { "comp", json::array({0, 1, 2}) }, + } + ); + matCode["code"].push_back( + { + { "exp", "BRDF" }, + { "profile", "BlinnPhong" }, + { "values", { + {"baseColor", 1} + }} + } + ); } else { - matCode["code"]["baseColor"] = "return input.vertexColor.xyz;"; + matCode["code"].push_back( + { + { "exp", "BRDF" }, + { "profile", "BlinnPhong" }, + { "values", { + {"baseColor", "input.vertexColor.xyz"} + }} + } + ); } if(material->GetTexture(aiTextureType_SPECULAR, 0, &texPath) == AI_SUCCESS) { - std::string texFilename = std::filesystem::path(texPath.C_Str()).replace_extension("asset").stem().string(); - matCode["params"]["specularTexture"] = - { - {"type", "Texture2D"}, - {"default", texFilename} - }; - matCode["code"]["specular"] = "return specularTexture.Sample(textureSampler, input.texCoords[0]).x;"; } if(material->GetTexture(aiTextureType_NORMALS, 0, &texPath) == AI_SUCCESS) { - std::string texFilename = std::filesystem::path(texPath.C_Str()).replace_extension("asset").stem().string(); - matCode["params"]["normalTexture"] = - { - {"type", "Texture2D"}, - {"default", texFilename} - }; - matCode["code"]["normal"] = "return normalTexture.Sample(textureSampler, input.texCoords[0]).xyz;"; } std::string outMatFilename = matCode["name"].get().append(".asset"); std::ofstream outMatFile = std::ofstream(meshDirectory / outMatFilename); @@ -95,7 +112,7 @@ void MeshLoader::loadMaterials(const aiScene* scene, const std::string& baseName outMatFile.close(); std::cout << "writing json to " << outMatFilename << std::endl; - AssetRegistry::importMaterial(MaterialImportArgs{ + AssetImporter::importMaterial(MaterialImportArgs{ .filePath = meshDirectory / outMatFilename, .importPath = importPath, }); @@ -266,7 +283,7 @@ void MeshLoader::loadTextures(const aiScene* scene, const std::filesystem::path& delete[] texData; } std::cout << "Loading model texture " << texPngPath.string() << std::endl; - AssetRegistry::importTexture(TextureImportArgs { + AssetImporter::importTexture(TextureImportArgs { .filePath = texPath, .importPath = importPath, }); diff --git a/src/Engine/Asset/MeshLoader.h b/src/Editor/Asset/MeshLoader.h similarity index 100% rename from src/Engine/Asset/MeshLoader.h rename to src/Editor/Asset/MeshLoader.h diff --git a/src/Engine/Asset/TextureLoader.cpp b/src/Editor/Asset/TextureLoader.cpp similarity index 80% rename from src/Engine/Asset/TextureLoader.cpp rename to src/Editor/Asset/TextureLoader.cpp index 53790b3..1d13a3e 100644 --- a/src/Engine/Asset/TextureLoader.cpp +++ b/src/Editor/Asset/TextureLoader.cpp @@ -1,7 +1,7 @@ #include "TextureLoader.h" -#include "TextureAsset.h" +#include "Asset/TextureAsset.h" #include "Graphics/Graphics.h" -#include "AssetRegistry.h" +#include "Asset/AssetRegistry.h" #include "Graphics/Vulkan/VulkanGraphicsEnums.h" #define STB_IMAGE_IMPLEMENTATION #include @@ -115,40 +115,22 @@ void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset) .threadCount = std::thread::hardware_concurrency(), .qualityLevel = 0, }; - //ktx_error_code_e error = ktxTexture2_CompressBasisEx(kTexture, ¶ms); - //assert(error == KTX_SUCCESS); + ktx_error_code_e error = ktxTexture2_CompressBasisEx(kTexture, ¶ms); + assert(error == KTX_SUCCESS); //error = ktxTexture2_TranscodeBasis(kTexture, KTX_TTF_BC7_RGBA, 0); //assert(error == KTX_SUCCESS); + ktx_uint8_t* dest; + ktx_size_t size; + ktxTexture_WriteToMemory(ktxTexture(kTexture), &dest, &size); + + Array memory(size); + std::memcpy(memory.data(), dest, size); + + textureAsset->createFromMemory(std::move(memory), graphics); + + free(dest); stbi_image_free(data); - - TextureCreateInfo texInfo = { - .resourceData = { - .size = ktxTexture_GetDataSize(ktxTexture(kTexture)), - .data = ktxTexture_GetData(ktxTexture(kTexture)), - }, - .width = createInfo.baseWidth, - .height = createInfo.baseHeight, - .depth = createInfo.baseDepth, - .bArray = false, - .arrayLayers = createInfo.numFaces, - .mipLevels = 1, - .samples = 1, - .format = (Gfx::SeFormat)kTexture->vkFormat, - .usage = args.usage, - }; - - if (createInfo.numFaces == 1) - { - textureAsset->setTexture(graphics->createTexture2D(texInfo)); - } - else - { - textureAsset->setTexture(graphics->createTextureCube(texInfo)); - } - - ktxTexture_Destroy(ktxTexture(kTexture)); - textureAsset->setStatus(Asset::Status::Ready); ////co_return; } \ No newline at end of file diff --git a/src/Engine/Asset/TextureLoader.h b/src/Editor/Asset/TextureLoader.h similarity index 100% rename from src/Engine/Asset/TextureLoader.h rename to src/Editor/Asset/TextureLoader.h diff --git a/src/Editor/CMakeLists.txt b/src/Editor/CMakeLists.txt index 7f5de55..3f02d1f 100644 --- a/src/Editor/CMakeLists.txt +++ b/src/Editor/CMakeLists.txt @@ -1,4 +1,4 @@ -add_subdirectory(Platform/) +add_subdirectory(Asset/) add_subdirectory(Window/) target_sources(Editor diff --git a/src/Editor/Platform/Windows/CMakeLists.txt b/src/Editor/Platform/Windows/CMakeLists.txt deleted file mode 100644 index 0698097..0000000 --- a/src/Editor/Platform/Windows/CMakeLists.txt +++ /dev/null @@ -1,4 +0,0 @@ -target_sources(Editor - PRIVATE - GameInterface.h - GameInterface.cpp) \ No newline at end of file diff --git a/src/Editor/Window/CMakeLists.txt b/src/Editor/Window/CMakeLists.txt index 279cf0e..3ccab7d 100644 --- a/src/Editor/Window/CMakeLists.txt +++ b/src/Editor/Window/CMakeLists.txt @@ -1,9 +1,9 @@ target_sources(Editor PRIVATE - GameView.h - GameView.cpp InspectorView.h InspectorView.cpp + PlayView.h + PlayView.cpp SceneView.h SceneView.cpp ViewportControl.h diff --git a/src/Editor/Window/GameView.cpp b/src/Editor/Window/GameView.cpp deleted file mode 100644 index 7d5435d..0000000 --- a/src/Editor/Window/GameView.cpp +++ /dev/null @@ -1,324 +0,0 @@ -#include "GameView.h" -#include "Graphics/Graphics.h" -#include "Window/Window.h" -#include "Component/KeyboardInput.h" -#include "Actor/CameraActor.h" -#include "Asset/AssetRegistry.h" -#include "Asset/MeshLoader.h" -#include "Asset/TextureLoader.h" -#include "Asset/MaterialLoader.h" - -using namespace Seele; - -AssetRegistry* instance = new AssetRegistry(); - -GameView::GameView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo &createInfo) - : View(graphics, window, createInfo, "Game") - , gameInterface("C:\\Users\\Dynamitos\\TrackClear\\bin\\TrackCleard.dll") - , renderGraph(RenderGraphBuilder::build( - DepthPrepass(graphics), - LightCullingPass(graphics), - BasePass(graphics), -#ifdef EDITOR - DebugPass(graphics), -#endif - SkyboxRenderPass(graphics) - )) -{ - scene = new Scene(graphics); - gameInterface.reload(instance); - AssetRegistry::importMesh(MeshImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/arena.fbx", - }); - AssetRegistry::importMesh(MeshImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/train.fbx", - }); - AssetRegistry::importMesh(MeshImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/bird.fbx", - }); - AssetRegistry::importMesh(MeshImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/cube.fbx", - }); - AssetRegistry::importMesh(MeshImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/flameThrower.fbx", - }); - AssetRegistry::importMesh(MeshImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/player.fbx", - }); - AssetRegistry::importMesh(MeshImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/shotgun.fbx", - }); - AssetRegistry::importMesh(MeshImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/track.fbx", - }); - AssetRegistry::importMesh(MeshImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/zombie.fbx", - }); - - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Dirt.png", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/DirtGrass.png", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Grass.png", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Ice.png", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Lava.png", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Obsidian.png", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Rocks.png", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Sand.png", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Water.png", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Wood.png", - }); - - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level0/blendMap.png", - .importPath = "level0", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level0/heightMap.png", - .importPath = "level0", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level0/trackMap.png", - .importPath = "level0", - }); - AssetRegistry::importMaterial(MaterialImportArgs{ - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level0/TerrainLevel0.asset", - .importPath = "level0", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level1/blendMap.png", - .importPath = "level1", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level1/heightMap.png", - .importPath = "level1", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level1/trackMap.png", - .importPath = "level1", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level2/blendMap.png", - .importPath = "level2", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level2/heightMap.png", - .importPath = "level2", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level2/trackMap.png", - .importPath = "level2", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level3/blendMap.png", - .importPath = "level3", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level3/heightMap.png", - .importPath = "level3", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level3/trackMap.png", - .importPath = "level3", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level4/blendMap.png", - .importPath = "level4", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level4/heightMap.png", - .importPath = "level4", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level4/trackMap.png", - .importPath = "level4", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level5/blendMap.png", - .importPath = "level5", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level5/heightMap.png", - .importPath = "level5", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level5/trackMap.png", - .importPath = "level5", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level6/blendMap.png", - .importPath = "level6", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level6/heightMap.png", - .importPath = "level6", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level6/trackMap.png", - .importPath = "level6", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level7/blendMap.png", - .importPath = "level7", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level7/heightMap.png", - .importPath = "level7", - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level7/trackMap.png", - .importPath = "level7", - }); - - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/skyboxes/FS000_Day_01.png", - .type = TextureImportType::TEXTURE_CUBEMAP, - }); - AssetRegistry::importTexture(TextureImportArgs { - .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/skyboxes/FS000_Night_01.png", - .type = TextureImportType::TEXTURE_CUBEMAP, - }); - - AssetRegistry::saveRegistry(); - systemGraph = new SystemGraph(); - gameInterface.getGame()->setupScene(scene, systemGraph); - renderGraph.updateViewport(viewport); -} - -GameView::~GameView() -{ - -} - -void GameView::beginUpdate() -{ -} - -void GameView::update() -{ - static auto startTime = std::chrono::high_resolution_clock::now(); - systemGraph->run(threadPool, updateTime); - scene->update(updateTime); - auto endTime = std::chrono::high_resolution_clock::now(); - std::chrono::duration duration = (endTime - startTime); - updateTime = duration.count(); - startTime = endTime; -} - -void GameView::commitUpdate() -{ - depthPrepassData.staticDrawList = scene->getStaticMeshes(); - depthPrepassData.sceneDataBuffer = scene->getSceneDataBuffer(); - lightCullingData.lightEnv = scene->getLightBuffer(); - basePassData.staticDrawList = scene->getStaticMeshes(); - basePassData.sceneDataBuffer = scene->getSceneDataBuffer(); - skyboxData.skybox = scene->getSkybox(); -#ifdef EDITOR - if(showDebug) - { - debugPassData.vertices = Seele::gDebugVertices; - } -#endif - Seele::gDebugVertices.clear(); -} - -void GameView::prepareRender() -{ -#ifdef EDITOR - renderGraph.updatePassData(depthPrepassData, lightCullingData, basePassData, debugPassData, skyboxData); -#else - renderGraph.updatePassData(depthPrepassData, lightCullingData, basePassData, skyboxData); -#endif -} - -void GameView::render() -{ - scene->view([&](Component::Camera& cam) - { - if(cam.mainCamera) - { - renderGraph.render(cam); - } - }); -} - -void GameView::keyCallback(KeyCode code, InputAction action, KeyModifier) -{ - scene->view([=](Component::KeyboardInput& input) - { - //if(code == KeyCode::KEY_R && action == InputAction::PRESS) - //{ - // auto cubeMesh = AssetRegistry::findMesh("cube"); - // PEntity cube2 = new Entity(scene); - // Component::Transform& cube2Transform = cube2->attachComponent(); - // cube2Transform.setPosition(Vector(0, 20, 0)); - // cube2Transform.setRotation(Quaternion(Vector(0.f, 90.f, 90.f))); - // cube2Transform.setScale(Vector(2.f, 2.f, 2.f)); - // cubeMesh->physicsMesh.type = Component::ColliderType::DYNAMIC; - // cube2->attachComponent(cubeMesh->physicsMesh); - // cube2->attachComponent(cubeMesh); - // Component::RigidBody& physics2 = cube2->attachComponent(); - // physics2.linearMomentum = Vector(0, -10, 0); - // physics2.angularMomentum = Vector(0, 0, 0); - //} - // - //if(code == KeyCode::KEY_B && action == InputAction::PRESS) - //{ - // showDebug = !showDebug; - // debugPassData.vertices.clear(); - //} - - input.keys[code] = action != InputAction::RELEASE; - }); -} - -void GameView::mouseMoveCallback(double xPos, double yPos) -{ - scene->view([=](Component::KeyboardInput& input) - { - input.mouseX = static_cast(xPos); - input.mouseY = static_cast(yPos); - }); -} - -void GameView::mouseButtonCallback(MouseButton button, InputAction action, KeyModifier) -{ - scene->view([=](Component::KeyboardInput& input) - { - if (button == MouseButton::MOUSE_BUTTON_1) - { - input.mouse1 = action != InputAction::RELEASE; - } - if (button == MouseButton::MOUSE_BUTTON_2) - { - input.mouse2 = action != InputAction::RELEASE; - } - }); -} - -void GameView::scrollCallback(double, double) -{ - -} - -void GameView::fileCallback(int, const char**) -{ - -} diff --git a/src/Editor/Window/InspectorView.cpp b/src/Editor/Window/InspectorView.cpp index 4a08a5e..9085c95 100644 --- a/src/Editor/Window/InspectorView.cpp +++ b/src/Editor/Window/InspectorView.cpp @@ -1,24 +1,22 @@ #include "InspectorView.h" #include "Graphics/Graphics.h" #include "Actor/Actor.h" -#include "Window/Window.h" #include "Asset/AssetRegistry.h" #include "Asset/FontLoader.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) - : View(graphics, window, createInfo, "InspectorView") + : View(graphics, std::move(window), std::move(createInfo), "InspectorView") , renderGraph(RenderGraphBuilder::build( UIPass(graphics), TextPass(graphics) )) , uiSystem(new UI::System()) { - AssetRegistry::importFont(FontImportArgs{ - .filePath = "./fonts/Calibri.ttf", - }); renderGraph.updateViewport(viewport); uiSystem->updateViewport(viewport); } diff --git a/src/Editor/Window/InspectorView.h b/src/Editor/Window/InspectorView.h index 9b16af9..d373513 100644 --- a/src/Editor/Window/InspectorView.h +++ b/src/Editor/Window/InspectorView.h @@ -8,6 +8,8 @@ namespace Seele { DECLARE_REF(Actor) +namespace Editor +{ class InspectorView : public View { public: @@ -39,4 +41,5 @@ protected: virtual void fileCallback(int count, const char** paths) override; }; DEFINE_REF(InspectorView) +} // namespace Editor } // namespace Seele diff --git a/src/Editor/Window/PlayView.cpp b/src/Editor/Window/PlayView.cpp new file mode 100644 index 0000000..e7434bc --- /dev/null +++ b/src/Editor/Window/PlayView.cpp @@ -0,0 +1,39 @@ +#include "PlayView.h" +#include "Window/Window.h" + +using namespace Seele; +using namespace Seele::Editor; + +PlayView::PlayView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::string dllPath) + : GameView(std::move(graphics), std::move(window), std::move(createInfo), dllPath) +{ +} + +PlayView::~PlayView() +{ +} + +void PlayView::beginUpdate() +{ + GameView::beginUpdate(); +} + +void PlayView::update() +{ + GameView::update(); +} + +void PlayView::commitUpdate() +{ + GameView::commitUpdate(); +} + +void PlayView::prepareRender() +{ + GameView::prepareRender(); +} + +void PlayView::render() +{ + GameView::render(); +} diff --git a/src/Editor/Window/PlayView.h b/src/Editor/Window/PlayView.h new file mode 100644 index 0000000..6c9cbf5 --- /dev/null +++ b/src/Editor/Window/PlayView.h @@ -0,0 +1,23 @@ +#pragma once +#include "Window/GameView.h" + +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 prepareRender() override; + virtual void render() override; +private: +}; +DECLARE_REF(PlayView) +} // namespace Editor +} // namespace Seele \ No newline at end of file diff --git a/src/Editor/Window/SceneView.h b/src/Editor/Window/SceneView.h index 7f49d83..1532ca8 100644 --- a/src/Editor/Window/SceneView.h +++ b/src/Editor/Window/SceneView.h @@ -11,7 +11,6 @@ namespace Seele DECLARE_REF(Scene) namespace Editor { - class SceneView : public View { public: diff --git a/src/Editor/Window/ViewportControl.cpp b/src/Editor/Window/ViewportControl.cpp index 117e63c..da7ff27 100644 --- a/src/Editor/Window/ViewportControl.cpp +++ b/src/Editor/Window/ViewportControl.cpp @@ -2,6 +2,7 @@ #include "Component/Camera.h" using namespace Seele; +using namespace Seele::Editor; ViewportControl::ViewportControl(const URect& viewportDimensions, Vector initialPos) : position(initialPos) diff --git a/src/Editor/Window/ViewportControl.h b/src/Editor/Window/ViewportControl.h index 98ef264..ec7c4f4 100644 --- a/src/Editor/Window/ViewportControl.h +++ b/src/Editor/Window/ViewportControl.h @@ -5,27 +5,30 @@ namespace Seele { -class ViewportControl +namespace Editor { -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; -}; + 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 f5ace13..ee37c11 100644 --- a/src/Editor/main.cpp +++ b/src/Editor/main.cpp @@ -1,14 +1,22 @@ #include "Window/WindowManager.h" #include "Window/SceneView.h" -#include "Window/GameView.h" +#include "Window/PlayView.h" #include "Window/InspectorView.h" #include "Asset/AssetRegistry.h" +#include "Asset/AssetImporter.h" #include "Asset/TextureLoader.h" #include "Graphics/Vulkan/VulkanGraphics.h" +#include "Asset/MeshLoader.h" +#include "Asset/TextureLoader.h" +#include "Asset/MaterialLoader.h" +#include "Asset/FontLoader.h" +#include "Asset/AssetImporter.h" using namespace Seele; using namespace Seele::Editor; +extern AssetRegistry* instance; + int main() { Gfx::PGraphics graphics = new Vulkan::Graphics(); @@ -17,6 +25,180 @@ int main() graphics->init(initializer); PWindowManager windowManager = new WindowManager(); AssetRegistry::init(std::string("C:\\Users\\Dynamitos\\TrackClear\\Assets"), graphics); + AssetImporter::init(graphics, instance); + AssetImporter::importFont(FontImportArgs{ + .filePath = "./fonts/Calibri.ttf", + }); + AssetImporter::importMesh(MeshImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/arena.fbx", + }); + AssetImporter::importMesh(MeshImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/train.fbx", + }); + AssetImporter::importMesh(MeshImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/bird.fbx", + }); + AssetImporter::importMesh(MeshImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/cube.fbx", + }); + AssetImporter::importMesh(MeshImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/flameThrower.fbx", + }); + AssetImporter::importMesh(MeshImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/player.fbx", + }); + AssetImporter::importMesh(MeshImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/shotgun.fbx", + }); + AssetImporter::importMesh(MeshImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/track.fbx", + }); + AssetImporter::importMesh(MeshImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/models/zombie.fbx", + }); + + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Dirt.png", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/DirtGrass.png", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Grass.png", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Ice.png", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Lava.png", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Obsidian.png", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Rocks.png", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Sand.png", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Water.png", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/Wood.png", + }); + + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level0/blendMap.png", + .importPath = "level0", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level0/heightMap.png", + .importPath = "level0", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level0/trackMap.png", + .importPath = "level0", + }); + AssetImporter::importMaterial(MaterialImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/shaders/TerrainMaterial.json", + .importPath = "level0", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level1/blendMap.png", + .importPath = "level1", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level1/heightMap.png", + .importPath = "level1", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level1/trackMap.png", + .importPath = "level1", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level2/blendMap.png", + .importPath = "level2", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level2/heightMap.png", + .importPath = "level2", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level2/trackMap.png", + .importPath = "level2", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level3/blendMap.png", + .importPath = "level3", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level3/heightMap.png", + .importPath = "level3", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level3/trackMap.png", + .importPath = "level3", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level4/blendMap.png", + .importPath = "level4", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level4/heightMap.png", + .importPath = "level4", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level4/trackMap.png", + .importPath = "level4", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level5/blendMap.png", + .importPath = "level5", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level5/heightMap.png", + .importPath = "level5", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level5/trackMap.png", + .importPath = "level5", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level6/blendMap.png", + .importPath = "level6", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level6/heightMap.png", + .importPath = "level6", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level6/trackMap.png", + .importPath = "level6", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level7/blendMap.png", + .importPath = "level7", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level7/heightMap.png", + .importPath = "level7", + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/textures/level7/trackMap.png", + .importPath = "level7", + }); + + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/skyboxes/FS000_Day_01.png", + .type = TextureImportType::TEXTURE_CUBEMAP, + }); + AssetImporter::importTexture(TextureImportArgs{ + .filePath = "C:/Users/Dynamitos/TrackClear/old_resources/skyboxes/FS000_Night_01.png", + .type = TextureImportType::TEXTURE_CUBEMAP, + }); + + AssetRegistry::saveRegistry(); WindowCreateInfo mainWindowInfo; mainWindowInfo.title = "SeeleEngine"; @@ -31,7 +213,7 @@ int main() sceneViewInfo.dimensions.size.y = 720; sceneViewInfo.dimensions.offset.x = 0; sceneViewInfo.dimensions.offset.y = 0; - PGameView sceneView = new GameView(graphics, window, sceneViewInfo); + PGameView sceneView = new Editor::PlayView(graphics, window, sceneViewInfo, "C:\\Users\\Dynamitos\\TrackClear\\bin\\TrackCleard.dll"); //ViewportCreateInfo inspectorViewInfo; //inspectorViewInfo.dimensions.size.x = 640; diff --git a/src/Engine/Asset/Asset.cpp b/src/Engine/Asset/Asset.cpp index da51349..f234356 100644 --- a/src/Engine/Asset/Asset.cpp +++ b/src/Engine/Asset/Asset.cpp @@ -31,6 +31,13 @@ Asset::~Asset() { } +void Asset::updateByteSize() +{ + ArchiveBuffer buffer; + save(buffer); + byteSize = buffer.size(); +} + std::string Asset::getFolderPath() const { return folderPath; diff --git a/src/Engine/Asset/Asset.h b/src/Engine/Asset/Asset.h index 30e206f..b95b9af 100644 --- a/src/Engine/Asset/Asset.h +++ b/src/Engine/Asset/Asset.h @@ -18,6 +18,8 @@ public: Asset(std::string_view folderPath, std::string_view name); virtual ~Asset(); + void updateByteSize(); + virtual void save(ArchiveBuffer& buffer) const = 0; virtual void load(ArchiveBuffer& buffer) = 0; @@ -27,6 +29,8 @@ public: std::string getFolderPath() const; // returns the identifier with which it can be found from the asset registry std::string getAssetIdentifier() const; + // returns the size of the assets data in bytes(excluding name and folder) + uint64 getByteSize() const { return byteSize; } constexpr Status getStatus() { @@ -41,7 +45,7 @@ protected: std::string name; std::string assetId; Status status; - uint32 byteSize; + uint64 byteSize; }; DEFINE_REF(Asset) } // namespace Seele \ No newline at end of file diff --git a/src/Engine/Asset/AssetRegistry.cpp b/src/Engine/Asset/AssetRegistry.cpp index e8f0eca..6c49b43 100644 --- a/src/Engine/Asset/AssetRegistry.cpp +++ b/src/Engine/Asset/AssetRegistry.cpp @@ -4,10 +4,6 @@ #include "TextureAsset.h" #include "MaterialAsset.h" #include "MaterialInstanceAsset.h" -#include "FontLoader.h" -#include "TextureLoader.h" -#include "MaterialLoader.h" -#include "MeshLoader.h" #include "Graphics/Mesh.h" #include "Graphics/Graphics.h" #include "Window/WindowManager.h" @@ -29,46 +25,6 @@ void AssetRegistry::init(const std::string& rootFolder, Gfx::PGraphics graphics) get().initialize(rootFolder, graphics); } -void AssetRegistry::importMesh(MeshImportArgs args) -{ - if (get().getOrCreateFolder(args.importPath)->meshes.contains(args.filePath.stem().string())) - { - // skip importing duplicates - return; - } - get().meshLoader->importAsset(args); -} - -void AssetRegistry::importTexture(TextureImportArgs args) -{ - if (get().getOrCreateFolder(args.importPath)->textures.contains(args.filePath.stem().string())) - { - // skip importing duplicates - return; - } - get().textureLoader->importAsset(args); -} - -void AssetRegistry::importFont(FontImportArgs args) -{ - if (get().getOrCreateFolder(args.importPath)->fonts.contains(args.filePath.stem().string())) - { - // skip importing duplicates - return; - } - get().fontLoader->importAsset(args); -} - -void AssetRegistry::importMaterial(MaterialImportArgs args) -{ - if (get().getOrCreateFolder(args.importPath)->materials.contains(args.filePath.stem().string())) - { - // skip importing duplicates - return; - } - get().materialLoader->importAsset(args); -} - PMeshAsset AssetRegistry::findMesh(const std::string &filePath) { AssetFolder* folder = get().assetRoot; @@ -150,15 +106,12 @@ void AssetRegistry::saveRegistry() get().saveRegistryInternal(); } + void AssetRegistry::initialize(const std::filesystem::path &_rootFolder, Gfx::PGraphics _graphics) { this->graphics = _graphics; this->rootFolder = _rootFolder; this->assetRoot = new AssetFolder(""); - this->fontLoader = new FontLoader(graphics); - this->meshLoader = new MeshLoader(graphics); - this->textureLoader = new TextureLoader(graphics); - this->materialLoader = new MaterialLoader(graphics); loadRegistryInternal(); } @@ -168,7 +121,6 @@ void AssetRegistry::loadRegistryInternal() loadFolder(assetRoot); } - void AssetRegistry::peekFolder(AssetFolder* folder) { for (const auto& entry : std::filesystem::directory_iterator(rootFolder / folder->folderPath)) @@ -192,49 +144,10 @@ void AssetRegistry::peekFolder(AssetFolder* folder) ArchiveBuffer buffer(graphics); buffer.readFromStream(stream); - - // Read asset type - uint64 identifier; - Serialization::load(buffer, identifier); - - // Read name - std::string name; - Serialization::load(buffer, name); - - // Read folder - std::string folderPath; - Serialization::load(buffer, folderPath); - - PAsset asset; - switch (identifier) - { - case TextureAsset::IDENTIFIER: - asset = new TextureAsset(folderPath, name); - folder->textures[asset->getName()] = asset; - break; - case MeshAsset::IDENTIFIER: - asset = new MeshAsset(folderPath, name); - folder->meshes[asset->getName()] = asset; - break; - case MaterialAsset::IDENTIFIER: - asset = new MaterialAsset(folderPath, name); - folder->materials[asset->getName()] = asset; - break; - case MaterialInstanceAsset::IDENTIFIER: - asset = new MaterialInstanceAsset(folderPath, name); - // TODO - break; - case FontAsset::IDENTIFIER: - asset = new FontAsset(folderPath, name); - folder->fonts[asset->getName()] = asset; - break; - default: - throw new std::logic_error("Unknown Identifier"); - } + peekAsset(buffer); } } - void AssetRegistry::loadFolder(AssetFolder* folder) { for (const auto& entry : std::filesystem::directory_iterator(rootFolder / folder->folderPath)) @@ -251,45 +164,101 @@ void AssetRegistry::loadFolder(AssetFolder* folder) ArchiveBuffer buffer(graphics); buffer.readFromStream(stream); - - // Read asset type - uint64 identifier; - Serialization::load(buffer, identifier); - - // Read name - std::string name; - Serialization::load(buffer, name); - - // Read folder - std::string folderPath; - Serialization::load(buffer, folderPath); - - PAsset asset; - switch (identifier) - { - case TextureAsset::IDENTIFIER: - asset = folder->textures.at(name); - break; - case MeshAsset::IDENTIFIER: - asset = folder->meshes.at(name); - break; - case MaterialAsset::IDENTIFIER: - asset = folder->materials.at(name); - break; - case MaterialInstanceAsset::IDENTIFIER: - //asset = new MaterialInstanceAsset(path); - // TODO - break; - case FontAsset::IDENTIFIER: - asset = folder->fonts.at(name); - break; - default: - throw new std::logic_error("Unknown Identifier"); - } - asset->load(buffer); + loadAsset(buffer); } } +void AssetRegistry::peekAsset(ArchiveBuffer& buffer) +{ + // Read asset type + uint64 identifier; + Serialization::load(buffer, identifier); + + // Read name + std::string name; + Serialization::load(buffer, name); + + // Read folder + std::string folderPath; + Serialization::load(buffer, folderPath); + + uint64 assetSize; + Serialization::load(buffer, assetSize); + + AssetFolder* folder = getOrCreateFolder(folderPath); + + PAsset asset; + switch (identifier) + { + case TextureAsset::IDENTIFIER: + asset = new TextureAsset(folderPath, name); + folder->textures[asset->getName()] = asset; + break; + case MeshAsset::IDENTIFIER: + asset = new MeshAsset(folderPath, name); + folder->meshes[asset->getName()] = asset; + break; + case MaterialAsset::IDENTIFIER: + asset = new MaterialAsset(folderPath, name); + folder->materials[asset->getName()] = asset; + break; + case MaterialInstanceAsset::IDENTIFIER: + asset = new MaterialInstanceAsset(folderPath, name); + // TODO + break; + case FontAsset::IDENTIFIER: + asset = new FontAsset(folderPath, name); + folder->fonts[asset->getName()] = asset; + break; + default: + throw new std::logic_error("Unknown Identifier"); + } +} + +void AssetRegistry::loadAsset(ArchiveBuffer& buffer) +{ + // Read asset type + uint64 identifier; + Serialization::load(buffer, identifier); + + // Read name + std::string name; + Serialization::load(buffer, name); + + // Read folder + std::string folderPath; + Serialization::load(buffer, folderPath); + + uint64 assetSize; + Serialization::load(buffer, assetSize); + + AssetFolder* folder = getOrCreateFolder(folderPath); + + PAsset asset; + switch (identifier) + { + case TextureAsset::IDENTIFIER: + asset = folder->textures.at(name); + break; + case MeshAsset::IDENTIFIER: + asset = folder->meshes.at(name); + break; + case MaterialAsset::IDENTIFIER: + asset = folder->materials.at(name); + break; + case MaterialInstanceAsset::IDENTIFIER: + //asset = new MaterialInstanceAsset(path); + // TODO + break; + case FontAsset::IDENTIFIER: + asset = folder->fonts.at(name); + break; + default: + throw new std::logic_error("Unknown Identifier"); + } + asset->load(buffer); +} + void AssetRegistry::saveRegistryInternal() { saveFolder("", assetRoot); @@ -334,6 +303,9 @@ void AssetRegistry::saveAsset(PAsset asset, uint64 identifier, const std::filesy Serialization::save(assetBuffer, name); // write folder Serialization::save(assetBuffer, folderPath.string()); + // write the asset size + asset->updateByteSize(); + Serialization::save(assetBuffer, asset->getByteSize()); // write asset data asset->save(assetBuffer); assetBuffer.writeToStream(assetStream); @@ -420,3 +392,4 @@ AssetRegistry::AssetFolder::~AssetFolder() delete child; } } + diff --git a/src/Engine/Asset/AssetRegistry.h b/src/Engine/Asset/AssetRegistry.h index c1aad2d..794209b 100644 --- a/src/Engine/Asset/AssetRegistry.h +++ b/src/Engine/Asset/AssetRegistry.h @@ -6,10 +6,6 @@ namespace Seele { -DECLARE_REF(TextureLoader) -DECLARE_REF(FontLoader) -DECLARE_REF(MeshLoader) -DECLARE_REF(MaterialLoader) DECLARE_REF(TextureAsset) DECLARE_REF(FontAsset) DECLARE_REF(MeshAsset) @@ -32,22 +28,14 @@ public: static std::ofstream createWriteStream(const std::string& relativePath, std::ios_base::openmode openmode = std::ios::out); static std::ifstream createReadStream(const std::string& relativePath, std::ios_base::openmode openmode = std::ios::in); - 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 set(AssetRegistry registry); static void loadRegistry(); static void saveRegistry(); - - AssetRegistry(); -private: struct AssetFolder { std::string folderPath; Map children; - //Todo: Seele::Map doesn't really work with strings for some reason, so just use std::map for now Map textures; Map fonts; Map meshes; @@ -55,13 +43,17 @@ private: AssetFolder(std::string_view folderPath); ~AssetFolder(); }; - + AssetFolder* getOrCreateFolder(std::string foldername); + AssetRegistry(); +private: static AssetRegistry& get(); void initialize(const std::filesystem::path& rootFolder, Gfx::PGraphics graphics); void loadRegistryInternal(); void peekFolder(AssetFolder* folder); void loadFolder(AssetFolder* folder); + void peekAsset(ArchiveBuffer& buffer); + void loadAsset(ArchiveBuffer& buffer); void saveRegistryInternal(); void saveFolder(const std::filesystem::path& folderPath, AssetFolder* folder); void saveAsset(PAsset asset, uint64 identifier, const std::filesystem::path& folderPath, std::string name); @@ -71,18 +63,14 @@ private: void registerFont(PFontAsset font); void registerMaterial(PMaterialAsset material); - AssetFolder* getOrCreateFolder(std::string foldername); - std::ofstream internalCreateWriteStream(const std::string& relativePath, std::ios_base::openmode openmode = std::ios::out); std::ifstream internalCreateReadStream(const std::string& relaitvePath, std::ios_base::openmode openmode = std::ios::in); std::filesystem::path rootFolder; AssetFolder* assetRoot; Gfx::PGraphics graphics; - UPTextureLoader textureLoader; - UPFontLoader fontLoader; - UPMeshLoader meshLoader; - UPMaterialLoader materialLoader; + ArchiveBuffer assetBuffer; + bool release = false; friend class TextureLoader; friend class FontLoader; friend class MaterialLoader; diff --git a/src/Engine/Asset/CMakeLists.txt b/src/Engine/Asset/CMakeLists.txt index 3dfb127..52676b3 100644 --- a/src/Engine/Asset/CMakeLists.txt +++ b/src/Engine/Asset/CMakeLists.txt @@ -6,22 +6,14 @@ target_sources(Engine AssetRegistry.cpp FontAsset.h FontAsset.cpp - FontLoader.h - FontLoader.cpp MaterialAsset.h MaterialAsset.cpp MaterialInstanceAsset.h MaterialInstanceAsset.cpp - MaterialLoader.h - MaterialLoader.cpp MeshAsset.h MeshAsset.cpp - MeshLoader.h - MeshLoader.cpp TextureAsset.h - TextureAsset.cpp - TextureLoader.h - TextureLoader.cpp) + TextureAsset.cpp) target_sources(Engine PUBLIC FILE_SET HEADERS @@ -29,11 +21,7 @@ target_sources(Engine Asset.h AssetRegistry.h FontAsset.h - FontLoader.h MaterialAsset.h MaterialInstanceAsset.h - MaterialLoader.h MeshAsset.h - MeshLoader.h - TextureAsset.h - TextureLoader.h) \ No newline at end of file + TextureAsset.h) \ No newline at end of file diff --git a/src/Engine/Asset/FontAsset.cpp b/src/Engine/Asset/FontAsset.cpp index df89c5c..33013af 100644 --- a/src/Engine/Asset/FontAsset.cpp +++ b/src/Engine/Asset/FontAsset.cpp @@ -22,10 +22,9 @@ FontAsset::~FontAsset() void FontAsset::save(ArchiveBuffer& buffer) const { uint64 numGlyphs = glyphs.size(); - buffer.writeBytes(&numGlyphs, sizeof(uint64)); + Serialization::save(buffer, numGlyphs); for (auto& [index, glyph] : glyphs) { - Serialization::save(buffer, index); Array textureData; ktxTexture2* kTexture; @@ -36,6 +35,7 @@ void FontAsset::save(ArchiveBuffer& buffer) const .baseDepth = glyph.texture->getSizeZ(), .numDimensions = glyph.texture->getSizeZ() > 1 ? 3u : glyph.texture->getSizeY() > 1 ? 2u : 1u, .numLevels = glyph.texture->getMipLevels(), + .numLayers = glyph.texture->getSizeZ(), .numFaces = glyph.texture->getNumFaces(), .isArray = false, .generateMipmaps = false, @@ -64,9 +64,13 @@ void FontAsset::save(ArchiveBuffer& buffer) const ktx_size_t texSize; ktxTexture_WriteToMemory(ktxTexture(kTexture), &texData, &texSize); - buffer.writeBytes(texData, texSize); + Array rawData(texSize); + std::memcpy(rawData.data(), texData, texSize); + free(texData); + Serialization::save(buffer, index); + Serialization::save(buffer, rawData); Serialization::save(buffer, glyph.size); Serialization::save(buffer, glyph.bearing); Serialization::save(buffer, glyph.advance); @@ -77,7 +81,7 @@ void FontAsset::save(ArchiveBuffer& buffer) const void FontAsset::load(ArchiveBuffer& buffer) { uint64 numGlyphs = glyphs.size(); - buffer.readBytes(&numGlyphs, sizeof(uint64)); + Serialization::load(buffer, numGlyphs); for (uint64 x = 0; x < numGlyphs; ++x) { uint32 index; @@ -85,11 +89,8 @@ void FontAsset::load(ArchiveBuffer& buffer) Glyph& glyph = glyphs[index]; - uint64 texSize; - buffer.readBytes(&texSize, sizeof(uint64)); Array rawTex; - rawTex.resize(texSize); - buffer.readBytes(rawTex.data(), rawTex.size()); + Serialization::load(buffer, rawTex); ktxTexture2* kTexture; ktxTexture2_CreateFromMemory(rawTex.data(), diff --git a/src/Engine/Asset/TextureAsset.cpp b/src/Engine/Asset/TextureAsset.cpp index 2466610..ce02940 100644 --- a/src/Engine/Asset/TextureAsset.cpp +++ b/src/Engine/Asset/TextureAsset.cpp @@ -25,7 +25,7 @@ TextureAsset::~TextureAsset() void TextureAsset::save(ArchiveBuffer& buffer) const { - Array textureData; + /*Array textureData; ktxTexture2* kTexture; ktxTextureCreateInfo createInfo = { .vkFormat = (uint32_t)texture->getFormat(), @@ -66,25 +66,28 @@ void TextureAsset::save(ArchiveBuffer& buffer) const Array rawData(texSize); std::memcpy(rawData.data(), texData, texSize); free(texData); - - Serialization::save(buffer, rawData); + */ + Serialization::save(buffer, textureData); } void TextureAsset::load(ArchiveBuffer& buffer) { - setStatus(Status::Loading); - Array rawData; Serialization::load(buffer, rawData); + createFromMemory(std::move(rawData), buffer.getGraphics()); +} +void TextureAsset::createFromMemory(Array memory, Gfx::PGraphics graphics) +{ + textureData = std::move(memory); ktxTexture2* kTexture; std::cout << "Loading texture " << name << std::endl; - KTX_CHECK(ktxTexture_CreateFromMemory(rawData.data(), - rawData.size(), - KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, - (ktxTexture**) & kTexture)); + KTX_CHECK(ktxTexture_CreateFromMemory(textureData.data(), + textureData.size(), + KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, + (ktxTexture**)&kTexture)); - //ktxTexture2_TranscodeBasis(kTexture, KTX_TTF_BC7_RGBA, 0); + ktxTexture2_TranscodeBasis(kTexture, KTX_TTF_BC7_RGBA, 0); TextureCreateInfo createInfo = { .resourceData = { @@ -101,21 +104,18 @@ void TextureAsset::load(ArchiveBuffer& buffer) .format = Vulkan::cast((VkFormat)kTexture->vkFormat), .usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT, }; - Gfx::PTexture tex; if (kTexture->isCubemap) { - tex = buffer.getGraphics()->createTextureCube(createInfo); + texture = graphics->createTextureCube(createInfo); } else if (kTexture->isArray) { - tex = buffer.getGraphics()->createTexture3D(createInfo); + texture = graphics->createTexture3D(createInfo); } else { - tex = buffer.getGraphics()->createTexture2D(createInfo); + texture = graphics->createTexture2D(createInfo); } - tex->transferOwnership(Gfx::QueueType::GRAPHICS); - setTexture(tex); + texture->transferOwnership(Gfx::QueueType::GRAPHICS); ktxTexture_Destroy(ktxTexture(kTexture)); - setStatus(Asset::Status::Ready); } \ No newline at end of file diff --git a/src/Engine/Asset/TextureAsset.h b/src/Engine/Asset/TextureAsset.h index 264d9ce..1126302 100644 --- a/src/Engine/Asset/TextureAsset.h +++ b/src/Engine/Asset/TextureAsset.h @@ -13,6 +13,7 @@ public: virtual ~TextureAsset(); virtual void save(ArchiveBuffer& buffer) const override; virtual void load(ArchiveBuffer& buffer) override; + void createFromMemory(Array memory, Gfx::PGraphics graphics); void setTexture(Gfx::PTexture _texture) { texture = _texture; @@ -22,6 +23,7 @@ public: return texture; } private: + Array textureData; Gfx::PTexture texture; friend class TextureLoader; }; diff --git a/src/Engine/CMakeLists.txt b/src/Engine/CMakeLists.txt index a103123..7c3fafe 100644 --- a/src/Engine/CMakeLists.txt +++ b/src/Engine/CMakeLists.txt @@ -22,6 +22,7 @@ add_subdirectory(Graphics/) add_subdirectory(Material/) add_subdirectory(Math/) add_subdirectory(Physics/) +add_subdirectory(Platform/) add_subdirectory(Serialization/) add_subdirectory(Scene/) add_subdirectory(System/) diff --git a/src/Engine/Component/CMakeLists.txt b/src/Engine/Component/CMakeLists.txt index 1d7b0c2..af2d8dc 100644 --- a/src/Engine/Component/CMakeLists.txt +++ b/src/Engine/Component/CMakeLists.txt @@ -18,6 +18,7 @@ target_sources(Engine Transform.h Transform.cpp) + target_sources(Engine PUBLIC FILE_SET HEADERS FILES diff --git a/src/Engine/Containers/CMakeLists.txt b/src/Engine/Containers/CMakeLists.txt index fe2b81a..fe109a1 100644 --- a/src/Engine/Containers/CMakeLists.txt +++ b/src/Engine/Containers/CMakeLists.txt @@ -5,7 +5,6 @@ target_sources(Engine Map.h Pair.h) - target_sources(Engine PUBLIC FILE_SET HEADERS FILES diff --git a/src/Engine/Containers/Map.h b/src/Engine/Containers/Map.h index 45d14e3..249e858 100644 --- a/src/Engine/Containers/Map.h +++ b/src/Engine/Containers/Map.h @@ -290,6 +290,18 @@ public: markIteratorsDirty(); return getNode(root)->pair.value; } + + constexpr const mapped_type& at(const key_type& key) const + { + for(const auto& node : nodeContainer) + { + if(equal(node.pair.key, key)) + { + return node.pair.value; + } + } + throw std::logic_error("Key not found"); + } constexpr iterator find(const key_type& key) { root = splay(root, key); @@ -621,7 +633,7 @@ private: return (!isValid(node->rightChild)) ? r : rotateLeft(r); } } - bool equal(const key_type& a, const key_type& b) + bool equal(const key_type& a, const key_type& b) const { return !comp(a, b) && !comp(b, a); } diff --git a/src/Engine/Graphics/CMakeLists.txt b/src/Engine/Graphics/CMakeLists.txt index f61c4ee..403bbaf 100644 --- a/src/Engine/Graphics/CMakeLists.txt +++ b/src/Engine/Graphics/CMakeLists.txt @@ -18,7 +18,7 @@ target_sources(Engine VertexShaderInput.cpp StaticMeshVertexInput.h StaticMeshVertexInput.cpp) - + target_sources(Engine PUBLIC FILE_SET HEADERS FILES diff --git a/src/Engine/Graphics/Vulkan/CMakeLists.txt b/src/Engine/Graphics/Vulkan/CMakeLists.txt index a26c910..2ff5e1e 100644 --- a/src/Engine/Graphics/Vulkan/CMakeLists.txt +++ b/src/Engine/Graphics/Vulkan/CMakeLists.txt @@ -29,7 +29,7 @@ target_sources(Engine VulkanQueue.h VulkanQueue.cpp VulkanViewport.cpp) - + target_sources(Engine PUBLIC FILE_SET HEADERS FILES diff --git a/src/Engine/Graphics/Vulkan/VulkanBuffer.cpp b/src/Engine/Graphics/Vulkan/VulkanBuffer.cpp index 34dd3c7..9d6f5e2 100644 --- a/src/Engine/Graphics/Vulkan/VulkanBuffer.cpp +++ b/src/Engine/Graphics/Vulkan/VulkanBuffer.cpp @@ -235,7 +235,7 @@ void *ShaderBuffer::lockRegion(uint64 regionOffset, uint64 regionSize, bool bWri graphics->getQueueCommands(owner)->submitCommands(); vkQueueWaitIdle(graphics->getQueueCommands(owner)->getQueue()->getHandle()); - + stagingBuffer->getMappedPointer(); // this maps the memory if not mapped already stagingBuffer->flushMappedMemory(); pending.stagingBuffer = stagingBuffer; diff --git a/src/Engine/Material/BRDF.cpp b/src/Engine/Material/BRDF.cpp deleted file mode 100644 index eef208f..0000000 --- a/src/Engine/Material/BRDF.cpp +++ /dev/null @@ -1,111 +0,0 @@ -#include "BRDF.h" -#include -#include -#include - -using namespace Seele; -using json = nlohmann::json; - -List BRDF::globalBRDFList; - -BRDF::BRDF(const char* name) - : name(name) -{ - globalBRDFList.add(this); -} - -BRDF::~BRDF() -{ - globalBRDFList.remove(globalBRDFList.find(this)); -} - - -BRDF* BRDF::getBRDFByName(const std::string& name) -{ - for(auto brdf : globalBRDFList) - { - if(name.compare(brdf->name) == 0) - { - return brdf; - } - } - return nullptr; -} - -List BRDF::getBRDFList() -{ - return globalBRDFList; -} - -BlinnPhong::BlinnPhong(const char* name) - : BRDF(name) -{ -} - -BlinnPhong::~BlinnPhong() -{ -} - -void BlinnPhong::generateMaterialCode(std::ofstream& codeStream, json codeJson) -{ - std::stringstream accessorStream; - - auto generateAccessor = [codeJson](std::stringstream& accessorStream, const std::string& key, const std::string& defaultVal) - { - if(codeJson.contains(key)) - { - for(auto code : codeJson[key].items()) - { - accessorStream << "\t\t" << code.value().get() << ";" << std::endl; - } - } - else - { - accessorStream << "\t\treturn " << defaultVal << ";\n"; - } - - }; - accessorStream << "\tfloat3 getBaseColor(MaterialFragmentParameter input) {\n"; - generateAccessor(accessorStream, "baseColor", "float3(0.5f, 0.5f, 0.5f)"); - accessorStream << "\t}\n"; - - accessorStream << "\tfloat getMetallic(MaterialFragmentParameter input) {\n"; - generateAccessor(accessorStream, "metallic", "0.f"); - accessorStream << "\t}\n"; - - accessorStream << "\tfloat3 getNormal(MaterialFragmentParameter input) {\n"; - generateAccessor(accessorStream, "normal", "float3(0, 1, 0)"); - accessorStream << "\t}\n"; - - accessorStream << "\tfloat getSpecular(MaterialFragmentParameter input) {\n"; - generateAccessor(accessorStream, "specular", "0.f"); - accessorStream << "\t}\n"; - - accessorStream << "\tfloat getRoughness(MaterialFragmentParameter input) {\n"; - generateAccessor(accessorStream, "roughness", "0.f"); - accessorStream << "\t}\n"; - - accessorStream << "\tfloat getSheen(MaterialFragmentParameter input) {\n"; - generateAccessor(accessorStream, "sheen", "0.f"); - accessorStream << "\t}\n"; - - accessorStream << "\tfloat3 getWorldOffset() {\n"; - generateAccessor(accessorStream, "worldOffset", "0.f"); - accessorStream << "\t}\n"; - - codeStream << accessorStream.str(); - - codeStream << "\ttypedef " << name << " BRDF;" << std::endl; - codeStream << "\t" << name << " prepare(MaterialFragmentParameter geometry) {" << std::endl; - codeStream << "\t\t" << name << " result;" << std::endl; - codeStream << "\t\tresult.baseColor = getBaseColor(geometry);" << std::endl; - codeStream << "\t\tresult.metallic = getMetallic(geometry);" << std::endl; - codeStream << "\t\tresult.normal = getNormal(geometry);" << std::endl; - codeStream << "\t\tresult.specular = getSpecular(geometry);" << std::endl; - codeStream << "\t\tresult.roughness = getRoughness(geometry);" << std::endl; - codeStream << "\t\tresult.sheen = getSheen(geometry);" << std::endl; - codeStream << "\t\treturn result;" << std::endl; - codeStream << "\t}" << std::endl; -} - -IMPLEMENT_BRDF(BlinnPhong) \ No newline at end of file diff --git a/src/Engine/Material/BRDF.h b/src/Engine/Material/BRDF.h deleted file mode 100644 index 806b51c..0000000 --- a/src/Engine/Material/BRDF.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once -#include "MinimalEngine.h" -#include "Containers/List.h" -#include - -namespace Seele -{ -class BRDF -{ -public: - static BRDF* getBRDFByName(const std::string& name); - static List getBRDFList(); - - virtual void generateMaterialCode(std::ofstream& codeStream, nlohmann::json codeJson) = 0; -protected: - BRDF(const char* name); - virtual ~BRDF(); - static List globalBRDFList; - const char* name; -}; - -#define DECLARE_BRDF(inputClass) \ - public: \ - static inputClass staticType; - -#define IMPLEMENT_BRDF(inputClass) \ - inputClass inputClass::staticType( \ - #inputClass); - -class BlinnPhong : public BRDF -{ - DECLARE_BRDF(BlinnPhong) -public: - virtual void generateMaterialCode(std::ofstream& codeStream, nlohmann::json codeJson); -protected: - BlinnPhong(const char* name); - virtual ~BlinnPhong(); -}; -} // namespace Seele diff --git a/src/Engine/Material/CMakeLists.txt b/src/Engine/Material/CMakeLists.txt index 6f41849..484dad9 100644 --- a/src/Engine/Material/CMakeLists.txt +++ b/src/Engine/Material/CMakeLists.txt @@ -1,7 +1,5 @@ target_sources(Engine PRIVATE - BRDF.h - BRDF.cpp Material.h Material.cpp MaterialInstance.h @@ -10,11 +8,10 @@ target_sources(Engine MaterialInterface.cpp ShaderExpression.h ShaderExpression.cpp) - + target_sources(Engine PUBLIC FILE_SET HEADERS FILES - BRDF.h Material.h MaterialInstance.h MaterialInterface.h diff --git a/src/Engine/Material/Material.cpp b/src/Engine/Material/Material.cpp index 700c63f..8e9dac2 100644 --- a/src/Engine/Material/Material.cpp +++ b/src/Engine/Material/Material.cpp @@ -9,10 +9,19 @@ using namespace Seele; Gfx::ShaderMap Material::shaderMap; std::mutex Material::shaderMapLock; -Material::Material(Gfx::PGraphics graphics, Array parameter, Gfx::PDescriptorLayout layout, uint32 uniformDataSize, uint32 uniformBinding, std::string materialName) +Material::Material(Gfx::PGraphics graphics, + Array parameter, + Gfx::PDescriptorLayout layout, + uint32 uniformDataSize, + uint32 uniformBinding, + std::string materialName, + Array expressions, + MaterialNode brdf) : MaterialInterface(graphics, parameter, uniformDataSize, uniformBinding) , layout(layout) , materialName(materialName) + , codeExpressions(expressions) + , brdf(brdf) { } @@ -89,6 +98,34 @@ void Material::load(ArchiveBuffer& buffer) layout->create(); } +void Material::compile() +{ + std::ofstream codeStream("./shaders/generated/"+materialName+".slang"); + codeStream << "import Material;\n"; + codeStream << "import BRDF;\n"; + codeStream << "import MaterialParameter;\n"; + codeStream << "struct " << materialName << " : IMaterial {\n"; + for(const auto& parameter : parameters) + { + parameter->generateDeclaration(codeStream); + } + codeStream << "\ttypedef " << brdf.profile << " BRDF;\n"; + codeStream << "\t" << brdf.profile << " prepare(MaterialFragmentParameter input) {\n"; + codeStream << "\t\t" << brdf.profile << " result;\n"; + Map varState; + for(const auto& expr : codeExpressions) + { + codeStream << expr->evaluate(varState); + } + for(const auto& [name, exp] : brdf.variables) + { + codeStream << "\t\tresult." << name << " = " << varState[exp->key] << ";"; + } + codeStream << "\t\treturn result;\n"; + codeStream << "\t}\n"; + codeStream << "};\n"; +} + const Gfx::ShaderCollection* Material::getShaders(Gfx::RenderPassType renderPass, VertexInputType* vertexInput) const { Gfx::ShaderPermutation permutation; diff --git a/src/Engine/Material/Material.h b/src/Engine/Material/Material.h index 8c9ac7b..d60dc14 100644 --- a/src/Engine/Material/Material.h +++ b/src/Engine/Material/Material.h @@ -8,7 +8,14 @@ class Material : public MaterialInterface { public: Material() {} - Material(Gfx::PGraphics graphics, Array parameter, Gfx::PDescriptorLayout layout, uint32 uniformDataSize, uint32 uniformBinding, std::string materialName); + Material(Gfx::PGraphics graphics, + Array parameter, + Gfx::PDescriptorLayout layout, + uint32 uniformDataSize, + uint32 uniformBinding, + std::string materialName, + Array expressions, + MaterialNode brdf); virtual ~Material(); virtual Gfx::PDescriptorSet createDescriptorSet(); virtual Gfx::PDescriptorLayout getDescriptorLayout() const { return layout; } @@ -17,6 +24,8 @@ public: virtual void save(ArchiveBuffer& buffer) const; virtual void load(ArchiveBuffer& buffer); + void compile(); + virtual const Gfx::ShaderCollection* getShaders(Gfx::RenderPassType renderPass, VertexInputType* vertexInput) const; virtual Gfx::ShaderCollection& createShaders(Gfx::PGraphics graphics, Gfx::RenderPassType renderPass, VertexInputType* vertexInput); private: @@ -25,6 +34,8 @@ private: Gfx::PDescriptorLayout layout; std::string materialName; + Array codeExpressions; + MaterialNode brdf; // With draw-indirect, we batch vertex data into big vertex buffers // Gfx::PVertexDataManager vertexData; diff --git a/src/Engine/Material/MaterialInterface.h b/src/Engine/Material/MaterialInterface.h index afa039e..a77b876 100644 --- a/src/Engine/Material/MaterialInterface.h +++ b/src/Engine/Material/MaterialInterface.h @@ -25,7 +25,7 @@ public: virtual Gfx::ShaderCollection& createShaders(Gfx::PGraphics graphics, Gfx::RenderPassType renderPass, VertexInputType* vertexInput) = 0; protected: Gfx::PGraphics graphics; - //For now its simply the collection of parameters, since there is no point for expressions + std::string brdfName; Array parameters; Gfx::PUniformBuffer uniformBuffer; uint32 uniformDataSize; diff --git a/src/Engine/Material/ShaderExpression.cpp b/src/Engine/Material/ShaderExpression.cpp index e42b01c..53cfaed 100644 --- a/src/Engine/Material/ShaderExpression.cpp +++ b/src/Engine/Material/ShaderExpression.cpp @@ -6,6 +6,16 @@ using namespace Seele; +void ShaderExpression::save(ArchiveBuffer& buffer) const +{ + Serialization::save(buffer, key); +} + +void ShaderExpression::load(ArchiveBuffer& buffer) +{ + Serialization::load(buffer, key); +} + ShaderParameter::ShaderParameter(std::string name, uint32 byteOffset, uint32 binding) : name(name) , byteOffset(byteOffset) @@ -17,8 +27,15 @@ ShaderParameter::~ShaderParameter() { } +std::string ShaderParameter::evaluate(Map& varState) const +{ + varState[key] = name; + return ""; +} + void ShaderParameter::save(ArchiveBuffer& buffer) const { + ShaderExpression::save(buffer); Serialization::save(buffer, name); Serialization::save(buffer, byteOffset); Serialization::save(buffer, binding); @@ -26,6 +43,7 @@ void ShaderParameter::save(ArchiveBuffer& buffer) const void ShaderParameter::load(ArchiveBuffer& buffer) { + ShaderExpression::load(buffer); Serialization::load(buffer, name); Serialization::load(buffer, byteOffset); Serialization::load(buffer, binding); @@ -35,6 +53,8 @@ FloatParameter::FloatParameter(std::string name, uint32 byteOffset, uint32 bindi : ShaderParameter(name, byteOffset, binding) , data(0) { + output.name = name; + output.type = ExpressionType::FLOAT; } FloatParameter::~FloatParameter() @@ -58,22 +78,33 @@ void FloatParameter::updateDescriptorSet(Gfx::PDescriptorSet, uint8* dst) std::memcpy(dst + byteOffset, &data, sizeof(float)); } +void FloatParameter::generateDeclaration(std::ofstream& stream) const +{ + stream << "\tlayout(offset = " << byteOffset << ") float " << name << ";\n"; +} + VectorParameter::VectorParameter(std::string name, uint32 byteOffset, uint32 binding) : ShaderParameter(name, byteOffset, binding) , data() { + output.name = name; + output.type = ExpressionType::FLOAT3; } VectorParameter::~VectorParameter() { } - void VectorParameter::updateDescriptorSet(Gfx::PDescriptorSet, uint8* dst) { std::memcpy(dst + byteOffset, &data, sizeof(Vector)); } +void VectorParameter::generateDeclaration(std::ofstream& stream) const +{ + stream << "\tlayout(offset = " << byteOffset << ") float3 " << name << ";\n"; +} + void VectorParameter::save(ArchiveBuffer& buffer) const { ShaderParameter::save(buffer); @@ -88,7 +119,9 @@ void VectorParameter::load(ArchiveBuffer& buffer) TextureParameter::TextureParameter(std::string name, uint32 byteOffset, uint32 binding) : ShaderParameter(name, byteOffset, binding) -{ +{ + output.name = name; + output.type = ExpressionType::TEXTURE; } TextureParameter::~TextureParameter() @@ -100,6 +133,11 @@ void TextureParameter::updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, ui descriptorSet->updateTexture(binding, data->getTexture()); } +void TextureParameter::generateDeclaration(std::ofstream& stream) const +{ + stream << "\tTexture2D " << name << ";\n"; +} + void TextureParameter::save(ArchiveBuffer& buffer) const { ShaderParameter::save(buffer); @@ -117,6 +155,8 @@ void TextureParameter::load(ArchiveBuffer& buffer) SamplerParameter::SamplerParameter(std::string name, uint32 byteOffset, uint32 binding) : ShaderParameter(name, byteOffset, binding) { + output.name = name; + output.type = ExpressionType::SAMPLER; } SamplerParameter::~SamplerParameter() @@ -129,6 +169,10 @@ void SamplerParameter::updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, ui descriptorSet->updateSampler(binding, data); } +void SamplerParameter::generateDeclaration(std::ofstream& stream) const +{ + stream << "\tSamplerState " << name << ";\n"; +} void SamplerParameter::save(ArchiveBuffer& buffer) const { @@ -144,6 +188,8 @@ void SamplerParameter::load(ArchiveBuffer& buffer) CombinedTextureParameter::CombinedTextureParameter(std::string name, uint32 byteOffset, uint32 binding) : ShaderParameter(name, byteOffset, binding) { + output.name = name; + output.type = ExpressionType::TEXTURE; } CombinedTextureParameter::~CombinedTextureParameter() @@ -151,12 +197,16 @@ CombinedTextureParameter::~CombinedTextureParameter() } - void CombinedTextureParameter::updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, uint8*) { descriptorSet->updateTexture(binding, data->getTexture(), sampler); } +void CombinedTextureParameter::generateDeclaration(std::ofstream& stream) const +{ + stream << "\tTexture2D " << name << ";\n"; +} + void CombinedTextureParameter::save(ArchiveBuffer& buffer) const { ShaderParameter::save(buffer); @@ -172,6 +222,213 @@ void CombinedTextureParameter::load(ArchiveBuffer& buffer) sampler = buffer.getGraphics()->createSamplerState({}); } +ConstantExpression::ConstantExpression() +{ +} + +ConstantExpression::ConstantExpression(std::string expr, ExpressionType type) + : expr(expr) +{ + output.name = "cexpr"; + output.type = type; +} + +ConstantExpression::~ConstantExpression() +{ + +} + +std::string ConstantExpression::evaluate(Map& varState) const +{ + std::string varName = std::format("const_exp_{}", std::abs(key)); + varState[key] = varName; + return std::format("let {} = {};\n", varName, expr); +} + +void ConstantExpression::save(ArchiveBuffer& buffer) const +{ + ShaderExpression::save(buffer); + Serialization::save(buffer, expr); +} + +void ConstantExpression::load(ArchiveBuffer& buffer) +{ + ShaderExpression::load(buffer); + Serialization::load(buffer, expr); +} + +AddExpression::AddExpression() +{ + +} + +AddExpression::~AddExpression() +{ + +} + +std::string AddExpression::evaluate(Map& varState) const +{ + std::string varName = std::format("exp_{}", key); + varState[key] = varName; + return std::format("let {} = {} + {};\n", varName, varState[inputs.at("lhs").source], varState[inputs.at("rhs").source]); +} + +void AddExpression::save(ArchiveBuffer& buffer) const +{ + ShaderExpression::save(buffer); +} + +void AddExpression::load(ArchiveBuffer& buffer) +{ + ShaderExpression::load(buffer); +} + +std::string SubExpression::evaluate(Map& varState) const +{ + std::string varName = std::format("exp_{}", key); + varState[key] = varName; + return std::format("let {} = {} - {};\n", varName, varState[inputs.at("lhs").source], varState[inputs.at("rhs").source]); +} + +void SubExpression::save(ArchiveBuffer& buffer) const +{ + ShaderExpression::save(buffer); +} + +void SubExpression::load(ArchiveBuffer& buffer) +{ + ShaderExpression::load(buffer); +} + +std::string MulExpression::evaluate(Map& varState) const +{ + std::string varName = std::format("exp_{}", key); + varState[key] = varName; + return std::format("let {} = mul({}, {});\n", varName, varState[inputs.at("lhs").source], varState[inputs.at("rhs").source]); +} + +void MulExpression::save(ArchiveBuffer& buffer) const +{ + ShaderExpression::save(buffer); +} + +void MulExpression::load(ArchiveBuffer& buffer) +{ + ShaderExpression::load(buffer); +} + +std::string SwizzleExpression::evaluate(Map& varState) const +{ + std::string varName = std::format("exp_{}", key); + std::string swizzle = ""; + for(uint32 i = 0; i < 4; ++i) + { + if(comp[i] == -1) + { + break; + } + switch (comp[i]) + { + case 0: + swizzle += "x"; + break; + case 1: + swizzle += "y"; + break; + case 2: + swizzle += "z"; + break; + case 3: + swizzle += "w"; + default: + throw std::logic_error("invalid component"); + } + } + varState[key] = varName; + return std::format("let {} = {}.{};\n", varName, varState[inputs.at("target").source], swizzle); +} + +void SwizzleExpression::save(ArchiveBuffer& buffer) const +{ + ShaderExpression::save(buffer); + Serialization::save(buffer, comp); +} + +void SwizzleExpression::load(ArchiveBuffer& buffer) +{ + ShaderExpression::load(buffer); + Serialization::load(buffer, comp); +} + +std::string SampleExpression::evaluate(Map& varState) const +{ + std::string varName = std::format("exp_{}", key); + varState[key] = varName; + return std::format("let {} = {}.Sample({}, {});\n", varName, varState[inputs.at("texture").source], varState[inputs.at("sampler").source], varState[inputs.at("coords").source]); +} + +void SampleExpression::save(ArchiveBuffer& buffer) const +{ + ShaderExpression::save(buffer); +} + +void SampleExpression::load(ArchiveBuffer& buffer) +{ + ShaderExpression::load(buffer); +} + +void Serialization::save(ArchiveBuffer& buffer, const PShaderExpression& parameter) +{ + Serialization::save(buffer, parameter->getIdentifier()); + parameter->save(buffer); +} + +void Serialization::load(ArchiveBuffer& buffer, PShaderExpression& parameter) +{ + uint64 identifier = 0; + Serialization::load(buffer, identifier); + switch (identifier) + { + case FloatParameter::IDENTIFIER: + parameter = new FloatParameter(); + break; + case VectorParameter::IDENTIFIER: + parameter = new VectorParameter(); + break; + case TextureParameter::IDENTIFIER: + parameter = new TextureParameter(); + break; + case SamplerParameter::IDENTIFIER: + parameter = new SamplerParameter(); + break; + case CombinedTextureParameter::IDENTIFIER: + parameter = new CombinedTextureParameter(); + break; + case ConstantExpression::IDENTIFIER: + parameter = new ConstantExpression(); + break; + case AddExpression::IDENTIFIER: + parameter = new AddExpression(); + break; + case SubExpression::IDENTIFIER: + parameter = new SubExpression(); + break; + case MulExpression::IDENTIFIER: + parameter = new MulExpression(); + break; + case SwizzleExpression::IDENTIFIER: + parameter = new SwizzleExpression(); + break; + case SampleExpression::IDENTIFIER: + parameter = new SampleExpression(); + break; + default: + throw std::runtime_error("Unknown Identifier"); + } + parameter->load(buffer); +} + void Serialization::save(ArchiveBuffer& buffer, const PShaderParameter& parameter) { Serialization::save(buffer, parameter->getIdentifier()); diff --git a/src/Engine/Material/ShaderExpression.h b/src/Engine/Material/ShaderExpression.h index b4a4b33..68a92cf 100644 --- a/src/Engine/Material/ShaderExpression.h +++ b/src/Engine/Material/ShaderExpression.h @@ -1,21 +1,44 @@ #pragma once #include "MinimalEngine.h" +#include "Containers/Map.h" #include "Math/Math.h" #include "Asset/TextureAsset.h" namespace Seele { +enum class ExpressionType +{ + UNKNOWN, + FLOAT, + FLOAT2, + FLOAT3, + FLOAT4, + TEXTURE, + SAMPLER, +}; struct ExpressionInput { - + int source; + ExpressionType type = ExpressionType::UNKNOWN; }; struct ExpressionOutput { - + std::string name; + ExpressionType type = ExpressionType::UNKNOWN; }; +DECLARE_REF(ShaderExpression); struct ShaderExpression { + Map inputs; + ExpressionOutput output; + int32 key; + virtual uint64 getIdentifier() const = 0; + virtual std::string evaluate(Map& varState) const = 0; + virtual void save(ArchiveBuffer& buffer) const; + virtual void load(ArchiveBuffer& buffer); }; +DEFINE_REF(ShaderExpression) + DECLARE_NAME_REF(Gfx, DescriptorSet) struct ShaderParameter : public ShaderExpression { @@ -27,7 +50,9 @@ struct ShaderParameter : public ShaderExpression virtual ~ShaderParameter(); // update a descriptorset, in case of a uniform buffer, copy the data to the dst + byteOffset virtual void updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, uint8* dst) = 0; + virtual void generateDeclaration(std::ofstream& stream) const = 0; virtual uint64 getIdentifier() const = 0; + virtual std::string evaluate(Map& varState) const override; virtual void save(ArchiveBuffer& buffer) const; virtual void load(ArchiveBuffer& buffer); }; @@ -40,6 +65,7 @@ struct FloatParameter : public ShaderParameter FloatParameter(std::string name, uint32 byteOffset, uint32 binding); virtual ~FloatParameter(); virtual void updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, uint8* dst) override; + virtual void generateDeclaration(std::ofstream& stream) const override; virtual uint64 getIdentifier() const override { return IDENTIFIER; } virtual void save(ArchiveBuffer& buffer) const override; virtual void load(ArchiveBuffer& buffer) override; @@ -53,6 +79,7 @@ struct VectorParameter : public ShaderParameter VectorParameter(std::string name, uint32 byteOffset, uint32 binding); virtual ~VectorParameter(); virtual void updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, uint8* dst) override; + virtual void generateDeclaration(std::ofstream& stream) const override; virtual uint64 getIdentifier() const override { return IDENTIFIER; } virtual void save(ArchiveBuffer& buffer) const override; virtual void load(ArchiveBuffer& buffer) override; @@ -66,6 +93,7 @@ struct TextureParameter : public ShaderParameter TextureParameter(std::string name, uint32 byteOffset, uint32 binding); virtual ~TextureParameter(); virtual void updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, uint8* dst) override; + virtual void generateDeclaration(std::ofstream& stream) const override; virtual uint64 getIdentifier() const override { return IDENTIFIER; } virtual void save(ArchiveBuffer& buffer) const override; virtual void load(ArchiveBuffer& buffer) override; @@ -80,6 +108,7 @@ struct SamplerParameter : public ShaderParameter SamplerParameter(std::string name, uint32 byteOffset, uint32 binding); virtual ~SamplerParameter(); virtual void updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, uint8* dst) override; + virtual void generateDeclaration(std::ofstream& stream) const override; virtual uint64 getIdentifier() const override { return IDENTIFIER; } virtual void save(ArchiveBuffer& buffer) const override; virtual void load(ArchiveBuffer& buffer) override; @@ -94,13 +123,99 @@ struct CombinedTextureParameter : public ShaderParameter CombinedTextureParameter(std::string name, uint32 byteOffset, uint32 binding); virtual ~CombinedTextureParameter(); virtual void updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, uint8* dst) override; + virtual void generateDeclaration(std::ofstream& stream) const override; virtual uint64 getIdentifier() const override { return IDENTIFIER; } virtual void save(ArchiveBuffer& buffer) const override; virtual void load(ArchiveBuffer& buffer) override; }; DEFINE_REF(CombinedTextureParameter) + + +struct ConstantExpression : public ShaderExpression +{ + static constexpr uint64 IDENTIFIER = 0x11; + std::string expr; + ConstantExpression(); + ConstantExpression(std::string expr, ExpressionType type); + virtual ~ConstantExpression(); + virtual uint64 getIdentifier() const { return IDENTIFIER; } + virtual std::string evaluate(Map& varState) const override; + virtual void save(ArchiveBuffer& buffer) const override; + virtual void load(ArchiveBuffer& buffer) override; +}; +DEFINE_REF(ConstantExpression) +struct AddExpression : public ShaderExpression +{ + static constexpr uint64 IDENTIFIER = 0x12; + AddExpression(); + virtual ~AddExpression(); + virtual uint64 getIdentifier() const { return IDENTIFIER; } + virtual std::string evaluate(Map& varState) const override; + virtual void save(ArchiveBuffer& buffer) const override; + virtual void load(ArchiveBuffer& buffer) override; +}; +DEFINE_REF(AddExpression) +struct SubExpression : public ShaderExpression +{ + static constexpr uint64 IDENTIFIER = 0x13; + SubExpression() {} + virtual ~SubExpression() {} + virtual uint64 getIdentifier() const { return IDENTIFIER; } + virtual std::string evaluate(Map& varState) const override; + virtual void save(ArchiveBuffer& buffer) const override; + virtual void load(ArchiveBuffer& buffer) override; +}; +DEFINE_REF(SubExpression) +struct MulExpression : public ShaderExpression +{ + static constexpr uint64 IDENTIFIER = 0x14; + MulExpression() {} + virtual ~MulExpression() {} + virtual uint64 getIdentifier() const { return IDENTIFIER; } + virtual std::string evaluate(Map& varState) const override; + virtual void save(ArchiveBuffer& buffer) const override; + virtual void load(ArchiveBuffer& buffer) override; +}; +DEFINE_REF(MulExpression) +struct SwizzleExpression : public ShaderExpression +{ + static constexpr uint64 IDENTIFIER = 0x15; + StaticArray comp = {-1, -1, -1, -1}; + SwizzleExpression() {} + virtual ~SwizzleExpression() {} + virtual uint64 getIdentifier() const { return IDENTIFIER; } + virtual std::string evaluate(Map& varState) const override; + virtual void save(ArchiveBuffer& buffer) const override; + virtual void load(ArchiveBuffer& buffer) override; +}; +DEFINE_REF(SwizzleExpression) +struct SampleExpression : public ShaderExpression +{ + static constexpr uint64 IDENTIFIER = 0x16; + SampleExpression() {} + virtual ~SampleExpression() {} + virtual uint64 getIdentifier() const { return IDENTIFIER; } + virtual std::string evaluate(Map& varState) const override; + virtual void save(ArchiveBuffer& buffer) const override; + virtual void load(ArchiveBuffer& buffer) override; +}; +DEFINE_REF(SampleExpression) + +struct MaterialNode +{ + std::string profile; + Map variables; + MaterialNode() {} + virtual ~MaterialNode() {} + virtual std::string evaluate() const { return ""; } + void save(ArchiveBuffer& buffer) const; + void load(ArchiveBuffer& buffer); +}; +DEFINE_REF(MaterialNode) namespace Serialization { + void save(ArchiveBuffer& buffer, const PShaderExpression& parameter); + void load(ArchiveBuffer& buffer, PShaderExpression& parameter); void save(ArchiveBuffer& buffer, const PShaderParameter& parameter); void load(ArchiveBuffer& buffer, PShaderParameter& parameter); } // namespace Serialization diff --git a/src/Engine/Math/CMakeLists.txt b/src/Engine/Math/CMakeLists.txt index 70547c0..09c665c 100644 --- a/src/Engine/Math/CMakeLists.txt +++ b/src/Engine/Math/CMakeLists.txt @@ -6,7 +6,7 @@ target_sources(Engine Transform.cpp Vector.h Vector.cpp) - + target_sources(Engine PUBLIC FILE_SET HEADERS FILES diff --git a/src/Editor/Platform/CMakeLists.txt b/src/Engine/Platform/CMakeLists.txt similarity index 100% rename from src/Editor/Platform/CMakeLists.txt rename to src/Engine/Platform/CMakeLists.txt diff --git a/src/Engine/Platform/Windows/CMakeLists.txt b/src/Engine/Platform/Windows/CMakeLists.txt new file mode 100644 index 0000000..4613346 --- /dev/null +++ b/src/Engine/Platform/Windows/CMakeLists.txt @@ -0,0 +1,10 @@ +target_sources(Engine + PRIVATE + GameInterface.h + GameInterface.cpp) + + +target_sources(Engine + PUBLIC FILE_SET HEADERS + FILES + GameInterface.h) \ No newline at end of file diff --git a/src/Editor/Platform/Windows/GameInterface.cpp b/src/Engine/Platform/Windows/GameInterface.cpp similarity index 100% rename from src/Editor/Platform/Windows/GameInterface.cpp rename to src/Engine/Platform/Windows/GameInterface.cpp diff --git a/src/Editor/Platform/Windows/GameInterface.h b/src/Engine/Platform/Windows/GameInterface.h similarity index 100% rename from src/Editor/Platform/Windows/GameInterface.h rename to src/Engine/Platform/Windows/GameInterface.h diff --git a/src/Engine/Scene/Scene.cpp b/src/Engine/Scene/Scene.cpp index 51e9635..6b8f528 100644 --- a/src/Engine/Scene/Scene.cpp +++ b/src/Engine/Scene/Scene.cpp @@ -86,13 +86,14 @@ LightEnv Scene::getLightBuffer() const { LightEnv result; result.directionalLights[0].color = Vector4(0.4, 0.3, 0.5, 1.0); - result.directionalLights[0].direction = Vector4(0.5, 0.5, 0, 0); - result.directionalLights[0].intensity = Vector4(1.0, 0.9, 0.7, 0.5);\ + result.directionalLights[0].direction = Vector4(0.5, -0.5, 0, 0); + result.directionalLights[0].intensity = Vector4(1.0, 0.9, 0.7, 0.5); result.numDirectionalLights = 1; result.numPointLights = 0; return result; } + Component::Skybox Scene::getSkybox() { return Seele::Component::Skybox { diff --git a/src/Engine/Serialization/ArchiveBuffer.cpp b/src/Engine/Serialization/ArchiveBuffer.cpp index 601411c..fe2c7e9 100644 --- a/src/Engine/Serialization/ArchiveBuffer.cpp +++ b/src/Engine/Serialization/ArchiveBuffer.cpp @@ -44,11 +44,35 @@ void ArchiveBuffer::readFromStream(std::istream& stream) stream.read((char*)memory.data(), bufferLength); } +void ArchiveBuffer::seek(int64 s, SeekOp op) +{ + int64 newPos = position; + switch (op) + { + case SeekOp::BEGIN: + newPos = s; + break; + case SeekOp::END: + newPos = memory.size() + s; + break; + case SeekOp::CURRENT: + newPos = position + s; + break; + } + assert(newPos >= 0 && newPos < memory.size()); + newPos = position; +} + bool ArchiveBuffer::eof() const { return position == memory.size(); } +size_t Seele::ArchiveBuffer::size() const +{ + return memory.size(); +} + void ArchiveBuffer::rewind() { position = 0; diff --git a/src/Engine/Serialization/ArchiveBuffer.h b/src/Engine/Serialization/ArchiveBuffer.h index e9563c2..78cb487 100644 --- a/src/Engine/Serialization/ArchiveBuffer.h +++ b/src/Engine/Serialization/ArchiveBuffer.h @@ -16,7 +16,15 @@ public: void readBytes(void* dest, uint64 size); void writeToStream(std::ostream& stream); void readFromStream(std::istream& stream); + enum class SeekOp + { + CURRENT, + BEGIN, + END, + }; + void seek(int64 s, SeekOp op); bool eof() const; + size_t size() const; void rewind(); Gfx::PGraphics& getGraphics(); private: @@ -105,7 +113,6 @@ namespace Serialization type.resize(length); buffer.readBytes(type.data(), sizeof(T) * type.size()); } - template static void save(ArchiveBuffer& buffer, const Array& type) { @@ -121,6 +128,26 @@ namespace Serialization type.resize(length); buffer.readBytes(type.data(), sizeof(T) * type.size()); } + template + static void save(ArchiveBuffer& buffer, const StaticArray& type) + { + buffer.writeBytes(type.data(), sizeof(T) * N); + } + template + static void load(ArchiveBuffer& buffer, StaticArray& type) + { + buffer.readBytes(type.data(), sizeof(T) * N); + } + template + static void save(ArchiveBuffer& buffer, const StaticArray& type) + { + buffer.writeBytes(type.data(), sizeof(T) * N); + } + template + static void load(ArchiveBuffer& buffer, StaticArray& type) + { + buffer.readBytes(type.data(), sizeof(T) * N); + } template static void save(ArchiveBuffer& buffer, const Array& type) requires (!std::is_integral_v && !std::is_floating_point_v) { diff --git a/src/Engine/Serialization/CMakeLists.txt b/src/Engine/Serialization/CMakeLists.txt index 3e27498..13d9b13 100644 --- a/src/Engine/Serialization/CMakeLists.txt +++ b/src/Engine/Serialization/CMakeLists.txt @@ -3,7 +3,6 @@ target_sources(Engine ArchiveBuffer.h ArchiveBuffer.cpp) - target_sources(Engine PUBLIC FILE_SET HEADERS FILES diff --git a/src/Engine/Window/CMakeLists.txt b/src/Engine/Window/CMakeLists.txt index 68c4ab7..4a935bb 100644 --- a/src/Engine/Window/CMakeLists.txt +++ b/src/Engine/Window/CMakeLists.txt @@ -1,5 +1,7 @@ target_sources(Engine PRIVATE + GameView.h + GameView.cpp View.h View.cpp Window.cpp @@ -10,6 +12,7 @@ target_sources(Engine target_sources(Engine PUBLIC FILE_SET HEADERS FILES + GameView.h View.h Window.h WindowManager.h) diff --git a/src/Engine/Window/GameView.cpp b/src/Engine/Window/GameView.cpp new file mode 100644 index 0000000..d66c4f1 --- /dev/null +++ b/src/Engine/Window/GameView.cpp @@ -0,0 +1,138 @@ +#include "GameView.h" +#include "Graphics/Graphics.h" +#include "Window/Window.h" +#include "Component/KeyboardInput.h" +#include "Actor/CameraActor.h" +#include "Asset/AssetRegistry.h" + +using namespace Seele; + +AssetRegistry* instance = new AssetRegistry(); + +GameView::GameView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo &createInfo, std::string dllPath) + : View(graphics, window, createInfo, "Game") + , gameInterface(dllPath) + , renderGraph(RenderGraphBuilder::build( + DepthPrepass(graphics), + LightCullingPass(graphics), + BasePass(graphics), + SkyboxRenderPass(graphics) + )) +{ + scene = new Scene(graphics); + gameInterface.reload(instance); + + systemGraph = new SystemGraph(); + gameInterface.getGame()->setupScene(scene, systemGraph); + renderGraph.updateViewport(viewport); +} + +GameView::~GameView() +{ + +} + +void GameView::beginUpdate() +{ +} + +void GameView::update() +{ + static auto startTime = std::chrono::high_resolution_clock::now(); + systemGraph->run(threadPool, updateTime); + scene->update(updateTime); + auto endTime = std::chrono::high_resolution_clock::now(); + std::chrono::duration duration = (endTime - startTime); + updateTime = duration.count(); + startTime = endTime; +} + +void GameView::commitUpdate() +{ + depthPrepassData.staticDrawList = scene->getStaticMeshes(); + depthPrepassData.sceneDataBuffer = scene->getSceneDataBuffer(); + lightCullingData.lightEnv = scene->getLightBuffer(); + basePassData.staticDrawList = scene->getStaticMeshes(); + basePassData.sceneDataBuffer = scene->getSceneDataBuffer(); + skyboxData.skybox = scene->getSkybox(); +} + +void GameView::prepareRender() +{ + renderGraph.updatePassData(depthPrepassData, lightCullingData, basePassData, skyboxData); +} + +void GameView::render() +{ + scene->view([&](Component::Camera& cam) + { + if(cam.mainCamera) + { + renderGraph.render(cam); + } + }); +} + +void GameView::keyCallback(KeyCode code, InputAction action, KeyModifier) +{ + scene->view([=](Component::KeyboardInput& input) + { + //if(code == KeyCode::KEY_R && action == InputAction::PRESS) + //{ + // auto cubeMesh = AssetRegistry::findMesh("cube"); + // PEntity cube2 = new Entity(scene); + // Component::Transform& cube2Transform = cube2->attachComponent(); + // cube2Transform.setPosition(Vector(0, 20, 0)); + // cube2Transform.setRotation(Quaternion(Vector(0.f, 90.f, 90.f))); + // cube2Transform.setScale(Vector(2.f, 2.f, 2.f)); + // cubeMesh->physicsMesh.type = Component::ColliderType::DYNAMIC; + // cube2->attachComponent(cubeMesh->physicsMesh); + // cube2->attachComponent(cubeMesh); + // Component::RigidBody& physics2 = cube2->attachComponent(); + // physics2.linearMomentum = Vector(0, -10, 0); + // physics2.angularMomentum = Vector(0, 0, 0); + //} + // + //if(code == KeyCode::KEY_B && action == InputAction::PRESS) + //{ + // showDebug = !showDebug; + // debugPassData.vertices.clear(); + //} + + input.keys[code] = action != InputAction::RELEASE; + }); +} + +void GameView::mouseMoveCallback(double xPos, double yPos) +{ + scene->view([=](Component::KeyboardInput& input) + { + input.mouseX = static_cast(xPos); + input.mouseY = static_cast(yPos); + }); +} + +void GameView::mouseButtonCallback(MouseButton button, InputAction action, KeyModifier) +{ + scene->view([=](Component::KeyboardInput& input) + { + if (button == MouseButton::MOUSE_BUTTON_1) + { + input.mouse1 = action != InputAction::RELEASE; + } + if (button == MouseButton::MOUSE_BUTTON_2) + { + input.mouse2 = action != InputAction::RELEASE; + } + }); +} + +void GameView::scrollCallback(double, double) +{ + +} + +void GameView::fileCallback(int, const char**) +{ + +} diff --git a/src/Editor/Window/GameView.h b/src/Engine/Window/GameView.h similarity index 88% rename from src/Editor/Window/GameView.h rename to src/Engine/Window/GameView.h index 9056dc3..0d70c6c 100644 --- a/src/Editor/Window/GameView.h +++ b/src/Engine/Window/GameView.h @@ -4,7 +4,6 @@ #include "Graphics/RenderPass/DepthPrepass.h" #include "Graphics/RenderPass/LightCullingPass.h" #include "Graphics/RenderPass/BasePass.h" -#include "Graphics/RenderPass/DebugPass.h" #include "Graphics/RenderPass/SkyboxRenderPass.h" #include "Platform/Windows/GameInterface.h" // TODO @@ -13,7 +12,7 @@ namespace Seele class GameView : public View { public: - GameView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo &createInfo); + GameView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo &createInfo, std::string dllPath); virtual ~GameView(); virtual void beginUpdate() override; virtual void update() override; @@ -27,9 +26,6 @@ private: DepthPrepass, LightCullingPass, BasePass, -#ifdef EDITOR - DebugPass, -#endif SkyboxRenderPass > renderGraph; @@ -37,17 +33,11 @@ private: LightCullingPassData lightCullingData; BasePassData basePassData; SkyboxPassData skyboxData; -#ifdef EDITOR - DebugPassData debugPassData; -#endif PScene scene; PSystemGraph systemGraph; dp::thread_pool<> threadPool; float updateTime = 0; -#ifdef EDITOR - bool showDebug = false; -#endif virtual void keyCallback(Seele::KeyCode code, Seele::InputAction action, Seele::KeyModifier modifier) override; virtual void mouseMoveCallback(double xPos, double yPos) override;