diff --git a/GlitchyEditor/content/Shaders/ACES.hlsl.ass b/GlitchyEditor/content/Shaders/ACES.hlsl.ass new file mode 100644 index 0000000..0dc97c1 --- /dev/null +++ b/GlitchyEditor/content/Shaders/ACES.hlsl.ass @@ -0,0 +1,4 @@ +{ + AssetLoader = "EffectAssetLoader", + Config = (GlitchyEditor.Assets.EffectAssetLoaderConfig){} +} \ No newline at end of file diff --git a/GlitchyEditor/content/Shaders/ClearUInt.hlsl.ass b/GlitchyEditor/content/Shaders/ClearUInt.hlsl.ass new file mode 100644 index 0000000..0dc97c1 --- /dev/null +++ b/GlitchyEditor/content/Shaders/ClearUInt.hlsl.ass @@ -0,0 +1,4 @@ +{ + AssetLoader = "EffectAssetLoader", + Config = (GlitchyEditor.Assets.EffectAssetLoaderConfig){} +} \ No newline at end of file diff --git a/GlitchyEditor/content/Shaders/GammaCorrect.hlsl.ass b/GlitchyEditor/content/Shaders/GammaCorrect.hlsl.ass new file mode 100644 index 0000000..0dc97c1 --- /dev/null +++ b/GlitchyEditor/content/Shaders/GammaCorrect.hlsl.ass @@ -0,0 +1,4 @@ +{ + AssetLoader = "EffectAssetLoader", + Config = (GlitchyEditor.Assets.EffectAssetLoaderConfig){} +} \ No newline at end of file diff --git a/GlitchyEditor/content/Shaders/LightingFunctions.hlsl.ass b/GlitchyEditor/content/Shaders/LightingFunctions.hlsl.ass new file mode 100644 index 0000000..0dc97c1 --- /dev/null +++ b/GlitchyEditor/content/Shaders/LightingFunctions.hlsl.ass @@ -0,0 +1,4 @@ +{ + AssetLoader = "EffectAssetLoader", + Config = (GlitchyEditor.Assets.EffectAssetLoaderConfig){} +} \ No newline at end of file diff --git a/GlitchyEditor/content/Shaders/PBR.hlsl.ass b/GlitchyEditor/content/Shaders/PBR.hlsl.ass new file mode 100644 index 0000000..0dc97c1 --- /dev/null +++ b/GlitchyEditor/content/Shaders/PBR.hlsl.ass @@ -0,0 +1,4 @@ +{ + AssetLoader = "EffectAssetLoader", + Config = (GlitchyEditor.Assets.EffectAssetLoaderConfig){} +} \ No newline at end of file diff --git a/GlitchyEditor/content/Shaders/ShaderHelpers.hlsl.ass b/GlitchyEditor/content/Shaders/ShaderHelpers.hlsl.ass new file mode 100644 index 0000000..0dc97c1 --- /dev/null +++ b/GlitchyEditor/content/Shaders/ShaderHelpers.hlsl.ass @@ -0,0 +1,4 @@ +{ + AssetLoader = "EffectAssetLoader", + Config = (GlitchyEditor.Assets.EffectAssetLoaderConfig){} +} \ No newline at end of file diff --git a/GlitchyEditor/content/Shaders/SimpleTonemapping.hlsl.ass b/GlitchyEditor/content/Shaders/SimpleTonemapping.hlsl.ass new file mode 100644 index 0000000..0dc97c1 --- /dev/null +++ b/GlitchyEditor/content/Shaders/SimpleTonemapping.hlsl.ass @@ -0,0 +1,4 @@ +{ + AssetLoader = "EffectAssetLoader", + Config = (GlitchyEditor.Assets.EffectAssetLoaderConfig){} +} \ No newline at end of file diff --git a/GlitchyEditor/content/Shaders/circlebatch.hlsl.ass b/GlitchyEditor/content/Shaders/circlebatch.hlsl.ass new file mode 100644 index 0000000..0dc97c1 --- /dev/null +++ b/GlitchyEditor/content/Shaders/circlebatch.hlsl.ass @@ -0,0 +1,4 @@ +{ + AssetLoader = "EffectAssetLoader", + Config = (GlitchyEditor.Assets.EffectAssetLoaderConfig){} +} \ No newline at end of file diff --git a/GlitchyEditor/content/Shaders/lineShader.hlsl.ass b/GlitchyEditor/content/Shaders/lineShader.hlsl.ass new file mode 100644 index 0000000..0dc97c1 --- /dev/null +++ b/GlitchyEditor/content/Shaders/lineShader.hlsl.ass @@ -0,0 +1,4 @@ +{ + AssetLoader = "EffectAssetLoader", + Config = (GlitchyEditor.Assets.EffectAssetLoaderConfig){} +} \ No newline at end of file diff --git a/GlitchyEditor/content/Shaders/msdfShader.hlsl.ass b/GlitchyEditor/content/Shaders/msdfShader.hlsl.ass new file mode 100644 index 0000000..0dc97c1 --- /dev/null +++ b/GlitchyEditor/content/Shaders/msdfShader.hlsl.ass @@ -0,0 +1,4 @@ +{ + AssetLoader = "EffectAssetLoader", + Config = (GlitchyEditor.Assets.EffectAssetLoaderConfig){} +} \ No newline at end of file diff --git a/GlitchyEditor/content/Shaders/myEffect.hlsl.ass b/GlitchyEditor/content/Shaders/myEffect.hlsl.ass new file mode 100644 index 0000000..0dc97c1 --- /dev/null +++ b/GlitchyEditor/content/Shaders/myEffect.hlsl.ass @@ -0,0 +1,4 @@ +{ + AssetLoader = "EffectAssetLoader", + Config = (GlitchyEditor.Assets.EffectAssetLoaderConfig){} +} \ No newline at end of file diff --git a/GlitchyEditor/content/Shaders/simpleLight.hlsl.ass b/GlitchyEditor/content/Shaders/simpleLight.hlsl.ass new file mode 100644 index 0000000..0dc97c1 --- /dev/null +++ b/GlitchyEditor/content/Shaders/simpleLight.hlsl.ass @@ -0,0 +1,4 @@ +{ + AssetLoader = "EffectAssetLoader", + Config = (GlitchyEditor.Assets.EffectAssetLoaderConfig){} +} \ No newline at end of file diff --git a/GlitchyEditor/content/Shaders/spritebatch.hlsl.ass b/GlitchyEditor/content/Shaders/spritebatch.hlsl.ass new file mode 100644 index 0000000..0dc97c1 --- /dev/null +++ b/GlitchyEditor/content/Shaders/spritebatch.hlsl.ass @@ -0,0 +1,4 @@ +{ + AssetLoader = "EffectAssetLoader", + Config = (GlitchyEditor.Assets.EffectAssetLoaderConfig){} +} \ No newline at end of file diff --git a/GlitchyEditor/content/Shaders/textureViewerShader.hlsl.ass b/GlitchyEditor/content/Shaders/textureViewerShader.hlsl.ass new file mode 100644 index 0000000..0dc97c1 --- /dev/null +++ b/GlitchyEditor/content/Shaders/textureViewerShader.hlsl.ass @@ -0,0 +1,4 @@ +{ + AssetLoader = "EffectAssetLoader", + Config = (GlitchyEditor.Assets.EffectAssetLoaderConfig){} +} \ No newline at end of file diff --git a/GlitchyEditor/content/Textures/TestMat/rustediron2_albedo.png.ass b/GlitchyEditor/content/Textures/TestMat/rustediron2_albedo.png.ass index 1cabcd8..1b89c85 100644 --- a/GlitchyEditor/content/Textures/TestMat/rustediron2_albedo.png.ass +++ b/GlitchyEditor/content/Textures/TestMat/rustediron2_albedo.png.ass @@ -4,13 +4,15 @@ _generateMipMaps = true, _isSrgb = true, _samplerStateDescription = { - MinFilter = .Linear, + MinFilter = .Anisotropic, + MagFilter = .Anisotropic, + MipFilter = .Anisotropic, ComparisonFunction = .Never, AddressModeU = .Wrap, AddressModeV = .Border, AddressModeW = .Clamp, MipMaxLOD = 160, - MaxAnisotropy = 5, + MaxAnisotropy = 16, BorderColor = { R = 0.756863, G = 0.2, diff --git a/GlitchyEditor/content/Textures/TestMat/rustediron2_roughness.png.ass b/GlitchyEditor/content/Textures/TestMat/rustediron2_roughness.png.ass index 1f70168..0d007db 100644 --- a/GlitchyEditor/content/Textures/TestMat/rustediron2_roughness.png.ass +++ b/GlitchyEditor/content/Textures/TestMat/rustediron2_roughness.png.ass @@ -1,6 +1,7 @@ { AssetLoader = "EditorTextureAssetLoader", Config = (GlitchyEditor.Assets.EditorTextureAssetLoaderConfig){ + _isSrgb = true, _samplerStateDescription = { MinFilter = .Linear, MagFilter = .Linear, diff --git a/GlitchyEditor/src/Assets/EffectAssetLoader.bf b/GlitchyEditor/src/Assets/EffectAssetLoader.bf new file mode 100644 index 0000000..4d21fd1 --- /dev/null +++ b/GlitchyEditor/src/Assets/EffectAssetLoader.bf @@ -0,0 +1,101 @@ +using Bon; +using GlitchyEngine.Content; +using System; +using System.Collections; +using System.IO; +using GlitchyEngine; +using GlitchyEngine.Renderer; + +namespace GlitchyEditor.Assets; + +class EffectAssetPropertiesEditor : AssetPropertiesEditor +{ + public this(AssetFile asset) : base(asset) + { + + } + + public override void ShowEditor() + { + + } + + public static AssetPropertiesEditor Factory(AssetFile assetFile) + { + return new Self(assetFile); + } +} + +[BonTarget, BonPolyRegister] +class EffectAssetLoaderConfig : AssetLoaderConfig +{ + +} + +class EffectAssetLoader : IAssetLoader //, IReloadingAssetLoader +{ + private static readonly List _fileExtensions = new .(){".hlsl"} ~ delete _; + + public static List FileExtensions => _fileExtensions; + + public AssetLoaderConfig GetDefaultConfig() + { + return new EffectAssetLoaderConfig(); + } + + public Asset LoadAsset(Stream file, AssetLoaderConfig config, StringView assetIdentifier, StringView? subAsset, IContentManager contentManager) + { + Effect effect = new Effect(file, assetIdentifier, contentManager); + + return effect; + + /*StreamReader reader = scope .(file); + + String text = scope .(); + + reader.ReadToEnd(text); + + MaterialFile materialFile = scope .(); + + var result = Bon.Deserialize(ref materialFile, text); + + if (result case .Err) + { + Log.EngineLogger.Error("Failed to load material."); + return null; + // TODO: return error material + } + + Effect fx = new Effect(materialFile.Effect); + + Material material = new Material(fx); + + for (let (slotName, textureIdentifier) in materialFile.Textures) + { + Texture texture = contentManager.LoadAsset(textureIdentifier) as Texture; + + if (texture == null) + { + Log.EngineLogger.Error("Failed to load texture."); + // TODO: LoadAsset should return an error texture. + } + + material.SetTexture(slotName, texture); + } + + fx.ReleaseRef(); + + /*for (let (slotName, textureIdentifier) in materialFile.Variables) + { + if (texture == null) + { + Log.EngineLogger.Error("Failed to load texture."); + // TODO: LoadAsset should return an error texture. + } + + material.SetVariable(slotName, ); + }*/ + + return material; //ModelLoader.LoadMesh(file, subAsset.Value, 0);*/ + } +} \ No newline at end of file diff --git a/GlitchyEditor/src/Assets/MaterialAssetLoader.bf b/GlitchyEditor/src/Assets/MaterialAssetLoader.bf index 37fad61..d348179 100644 --- a/GlitchyEditor/src/Assets/MaterialAssetLoader.bf +++ b/GlitchyEditor/src/Assets/MaterialAssetLoader.bf @@ -52,7 +52,7 @@ class MaterialAssetLoader : IAssetLoader //, IReloadingAssetLoader return new ModelAssetLoaderConfig(); } - public Asset LoadAsset(Stream file, AssetLoaderConfig config, StringView? subAsset, IContentManager contentManager) + public Asset LoadAsset(Stream file, AssetLoaderConfig config, StringView assetIdentifier, StringView? subAsset, IContentManager contentManager) { StreamReader reader = scope .(file); diff --git a/GlitchyEditor/src/Assets/ModelAssetLoader.bf b/GlitchyEditor/src/Assets/ModelAssetLoader.bf index 2b680a4..00d4ba3 100644 --- a/GlitchyEditor/src/Assets/ModelAssetLoader.bf +++ b/GlitchyEditor/src/Assets/ModelAssetLoader.bf @@ -42,7 +42,7 @@ class ModelAssetLoader : IAssetLoader //, IReloadingAssetLoader return new ModelAssetLoaderConfig(); } - public Asset LoadAsset(Stream file, AssetLoaderConfig config, StringView? subAsset, IContentManager contentManager) + public Asset LoadAsset(Stream file, AssetLoaderConfig config, StringView assetIdentifier, StringView? subAsset, IContentManager contentManager) { Log.EngineLogger.Assert(subAsset != null); diff --git a/GlitchyEditor/src/Assets/TextureAssetLoader.bf b/GlitchyEditor/src/Assets/TextureAssetLoader.bf index 670b87a..b1000fb 100644 --- a/GlitchyEditor/src/Assets/TextureAssetLoader.bf +++ b/GlitchyEditor/src/Assets/TextureAssetLoader.bf @@ -175,7 +175,7 @@ class EditorTextureAssetLoader : IAssetLoader, IReloadingAssetLoader return new EditorTextureAssetLoaderConfig(); } - public Asset LoadAsset(Stream data, AssetLoaderConfig config, StringView? subAsset, IContentManager contentManager) + public Asset LoadAsset(Stream data, AssetLoaderConfig config, StringView assetIdentifier, StringView? subAsset, IContentManager contentManager) { var config; diff --git a/GlitchyEditor/src/EditorApp.bf b/GlitchyEditor/src/EditorApp.bf index e2ddfc7..dbc7802 100644 --- a/GlitchyEditor/src/EditorApp.bf +++ b/GlitchyEditor/src/EditorApp.bf @@ -1,13 +1,41 @@ using System; using GlitchyEngine; +using GlitchyEngine.Content; +using GlitchyEditor.Assets; namespace GlitchyEditor { class EditorApp : Application { + EditorContentManager _contentManager; + public this() { - PushLayer(new EditorLayer()); + PushLayer(new EditorLayer(_contentManager)); + } + + protected override IContentManager InitContentManager() + { + _contentManager = new EditorContentManager(); + _contentManager.RegisterAssetLoader(); + _contentManager.SetAsDefaultAssetLoader(".png", ".dds"); + _contentManager.SetAssetPropertiesEditor(=> TextureAssetPropertiesEditor.Factory); + + _contentManager.RegisterAssetLoader(); + _contentManager.SetAsDefaultAssetLoader(".glb", ".gltf"); + _contentManager.SetAssetPropertiesEditor(=> ModelAssetPropertiesEditor.Factory); + + _contentManager.RegisterAssetLoader(); + _contentManager.SetAsDefaultAssetLoader(".mat"); + _contentManager.SetAssetPropertiesEditor(=> MaterialAssetPropertiesEditor.Factory); + + _contentManager.RegisterAssetLoader(); + _contentManager.SetAsDefaultAssetLoader(".hlsl"); + _contentManager.SetAssetPropertiesEditor(=> EffectAssetPropertiesEditor.Factory); + + _contentManager.SetContentDirectory("./content"); + + return _contentManager; } [Export, LinkName("CreateApplication")] diff --git a/GlitchyEditor/src/EditorContentManager.bf b/GlitchyEditor/src/EditorContentManager.bf index 5d32df3..cf0778e 100644 --- a/GlitchyEditor/src/EditorContentManager.bf +++ b/GlitchyEditor/src/EditorContentManager.bf @@ -511,7 +511,7 @@ class EditorContentManager : IContentManager _supportedExtensions.Add(new String(ext)); } - public void SetAsDefaultAssetLoader(params StringView[] fileExtensions) where T : IAssetLoader + public void SetAsDefaultAssetLoader(params Span fileExtensions) where T : IAssetLoader { for (var ext in fileExtensions) { @@ -616,7 +616,7 @@ class EditorContentManager : IContentManager Stream stream = GetStream(filePath); - Asset loadedAsset = assetLoader.LoadAsset(stream, file.AssetConfig.Config, subassetName, this); + Asset loadedAsset = assetLoader.LoadAsset(stream, file.AssetConfig.Config, resourceName, subassetName, this); delete stream; @@ -637,9 +637,22 @@ class EditorContentManager : IContentManager // TODO: probably not needed public Stream GetStream(StringView assetIdentifier) { + var assetIdentifier; + + if (!assetIdentifier.StartsWith(_contentDirectory)) + { + String filePath = scope:: String(assetIdentifier.Length + _contentDirectory.Length + 2); + Path.Combine(filePath, _contentDirectory, assetIdentifier); + + assetIdentifier = filePath; + } + FileStream fs = new FileStream(); var result = fs.Open(assetIdentifier, .Open, .Read, .ReadWrite); + if (result case .Err) + return null; + return fs; } diff --git a/GlitchyEditor/src/EditorLayer.bf b/GlitchyEditor/src/EditorLayer.bf index 4cff6c0..45617aa 100644 --- a/GlitchyEditor/src/EditorLayer.bf +++ b/GlitchyEditor/src/EditorLayer.bf @@ -27,7 +27,7 @@ namespace GlitchyEditor BlendState _opaqueBlendState ~ _.ReleaseRef(); DepthStencilState _depthStencilState ~ _.ReleaseRef(); - Scene _scene = new Scene() ~ delete _; + Scene _scene ~ delete _; String _sceneFilePath = new String() ~ delete _; public String SceneFilePath @@ -69,14 +69,17 @@ namespace GlitchyEditor SceneState _sceneState = .Edit; - public this() : base("Example") + public this(EditorContentManager contentManager) : base("Example") { Application.Get().Window.IsVSync = false; - InitContentManager(); + //InitContentManager(); + _contentManager = contentManager; InitGraphics(); + _scene = new Scene(); + _camera = EditorCamera(Vector3(3.5f, 1.25f, 2.75f), Quaternion.FromEulerAngles(MathHelper.ToRadians(40), MathHelper.ToRadians(25), 0), MathHelper.ToRadians(75), 0.1f, 1); _camera.RenderTarget = _cameraTarget; @@ -85,7 +88,7 @@ namespace GlitchyEditor NewScene(); } - private void InitContentManager() + /*private void InitContentManager() { _contentManager = new EditorContentManager(); _contentManager.RegisterAssetLoader(); @@ -99,12 +102,16 @@ namespace GlitchyEditor _contentManager.RegisterAssetLoader(); _contentManager.SetAsDefaultAssetLoader(".mat"); _contentManager.SetAssetPropertiesEditor(=> MaterialAssetPropertiesEditor.Factory); + + _contentManager.RegisterAssetLoader(); + _contentManager.SetAsDefaultAssetLoader(".hlsl"); + _contentManager.SetAssetPropertiesEditor(=> EffectAssetPropertiesEditor.Factory); _contentManager.SetContentDirectory("./content"); // Todo: Sketchy... Application.Get().[Friend]_contentManager = _contentManager; - } + }*/ private void InitGraphics() { diff --git a/GlitchyEngine/src/Application.bf b/GlitchyEngine/src/Application.bf index 0331a42..5f951c6 100644 --- a/GlitchyEngine/src/Application.bf +++ b/GlitchyEngine/src/Application.bf @@ -7,13 +7,12 @@ using GlitchyEngine.Content; namespace GlitchyEngine { - public class Application + public abstract class Application { static Application s_Instance = null; private Window _window; private RendererAPI _rendererApi; - private EffectLibrary _effectLibrary; private bool _running = true; private bool _isMinimized = false; @@ -31,8 +30,6 @@ namespace GlitchyEngine public bool IsRunning => _running; public Window Window => _window; - public EffectLibrary EffectLibrary => _effectLibrary; - public IContentManager ContentManager => _contentManager; public bool IsMinimized => _isMinimized; @@ -56,19 +53,19 @@ namespace GlitchyEngine _window.EventCallback = new => OnEvent; Input.Init(); + + _contentManager = InitContentManager(); + // TODO: RenderAPI in RenderCommand initialisieren? _rendererApi = new RendererAPI(); _rendererApi.Context = _window.Context; - //_contentManager = new ContentManager("./content"); - SamplerStateManager.Init(); + // TODO: Rendercommmand in Renderer initialisieren? RenderCommand.RendererAPI = _rendererApi; - _effectLibrary = new EffectLibrary(); - - Renderer.Init(_effectLibrary); + Renderer.Init(); #if IMGUI _imGuiLayer = new ImGuiLayer(); @@ -79,6 +76,13 @@ namespace GlitchyEngine Settings.Apply(); } + /// Initializes the content manager. + protected abstract IContentManager InitContentManager(); + //{ + // TODO: init default content manager? + //_contentManager = new ContentManager("./content"); + //} + public ~this() { Profiler.ProfileFunction!(); @@ -86,8 +90,6 @@ namespace GlitchyEngine SamplerStateManager.Uninit(); Renderer.Deinit(); - delete _effectLibrary; - delete _contentManager; delete _rendererApi; diff --git a/GlitchyEngine/src/Content/ContentManager.bf b/GlitchyEngine/src/Content/ContentManager.bf index 9905237..41d6a94 100644 --- a/GlitchyEngine/src/Content/ContentManager.bf +++ b/GlitchyEngine/src/Content/ContentManager.bf @@ -56,24 +56,24 @@ namespace GlitchyEngine.Content /// @param config The configuration which specifies the settings used to load the asset. /// @param contentManager The content manager used to load the asset. /// @returns The loaded asset. - Asset LoadAsset(Stream file, AssetLoaderConfig config, StringView? subAsset, IContentManager contentManager); + Asset LoadAsset(Stream file, AssetLoaderConfig config, StringView assetIdentifier, StringView? subAsset, IContentManager contentManager); } static { /// Loads the specified asset with the given contentManager or the current applications content manager. - public static T LoadAsset(StringView assetIdentifier, IContentManager contentManager = null) where T : IRefCounted + public static T LoadAsset(StringView assetIdentifier, IContentManager contentManager = null) where T : Asset { var contentManager; if (contentManager == null) contentManager = Application.Get().ContentManager; - Object o = contentManager.LoadAsset(assetIdentifier); + Asset asset = contentManager.LoadAsset(assetIdentifier); - Log.EngineLogger.AssertDebug(o is T); + Log.EngineLogger.AssertDebug(asset is T); - return (T)o; + return (T)asset; } } @@ -96,7 +96,7 @@ namespace GlitchyEngine.Content Stream GetStream(StringView assetIdentifier); void RegisterAssetLoader() where T : new, class, IAssetLoader; - void SetAsDefaultAssetLoader(params StringView[] fileExtensions) where T : IAssetLoader; + void SetAsDefaultAssetLoader(params Span fileExtensions) where T : IAssetLoader; //void GetFilePath(String outFilename, String filename); //Stream GetFile(String filename); @@ -104,6 +104,11 @@ namespace GlitchyEngine.Content class RuntimeContentManager : IContentManager { + public this() + { + Runtime.NotImplemented(); + } + public Asset LoadAsset(StringView assetIdentifier) { Runtime.NotImplemented(); @@ -134,7 +139,7 @@ namespace GlitchyEngine.Content Runtime.NotImplemented(); } - public void SetAsDefaultAssetLoader(params StringView[] fileExtensions) where T : IAssetLoader + public void SetAsDefaultAssetLoader(params Span fileExtensions) where T : IAssetLoader { Runtime.NotImplemented(); } diff --git a/GlitchyEngine/src/Platform/DX11/Renderer/Dx11PixelShader.bf b/GlitchyEngine/src/Platform/DX11/Renderer/Dx11PixelShader.bf index 5763efa..e85d9bc 100644 --- a/GlitchyEngine/src/Platform/DX11/Renderer/Dx11PixelShader.bf +++ b/GlitchyEngine/src/Platform/DX11/Renderer/Dx11PixelShader.bf @@ -4,6 +4,7 @@ using System; using DirectX.D3D11; using DirectX.D3DCompiler; using GlitchyEngine.Platform.DX11; +using GlitchyEngine.Content; using internal GlitchyEngine.Renderer; using internal GlitchyEngine.Platform.DX11; @@ -12,11 +13,11 @@ namespace GlitchyEngine.Renderer { extension PixelShader { - public override void CompileFromSource(StringView code, StringView? fileName, String entryPoint, ShaderDefine[] macros = null) + public override void CompileFromSource(StringView code, StringView? fileName, String entryPoint, IContentManager contentManager, ShaderDefine[] macros = null) { Debug.Profiler.ProfileRendererFunction!(); - Shader.PlattformCompileShaderFromSource(code, fileName, macros, entryPoint, "ps_5_0", DefaultCompileFlags, out nativeCode); + Shader.PlattformCompileShaderFromSource(code, fileName, macros, entryPoint, "ps_5_0", DefaultCompileFlags, contentManager, out nativeCode); { Debug.Profiler.ProfileResourceScope!("CreateNativePixelShader"); diff --git a/GlitchyEngine/src/Platform/DX11/Renderer/Dx11Shader.bf b/GlitchyEngine/src/Platform/DX11/Renderer/Dx11Shader.bf index 7025d1e..44d1f5e 100644 --- a/GlitchyEngine/src/Platform/DX11/Renderer/Dx11Shader.bf +++ b/GlitchyEngine/src/Platform/DX11/Renderer/Dx11Shader.bf @@ -6,11 +6,106 @@ using DirectX.Common; using DirectX.D3D11; using DirectX.D3DCompiler; using DirectX.D3D11Shader; +using System.IO; +using GlitchyEngine.Content; +using System.Collections; using internal GlitchyEngine.Renderer; namespace GlitchyEngine.Renderer { + struct ContentManagerInclude : ID3DInclude, IDisposable + { + private VTable _vTable; + + private IContentManager _contentManager; + + private Dictionary _loadedFiles; + + private String _parentFileDirectory; + + public this(IContentManager contentManager, String parentFileDirectory) + { + _contentManager = contentManager; + _parentFileDirectory = parentFileDirectory; + _loadedFiles = new Dictionary(); + + _vTable.Open = => Open; + _vTable.Close = => Close; + + _vt = &_vTable; + } + + public void Dispose() + { + delete _loadedFiles; + } + + public static HResult Open(ID3DInclude* self, IncludeType includeType, char8* fileName, void* parentData, void** data, uint32* bytes) + { + ContentManagerInclude* includer = (.)self; + + if (includer._loadedFiles.TryGetValue(fileName, let value)) + { + *data = value.Data; + *bytes = value.Length; + + return .S_OK; + } + + String pathNextToParent = scope .(); + + Path.Combine(pathNextToParent, includer._parentFileDirectory, StringView(fileName)); + + Stream fileStream = Application.Get().ContentManager.GetStream(pathNextToParent); + + if (fileStream == null) + { + fileStream = Application.Get().ContentManager.GetStream(StringView(fileName)); + } + + if (fileStream == null) + { + Log.EngineLogger.Error($"Failed to include file \"{fileName}\""); + return .E_FILENOTFOUND; + } + + String fileContent = new String(); + + { + StreamReader reader = scope .(fileStream); + + reader.ReadToEnd(fileContent); + + includer._loadedFiles.Add(fileName, (fileContent, fileContent.Ptr, (uint32)fileContent.Length)); + } + + delete fileStream; + + *data = (void*)fileContent.Ptr; + *bytes = (uint32)fileContent.Length; + + return .S_OK; + } + + public static HResult Close(ID3DInclude* self, void** data) + { + ContentManagerInclude* includer = (.)self; + + for (var v in includer._loadedFiles) + { + if (v.value.Data == data) + { + delete v.value.FileContent; + + includer._loadedFiles.Remove(v.key); + } + } + + return .S_OK; + } + } + extension Shader { internal ID3D11DeviceChild* nativeShader ~ _?.Release(); @@ -27,7 +122,7 @@ namespace GlitchyEngine.Renderer .OptimizationLevel3; #endif - internal static void PlattformCompileShaderFromSource(StringView code, StringView? fileName, ShaderDefine[] macros, String entryPoint, String target, ShaderCompileFlags compileFlags, out ID3DBlob* shaderBlob) + internal static void PlattformCompileShaderFromSource(StringView code, StringView? fileName, ShaderDefine[] macros, String entryPoint, String target, ShaderCompileFlags compileFlags, IContentManager contentManager, out ID3DBlob* shaderBlob) { Debug.Profiler.ProfileResourceFunction!(); @@ -44,12 +139,22 @@ namespace GlitchyEngine.Renderer ID3DBlob* errorBlob = null; - shaderBlob = null; - var result = D3DCompiler.D3DCompile(code.Ptr, (.)code.Length, fileName?.ToScopeCStr!(), nativeMacros, ID3DInclude.StandardInclude, entryPoint, target, compileFlags, .None, &shaderBlob, &errorBlob); - if(result.Failed) + String directory = scope .(); + + Path.GetDirectoryPath(fileName.Value, directory); + + using (ContentManagerInclude includer = .(contentManager, directory)) { - StringView str = StringView((char8*)errorBlob.GetBufferPointer(), (int)errorBlob.GetBufferSize()); - Log.EngineLogger.Error($"Failed to compile Shader: Error Code({(int)result}): {result} | Error Message: {str}"); + //ID3DInclude.StandardInclude + + shaderBlob = null; + var result = D3DCompiler.D3DCompile(code.Ptr, (.)code.Length, fileName?.ToScopeCStr!(), nativeMacros, &includer, entryPoint, target, compileFlags, .None, &shaderBlob, &errorBlob); + + if(result.Failed) + { + StringView str = StringView((char8*)errorBlob.GetBufferPointer(), (int)errorBlob.GetBufferSize()); + Log.EngineLogger.Error($"Failed to compile Shader: Error Code({(int)result}): {result} | Error Message: {str}"); + } } Log.EngineLogger.Assert(shaderBlob != null, "Shader compilation failed."); diff --git a/GlitchyEngine/src/Platform/DX11/Renderer/Dx11VertexShader.bf b/GlitchyEngine/src/Platform/DX11/Renderer/Dx11VertexShader.bf index 7a79ce8..49e48e9 100644 --- a/GlitchyEngine/src/Platform/DX11/Renderer/Dx11VertexShader.bf +++ b/GlitchyEngine/src/Platform/DX11/Renderer/Dx11VertexShader.bf @@ -5,6 +5,7 @@ using GlitchyEngine.Renderer; using DirectX.D3D11; using DirectX.D3DCompiler; using GlitchyEngine.Platform.DX11; +using GlitchyEngine.Content; using internal GlitchyEngine.Renderer; using internal GlitchyEngine.Platform.DX11; @@ -13,11 +14,11 @@ namespace GlitchyEngine.Renderer { extension VertexShader { - public override void CompileFromSource(StringView code, StringView? fileName, String entryPoint, ShaderDefine[] macros = null) + public override void CompileFromSource(StringView code, StringView? fileName, String entryPoint, IContentManager contentManager = null, ShaderDefine[] macros = null) { Debug.Profiler.ProfileResourceFunction!(); - Shader.PlattformCompileShaderFromSource(code, fileName, macros, entryPoint, "vs_5_0", DefaultCompileFlags, out nativeCode); + Shader.PlattformCompileShaderFromSource(code, fileName, macros, entryPoint, "vs_5_0", DefaultCompileFlags, contentManager, out nativeCode); { Debug.Profiler.ProfileResourceScope!("CreateNativeVertexShader"); diff --git a/GlitchyEngine/src/Renderer/Effect.bf b/GlitchyEngine/src/Renderer/Effect.bf index 35daaad..657b346 100644 --- a/GlitchyEngine/src/Renderer/Effect.bf +++ b/GlitchyEngine/src/Renderer/Effect.bf @@ -3,733 +3,751 @@ using System.IO; using System.Collections; using GlitchyEngine.Core; using GlitchyEngine.Math; +using GlitchyEngine.Content; -namespace GlitchyEngine.Renderer +namespace GlitchyEngine.Renderer; + +/*/// Obsolete because of the ContentManager? +public class EffectLibrary { - public class EffectLibrary + private Dictionary _effects = new .() ~ delete _; + + private List _ownedStrings = new .() ~ DeleteContainerAndItems!(_); + + public this() { - private Dictionary _effects = new .() ~ delete _; - - private List _ownedStrings = new .() ~ DeleteContainerAndItems!(_); - - public this() - { - } - - public ~this() - { - for(let pair in _effects) - { - pair.value.ReleaseRef(); - } - } - - public void Add(Effect effect, String effectName = null) - { - Debug.Profiler.ProfileResourceFunction!(); - - String name; - - if(effectName == null) - { - name = effect.Name; - } - else - { - name = new String(effectName); - _ownedStrings.Add(name); - } - - Log.EngineLogger.AssertDebug(!Exists(name), "Can't add two effects with the same name to library."); - - _effects.Add(name, effect..AddRef()); - } - - /** - * Loads the effect with the given file name. - * @param filepath The path to the effect file. - * @param effectName The optional custom effect name which will be used to identify the effect. - * @returns The loaded Effect. Note: This function will increment the reference counter of the effect, so the programmer must decrement it once it's not used anymore. - * If the return-value is not needed, use LoadNoRefInc instead. - */ - public Effect Load(String filepath, String effectName = null) - { - Debug.Profiler.ProfileResourceFunction!(); - - String name = effectName; - - if(name == null) - { - name = scope:: String(); - Path.GetFileNameWithoutExtension(filepath, name); - } - - if (Exists(name)) - { - return Get(name); - } - else - { - Log.EngineLogger.AssertDebug(!Exists(name), "Can't add two effects with the same name to library."); - - Effect effect = new Effect(filepath, name); - Add(effect); - - return effect; - } - } - - /** - * Loads the effect with the given file name. - * @param filepath The path to the effect file. - * @param effectName The optional custom effect name which will be used to identify the effect. - */ - public void LoadNoRefInc(String filepath, String effectName = null) - { - var v = Load(filepath, effectName); - v.ReleaseRef(); - } - - public Effect Get(String effectName) - { - Debug.Profiler.ProfileResourceFunction!(); - - Log.EngineLogger.AssertDebug(Exists(effectName), "Effect not found!"); - - return _effects.GetValue(effectName).Get()..AddRef(); - } - - public bool Exists(String effectName) => _effects.ContainsKey(effectName); } - public class Effect : RefCounter + public ~this() { - internal VertexShader _vs ~ _?.ReleaseRef(); - internal PixelShader _ps ~ _?.ReleaseRef(); - protected String _name ~ delete _; + for(let pair in _effects) + { + pair.value.ReleaseRef(); + } + } - typealias VariableDesc = Dictionary>; + public void Add(Effect effect, String effectName = null) + { + Debug.Profiler.ProfileResourceFunction!(); - protected VariableDesc _variableDescriptions ~ { - for (var (key, value) in _) + String name; + + if(effectName == null) + { + name = effect.Name; + } + else + { + name = new String(effectName); + _ownedStrings.Add(name); + } + + Log.EngineLogger.AssertDebug(!Exists(name), "Can't add two effects with the same name to library."); + + _effects.Add(name, effect..AddRef()); + } + + /** + * Loads the effect with the given file name. + * @param filepath The path to the effect file. + * @param effectName The optional custom effect name which will be used to identify the effect. + * @returns The loaded Effect. Note: This function will increment the reference counter of the effect, so the programmer must decrement it once it's not used anymore. + * If the return-value is not needed, use LoadNoRefInc instead. + */ + public Effect Load(String filepath, String effectName = null) + { + Debug.Profiler.ProfileResourceFunction!(); + + String name = effectName; + + if(name == null) + { + name = scope:: String(); + Path.GetFileNameWithoutExtension(filepath, name); + } + + if (Exists(name)) + { + return Get(name); + } + else + { + Log.EngineLogger.AssertDebug(!Exists(name), "Can't add two effects with the same name to library."); + + Effect effect = new Effect(filepath, name); + Add(effect); + + return effect; + } + } + + /** + * Loads the effect with the given file name. + * @param filepath The path to the effect file. + * @param effectName The optional custom effect name which will be used to identify the effect. + */ + public void LoadNoRefInc(String filepath, String effectName = null) + { + var v = Load(filepath, effectName); + v.ReleaseRef(); + } + + public Effect Get(String effectName) + { + Debug.Profiler.ProfileResourceFunction!(); + + Log.EngineLogger.AssertDebug(Exists(effectName), "Effect not found!"); + + return _effects.GetValue(effectName).Get()..AddRef(); + } + + public bool Exists(String effectName) => _effects.ContainsKey(effectName); +}*/ + +public class Effect : Asset +{ + internal VertexShader _vs ~ _?.ReleaseRef(); + internal PixelShader _ps ~ _?.ReleaseRef(); + + typealias VariableDesc = Dictionary>; + + protected VariableDesc _variableDescriptions = new .() ~ { + for (var (key, value) in _) + { + delete key; + + for (var (entryKey, entry) in value) { - delete key; - - for (var (entryKey, entry) in value) - { - delete entryKey; - entry.Dispose(); - } - - delete value; + delete entryKey; + entry.Dispose(); } - delete _; - }; - - protected Dictionary _engineBuffers ~ DeleteDictionaryAndKeysAndValues!(_); - - BufferCollection _bufferCollection ~ _.ReleaseRef(); - - BufferVariableCollection _variables ~ delete _; - - typealias TextureEntry = (TextureViewBinding BoundTexture, ShaderTextureCollection.ResourceEntry* VsSlot, ShaderTextureCollection.ResourceEntry* PsSlot); - Dictionary _textures ~ delete _; - - public Dictionary Textures => _textures; - - public VertexShader VertexShader - { - get => _vs; - private set => SetReference!(_vs, value); - } - - public PixelShader PixelShader - { - get => _ps; - private set => SetReference!(_ps, value); + delete value; } - public BufferCollection Buffers => _bufferCollection; - public BufferVariableCollection Variables => _variables; + delete _; + }; - public String Name => _name; + protected Dictionary _engineBuffers = new .() ~ DeleteDictionaryAndKeysAndValues!(_); - public this(String filename, String shaderName = null) + BufferCollection _bufferCollection ~ _.ReleaseRef(); + + BufferVariableCollection _variables ~ delete _; + + typealias TextureEntry = (TextureViewBinding BoundTexture, ShaderTextureCollection.ResourceEntry* VsSlot, ShaderTextureCollection.ResourceEntry* PsSlot); + Dictionary _textures ~ delete _; + + public Dictionary Textures => _textures; + + public VertexShader VertexShader + { + get => _vs; + private set => SetReference!(_vs, value); + } + + public PixelShader PixelShader + { + get => _ps; + private set => SetReference!(_ps, value); + } + + public BufferCollection Buffers => _bufferCollection; + public BufferVariableCollection Variables => _variables; + + [Obsolete("", false)] + public this(String filename) + { + Debug.Profiler.ProfileResourceFunction!(); + + String fileContent = scope String(); + String vsName = scope String(); + String psName = scope String(); + + ProcessFile(filename, fileContent, vsName, psName, _variableDescriptions, _engineBuffers); + + Compile(fileContent, filename, vsName, psName); + + MergeResources(); + } + + public this(Stream data, StringView assetIdentifier, IContentManager contentManager) + { + Debug.Profiler.ProfileResourceFunction!(); + + String fileContent = scope String(); + String vsName = scope String(); + String psName = scope String(); + + ProcessStream(data, fileContent, vsName, psName, _variableDescriptions, _engineBuffers); + + Compile(fileContent, assetIdentifier, vsName, psName, contentManager); + + MergeResources(); + } + + public ~this() + { + Debug.Profiler.ProfileResourceFunction!(); + + for(let entry in _textures) { - Debug.Profiler.ProfileResourceFunction!(); + entry.value.BoundTexture.Release(); + } + } - String fileContent = scope String(); - String vsName = scope String(); - String psName = scope String(); + public void SetTexture(String name, Texture texture) + { + Debug.Profiler.ProfileRendererFunction!(); - _variableDescriptions = new VariableDesc(); - _engineBuffers = new Dictionary(); + [Inline]InternalSetTexture(name, texture.GetViewBinding()); + } + + public void SetTexture(String name, RenderTargetGroup renderTargetGroup, int32 firstTarget, uint32 targetCount = 1) + { + Debug.Profiler.ProfileRendererFunction!(); - ProcessFile(filename, fileContent, vsName, psName, _variableDescriptions, _engineBuffers); + if (targetCount != 1) + Runtime.NotImplemented("Binding multiple rendertargets to a slot is not yet implemented."); - Compile(fileContent, filename, vsName, psName); + // We have to release the viewBinding because GetViewBinding internally increases the counter + [Inline]InternalSetTexture(name, renderTargetGroup.GetViewBinding(firstTarget)); + } - MergeResources(); + public void SetTexture(String name, TextureViewBinding textureViewBinding) + { + Debug.Profiler.ProfileRendererFunction!(); + + [Inline]InternalSetTexture(name, textureViewBinding..AddRef()); + } + + private void InternalSetTexture(String name, TextureViewBinding textureViewBinding) + { + Debug.Profiler.ProfileRendererFunction!(); + + ref TextureEntry entry = ref _textures[name]; + + entry.BoundTexture.Release(); + entry.BoundTexture = textureViewBinding; + + entry.VsSlot?.BoundTexture..Release() = entry.BoundTexture..AddRef(); + entry.PsSlot?.BoundTexture..Release() = entry.BoundTexture..AddRef(); + } + + /*private void ApplyTextures() + { + Debug.Profiler.ProfileRendererFunction!(); + + for(let (name, entry) in _textures) + { + entry.VsSlot?.BoundTexture.Release(); + entry.VsSlot?.BoundTexture = entry.BoundTexture; + entry.VsSlot?.BoundTexture.AddRef(); - if(shaderName == null) - { - _name = new String(); - Path.GetFileNameWithoutExtension(filename, _name); - } - else - { - _name = new String(shaderName); - } + entry.PsSlot?.BoundTexture.Release(); + entry.PsSlot?.BoundTexture = entry.BoundTexture; + entry.PsSlot?.BoundTexture.AddRef(); } + }*/ - public ~this() - { - Debug.Profiler.ProfileResourceFunction!(); - - for(let entry in _textures) - { - entry.value.BoundTexture.Release(); - } - } - - public void SetTexture(String name, Texture texture) - { - Debug.Profiler.ProfileRendererFunction!(); - - [Inline]InternalSetTexture(name, texture.GetViewBinding()); - } + public void ApplyChanges() + { + Debug.Profiler.ProfileRendererFunction!(); - public void SetTexture(String name, RenderTargetGroup renderTargetGroup, int32 firstTarget, uint32 targetCount = 1) + //ApplyTextures(); + + for(let buffer in _bufferCollection) { - Debug.Profiler.ProfileRendererFunction!(); - - if (targetCount != 1) - Runtime.NotImplemented("Binding multiple rendertargets to a slot is not yet implemented."); - - // We have to release the viewBinding because GetViewBinding internally increases the counter - [Inline]InternalSetTexture(name, renderTargetGroup.GetViewBinding(firstTarget)); - } - - public void SetTexture(String name, TextureViewBinding textureViewBinding) - { - Debug.Profiler.ProfileRendererFunction!(); - - [Inline]InternalSetTexture(name, textureViewBinding..AddRef()); - } - - private void InternalSetTexture(String name, TextureViewBinding textureViewBinding) - { - Debug.Profiler.ProfileRendererFunction!(); - - ref TextureEntry entry = ref _textures[name]; - - entry.BoundTexture.Release(); - entry.BoundTexture = textureViewBinding; - - entry.VsSlot?.BoundTexture..Release() = entry.BoundTexture..AddRef(); - entry.PsSlot?.BoundTexture..Release() = entry.BoundTexture..AddRef(); - } - - /*private void ApplyTextures() - { - Debug.Profiler.ProfileRendererFunction!(); - - for(let (name, entry) in _textures) + if(let cbuffer = buffer.Buffer as ConstantBuffer) { - entry.VsSlot?.BoundTexture.Release(); - entry.VsSlot?.BoundTexture = entry.BoundTexture; - entry.VsSlot?.BoundTexture.AddRef(); - - entry.PsSlot?.BoundTexture.Release(); - entry.PsSlot?.BoundTexture = entry.BoundTexture; - entry.PsSlot?.BoundTexture.AddRef(); + cbuffer.Update(); } - }*/ + } + } - public void ApplyChanges() + public void Bind() + { + Debug.Profiler.ProfileRendererFunction!(); + + //ApplyTextures(); + //ApplyChanges(); + + RenderCommand.BindVertexShader(_vs); + RenderCommand.BindPixelShader(_ps); + } + + /*private void CompileFromFile(String filename, String vsEntry, String psEntry) + { + Debug.Profiler.ProfileResourceFunction!(); + + let vs = Shader.FromFile!(filename, vsEntry); + VertexShader = vs; + vs.ReleaseRef(); + let ps = Shader.FromFile!(filename, psEntry); + PixelShader = ps; + ps.ReleaseRef(); + }*/ + + private void Compile(String fileContent, StringView fileName, String vsEntry, String psEntry, IContentManager contentManager = null) + { + Debug.Profiler.ProfileResourceFunction!(); + + // TODO: vsEntry and psEntry could be empty (which is a valid case.) + let vs = new VertexShader(fileContent, fileName, vsEntry, contentManager); + VertexShader = vs; + vs.ReleaseRef(); + let ps = new PixelShader(fileContent, fileName, psEntry, contentManager); + PixelShader = ps; + ps.ReleaseRef(); + } + + const String effectKeyword = "#effect"; + + private static void CommentLine(StringView code, int commentPosition) + { + code[commentPosition] = '/'; + code[commentPosition + 1] = '/'; + } + + private static Result<(int Start, int End)> GetNextPreprocessor(StringView code, int startindex, out StringView name, Dictionary arguments) + { + name = .(); + + int startOfLine; + int endOfLine; + do { - Debug.Profiler.ProfileRendererFunction!(); + startOfLine = code.IndexOf("#pragma", startindex); + + if (startOfLine == -1) + return .Err; + + endOfLine = code.IndexOf('\n', startOfLine); + + StringView line = (endOfLine != -1) ? code.Substring(startOfLine, endOfLine - startOfLine) : code.Substring(startOfLine); + + // cut off the #pragma + line = line.Substring(7); + + int lBracketIndex = line.IndexOf('['); + + if (lBracketIndex == -1) + { + name = line..Trim(); + break; + } + + name = line.Substring(0, lBracketIndex); + name.Trim(); - //ApplyTextures(); + int rBracketIndex = line.IndexOf(']'); - for(let buffer in _bufferCollection) + if (rBracketIndex == -1) { - if(let cbuffer = buffer.Buffer as ConstantBuffer) + Log.EngineLogger.Error($"Pragma is missing closing Bracket (\"{line}\")"); + rBracketIndex = line.Length; + } + + StringView argumentText = line.Substring(lBracketIndex + 1, rBracketIndex - lBracketIndex - 1); + + for (StringView argument in argumentText.Split(';')) + { + int equalsIndex = argument.IndexOf('='); + + StringView argumentName = .(); + StringView argumentValue = .(); + + if (equalsIndex == -1) { - cbuffer.Update(); + argumentName = argument; + argumentName.Trim(); } + else + { + argumentName = argument.Substring(0, equalsIndex); + argumentName.Trim(); + + argumentValue = argument.Substring(equalsIndex + 1); + argumentValue.Trim(); + } + + if (arguments.ContainsKey(argumentName)) + { + Log.EngineLogger.Error($"Arguments \"{argumentName}\" already exists."); + continue; + } + + arguments.Add(argumentName, argumentValue); } } - public void Bind() - { - Debug.Profiler.ProfileRendererFunction!(); + return .Ok((startOfLine, endOfLine)); + } - //ApplyTextures(); - //ApplyChanges(); + private static void ProcessStream(Stream rawData, String fileContent, String outVsName, String outPsName, VariableDesc outVarDescs, Dictionary outEngineBuffers) + { + Debug.Profiler.ProfileResourceFunction!(); - RenderCommand.BindVertexShader(_vs); - RenderCommand.BindPixelShader(_ps); - } - - private void CompileFromFile(String filename, String vsEntry, String psEntry) - { - Debug.Profiler.ProfileResourceFunction!(); - - let vs = Shader.FromFile!(filename, vsEntry); - VertexShader = vs; - vs.ReleaseRef(); - let ps = Shader.FromFile!(filename, psEntry); - PixelShader = ps; - ps.ReleaseRef(); - } - - private void Compile(String fileContent, String fileName, String vsEntry, String psEntry) - { - Debug.Profiler.ProfileResourceFunction!(); - - // TODO: vsEntry and psEntry could be empty (which is a valid case.) - let vs = new VertexShader(fileContent, (StringView)fileName, vsEntry); - VertexShader = vs; - vs.ReleaseRef(); - let ps = new PixelShader(fileContent, (StringView)fileName, psEntry); - PixelShader = ps; - ps.ReleaseRef(); - } - - const String effectKeyword = "#effect"; + StreamReader streamReader = scope .(rawData); + streamReader.ReadToEnd(fileContent); + // append line ending just in case the file doesn't end with one. + fileContent.Append('\n'); - private static void CommentLine(StringView code, int commentPosition) - { - code[commentPosition] = '/'; - code[commentPosition + 1] = '/'; - } + ProcessFileContent(fileContent, outVsName, outPsName, outVarDescs, outEngineBuffers); + } - private static Result<(int Start, int End)> GetNextPreprocessor(StringView code, int startindex, out StringView name, Dictionary arguments) - { - name = .(); + /** + * Loads the effect file and extracts the names of the vertex- and pixel-shader. + * @param filename The path of the effect file. + * @param fileContent The preprocessed effect file. + * @param outVsName The string that will receive the vertex shader entry point. + * @param outPsName The string that will receive the pixel shader entry point. + * @param outVarDescs The dictionary that will contain the Variable descriptions. + */ + private static void ProcessFile(String filename, String fileContent, String outVsName, String outPsName, VariableDesc outVarDescs, Dictionary outEngineBuffers) + { + Debug.Profiler.ProfileResourceFunction!(); - int startOfLine; - int endOfLine; - do + File.ReadAllText(filename, fileContent, true); + // append line ending just in case the file doesn't end with one. + fileContent.Append('\n'); + + ProcessFileContent(fileContent, outVsName, outPsName, outVarDescs, outEngineBuffers); + } + + private static void ProcessFileContent(String fileContent, String outVsName, String outPsName, VariableDesc outVarDescs, Dictionary outEngineBuffers) + { + Debug.Profiler.ProfileResourceFunction!(); + + Dictionary arguments = scope .(); + + int index = 0; + + while (true) + { + Result<(int Start, int End)> result = GetNextPreprocessor(fileContent, index, let name, arguments..Clear()); + + if (result case .Err) + break; + else if (result case .Ok(let value)) { - startOfLine = code.IndexOf("#pragma", startindex); - - if (startOfLine == -1) - return .Err; - - endOfLine = code.IndexOf('\n', startOfLine); - - StringView line = (endOfLine != -1) ? code.Substring(startOfLine, endOfLine - startOfLine) : code.Substring(startOfLine); - - // cut off the #pragma - line = line.Substring(7); - - int lBracketIndex = line.IndexOf('['); - - if (lBracketIndex == -1) - { - name = line..Trim(); - break; - } - - name = line.Substring(0, lBracketIndex); - name.Trim(); - - int rBracketIndex = line.IndexOf(']'); - - if (rBracketIndex == -1) - { - Log.EngineLogger.Error($"Pragma is missing closing Bracket (\"{line}\")"); - rBracketIndex = line.Length; - } - - StringView argumentText = line.Substring(lBracketIndex + 1, rBracketIndex - lBracketIndex - 1); - - for (StringView argument in argumentText.Split(';')) - { - int equalsIndex = argument.IndexOf('='); - - StringView argumentName = .(); - StringView argumentValue = .(); - - if (equalsIndex == -1) - { - argumentName = argument; - argumentName.Trim(); - } - else - { - argumentName = argument.Substring(0, equalsIndex); - argumentName.Trim(); - - argumentValue = argument.Substring(equalsIndex + 1); - argumentValue.Trim(); - } - - if (arguments.ContainsKey(argumentName)) - { - Log.EngineLogger.Error($"Arguments \"{argumentName}\" already exists."); - continue; - } - - arguments.Add(argumentName, argumentValue); - } - } - - return .Ok((startOfLine, endOfLine)); - } - - /** - * Loads the effect file and extracts the names of the vertex- and pixel-shader. - * @param filename The path of the effect file. - * @param fileContent The preprocessed effect file. - * @param outVsName The string that will receive the vertex shader entry point. - * @param outPsName The string that will receive the pixel shader entry point. - * @param outVarDescs The dictionary that will contain the Variable descriptions. - */ - private static void ProcessFile(String filename, String fileContent, String outVsName, String outPsName, VariableDesc outVarDescs, Dictionary outEngineBuffers) - { - Debug.Profiler.ProfileResourceFunction!(); - - File.ReadAllText(filename, fileContent, true); - // append line ending just in case the file doesn't end with one. - fileContent.Append('\n'); - - { - Dictionary arguments = scope .(); - - int index = 0; - - while (true) - { - Result<(int Start, int End)> result = GetNextPreprocessor(fileContent, index, let name, arguments..Clear()); - - if (result case .Err) - break; - else if (result case .Ok(let value)) - { - index = value.End; - - switch(name) - { - case "Effect": - for (let (argName, argValue) in arguments) - { - switch(argName) - { - case "VS", "VertexShader": - outVsName.Append(argValue); - case "PS", "PixelShader": - outPsName.Append(argValue); - default: - Log.EngineLogger.Assert(false, scope $"Unknown parameter name \"{name}\"."); - } - } - case "EditorVariable": - ProcessEditorVariables(arguments, outVarDescs); - case "EngineBuffer": - ProcessEngineBuffer(arguments, outEngineBuffers); - default: - continue; - } - - CommentLine(fileContent, value.Start); - } - } - } - } - - private static void ProcessEngineBuffer(Dictionary arguments, Dictionary outEngineBuffers) - { - String nameInEngine = null; - String nameInShader = null; - - for (var (argName, argValue) in arguments) - { - if (argValue.StartsWith('"') && argValue.EndsWith('"')) - { - argValue = argValue[1...^2]; - } - switch (argName) - { - case "Name": - nameInShader = new String(argValue); - case "Binding": - nameInEngine = new String(argValue); - default: - Log.EngineLogger.Assert(false, scope $"Unknown parameter for EngineBuffer: \"{argName}\"."); - } - } - - Log.EngineLogger.AssertDebug(nameInEngine != null); - Log.EngineLogger.AssertDebug(nameInShader != null); - - outEngineBuffers.Add(nameInEngine, nameInShader); - } - - private static void ProcessEditorVariables(Dictionary arguments, VariableDesc outVarDescs) - { - String variableName = null; - - Dictionary parameters = new .(); - - for (var (name, value) in arguments) - { - if (value.StartsWith('"') && value.EndsWith('"')) - { - value = value[1...^2]; - } + index = value.End; switch(name) { - case "Name": - variableName = new String(value); - case "Min", "Max": - Variant paramValue = ParseVariableValue(value); - parameters.Add(new String(name), paramValue); + case "Effect": + for (let (argName, argValue) in arguments) + { + switch(argName) + { + case "VS", "VertexShader": + outVsName.Append(argValue); + case "PS", "PixelShader": + outPsName.Append(argValue); + default: + Log.EngineLogger.Assert(false, scope $"Unknown parameter name \"{name}\"."); + } + } + case "EditorVariable": + ProcessEditorVariables(arguments, outVarDescs); + case "EngineBuffer": + ProcessEngineBuffer(arguments, outEngineBuffers); default: - Variant paramValue = Variant.Create(new String(value), true); - parameters.Add(new String(name), paramValue); - } - } - - Log.EngineLogger.AssertDebug(variableName != null, "Missing argument \"Name\" int variable description."); - - outVarDescs.Add(variableName, parameters); - - } - - private static Variant ParseVariableValue(StringView valueString) - { - if (valueString[0].IsDigit || valueString[0] == '-') - { - var valueString; - - if (valueString.EndsWith('f')) - valueString.Length--; - - var result = float.Parse(valueString); - - Log.EngineLogger.AssertDebug(result case .Ok); - - if (result case .Ok(let value)) - return Variant.Create(value); - } - else if (valueString.StartsWith("float")) - { - int index = 5; - - int numComponents = valueString[index++] - '0'; - - while (valueString[index] != '(') - { - Log.EngineLogger.AssertDebug(valueString[index].IsWhiteSpace, "Expected '('."); - - index++; + continue; } - Log.EngineLogger.AssertDebug(numComponents >= 2 && numComponents <= 4, scope $"Unsupported component count {numComponents}. Value must be between 2 and 4"); - - float[] floats = scope float[numComponents]; - - for (int i < numComponents) - { - while (true) - { - char8 c = valueString[++index]; - - if (c.IsDigit || c == '.' || c == '-') - break; - } - - int start = index; - - while (true) - { - char8 c = valueString[++index]; - - if (!c.IsDigit && c != '.') - break; - } - - int end = index; - - StringView numberView = .(valueString, start, end - start); - - var result = float.Parse(numberView); - - if (result case .Ok(let value)) - { - floats[i] = value; - } - } - - if (numComponents == 2) - return Variant.Create(*(Vector2*)floats.Ptr); - else if (numComponents == 3) - return Variant.Create(*(Vector3*)floats.Ptr); - else if (numComponents == 4) - return Variant.Create(*(Vector4*)floats.Ptr); - } - else - { - Log.EngineLogger.Error($"Unsupported variable value: \"{valueString}\""); - } - - return Variant.Create(0.0f); - } - - //protected extern void Compile(String code, String fileName, String vsEntry, String psEntry); - - private void MergeResources() - { - Debug.Profiler.ProfileResourceFunction!(); - - MergeConstantBuffers(); - MergeBufferVariables(); - MergeTextures(); - } - - private void MergeConstantBuffers() - { - Debug.Profiler.ProfileResourceFunction!(); - - _bufferCollection = new BufferCollection(); - - HashSet bufferNames = scope HashSet(); - - AddShaderBuffers(_vs, bufferNames); - AddShaderBuffers(_ps, bufferNames); - - int internalIndex = 0; - - for(String bufferName in bufferNames) - { - let vsBuffer = _vs.Buffers.TryGetBufferEntry(bufferName); - let psBuffer = _ps.Buffers.TryGetBufferEntry(bufferName); - - if(vsBuffer != null && psBuffer != null) - { - BufferCollection.BufferEntry* fxBuffer = null; - // choose the larger of the two - if(psBuffer.Buffer.Description.Size > vsBuffer.Buffer.Description.Size) - fxBuffer = psBuffer; - else - fxBuffer = vsBuffer; - - _bufferCollection.Add(internalIndex, bufferName, fxBuffer.Buffer); - - _vs.Buffers.TryReplaceBuffer(vsBuffer.Index, fxBuffer.Buffer); - _ps.Buffers.TryReplaceBuffer(psBuffer.Index, fxBuffer.Buffer); - } - else if(vsBuffer != null) - { - _bufferCollection.Add(internalIndex, bufferName, vsBuffer.Buffer); - } - else if(psBuffer != null) - { - _bufferCollection.Add(internalIndex, bufferName, psBuffer.Buffer); - } - - internalIndex++; - } - - SetReference!(_vs.[Friend]_buffers, _bufferCollection); - SetReference!(_ps.[Friend]_buffers, _bufferCollection); - } - - private void MergeBufferVariables() - { - Debug.Profiler.ProfileResourceFunction!(); - - _variables = new BufferVariableCollection(false); - - outer: for(let buffer in _bufferCollection) - { - for (let eb in _engineBuffers) - { - if (eb.value == buffer.Name) - { - continue outer; - } - } - - if(let cbuffer = buffer.Buffer as ConstantBuffer) - { - for(let variable in cbuffer.Variables) - { - _variables.TryAdd(variable); - } - } - } - } - - private void AddShaderBuffers(Shader shader, HashSet bufferNames) - { - Debug.Profiler.ProfileResourceFunction!(); - - if(shader != null) - { - for(let buffer in shader.Buffers) - { - bufferNames.Add(buffer.Name); - } - } - } - - /// Merges the texture slots of all shaders into one dictionary. - private void MergeTextures() - { - Debug.Profiler.ProfileResourceFunction!(); - - delete _textures; - _textures = new .(); - - EnumerateShaderTextures(_vs); - EnumerateShaderTextures(_ps); - } - - /** @brief Merges all textures of the given shader into the _textures dictionary. - * @param shader The shader whose textures will be merged into the dictionary. - */ - private void EnumerateShaderTextures(T shader) where T : Shader - { - Debug.Profiler.ProfileResourceFunction!(); - - //for(var (name, index, texture) in shader.Resources) - for(var shaderEntry in ref shader.Textures) - { - TextureEntry entry; - - // Get existing entry or create new - if(!_textures.TryGetValue(shaderEntry.Name, out entry)) - { - entry = (shaderEntry.BoundTexture, null, null); - entry.BoundTexture.AddRef(); - } - - // Set the corresponding shader resource slot - if(typeof(T) == typeof(VertexShader)) - { - entry.VsSlot = &shaderEntry; - } - else if(typeof(T) == typeof(PixelShader)) - { - entry.PsSlot = &shaderEntry; - } - - // If the entry has no texture but the shader has one -> set texture - if(entry.BoundTexture.IsEmpty && !shaderEntry.BoundTexture.IsEmpty) - { - entry.BoundTexture = shaderEntry.BoundTexture; - entry.BoundTexture.AddRef(); - } - - // save entry - _textures[shaderEntry.Name] = entry; + CommentLine(fileContent, value.Start); } } } + + private static void ProcessEngineBuffer(Dictionary arguments, Dictionary outEngineBuffers) + { + String nameInEngine = null; + String nameInShader = null; + + for (var (argName, argValue) in arguments) + { + if (argValue.StartsWith('"') && argValue.EndsWith('"')) + { + argValue = argValue[1...^2]; + } + switch (argName) + { + case "Name": + nameInShader = new String(argValue); + case "Binding": + nameInEngine = new String(argValue); + default: + Log.EngineLogger.Assert(false, scope $"Unknown parameter for EngineBuffer: \"{argName}\"."); + } + } + + Log.EngineLogger.AssertDebug(nameInEngine != null); + Log.EngineLogger.AssertDebug(nameInShader != null); + + outEngineBuffers.Add(nameInEngine, nameInShader); + } + + private static void ProcessEditorVariables(Dictionary arguments, VariableDesc outVarDescs) + { + String variableName = null; + + Dictionary parameters = new .(); + + for (var (name, value) in arguments) + { + if (value.StartsWith('"') && value.EndsWith('"')) + { + value = value[1...^2]; + } + + switch(name) + { + case "Name": + variableName = new String(value); + case "Min", "Max": + Variant paramValue = ParseVariableValue(value); + parameters.Add(new String(name), paramValue); + default: + Variant paramValue = Variant.Create(new String(value), true); + parameters.Add(new String(name), paramValue); + } + } + + Log.EngineLogger.AssertDebug(variableName != null, "Missing argument \"Name\" int variable description."); + + outVarDescs.Add(variableName, parameters); + + } + + private static Variant ParseVariableValue(StringView valueString) + { + if (valueString[0].IsDigit || valueString[0] == '-') + { + var valueString; + + if (valueString.EndsWith('f')) + valueString.Length--; + + var result = float.Parse(valueString); + + Log.EngineLogger.AssertDebug(result case .Ok); + + if (result case .Ok(let value)) + return Variant.Create(value); + } + else if (valueString.StartsWith("float")) + { + int index = 5; + + int numComponents = valueString[index++] - '0'; + + while (valueString[index] != '(') + { + Log.EngineLogger.AssertDebug(valueString[index].IsWhiteSpace, "Expected '('."); + + index++; + } + + Log.EngineLogger.AssertDebug(numComponents >= 2 && numComponents <= 4, scope $"Unsupported component count {numComponents}. Value must be between 2 and 4"); + + float[] floats = scope float[numComponents]; + + for (int i < numComponents) + { + while (true) + { + char8 c = valueString[++index]; + + if (c.IsDigit || c == '.' || c == '-') + break; + } + + int start = index; + + while (true) + { + char8 c = valueString[++index]; + + if (!c.IsDigit && c != '.') + break; + } + + int end = index; + + StringView numberView = .(valueString, start, end - start); + + var result = float.Parse(numberView); + + if (result case .Ok(let value)) + { + floats[i] = value; + } + } + + if (numComponents == 2) + return Variant.Create(*(Vector2*)floats.Ptr); + else if (numComponents == 3) + return Variant.Create(*(Vector3*)floats.Ptr); + else if (numComponents == 4) + return Variant.Create(*(Vector4*)floats.Ptr); + } + else + { + Log.EngineLogger.Error($"Unsupported variable value: \"{valueString}\""); + } + + return Variant.Create(0.0f); + } + + //protected extern void Compile(String code, String fileName, String vsEntry, String psEntry); + + private void MergeResources() + { + Debug.Profiler.ProfileResourceFunction!(); + + MergeConstantBuffers(); + MergeBufferVariables(); + MergeTextures(); + } + + private void MergeConstantBuffers() + { + Debug.Profiler.ProfileResourceFunction!(); + + _bufferCollection = new BufferCollection(); + + HashSet bufferNames = scope HashSet(); + + AddShaderBuffers(_vs, bufferNames); + AddShaderBuffers(_ps, bufferNames); + + int internalIndex = 0; + + for(String bufferName in bufferNames) + { + let vsBuffer = _vs.Buffers.TryGetBufferEntry(bufferName); + let psBuffer = _ps.Buffers.TryGetBufferEntry(bufferName); + + if(vsBuffer != null && psBuffer != null) + { + BufferCollection.BufferEntry* fxBuffer = null; + // choose the larger of the two + if(psBuffer.Buffer.Description.Size > vsBuffer.Buffer.Description.Size) + fxBuffer = psBuffer; + else + fxBuffer = vsBuffer; + + _bufferCollection.Add(internalIndex, bufferName, fxBuffer.Buffer); + + _vs.Buffers.TryReplaceBuffer(vsBuffer.Index, fxBuffer.Buffer); + _ps.Buffers.TryReplaceBuffer(psBuffer.Index, fxBuffer.Buffer); + } + else if(vsBuffer != null) + { + _bufferCollection.Add(internalIndex, bufferName, vsBuffer.Buffer); + } + else if(psBuffer != null) + { + _bufferCollection.Add(internalIndex, bufferName, psBuffer.Buffer); + } + + internalIndex++; + } + + SetReference!(_vs.[Friend]_buffers, _bufferCollection); + SetReference!(_ps.[Friend]_buffers, _bufferCollection); + } + + private void MergeBufferVariables() + { + Debug.Profiler.ProfileResourceFunction!(); + + _variables = new BufferVariableCollection(false); + + outer: for(let buffer in _bufferCollection) + { + for (let eb in _engineBuffers) + { + if (eb.value == buffer.Name) + { + continue outer; + } + } + + if(let cbuffer = buffer.Buffer as ConstantBuffer) + { + for(let variable in cbuffer.Variables) + { + _variables.TryAdd(variable); + } + } + } + } + + private void AddShaderBuffers(Shader shader, HashSet bufferNames) + { + Debug.Profiler.ProfileResourceFunction!(); + + if(shader != null) + { + for(let buffer in shader.Buffers) + { + bufferNames.Add(buffer.Name); + } + } + } + + /// Merges the texture slots of all shaders into one dictionary. + private void MergeTextures() + { + Debug.Profiler.ProfileResourceFunction!(); + + delete _textures; + _textures = new .(); + + EnumerateShaderTextures(_vs); + EnumerateShaderTextures(_ps); + } + + /** @brief Merges all textures of the given shader into the _textures dictionary. + * @param shader The shader whose textures will be merged into the dictionary. + */ + private void EnumerateShaderTextures(T shader) where T : Shader + { + Debug.Profiler.ProfileResourceFunction!(); + + //for(var (name, index, texture) in shader.Resources) + for(var shaderEntry in ref shader.Textures) + { + TextureEntry entry; + + // Get existing entry or create new + if(!_textures.TryGetValue(shaderEntry.Name, out entry)) + { + entry = (shaderEntry.BoundTexture, null, null); + entry.BoundTexture.AddRef(); + } + + // Set the corresponding shader resource slot + if(typeof(T) == typeof(VertexShader)) + { + entry.VsSlot = &shaderEntry; + } + else if(typeof(T) == typeof(PixelShader)) + { + entry.PsSlot = &shaderEntry; + } + + // If the entry has no texture but the shader has one -> set texture + if(entry.BoundTexture.IsEmpty && !shaderEntry.BoundTexture.IsEmpty) + { + entry.BoundTexture = shaderEntry.BoundTexture; + entry.BoundTexture.AddRef(); + } + + // save entry + _textures[shaderEntry.Name] = entry; + } + } } diff --git a/GlitchyEngine/src/Renderer/PixelShader.bf b/GlitchyEngine/src/Renderer/PixelShader.bf index b8ce828..7d222b5 100644 --- a/GlitchyEngine/src/Renderer/PixelShader.bf +++ b/GlitchyEngine/src/Renderer/PixelShader.bf @@ -1,11 +1,12 @@ using System; +using GlitchyEngine.Content; namespace GlitchyEngine.Renderer { public class PixelShader : Shader { [AllowAppend] - public this(StringView code, StringView? fileName, String entryPoint, ShaderDefine[] macros = null) - : base(code, fileName, entryPoint, macros) { } + public this(StringView code, StringView? fileName, String entryPoint, IContentManager contentManager, ShaderDefine[] macros = null) + : base(code, fileName, entryPoint, contentManager, macros) { } } } diff --git a/GlitchyEngine/src/Renderer/Renderer.bf b/GlitchyEngine/src/Renderer/Renderer.bf index f0441dc..3dc39aa 100644 --- a/GlitchyEngine/src/Renderer/Renderer.bf +++ b/GlitchyEngine/src/Renderer/Renderer.bf @@ -104,7 +104,7 @@ namespace GlitchyEngine.Renderer private Vector3 _padding; } - public static void Init(EffectLibrary effectLibrary) + public static void Init() { Debug.Profiler.ProfileFunction!(); @@ -112,8 +112,8 @@ namespace GlitchyEngine.Renderer Renderer2D.Init(); FullscreenQuad.Init(); - InitLineRenderer(effectLibrary); - InitDeferredRenderer(effectLibrary); + InitLineRenderer(); + InitDeferredRenderer(); } public static void Deinit() @@ -128,11 +128,11 @@ namespace GlitchyEngine.Renderer Renderer2D.Deinit(); } - static void InitLineRenderer(EffectLibrary effectLibrary) + static void InitLineRenderer() { Debug.Profiler.ProfileFunction!(); - LineEffect = effectLibrary.Load("content\\Shaders\\lineShader.hlsl"); + LineEffect = Content.LoadAsset("Shaders\\lineShader.hlsl"); LineGeometry = new GeometryBinding(); LineGeometry.SetPrimitiveTopology(.LineList); @@ -161,10 +161,10 @@ namespace GlitchyEngine.Renderer LineEffect.ReleaseRef(); } - static void InitDeferredRenderer(EffectLibrary effectLibrary) + static void InitDeferredRenderer() { - TestFullscreenEffect = effectLibrary.Load("content\\Shaders\\simpleLight.hlsl"); - s_tonemappingEffect = effectLibrary.Load("content\\Shaders\\SimpleTonemapping.hlsl"); + TestFullscreenEffect = Content.LoadAsset("Shaders\\simpleLight.hlsl"); + s_tonemappingEffect = Content.LoadAsset("Shaders\\SimpleTonemapping.hlsl"); _gBuffer = new GBuffer(); BlendStateDescription gBufferBlendDesc = .Default; diff --git a/GlitchyEngine/src/Renderer/Shader.bf b/GlitchyEngine/src/Renderer/Shader.bf index d8d9552..1d33a07 100644 --- a/GlitchyEngine/src/Renderer/Shader.bf +++ b/GlitchyEngine/src/Renderer/Shader.bf @@ -2,6 +2,7 @@ using System; using System.IO; using System.Collections; using GlitchyEngine.Core; +using GlitchyEngine.Content; namespace GlitchyEngine.Renderer { @@ -30,7 +31,7 @@ namespace GlitchyEngine.Renderer public ShaderTextureCollection Textures => _textures; [AllowAppend] - public this(StringView code, StringView? fileName, String entryPoint, ShaderDefine[] macros = null) + public this(StringView code, StringView? fileName, String entryPoint, IContentManager contentManager, ShaderDefine[] macros = null) { Debug.Profiler.ProfileResourceFunction!(); @@ -39,7 +40,7 @@ namespace GlitchyEngine.Renderer _buffers = new BufferCollection(); _textures = new ShaderTextureCollection(); - CompileFromSource(code, fileName, entryPoint); + CompileFromSource(code, fileName, entryPoint, contentManager); } public ~this() @@ -47,19 +48,19 @@ namespace GlitchyEngine.Renderer Debug.Profiler.ProfileResourceFunction!(); } - public static mixin FromFile(String fileName, String entryPoint, ShaderDefine[] macros = null) where T : Shader + /*public static mixin FromFile(String fileName, String entryPoint, IContentManager contentManager, ShaderDefine[] macros = null) where T : Shader { Debug.Profiler.ProfileResourceFunction!(); String fileContent = new String(); File.ReadAllText(fileName, fileContent, true); - T shader = new T(fileContent, (StringView)fileName, entryPoint, macros); + T shader = new T(fileContent, (StringView)fileName, contentManager, entryPoint, macros); delete fileContent; shader - } + }*/ - public abstract void CompileFromSource(StringView code, StringView? fileName, String entryPoint, ShaderDefine[] macros = null); + public abstract void CompileFromSource(StringView code, StringView? fileName, String entryPoint, IContentManager contentManager, ShaderDefine[] macros = null); } } diff --git a/GlitchyEngine/src/Renderer/VertexShader.bf b/GlitchyEngine/src/Renderer/VertexShader.bf index 1340ea2..68fbc60 100644 --- a/GlitchyEngine/src/Renderer/VertexShader.bf +++ b/GlitchyEngine/src/Renderer/VertexShader.bf @@ -1,11 +1,12 @@ using System; +using GlitchyEngine.Content; namespace GlitchyEngine.Renderer { public class VertexShader : Shader { [AllowAppend] - public this(StringView code, StringView? fileName, String entryPoint, ShaderDefine[] macros = null) - : base(code, fileName, entryPoint, macros) { } + public this(StringView code, StringView? fileName, String entryPoint, IContentManager contentManager = null, ShaderDefine[] macros = null) + : base(code, fileName, entryPoint, contentManager, macros) { } } } diff --git a/GlitchyEngine/src/World/Scene.bf b/GlitchyEngine/src/World/Scene.bf index 33e089c..7531afb 100644 --- a/GlitchyEngine/src/World/Scene.bf +++ b/GlitchyEngine/src/World/Scene.bf @@ -4,6 +4,7 @@ using System; using System.Collections; using Box2D; using GlitchyEngine.Core; +using GlitchyEngine.Content; namespace GlitchyEngine.World { @@ -75,7 +76,7 @@ namespace GlitchyEngine.World DepthTargetDescription = .(.D24_UNorm_S8_UInt) }); - _gammaCorrectEffect = Application.Get().EffectLibrary.Load("content/Shaders/GammaCorrect.hlsl"); + _gammaCorrectEffect = Content.LoadAsset("Shaders/GammaCorrect.hlsl");//Application.Get().EffectLibrary.Load("content/Shaders/GammaCorrect.hlsl"); } public ~this() diff --git a/Sandbox/src/ExampleLayer.bf b/Sandbox/src/ExampleLayer.bf index 5df8d87..4652e67 100644 --- a/Sandbox/src/ExampleLayer.bf +++ b/Sandbox/src/ExampleLayer.bf @@ -85,13 +85,13 @@ namespace Sandbox _context = Application.Get().Window.Context..AddRef(); - var effectLibrary = Application.Get().EffectLibrary; + //var effectLibrary = Application.Get().EffectLibrary; - effectLibrary.LoadNoRefInc("content\\Shaders\\basicShader.hlsl"); + //effectLibrary.LoadNoRefInc("content\\Shaders\\basicShader.hlsl"); - effectLibrary.LoadNoRefInc("content\\Shaders\\testShader.hlsl"); + //effectLibrary.LoadNoRefInc("content\\Shaders\\testShader.hlsl"); - var textureEffect = effectLibrary.Load("content\\Shaders\\textureShader.hlsl"); + var textureEffect = Content.LoadAsset("Shaders\\textureShader.hlsl"); _depthTarget = new DepthStencilTarget(_context.SwapChain.Width, _context.SwapChain.Height); @@ -214,7 +214,7 @@ namespace Sandbox void TestLoadModel() { - var testEffect = Application.Get().EffectLibrary.Get("testShader"); + var testEffect = Content.LoadAsset("Shaders\\testShader.hlsl");//Application.Get().EffectLibrary.Get("testShader"); var materialTestMaterial = new Material(testEffect); animationMat = materialTestMaterial; @@ -266,7 +266,7 @@ namespace Sandbox _world.Register(); _world.Register(); - var basicEffect = Application.Get().EffectLibrary.Get("basicShader"); + var basicEffect = Content.LoadAsset("Shaders\\basicShader.hlsl");//Application.Get().EffectLibrary.Get("basicShader"); testMaterial1 = new Material(basicEffect); testMaterial1.SetVariable("BaseColor", _squareColor0); @@ -352,7 +352,7 @@ namespace Sandbox RenderCommand.SetBlendState(_opaqueBlendState); - var basicEffect = Application.Get().EffectLibrary.Get("basicShader"); + var basicEffect = Content.LoadAsset("Shaders\\basicShader.hlsl");//Application.Get().EffectLibrary.Get("basicShader"); RenderCommand.SetRasterizerState(_rasterizerState); diff --git a/Sandbox/src/SandboxApp.bf b/Sandbox/src/SandboxApp.bf index c19e7bc..5564465 100644 --- a/Sandbox/src/SandboxApp.bf +++ b/Sandbox/src/SandboxApp.bf @@ -32,5 +32,10 @@ namespace Sandbox { return new SandboxApp(); } + + protected override IContentManager InitContentManager() + { + Runtime.NotImplemented(); + } } }