Added support for Cube Textures, Improved dds import (and textures in general), Texture refactoring and DX11 DeviceContext synchronization

This commit is contained in:
Simon Lübeß
2023-06-25 17:58:16 +02:00
parent 46693666aa
commit bb520b43ec
20 changed files with 1222 additions and 241 deletions
+5 -1
View File
@@ -142,7 +142,11 @@ namespace GlitchyEngine.ImGui
RenderCommand.BindRenderTargets();
#if GE_GRAPHICS_DX11
ImGuiImplDX11.RenderDrawData(ImGui.GetDrawData());
using (ContextMonitor.Enter())
{
ImGuiImplDX11.RenderDrawData(ImGui.GetDrawData());
}
#endif
ImGui.CleanupFrame();
@@ -8,6 +8,7 @@ using DirectX.Common;
using DirectX.D3D11;
using DirectX.D3D11.SDKLayers;
using System.Diagnostics;
using System.Threading;
namespace GlitchyEngine.Platform.DX11
{
@@ -18,6 +19,8 @@ namespace GlitchyEngine.Platform.DX11
protected internal static ID3D11Device* NativeDevice;
protected internal static ID3D11DeviceContext* NativeContext;
protected internal static Monitor ContextMonitor = new Monitor() ~ delete _;
#if DEBUG
protected internal static ID3D11Debug* DebugDevice;
#endif
@@ -42,7 +45,10 @@ namespace GlitchyEngine.Platform.DX11
HResult deviceResult;
{
Debug.Profiler.ProfileScope!("D3D11.CreateDevice");
deviceResult = D3D11.CreateDevice(null, .Hardware, 0, deviceFlags, levels, &NativeDevice, &deviceLevel, &NativeContext);
using (ContextMonitor.Enter())
{
deviceResult = D3D11.CreateDevice(null, .Hardware, 0, deviceFlags, levels, &NativeDevice, &deviceLevel, &NativeContext);
}
}
Log.EngineLogger.Assert(deviceResult.Succeeded, scope $"Failed to create D3D11 Device. Message({(int32)deviceResult}): {deviceResult}");
@@ -100,14 +100,24 @@ namespace GlitchyEngine.Renderer
{
case .Default:
Box dataBox = .(dstByteOffset, 0, 0, dstByteOffset + byteLength, 1, 1);
NativeContext.UpdateSubresource(nativeBuffer, 0, &dataBox, data, byteLength, byteLength);
using (ContextMonitor.Enter())
{
NativeContext.UpdateSubresource(nativeBuffer, 0, &dataBox, data, byteLength, byteLength);
}
case .Dynamic:
Log.EngineLogger.Assert(mapType == .WriteDiscard || mapType == .WriteNoOverwrite, scope $"When writing to dynamic resources the map type must be {nameof(Renderer.MapType.WriteDiscard)} or {nameof(Renderer.MapType.WriteNoOverwrite)}.");
// Todo: DoNotWaitFlag
MappedSubresource map = ?;
NativeContext.Map(nativeBuffer, 0, (.)mapType, .None, &map);
using (ContextMonitor.Enter())
{
NativeContext.Map(nativeBuffer, 0, (.)mapType, .None, &map);
}
Internal.MemCpy(((uint8*)map.Data) + dstByteOffset, data, byteLength);
NativeContext.Unmap(nativeBuffer, 0);
using (ContextMonitor.Enter())
{
NativeContext.Unmap(nativeBuffer, 0);
}
case .Immutable:
Log.EngineLogger.Error("Can't set the data of an immutable resource.");
return .Err;
@@ -80,13 +80,16 @@ namespace GlitchyEngine.Renderer
public override void Bind()
{
Debug.Profiler.ProfileRendererFunction!();
NativeContext.InputAssembler.SetVertexBuffers(0, nativeBuffers.Count, &nativeBuffers, &bufferStrides, &bufferOffsets);
GraphicsContext.Get().SetVertexLayout(_vertexLayout);
NativeContext.InputAssembler.SetPrimitiveTopology((.)_primitiveTopology);
if(_indexBuffer != null)
NativeContext.InputAssembler.SetIndexBuffer(_indexBuffer.nativeBuffer, _indexBuffer.Format == .Index32Bit ? .R32_UInt : .R16_UInt, _indexByteOffset);
using (ContextMonitor.Enter())
{
NativeContext.InputAssembler.SetVertexBuffers(0, nativeBuffers.Count, &nativeBuffers, &bufferStrides, &bufferOffsets);
GraphicsContext.Get().SetVertexLayout(_vertexLayout);
NativeContext.InputAssembler.SetPrimitiveTopology((.)_primitiveTopology);
if(_indexBuffer != null)
NativeContext.InputAssembler.SetIndexBuffer(_indexBuffer.nativeBuffer, _indexBuffer.Format == .Index32Bit ? .R32_UInt : .R16_UInt, _indexByteOffset);
}
}
public override void Unbind()
@@ -96,12 +99,15 @@ namespace GlitchyEngine.Renderer
ID3D11Buffer*[nativeBuffers.Count] nullBuffers = .();
uint32[nativeBuffers.Count] zeroStrides = .();
uint32[nativeBuffers.Count] zeroOffsets = .();
NativeContext.InputAssembler.SetVertexBuffers(0, nativeBuffers.Count, &nullBuffers, &zeroStrides, &zeroOffsets);
NativeContext.InputAssembler.SetInputLayout(null);
NativeContext.InputAssembler.SetPrimitiveTopology(.Undefined);
NativeContext.InputAssembler.SetIndexBuffer(null, .R16_UNorm, 0);
using (ContextMonitor.Enter())
{
NativeContext.InputAssembler.SetVertexBuffers(0, nativeBuffers.Count, &nullBuffers, &zeroStrides, &zeroOffsets);
NativeContext.InputAssembler.SetInputLayout(null);
NativeContext.InputAssembler.SetPrimitiveTopology(.Undefined);
NativeContext.InputAssembler.SetIndexBuffer(null, .R16_UNorm, 0);
}
}
}
}
@@ -158,19 +158,28 @@ namespace GlitchyEngine.Renderer
public override void BindRenderTargets()
{
NativeContext.OutputMerger.SetRenderTargets(MaxRTVCount, &_renderTargets, _depthStencilTarget);
using (ContextMonitor.Enter())
{
NativeContext.OutputMerger.SetRenderTargets(MaxRTVCount, &_renderTargets, _depthStencilTarget);
}
}
public override void ClearRenderTarget(RenderTarget2D renderTarget, ColorRGBA color)
{
NativeContext.ClearRenderTargetView((renderTarget ?? _swapChain.BackBuffer)._nativeRenderTargetView, color);
using (ContextMonitor.Enter())
{
NativeContext.ClearRenderTargetView((renderTarget ?? _swapChain.BackBuffer)._nativeRenderTargetView, color);
}
}
public override void SetVertexBuffer(uint32 slot, Buffer buffer, uint32 stride, uint32 offset = 0)
{
// make stride and offset mutable so that we can take their pointers.
var stride, offset;
NativeContext.InputAssembler.SetVertexBuffers(slot, 1, &buffer.nativeBuffer, &stride, &offset);
using (ContextMonitor.Enter())
{
NativeContext.InputAssembler.SetVertexBuffers(slot, 1, &buffer.nativeBuffer, &stride, &offset);
}
}
[Inline]
@@ -180,8 +189,11 @@ namespace GlitchyEngine.Renderer
{
_currentInputLayout = _currentVertexLayout.GetNativeVertexLayout(_currentVertexShader.nativeCode);
_currentInputLayout.AddRef();
NativeContext.InputAssembler.SetInputLayout(_currentInputLayout);
using (ContextMonitor.Enter())
{
NativeContext.InputAssembler.SetInputLayout(_currentInputLayout);
}
}
}
@@ -190,7 +202,7 @@ namespace GlitchyEngine.Renderer
Debug.Profiler.ProfileRendererFunction!();
BindInputLayout();
if (_hasVs)
NativeContext.VertexShader.SetConstantBuffers(0, _vsBuffers.Count, &_vsBuffers);
@@ -200,33 +212,48 @@ namespace GlitchyEngine.Renderer
public override void Draw(uint32 vertexCount, uint32 startVertexIndex = 0)
{
BindState();
NativeContext.Draw(vertexCount, startVertexIndex);
using (ContextMonitor.Enter())
{
BindState();
NativeContext.Draw(vertexCount, startVertexIndex);
}
}
public override void DrawIndexed(uint32 indexCount, uint32 startIndexLocation = 0, int32 vertexOffset = 0)
{
BindState();
NativeContext.DrawIndexed(indexCount, startIndexLocation, vertexOffset);
using (ContextMonitor.Enter())
{
BindState();
NativeContext.DrawIndexed(indexCount, startIndexLocation, vertexOffset);
}
}
public override void DrawIndexedInstanced(uint32 indexCountPerInstance, uint32 instanceCount, uint32 startIndexLocation, int32 baseVertexLocation, uint32 startInstanceLocation)
{
BindState();
NativeContext.DrawIndexedInstanced(indexCountPerInstance, instanceCount, startIndexLocation, baseVertexLocation, startInstanceLocation);
using (ContextMonitor.Enter())
{
BindState();
NativeContext.DrawIndexedInstanced(indexCountPerInstance, instanceCount, startIndexLocation, baseVertexLocation, startInstanceLocation);
}
}
public override void SetIndexBuffer(Buffer buffer, IndexFormat indexFormat = .Index16Bit, uint32 byteOffset = 0)
{
NativeContext.InputAssembler.SetIndexBuffer(buffer.nativeBuffer, indexFormat == .Index32Bit ? .R32_UInt : .R16_UInt, byteOffset);
using (ContextMonitor.Enter())
{
NativeContext.InputAssembler.SetIndexBuffer(buffer.nativeBuffer, indexFormat == .Index32Bit ? .R32_UInt : .R16_UInt, byteOffset);
}
}
public override void SetViewports(uint32 viewportsCount, GlitchyEngine.Renderer.Viewport* viewports)
{
NativeContext.Rasterizer.SetViewports(viewportsCount, (.)viewports);
using (ContextMonitor.Enter())
{
NativeContext.Rasterizer.SetViewports(viewportsCount, (.)viewports);
}
}
public override void SetVertexLayout(VertexLayout vertexLayout)
@@ -241,7 +268,10 @@ namespace GlitchyEngine.Renderer
public override void SetPrimitiveTopology(GlitchyEngine.Renderer.PrimitiveTopology primitiveTopology)
{
NativeContext.InputAssembler.SetPrimitiveTopology((DirectX.Common.PrimitiveTopology)primitiveTopology);
using (ContextMonitor.Enter())
{
NativeContext.InputAssembler.SetPrimitiveTopology((DirectX.Common.PrimitiveTopology)primitiveTopology);
}
}
private uint32 _ps_FirstTexture;
@@ -343,19 +373,28 @@ namespace GlitchyEngine.Renderer
public override void UnbindTextures()
{
void** voidArray = scope void*[D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT]*;
NativeContext.PixelShader.SetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, (.)voidArray);
NativeContext.VertexShader.SetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, (.)voidArray);
using (ContextMonitor.Enter())
{
NativeContext.PixelShader.SetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, (.)voidArray);
NativeContext.VertexShader.SetShaderResources(0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, (.)voidArray);
}
}
public override void BindVertexShader(VertexShader vertexShader)
{
BindShaderToStage(vertexShader);
using (ContextMonitor.Enter())
{
BindShaderToStage(vertexShader);
}
}
public override void BindPixelShader(PixelShader pixelShader)
{
BindShaderToStage(pixelShader);
using (ContextMonitor.Enter())
{
BindShaderToStage(pixelShader);
}
}
public override void BindConstantBuffer(Buffer buffer, int slot, ShaderStage stage)
@@ -443,12 +443,25 @@ namespace GlitchyEngine.Renderer
uint32 srcSubResource = D3D11.CalcSubresource(mipLevel, arraySlice, _mipLevels);
Box srcBox = .(x, y, arraySlice, x + width, y + height, arraySlice + 1);
NativeContext.CopySubresourceRegion(stagingTexture, 0, 0, 0, 0, texture, srcSubResource, &srcBox);
using (ContextMonitor.Enter())
{
NativeContext.CopySubresourceRegion(stagingTexture, 0, 0, 0, 0, texture, srcSubResource, &srcBox);
}
MappedSubresource subresource = ?;
result = NativeContext.Map(stagingTexture, 0, .Read, .None, &subresource);
defer NativeContext.Unmap(stagingTexture, 0);
using (ContextMonitor.Enter())
{
result = NativeContext.Map(stagingTexture, 0, .Read, .None, &subresource);
}
defer
{
using (ContextMonitor.Enter())
{
NativeContext.Unmap(stagingTexture, 0);
}
}
if (result != 0)
return .Err;
@@ -474,8 +487,11 @@ namespace GlitchyEngine.Renderer
// TODO: Mips/Arrays
Box srcBox = .((.)srcTopLeft.X, (.)srcTopLeft.Y, 0, (.)(srcTopLeft.X + size.X), (.)(srcTopLeft.Y + size.Y), 1);
NativeContext.CopySubresourceRegion(dstTexture, 0, (.)dstTopLeft.X, (.)dstTopLeft.Y, 0, srcTexture, 0, &srcBox);
using (ContextMonitor.Enter())
{
NativeContext.CopySubresourceRegion(dstTexture, 0, (.)dstTopLeft.X, (.)dstTopLeft.Y, 0, srcTexture, 0, &srcBox);
}
}
}
}
@@ -44,8 +44,11 @@ namespace GlitchyEngine.Renderer
public override void Clear(RenderTarget2D renderTarget, ColorRGBA color)
{
Debug.Profiler.ProfileRendererFunction!();
NativeContext.ClearRenderTargetView(RtOrBackbuffer!(renderTarget)._nativeRenderTargetView, color);
using (ContextMonitor.Enter())
{
NativeContext.ClearRenderTargetView(RtOrBackbuffer!(renderTarget)._nativeRenderTargetView, color);
}
}
public override void Clear(DepthStencilTarget target, ClearOptions clearOptions, float depth, uint8 stencil)
@@ -66,37 +69,43 @@ namespace GlitchyEngine.Renderer
{
flags |= .Stencil;
}
NativeContext.ClearDepthStencilView(target.nativeView, flags, depth, stencil);
using (ContextMonitor.Enter())
{
NativeContext.ClearDepthStencilView(target.nativeView, flags, depth, stencil);
}
}
private void ClearRtv(DirectX.D3D11.ID3D11RenderTargetView* rtv, ClearColor clearColor)
{
switch(clearColor)
using (ContextMonitor.Enter())
{
case .Color(let color):
NativeContext.ClearRenderTargetView(rtv, color);
case .UInt(let value):
#unwarn
NativeContext.OutputMerger.SetRenderTargets(1, &rtv, null);
using (BlendState lastBlendState = _currentBlendState..AddRef())
switch(clearColor)
{
SetBlendState(_nonblendingState);
_clearUintFx.Variables["ClearValue"].SetData(value);
_clearUintFx.ApplyChanges();
_clearUintFx.Bind();
case .Color(let color):
NativeContext.ClearRenderTargetView(rtv, color);
case .UInt(let value):
#unwarn
NativeContext.OutputMerger.SetRenderTargets(1, &rtv, null);
FullscreenQuad.Draw();
using (BlendState lastBlendState = _currentBlendState..AddRef())
{
SetBlendState(_nonblendingState);
_clearUintFx.Variables["ClearValue"].SetData(value);
_clearUintFx.ApplyChanges();
_clearUintFx.Bind();
FullscreenQuad.Draw();
SetBlendState(lastBlendState);
}
SetBlendState(lastBlendState);
// Rebind the old render targets
BindRenderTargets();
default:
Runtime.NotImplemented();
}
// Rebind the old render targets
BindRenderTargets();
default:
Runtime.NotImplemented();
}
}
@@ -143,7 +152,10 @@ namespace GlitchyEngine.Renderer
clearDepth = depth ?? clearDepth;
clearStencil = stencil ?? clearStencil;
NativeContext.ClearDepthStencilView(renderTarget._nativeDepthTargetView, flags, clearDepth, clearStencil);
using (ContextMonitor.Enter())
{
NativeContext.ClearDepthStencilView(renderTarget._nativeDepthTargetView, flags, clearDepth, clearStencil);
}
}
}
}
@@ -199,7 +211,10 @@ namespace GlitchyEngine.Renderer
Debug.Profiler.ProfileRendererFunction!();
SetReference!(_currentRasterizerState, rasterizerState);
NativeContext.Rasterizer.SetState(_currentRasterizerState.nativeRasterizerState);
using (ContextMonitor.Enter())
{
NativeContext.Rasterizer.SetState(_currentRasterizerState.nativeRasterizerState);
}
}
private BlendState _currentBlendState ~ _?.ReleaseRef();
@@ -209,7 +224,11 @@ namespace GlitchyEngine.Renderer
Debug.Profiler.ProfileRendererFunction!();
SetReference!(_currentBlendState, blendState);
NativeContext.OutputMerger.SetBlendState(_currentBlendState.nativeBlendState, blendFactor);
using (ContextMonitor.Enter())
{
NativeContext.OutputMerger.SetBlendState(_currentBlendState.nativeBlendState, blendFactor);
}
}
private DepthStencilState _currentDepthStencilState ~ _?.ReleaseRef();
@@ -219,7 +238,11 @@ namespace GlitchyEngine.Renderer
Debug.Profiler.ProfileRendererFunction!();
SetReference!(_currentDepthStencilState, depthStencilState);
NativeContext.OutputMerger.SetDepthStencilState(_currentDepthStencilState.nativeDepthStencilState, stencilReference);
using (ContextMonitor.Enter())
{
NativeContext.OutputMerger.SetDepthStencilState(_currentDepthStencilState.nativeDepthStencilState, stencilReference);
}
}
public override void DrawIndexed(GeometryBinding geometry)
@@ -122,8 +122,11 @@ namespace GlitchyEngine.Renderer
public override void Bind(uint32 slot)
{
NativeContext.VertexShader.SetSamplers(slot, 1, &nativeSamplerState);
NativeContext.PixelShader.SetSamplers(slot, 1, &nativeSamplerState);
using (ContextMonitor.Enter())
{
NativeContext.VertexShader.SetSamplers(slot, 1, &nativeSamplerState);
NativeContext.PixelShader.SetSamplers(slot, 1, &nativeSamplerState);
}
}
}
}
@@ -205,7 +205,30 @@ namespace GlitchyEngine.Renderer
buffer.ReleaseRef();
}
case .Texture:
_textures.Add(scope String(bindDesc.Name), bindDesc.BindPoint, TextureViewBinding(null, null));
TextureDimension texDim;
switch (bindDesc.Dimension)
{
case .Texture1D:
texDim = .Texture1D;
case .Texture1DArray:
texDim = .Texture1DArray;
case .Texture2D:
texDim = .Texture2D;
case .Texture2DArray:
texDim = .Texture2DArray;
case .Texture3D:
texDim = .Texture3D;
case .TextureCube:
texDim = .TextureCube;
case .TextureCubeArray:
texDim = .TextureCubeArray;
default:
texDim = .Unknown;
}
_textures.Add(scope String(bindDesc.Name), bindDesc.BindPoint, TextureViewBinding(null, null), texDim);
case .Sampler:
// TODO: do we have to do something for samplers?
default:
@@ -19,43 +19,6 @@ namespace GlitchyEngine.Renderer
extension Texture
{
protected internal ID3D11ShaderResourceView* _nativeResourceView ~ _?.Release();
/** \brief Loads the texture from the specified path.
* @param path The path of the texture to load.
* @param texture The reference to the pointer that will hold the texture.
* @returns true if the texture was loaded successfully; false otherwise.
*/
protected bool LoadDdsResourcePlatform<T>(Stream stream, ref T* texture) where T : ID3D11Resource
{
Debug.Profiler.ProfileResourceFunction!();
uint8[] ddsData = new:ScopedAlloc! uint8[stream.Length];
var result = stream.TryRead(ddsData);
if (result case .Err(let err))
{
Log.EngineLogger.Error($"Failed to read texture data from stream. Error: {err}");
}
((ID3D11Resource*)texture)?.Release();
_nativeResourceView?.Release();
HResult loadResult = DDSTextureLoader.CreateDDSTextureFromMemory(NativeDevice,
ddsData.Ptr, (uint)ddsData.Count, (.)&texture, &_nativeResourceView);
if(loadResult.Failed)
{
Log.EngineLogger.Error($"Failed to load texture. Error({(int)loadResult}): {loadResult}");
ReleaseAndNullify!(texture);
ReleaseAndNullify!(_nativeResourceView);
return false;
}
return true;
}
}
extension Texture2DDesc
@@ -94,18 +57,6 @@ namespace GlitchyEngine.Renderer
public override uint32 ArraySize => nativeDesc.ArraySize;
public override uint32 MipLevels => nativeDesc.MipLevels;
protected override void LoadDdsPlatform(Stream stream)
{
Debug.Profiler.ProfileResourceFunction!();
LoadDdsResourcePlatform(stream, ref nativeTexture);
let resType = nativeTexture.GetResourceType();
Log.EngineLogger.Assert(resType == .Texture2D, scope $"The texture is not a 2D texture (it is {resType}).");
nativeTexture.GetDescription(out nativeDesc);
}
protected override void CreateTexturePlatform(Texture2DDesc desc, bool isRenderTarget, void* data, uint32 linePitch)
{
Debug.Profiler.ProfileResourceFunction!();
@@ -177,7 +128,12 @@ namespace GlitchyEngine.Renderer
case .Default:
Box dataBox = .(destX, destY, 0, destX + destWidth, destY + destHeight, 1);
var rowPitch = elementSize * destWidth;
NativeContext.UpdateSubresource(nativeTexture, subresourceIndex, &dataBox, data, rowPitch, rowPitch * destHeight);
using (ContextMonitor.Enter())
{
NativeContext.UpdateSubresource(nativeTexture, subresourceIndex, &dataBox, data, rowPitch, rowPitch * destHeight);
}
case .Dynamic:
Runtime.NotImplemented();
/*
@@ -220,6 +176,186 @@ namespace GlitchyEngine.Renderer
sourceBox.Back = 1;
}
// Make sure the destination was initialized
if(destination.nativeTexture == null)
destination.InternalCreateTexture(null, 0, 0);
using (ContextMonitor.Enter())
{
NativeContext.CopySubresourceRegion(destination.nativeTexture,
D3D11.CalcSubresource(destMipSlice, destArraySlice, destination.MipLevels), destX, destY, 0,
source.nativeTexture, D3D11.CalcSubresource(srcMipSlice, srcArraySlice, source.MipLevels), (.)&sourceBox);
}
}
public override void CopyTo(Texture2D destination)
{
Debug.Profiler.ProfileResourceFunction!();
if(nativeTexture == null)
return;
Log.EngineLogger.AssertDebug(nativeDesc.Format == destination.nativeDesc.Format,
"Source and destination resources must have the same texel-format.");
// Make sure the destination was initialized
if(destination.nativeTexture == null)
destination.InternalCreateTexture(null, 0, 0);
uint32 arraySlices = Math.Min(ArraySize, destination.ArraySize);
uint32 mipSlices = Math.Min(MipLevels, destination.MipLevels);
for(uint32 arraySlice < arraySlices)
for(uint32 mipSlice < mipSlices)
{
Box sourceBox = .(0, 0, 0, Width, Height, 1);
using (ContextMonitor.Enter())
{
NativeContext.CopySubresourceRegion(destination.nativeTexture,
D3D11.CalcSubresource(mipSlice, arraySlice, destination.MipLevels), 0, 0, 0,
nativeTexture, D3D11.CalcSubresource(mipSlice, arraySlice, MipLevels), (.)&sourceBox);
}
}
}
protected override TextureViewBinding PlatformGetViewBinding()
{
return .(_nativeResourceView, _samplerState?.nativeSamplerState);
}
}
extension TextureCube
{
protected internal ID3D11Texture2D* nativeTexture ~ _?.Release();
protected internal NativeTex2DDesc nativeDesc;
public override uint32 Width => nativeDesc.Width;
public override uint32 Height => nativeDesc.Height;
public override uint32 ArraySize => nativeDesc.ArraySize / 6;
public override uint32 MipLevels => nativeDesc.MipLevels;
protected override void CreateTexturePlatform(Texture2DDesc desc, bool isRenderTarget, void* data, uint32 linePitch)
{
Debug.Profiler.ProfileResourceFunction!();
PrepareTexturePlatform(desc, isRenderTarget);
InternalCreateTexture(data, linePitch, 0);
}
protected override void PrepareTexturePlatform(Texture2DDesc desc, bool isRenderTarget)
{
Debug.Profiler.ProfileResourceFunction!();
nativeTexture?.Release();
nativeTexture = null;
_nativeResourceView?.Release();
_nativeResourceView = null;
nativeDesc = (NativeTex2DDesc)desc;
// Make it a texture cube
nativeDesc.MiscFlags |= .TextureCube;
nativeDesc.ArraySize *= 6;
if(isRenderTarget)
nativeDesc.BindFlags |= .RenderTarget;
}
private void InternalCreateTexture(void* data, uint32 linePitch, uint32 slicePitch)
{
Debug.Profiler.ProfileResourceFunction!();
SubresourceData resData = .(data, linePitch, slicePitch);
// If data is null, set subresourceData null
SubresourceData* resDataPtr = null;//data == null ? null : &resData;
var result = NativeDevice.CreateTexture2D(ref nativeDesc, resDataPtr, &nativeTexture);
Log.EngineLogger.Assert(result.Succeeded, scope $"Failed to create texture 2D. Error ({result.Underlying}): {result}");
result = NativeDevice.CreateShaderResourceView(nativeTexture, null, &_nativeResourceView);
Log.EngineLogger.Assert(result.Succeeded, scope $"Failed to create texture view. Error ({result.Underlying}): {result}");
}
// TODO: Update Texture Arrays!
protected override Result<void> PlatformSetData(void* data, uint32 elementSize, uint32 destX,
uint32 destY, uint32 destWidth, uint32 destHeight, uint32 arraySlice, uint32 mipLevel, GlitchyEngine.Renderer.MapType mapType)
{
Debug.Profiler.ProfileResourceFunction!();
if(nativeTexture == null)
{
if(destX == 0 && destY == 0 && destWidth == nativeDesc.Width && destHeight == nativeDesc.Height)
{
// We can pass the data while creating the buffer, so we can return here.
var rowPitch = elementSize * destWidth;
InternalCreateTexture(data, rowPitch, rowPitch * destHeight);
}
else
{
// If we don't set the entire texture we need to create the texture with unknown content and set it manually
Log.EngineLogger.Assert(nativeDesc.Usage != .Immutable, "The entire immutable texture has to be initialized.");
InternalCreateTexture(null, 0, 0);
}
}
//Log.EngineLogger.AssertDebug();
// TODO: Debug.Assert(dstByteOffset + byteLength <= _description.Size, "The destination offset and byte length are too long for the target buffer.");
uint32 subresourceIndex = D3D11.CalcSubresource(mipLevel, arraySlice, nativeDesc.MipLevels);
switch(nativeDesc.Usage)
{
case .Default:
Box dataBox = .(destX, destY, 0, destX + destWidth, destY + destHeight, 1);
var rowPitch = elementSize * destWidth;
using (ContextMonitor.Enter())
{
NativeContext.UpdateSubresource(nativeTexture, subresourceIndex, &dataBox, data, rowPitch, rowPitch * destHeight);
}
case .Dynamic:
Runtime.NotImplemented();
/*
Log.EngineLogger.Assert(mapType.CanWrite, "The map type has to have write access.");
// Todo: DoNotWaitFlag
MappedSubresource map = ?;
_context.nativeContext.Map(nativeBuffer, 0, (.)mapType, .None, &map);
Internal.MemCpy(((uint8*)map.Data) + dstByteOffset, data, byteLength);
_context.nativeContext.Unmap(nativeBuffer, 0);
*/
case .Immutable:
Log.EngineLogger.Error("Can't set the data of an immutable resource.");
return .Err;
default:
Log.EngineLogger.Error($"Unknown resource usage: {nativeDesc.Usage}");
return .Err;
}
return .Ok;
}
/*public static override void CopySubresourceRegion(Texture2D source, Texture2D destination,
ResourceBox sourceBox = default, uint32 destX = 0, uint32 destY = 0,
uint32 srcArraySlice = 0, uint32 srcMipSlice = 0, uint32 destArraySlice = 0, uint32 destMipSlice = 0)
{
Debug.Profiler.ProfileResourceFunction!();
Log.EngineLogger.AssertDebug(source != destination || srcArraySlice != destArraySlice
|| srcMipSlice != destMipSlice, "Cannot copy from and to the same sub resource.");
Log.EngineLogger.AssertDebug(source.nativeDesc.Format == destination.nativeDesc.Format,
"Source and destination resources must have the same texel-format.");
var sourceBox;
if(sourceBox.Right == 0)
{
sourceBox.Right = source.Width;
sourceBox.Bottom = source.Height;
sourceBox.Back = 1;
}
// Make sure the destination was initialized
if(destination.nativeTexture == null)
destination.InternalCreateTexture(null, 0, 0);
@@ -255,44 +391,13 @@ namespace GlitchyEngine.Renderer
D3D11.CalcSubresource(mipSlice, arraySlice, destination.MipLevels), 0, 0, 0,
nativeTexture, D3D11.CalcSubresource(mipSlice, arraySlice, MipLevels), (.)&sourceBox);
}
}
}*/
protected override TextureViewBinding PlatformGetViewBinding()
{
return .(_nativeResourceView, _samplerState?.nativeSamplerState);
}
}
extension TextureCube
{
protected internal ID3D11Texture2D* nativeTexture ~ _?.Release();
protected internal NativeTex2DDesc nativeDesc;
public override uint32 Width => nativeDesc.Width;
public override uint32 Height => nativeDesc.Height;
public override uint32 ArraySize => nativeDesc.ArraySize / 6;
public override uint32 MipLevels => nativeDesc.MipLevels;
protected override void LoadTexturePlatform(Stream stream)
{
Debug.Profiler.ProfileResourceFunction!();
LoadDdsResourcePlatform(stream, ref nativeTexture);
let resType = nativeTexture.GetResourceType();
Log.EngineLogger.Assert(resType == .Texture2D, scope $"The texture \"{_path}\" is not a texture cube (it is {resType}).");
nativeTexture.GetDescription(out nativeDesc);
Log.EngineLogger.Assert(nativeDesc.MiscFlags.HasFlag(.TextureCube), scope $"The texture \"{_path}\" is not a texture cube.");
// TODO: load fallback texture
}
protected override TextureViewBinding PlatformGetViewBinding()
{
return .(_nativeResourceView, _samplerState.nativeSamplerState);
}
}
}
#endif
+16 -2
View File
@@ -104,6 +104,18 @@ public class EffectLibrary
public bool Exists(String effectName) => _effects.ContainsKey(effectName);
}*/
public enum TextureDimension
{
Unknown,
Texture1D,
Texture1DArray,
Texture2D,
Texture2DArray,
Texture3D,
TextureCube,
TextureCubeArray
}
public class Effect : Asset
{
internal VertexShader _vs ~ _?.ReleaseRef();
@@ -137,14 +149,16 @@ public class Effect : Asset
public struct TextureEntry
{
public TextureViewBinding BoundTexture;
public TextureDimension TextureDimension;
public ShaderTextureCollection.ResourceEntry* VsSlot;
public ShaderTextureCollection.ResourceEntry* PsSlot;
public this(TextureViewBinding boundTexture, ShaderTextureCollection.ResourceEntry* vsSlot, ShaderTextureCollection.ResourceEntry* psSlot)
public this(TextureViewBinding boundTexture, TextureDimension textureDimension, ShaderTextureCollection.ResourceEntry* vsSlot, ShaderTextureCollection.ResourceEntry* psSlot)
{
BoundTexture = boundTexture;
VsSlot = vsSlot;
PsSlot = psSlot;
TextureDimension = textureDimension;
}
}
@@ -741,7 +755,7 @@ public class Effect : Asset
// Get existing entry or create new
if(!_textures.TryGetValue(shaderEntry.Name, out entry))
{
entry = .(shaderEntry.BoundTexture, null, null);
entry = .(shaderEntry.BoundTexture, shaderEntry.Dimension, null, null);
entry.BoundTexture.AddRef();
}
+31 -5
View File
@@ -14,7 +14,7 @@ public class Material : Asset
private uint8[] _rawVariables ~ delete _;
private Dictionary<String, AssetHandle<Texture>> _textures = new .() ~ delete _;
private Dictionary<String, (AssetHandle<Texture> Handle, TextureDimension Dimension)> _textures = new .() ~ delete _;
private Dictionary<String, (uint32 Offset, BufferVariable Variable)> _variables = new .() ~ delete _;
@@ -34,7 +34,7 @@ public class Material : Asset
// At best whole paths. Shouldn't be that hard to do...
/*var texture = entry.BoundTexture;*/
_textures.Add(name, .Invalid);
_textures.Add(name, (AssetHandle<Texture>.Invalid, entry.TextureDimension));
}
InitRawData();
@@ -66,7 +66,19 @@ public class Material : Asset
for(let (name, texture) in _textures)
{
_effect.SetTexture(name, texture);
switch (texture.Dimension)
{
//case .Texture1D, .Texture1DArray:
case .Texture2D, .Texture2DArray:
AssetHandle<Texture2D> handle2D = .(texture.Handle);
_effect.SetTexture(name, handle2D);
case .TextureCube, .TextureCubeArray:
AssetHandle<TextureCube> cubeHandle = .(texture.Handle);
_effect.SetTexture(name, cubeHandle);
//case .Texture3D:
default:
Log.EngineLogger.Error("Tryied to bind undefined texture dimension!");
}
}
for(let (name, variable) in _variables)
@@ -86,13 +98,27 @@ public class Material : Asset
{
if(_textures.TryGetValue(name, var entry))
{
/*switch (texture.Get().GetType())
{
//case .Texture1D:
// _textures[name].Dimension = .Texture1D;
case typeof(Texture2D):
_textures[name].Dimension = .Texture2D;
case typeof(TextureCube):
_textures[name].Dimension = .TextureCube;
//case .Texture3D:
// _textures[name].Dimension = .Texture3D;
default:
_textures[name].Dimension = .Unknown;
}*/
//entry?.ReleaseRef();
_textures[name] = texture;
_textures[name].Handle = texture;
//texture?.AddRef();
}
else
{
Log.EngineLogger.Assert(false);
Log.EngineLogger.Error($"Material doesn't have the texture slot \"{name}\"");
//Log.EngineLogger.Assert(false);
}
}
@@ -79,15 +79,6 @@ namespace GlitchyEngine.Renderer
protected extern TextureViewBinding PlatformGetViewBinding();
protected internal override void SneakySwappyTexture(Texture otherTexture)
{
Log.EngineLogger.AssertDebug(otherTexture is RenderTarget2D, "Swapping texture must be a RenderTarget2D!");
SamplerState = otherTexture.SamplerState;
PlatformSneakySwappyTexture(otherTexture as RenderTarget2D);
}
protected extern void PlatformSneakySwappyTexture(RenderTarget2D otherTexture);
}
@@ -3,9 +3,9 @@ using System.Collections;
namespace GlitchyEngine.Renderer
{
public class ShaderTextureCollection : IEnumerable<(String Name, uint32 Index, TextureViewBinding BoundTexture)>
public class ShaderTextureCollection : IEnumerable<(String Name, uint32 Index, TextureViewBinding BoundTexture, TextureDimension Dimension)>
{
public typealias ResourceEntry = (String Name, uint32 Index, TextureViewBinding BoundTexture);
public typealias ResourceEntry = (String Name, uint32 Index, TextureViewBinding BoundTexture, TextureDimension Dimension);
List<ResourceEntry> _textures ~ DeleteTextureEntries!(_);
@@ -39,14 +39,14 @@ namespace GlitchyEngine.Renderer
// TODO: finish implementation (like BufferCollection)
public void Add(String name, uint32 index, TextureViewBinding texture)
public void Add(String name, uint32 index, TextureViewBinding texture, TextureDimension dimension)
{
Add((name, index, texture));
Add((name, index, texture, dimension));
}
public void Add(ResourceEntry entry)
{
ResourceEntry copy = (new String(entry.Name), entry.Index, entry.BoundTexture);
ResourceEntry copy = (new String(entry.Name), entry.Index, entry.BoundTexture, entry.Dimension);
entry.BoundTexture.AddRef();
_textures.Add(copy);
+45 -45
View File
@@ -30,11 +30,6 @@ namespace GlitchyEngine.Renderer
public abstract uint32 MipLevels {get;}
public abstract TextureViewBinding GetViewBinding();
/// Very dirtily swaps the internals with the given texture.
/// TODO: Please do this differently!!!!!!!!!!!!!!!!!!!!!!
/// This is for texture hot reloading POC, I know... it's bad...
protected internal abstract void SneakySwappyTexture(Texture otherTexture);
}
public struct Texture2DDesc
@@ -69,17 +64,6 @@ namespace GlitchyEngine.Renderer
//public override extern uint32 ArraySize {get;}
//public override extern uint32 MipLevels {get;}
// TODO: remove
private this(Stream data)
{
LoadDds(data);
}
protected void LoadDds(Stream stream)
{
LoadDdsPlatform(stream);
}
public this(Texture2DDesc desc)
{
PrepareTexturePlatform(desc, false);
@@ -100,8 +84,6 @@ namespace GlitchyEngine.Renderer
uint32 mipLevels = 1, uint32 arraySize = 1, Usage usage = .Default, CPUAccessFlags cpuAccess = .None
*/
protected extern void LoadDdsPlatform(Stream stream);
protected extern void CreateTexturePlatform(Texture2DDesc desc, bool isRenderTarget, void* data, uint32 linePitch);
/**
@@ -130,17 +112,16 @@ namespace GlitchyEngine.Renderer
}
protected extern TextureViewBinding PlatformGetViewBinding();
}
protected internal override void SneakySwappyTexture(Texture otherTexture)
{
Log.EngineLogger.AssertDebug(otherTexture is Texture2D, "Swapping texture must be a Texture2D!");
SamplerState = otherTexture.SamplerState;
PlatformSneakySwappyTexture(otherTexture as Texture2D);
}
protected extern void PlatformSneakySwappyTexture(Texture2D otherTexture);
public enum TextureCubeFace
{
PositiveX = 0,
NegativeX = 1,
PositiveY = 2,
NegativeY = 3,
PositiveZ = 4,
NegativeZ = 5,
}
public class TextureCube : Texture
@@ -152,24 +133,48 @@ namespace GlitchyEngine.Renderer
public override uint32 Depth => 1;
// public override extern uint32 ArraySize {get;}
// public override extern uint32 MipLevels {get;}
public this(String path)
public this(Texture2DDesc desc)
{
this._path = new String(path);
LoadTexture();
PrepareTexturePlatform(desc, false);
}
private void LoadTexture()
public void SetData(void* data, int elementSize, TextureCubeFace cubeFace, uint32 arraySlice = 0, uint32 mipSlice = 0)
{
Debug.Profiler.ProfileResourceFunction!();
Stream data = Application.Get().ContentManager.GetStream(_path);
defer delete data;
LoadTexturePlatform(data);
PlatformSetData(data, (.)elementSize, 0, 0, Width, Height, arraySlice * 6 + (uint32)cubeFace, mipSlice, .Write);
}
protected extern void LoadTexturePlatform(Stream stream);
public void SetData<T>(T* data, TextureCubeFace cubeFace, uint32 arraySlice = 0, uint32 mipSlice = 0)
{
PlatformSetData(data, (.)sizeof(T), 0, 0, Width, Height, arraySlice * 6 + (uint32)cubeFace, mipSlice, .Write);
}
public void SetData<T>(T* data, uint32 x, uint32 y, uint32 width, uint32 height, TextureCubeFace cubeFace, uint32 arraySlice = 0, uint32 mipSlice = 0)
{
PlatformSetData(data, (.)sizeof(T), x, y, width, height, arraySlice * 6 + (uint32)cubeFace, mipSlice, .Write);
}
protected extern void CreateTexturePlatform(Texture2DDesc desc, bool isRenderTarget, void* data, uint32 linePitch);
/**
* Prepares the texture so that a call to SetData can successfully upload the data to the gpu.
*/
protected extern void PrepareTexturePlatform(Texture2DDesc desc, bool isRenderTarget);
protected extern Result<void> PlatformSetData(void* data, uint32 elementSize, uint32 destX,
uint32 destY, uint32 destWidth, uint32 destHeight, uint32 arraySlice, uint32 mipLevel, GlitchyEngine.Renderer.MapType mapType);
/**
* Copies the texel-data of this texture to the given destination texture.
*/
public static extern void CopySubresourceRegion(Texture2D source, Texture2D destination,
ResourceBox sourceBox = default, uint32 destX = 0, uint32 destY = 0,
uint32 srcArraySlice = 0, uint32 srcMipSlice = 0, uint32 destArraySlice = 0, uint32 destMipSlice = 0);
/**
* Copies the data to the given destination.
*/
//public extern void CopyTo(TextureCube destination);
public override TextureViewBinding GetViewBinding()
{
@@ -177,10 +182,5 @@ namespace GlitchyEngine.Renderer
}
protected extern TextureViewBinding PlatformGetViewBinding();
protected internal override void SneakySwappyTexture(Texture otherTexture)
{
Runtime.NotImplemented();
}
}
}