Ported DirectX12GameEngine.Graphics project
このコミットが含まれているのは:
1 親
36ef5b38b7
コミット
f74dc2374a
33ファイル変更
+2412
-8
検索条件に一致するファイルはありません
@@ -2,13 +2,6 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
using System;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public partial class Buffer
|
||||
{
|
||||
public static class Constant
|
||||
{
|
||||
public static unsafe Buffer New(GraphicsDevice device, int size, GraphicsHeapType heapType = GraphicsHeapType.Upload)
|
||||
{
|
||||
return Buffer.New(device, size, BufferFlags.ConstantBuffer, heapType);
|
||||
}
|
||||
|
||||
public static unsafe Buffer<T> New<T>(GraphicsDevice device, in T data, GraphicsHeapType heapType = GraphicsHeapType.Upload) where T : unmanaged
|
||||
{
|
||||
return Buffer.New(device, data, BufferFlags.ConstantBuffer, heapType);
|
||||
}
|
||||
|
||||
public static unsafe Buffer<T> New<T>(GraphicsDevice device, Span<T> data, GraphicsHeapType heapType = GraphicsHeapType.Upload) where T : unmanaged
|
||||
{
|
||||
return Buffer.New(device, data, BufferFlags.ConstantBuffer, heapType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System;
|
||||
using SharpDX.Direct3D12;
|
||||
using SharpDX.DXGI;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public partial class Buffer
|
||||
{
|
||||
public static class Index
|
||||
{
|
||||
public static unsafe Buffer New(GraphicsDevice device, int size, GraphicsHeapType heapType = GraphicsHeapType.Default)
|
||||
{
|
||||
return Buffer.New(device, size, BufferFlags.IndexBuffer, heapType);
|
||||
}
|
||||
|
||||
public static unsafe Buffer<T> New<T>(GraphicsDevice device, in T data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
return Buffer.New(device, data, BufferFlags.IndexBuffer, heapType);
|
||||
}
|
||||
|
||||
public static unsafe Buffer<T> New<T>(GraphicsDevice device, Span<T> data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
return Buffer.New(device, data, BufferFlags.IndexBuffer, heapType);
|
||||
}
|
||||
|
||||
public static IndexBufferView CreateIndexBufferView(Buffer indexBuffer, PixelFormat format, int size)
|
||||
{
|
||||
switch (format)
|
||||
{
|
||||
case PixelFormat.R16_UInt:
|
||||
case PixelFormat.R32_UInt:
|
||||
break;
|
||||
default:
|
||||
throw new NotSupportedException("Index buffer type must be ushort or uint");
|
||||
}
|
||||
|
||||
return new IndexBufferView
|
||||
{
|
||||
BufferLocation = indexBuffer.NativeResource.GPUVirtualAddress,
|
||||
Format = (Format)format,
|
||||
SizeInBytes = size
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public partial class Buffer
|
||||
{
|
||||
public static class Vertex
|
||||
{
|
||||
public static unsafe Buffer New(GraphicsDevice device, int size, GraphicsHeapType heapType = GraphicsHeapType.Default)
|
||||
{
|
||||
return Buffer.New(device, size, BufferFlags.VertexBuffer, heapType);
|
||||
}
|
||||
|
||||
public static unsafe Buffer<T> New<T>(GraphicsDevice device, in T data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
return Buffer.New(device, data, BufferFlags.VertexBuffer, heapType);
|
||||
}
|
||||
|
||||
public static unsafe Buffer<T> New<T>(GraphicsDevice device, Span<T> data, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
return Buffer.New(device, data, BufferFlags.VertexBuffer, heapType);
|
||||
}
|
||||
|
||||
public static VertexBufferView CreateVertexBufferView(Buffer vertexBuffer, int size, int stride)
|
||||
{
|
||||
return new VertexBufferView
|
||||
{
|
||||
BufferLocation = vertexBuffer.NativeResource.GPUVirtualAddress,
|
||||
StrideInBytes = stride,
|
||||
SizeInBytes = size
|
||||
};
|
||||
}
|
||||
|
||||
public static unsafe VertexBufferView CreateVertexBufferView<T>(Buffer vertexBuffer, int size) where T : unmanaged
|
||||
{
|
||||
return CreateVertexBufferView(vertexBuffer, size, Unsafe.SizeOf<T>());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using DirectX12GameEngine.Core;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public partial class Buffer : GraphicsResource
|
||||
{
|
||||
public Buffer()
|
||||
{
|
||||
}
|
||||
|
||||
protected Buffer(GraphicsDevice device) : base(device)
|
||||
{
|
||||
}
|
||||
|
||||
public BufferDescription Description { get; private set; }
|
||||
|
||||
public int SizeInBytes => Description.SizeInBytes;
|
||||
|
||||
public BufferFlags Flags => Description.Flags;
|
||||
|
||||
public GraphicsHeapType Usage => Description.HeapType;
|
||||
|
||||
public int ElementCount { get; protected set; }
|
||||
|
||||
public T[] GetData<T>() where T : unmanaged
|
||||
{
|
||||
T[] data = new T[SizeInBytes / Unsafe.SizeOf<T>()];
|
||||
GetData(data.AsSpan());
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
public void GetData<T>(ref T data) where T : unmanaged
|
||||
{
|
||||
if (Usage != GraphicsHeapType.Default)
|
||||
{
|
||||
Map(0);
|
||||
MemoryHelper.Copy(MappedResource, ref data);
|
||||
Unmap(0);
|
||||
}
|
||||
}
|
||||
|
||||
public void GetData<T>(Span<T> data) where T : unmanaged
|
||||
{
|
||||
if (Usage != GraphicsHeapType.Default)
|
||||
{
|
||||
Map(0);
|
||||
MemoryHelper.Copy(MappedResource, data);
|
||||
Unmap(0);
|
||||
}
|
||||
}
|
||||
|
||||
public void SetData<T>(in T data, int offsetInBytes = 0) where T : unmanaged
|
||||
{
|
||||
if (Usage != GraphicsHeapType.Default)
|
||||
{
|
||||
Map(0);
|
||||
MemoryHelper.Copy(data, MappedResource + offsetInBytes);
|
||||
Unmap(0);
|
||||
}
|
||||
}
|
||||
|
||||
public void SetData<T>(Span<T> data, int offsetInBytes = 0) where T : unmanaged
|
||||
{
|
||||
if (Usage != GraphicsHeapType.Default)
|
||||
{
|
||||
Map(0);
|
||||
MemoryHelper.Copy(data, MappedResource + offsetInBytes);
|
||||
Unmap(0);
|
||||
}
|
||||
}
|
||||
|
||||
public static Buffer New(GraphicsDevice device, BufferDescription description)
|
||||
{
|
||||
return new Buffer(device).InitializeFrom(description);
|
||||
}
|
||||
|
||||
public static Buffer New(GraphicsDevice device, int size, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default)
|
||||
{
|
||||
return New(device, new BufferDescription(size, bufferFlags, heapType));
|
||||
}
|
||||
|
||||
public static Buffer<T> New<T>(GraphicsDevice device, int elementCount, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
int bufferSize = elementCount * Unsafe.SizeOf<T>();
|
||||
|
||||
return new Buffer<T>(device, bufferSize, bufferFlags, heapType);
|
||||
}
|
||||
|
||||
public static unsafe Buffer<T> New<T>(GraphicsDevice device, in T data, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
fixed (T* pointer = &data)
|
||||
{
|
||||
return New(device, new Span<T>(pointer, 1), bufferFlags, heapType);
|
||||
}
|
||||
}
|
||||
|
||||
public static Buffer<T> New<T>(GraphicsDevice device, Span<T> data, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
Buffer<T> buffer = New<T>(device, data.Length, bufferFlags, heapType);
|
||||
buffer.Recreate(data);
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
protected internal Buffer InitializeFrom(BufferDescription description)
|
||||
{
|
||||
ResourceStates resourceStates = ResourceStates.Common;
|
||||
|
||||
if (description.HeapType == GraphicsHeapType.Upload)
|
||||
{
|
||||
resourceStates = ResourceStates.GenericRead;
|
||||
}
|
||||
else if (description.HeapType == GraphicsHeapType.Readback)
|
||||
{
|
||||
resourceStates = ResourceStates.CopyDestination;
|
||||
}
|
||||
|
||||
NativeResource ??= GraphicsDevice.NativeDevice.CreateCommittedResource(
|
||||
new HeapProperties((HeapType)description.HeapType), HeapFlags.None,
|
||||
ConvertToNativeDescription(description), resourceStates);
|
||||
|
||||
Description = description;
|
||||
|
||||
(NativeCpuDescriptorHandle, NativeGpuDescriptorHandle) = description.Flags switch
|
||||
{
|
||||
BufferFlags.ConstantBuffer => CreateConstantBufferView(),
|
||||
BufferFlags.ShaderResource => CreateShaderResourceView(),
|
||||
BufferFlags.UnorderedAccess => CreateUnorderedAccessView(),
|
||||
_ => default
|
||||
};
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
protected internal void Recreate<T>(Span<T> data) where T : unmanaged
|
||||
{
|
||||
if (Description.HeapType == GraphicsHeapType.Upload)
|
||||
{
|
||||
SetData(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
using Buffer uploadBuffer = New(GraphicsDevice, data, BufferFlags.None, GraphicsHeapType.Upload);
|
||||
|
||||
CommandList copyCommandList = GraphicsDevice.GetOrCreateCopyCommandList();
|
||||
|
||||
copyCommandList.CopyResource(uploadBuffer, this);
|
||||
copyCommandList.Flush(true);
|
||||
|
||||
GraphicsDevice.EnqueueCopyCommandList(copyCommandList);
|
||||
}
|
||||
}
|
||||
|
||||
private static ResourceDescription ConvertToNativeDescription(BufferDescription description)
|
||||
{
|
||||
int size = description.SizeInBytes;
|
||||
ResourceFlags flags = ResourceFlags.None;
|
||||
|
||||
if (description.Flags.HasFlag(BufferFlags.UnorderedAccess))
|
||||
{
|
||||
flags |= ResourceFlags.AllowUnorderedAccess;
|
||||
//flags |= ResourceFlags.AllowSimultaneousAccess;
|
||||
}
|
||||
|
||||
return ResourceDescription.Buffer(size, flags);
|
||||
}
|
||||
|
||||
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateConstantBufferView()
|
||||
{
|
||||
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
|
||||
|
||||
int constantBufferSize = (SizeInBytes + 255) & ~255;
|
||||
|
||||
ConstantBufferViewDescription cbvDescription = new ConstantBufferViewDescription
|
||||
{
|
||||
BufferLocation = NativeResource.GPUVirtualAddress,
|
||||
SizeInBytes = constantBufferSize
|
||||
};
|
||||
|
||||
GraphicsDevice.NativeDevice.CreateConstantBufferView(cbvDescription, cpuHandle);
|
||||
|
||||
return (cpuHandle, gpuHandle);
|
||||
}
|
||||
|
||||
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateShaderResourceView()
|
||||
{
|
||||
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
|
||||
GraphicsDevice.NativeDevice.CreateShaderResourceView(NativeResource, null, cpuHandle);
|
||||
|
||||
return (cpuHandle, gpuHandle);
|
||||
}
|
||||
|
||||
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateUnorderedAccessView()
|
||||
{
|
||||
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
|
||||
|
||||
var description = new UnorderedAccessViewDescription
|
||||
{
|
||||
Format = SharpDX.DXGI.Format.R32_Float,
|
||||
Dimension = UnorderedAccessViewDimension.Buffer,
|
||||
Buffer =
|
||||
{
|
||||
ElementCount = ElementCount,
|
||||
}
|
||||
};
|
||||
|
||||
GraphicsDevice.NativeDevice.CreateUnorderedAccessView(NativeResource, null, description, cpuHandle);
|
||||
|
||||
return (cpuHandle, gpuHandle);
|
||||
}
|
||||
}
|
||||
|
||||
public class Buffer<T> : Buffer where T : unmanaged
|
||||
{
|
||||
protected internal Buffer(GraphicsDevice device, int size, BufferFlags bufferFlags, GraphicsHeapType heapType = GraphicsHeapType.Default) : base(device)
|
||||
{
|
||||
ElementSize = Unsafe.SizeOf<T>();
|
||||
ElementCount = size / ElementSize;
|
||||
|
||||
InitializeFrom(new BufferDescription(size, bufferFlags, heapType));
|
||||
}
|
||||
|
||||
public int ElementSize { get; }
|
||||
|
||||
public T[] GetData() => GetData<T>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public struct BufferDescription
|
||||
{
|
||||
public BufferDescription(int sizeInBytes, BufferFlags bufferFlags, GraphicsHeapType heapType)
|
||||
{
|
||||
SizeInBytes = sizeInBytes;
|
||||
Flags = bufferFlags;
|
||||
HeapType = heapType;
|
||||
}
|
||||
|
||||
public int SizeInBytes;
|
||||
|
||||
public BufferFlags Flags;
|
||||
|
||||
public GraphicsHeapType HeapType;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using System;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
[Flags]
|
||||
public enum BufferFlags
|
||||
{
|
||||
None = 0,
|
||||
ConstantBuffer = 1,
|
||||
IndexBuffer = 2,
|
||||
VertexBuffer = 4,
|
||||
RenderTarget = 8,
|
||||
ShaderResource = 16,
|
||||
UnorderedAccess = 32,
|
||||
StructuredBuffer = 64,
|
||||
RawBuffer = 512,
|
||||
ArgumentBuffer = 1024
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
[Flags]
|
||||
public enum ClearFlags
|
||||
{
|
||||
None = 0,
|
||||
FlagsDepth = 1,
|
||||
FlagsStencil = 2
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
internal sealed class CommandAllocatorPool : IDisposable
|
||||
{
|
||||
private readonly Queue<(CommandAllocator, long)> commandAllocatorQueue = new Queue<(CommandAllocator, long)>();
|
||||
|
||||
public CommandAllocatorPool(GraphicsDevice device, CommandListType commandListType)
|
||||
{
|
||||
GraphicsDevice = device;
|
||||
CommandListType = commandListType;
|
||||
}
|
||||
|
||||
public CommandListType CommandListType { get; }
|
||||
|
||||
public GraphicsDevice GraphicsDevice { get; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (commandAllocatorQueue)
|
||||
{
|
||||
foreach ((CommandAllocator commandAllocator, long _) in commandAllocatorQueue)
|
||||
{
|
||||
commandAllocator.Dispose();
|
||||
}
|
||||
|
||||
commandAllocatorQueue.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
public void Enqueue(CommandAllocator commandAllocator, long fenceValue)
|
||||
{
|
||||
lock (commandAllocatorQueue)
|
||||
{
|
||||
commandAllocatorQueue.Enqueue((commandAllocator, fenceValue));
|
||||
}
|
||||
}
|
||||
|
||||
public CommandAllocator GetCommandAllocator()
|
||||
{
|
||||
lock (commandAllocatorQueue)
|
||||
{
|
||||
if (commandAllocatorQueue.Count > 0)
|
||||
{
|
||||
(CommandAllocator commandAllocator, long fenceValue) = commandAllocatorQueue.Peek();
|
||||
|
||||
long completedValue = CommandListType switch
|
||||
{
|
||||
CommandListType.Bundle => GraphicsDevice.NativeDirectFence.CompletedValue,
|
||||
CommandListType.Compute => GraphicsDevice.NativeComputeFence.CompletedValue,
|
||||
CommandListType.Copy => GraphicsDevice.NativeCopyFence.CompletedValue,
|
||||
CommandListType.Direct => GraphicsDevice.NativeDirectFence.CompletedValue,
|
||||
_ => throw new NotSupportedException("This command list type is not supported.")
|
||||
};
|
||||
|
||||
if (fenceValue <= completedValue)
|
||||
{
|
||||
commandAllocatorQueue.Dequeue();
|
||||
commandAllocator.Reset();
|
||||
|
||||
return commandAllocator;
|
||||
}
|
||||
}
|
||||
|
||||
return GraphicsDevice.NativeDevice.CreateCommandAllocator((SharpDX.Direct3D12.CommandListType)CommandListType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using SharpDX.Direct3D;
|
||||
using SharpDX.Direct3D12;
|
||||
using SharpDX.Mathematics.Interop;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public sealed class CommandList : IDisposable
|
||||
{
|
||||
private const int MaxRenderTargetCount = 8;
|
||||
private const int MaxViewportAndScissorRectangleCount = 16;
|
||||
|
||||
private readonly CompiledCommandList currentCommandList;
|
||||
|
||||
public CommandList(GraphicsDevice device, CommandListType commandListType)
|
||||
{
|
||||
GraphicsDevice = device;
|
||||
CommandListType = commandListType;
|
||||
|
||||
CommandAllocator commandAllocator = GetCommandAllocator();
|
||||
|
||||
GraphicsCommandList nativeCommandList = GraphicsDevice.NativeDevice.CreateCommandList((SharpDX.Direct3D12.CommandListType)CommandListType, commandAllocator, null);
|
||||
currentCommandList = new CompiledCommandList(this, commandAllocator, nativeCommandList);
|
||||
|
||||
SetDescriptorHeaps(GraphicsDevice.ShaderResourceViewAllocator.DescriptorHeap);
|
||||
}
|
||||
|
||||
public CommandListType CommandListType { get; }
|
||||
|
||||
public Texture? DepthStencilBuffer { get; private set; }
|
||||
|
||||
public GraphicsDevice GraphicsDevice { get; }
|
||||
|
||||
public Texture[] RenderTargets { get; private set; } = Array.Empty<Texture>();
|
||||
|
||||
public RawRectangle[] ScissorRectangles { get; private set; } = Array.Empty<RawRectangle>();
|
||||
|
||||
public RawViewportF[] Viewports { get; private set; } = Array.Empty<RawViewportF>();
|
||||
|
||||
public PrimitiveTopology PrimitiveTopology { set => currentCommandList.NativeCommandList.PrimitiveTopology = value; }
|
||||
|
||||
public void BeginRenderPass()
|
||||
{
|
||||
BeginRenderPass(DepthStencilBuffer, RenderTargets);
|
||||
}
|
||||
|
||||
public void BeginRenderPass(Texture? depthStencilView, params Texture[] renderTargetViews)
|
||||
{
|
||||
RenderPassRenderTargetDescription[] renderPassRenderTargetDescriptions = new RenderPassRenderTargetDescription[renderTargetViews.Length];
|
||||
|
||||
RenderPassBeginningAccess renderPassBeginningAccessPreserve = new RenderPassBeginningAccess { Type = RenderPassBeginningAccessType.Preserve };
|
||||
RenderPassEndingAccess renderPassEndingAccessPreserve = new RenderPassEndingAccess { Type = RenderPassEndingAccessType.Preserve };
|
||||
|
||||
for (int i = 0; i < renderTargetViews.Length; i++)
|
||||
{
|
||||
RenderPassRenderTargetDescription renderPassRenderTargetDescription = new RenderPassRenderTargetDescription
|
||||
{
|
||||
BeginningAccess = renderPassBeginningAccessPreserve,
|
||||
EndingAccess = renderPassEndingAccessPreserve,
|
||||
CpuDescriptor = renderTargetViews[i].NativeCpuDescriptorHandle
|
||||
};
|
||||
|
||||
renderPassRenderTargetDescriptions[i] = renderPassRenderTargetDescription;
|
||||
}
|
||||
|
||||
RenderPassBeginningAccess renderPassBeginningAccessNoAccess = new RenderPassBeginningAccess { Type = RenderPassBeginningAccessType.NoAccess };
|
||||
RenderPassEndingAccess renderPassEndingAccessNoAccess = new RenderPassEndingAccess { Type = RenderPassEndingAccessType.NoAccess };
|
||||
|
||||
RenderPassDepthStencilDescription? renderPassDepthStencilDescription = null;
|
||||
|
||||
if (depthStencilView != null)
|
||||
{
|
||||
renderPassDepthStencilDescription = new RenderPassDepthStencilDescription
|
||||
{
|
||||
DepthBeginningAccess = renderPassBeginningAccessNoAccess,
|
||||
DepthEndingAccess = renderPassEndingAccessNoAccess,
|
||||
StencilBeginningAccess = renderPassBeginningAccessNoAccess,
|
||||
StencilEndingAccess = renderPassEndingAccessNoAccess,
|
||||
CpuDescriptor = depthStencilView.NativeCpuDescriptorHandle,
|
||||
};
|
||||
}
|
||||
|
||||
BeginRenderPass(renderTargetViews.Length, renderPassRenderTargetDescriptions, renderPassDepthStencilDescription, RenderPassFlags.None);
|
||||
}
|
||||
|
||||
public void BeginRenderPass(int numRenderTargets, RenderPassRenderTargetDescription[] renderTargetsRef, RenderPassDepthStencilDescription? depthStencilRef, RenderPassFlags flags)
|
||||
{
|
||||
using GraphicsCommandList4 commandList = currentCommandList.NativeCommandList.QueryInterface<GraphicsCommandList4>();
|
||||
commandList.BeginRenderPass(numRenderTargets, renderTargetsRef, depthStencilRef, flags);
|
||||
}
|
||||
|
||||
public void EndRenderPass()
|
||||
{
|
||||
using GraphicsCommandList4 commandList = currentCommandList.NativeCommandList.QueryInterface<GraphicsCommandList4>();
|
||||
commandList.EndRenderPass();
|
||||
}
|
||||
|
||||
public void Clear(Texture depthStencilBuffer, ClearFlags clearFlags, float depth = 1, byte stencil = 0)
|
||||
{
|
||||
currentCommandList.NativeCommandList.ClearDepthStencilView(depthStencilBuffer.NativeCpuDescriptorHandle, (SharpDX.Direct3D12.ClearFlags)clearFlags, depth, stencil);
|
||||
}
|
||||
|
||||
public unsafe void Clear(Texture renderTarget, Vector4 color)
|
||||
{
|
||||
currentCommandList.NativeCommandList.ClearRenderTargetView(renderTarget.NativeCpuDescriptorHandle, *(RawColor4*)&color);
|
||||
}
|
||||
|
||||
public void ClearState()
|
||||
{
|
||||
Array.Clear(Viewports, 0, Viewports.Length);
|
||||
Array.Clear(ScissorRectangles, 0, ScissorRectangles.Length);
|
||||
|
||||
Texture? depthStencilBuffer = GraphicsDevice.Presenter?.DepthStencilBuffer;
|
||||
Texture? backBuffer = GraphicsDevice.Presenter?.BackBuffer;
|
||||
|
||||
if (backBuffer != null)
|
||||
{
|
||||
SetRenderTargets(depthStencilBuffer, backBuffer);
|
||||
SetViewports(new RawViewportF { X = 0, Y = 0, Width = backBuffer.Width, Height = backBuffer.Height, MaxDepth = 1.0f });
|
||||
SetScissorRectangles(new RawRectangle { Right = backBuffer.Width, Bottom = backBuffer.Height });
|
||||
}
|
||||
else if (depthStencilBuffer != null)
|
||||
{
|
||||
SetRenderTargets(depthStencilBuffer);
|
||||
SetViewports(new RawViewportF { X = 0, Y = 0, Width = depthStencilBuffer.Width, Height = depthStencilBuffer.Height, MaxDepth = 1.0f });
|
||||
SetScissorRectangles(new RawRectangle { Right = depthStencilBuffer.Width, Bottom = depthStencilBuffer.Height });
|
||||
}
|
||||
else
|
||||
{
|
||||
SetRenderTargets(null);
|
||||
}
|
||||
}
|
||||
|
||||
public CompiledCommandList Close()
|
||||
{
|
||||
//foreach (var renderTarget in RenderTargets)
|
||||
//{
|
||||
// ResourceBarrierTransition(renderTarget, ResourceStates.RenderTarget, ResourceStates.Present);
|
||||
//}
|
||||
|
||||
currentCommandList.NativeCommandList.Close();
|
||||
|
||||
return currentCommandList;
|
||||
}
|
||||
|
||||
public void CopyBufferRegion(GraphicsResource source, long sourceOffset, GraphicsResource destination, long destinationOffset, long numBytes)
|
||||
{
|
||||
currentCommandList.NativeCommandList.CopyBufferRegion(destination.NativeResource, destinationOffset, source.NativeResource, sourceOffset, numBytes);
|
||||
}
|
||||
|
||||
public void CopyResource(GraphicsResource source, GraphicsResource destination)
|
||||
{
|
||||
currentCommandList.NativeCommandList.CopyResource(destination.NativeResource, source.NativeResource);
|
||||
}
|
||||
|
||||
public void CopyTextureRegion(TextureCopyLocation source, TextureCopyLocation destination)
|
||||
{
|
||||
currentCommandList.NativeCommandList.CopyTextureRegion(destination, 0, 0, 0, source, null);
|
||||
}
|
||||
|
||||
public void Dispatch(int threadGroupCountX, int threadGroupCountY, int threadGroupCountZ)
|
||||
{
|
||||
currentCommandList.NativeCommandList.Dispatch(threadGroupCountX, threadGroupCountY, threadGroupCountZ);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
switch (CommandListType)
|
||||
{
|
||||
case CommandListType.Bundle:
|
||||
GraphicsDevice.BundleAllocatorPool.Enqueue(currentCommandList.NativeCommandAllocator, GraphicsDevice.NextDirectFenceValue - 1);
|
||||
break;
|
||||
case CommandListType.Direct:
|
||||
GraphicsDevice.DirectAllocatorPool.Enqueue(currentCommandList.NativeCommandAllocator, GraphicsDevice.NextDirectFenceValue - 1);
|
||||
break;
|
||||
case CommandListType.Compute:
|
||||
GraphicsDevice.ComputeAllocatorPool.Enqueue(currentCommandList.NativeCommandAllocator, GraphicsDevice.NextComputeFenceValue - 1);
|
||||
break;
|
||||
case CommandListType.Copy:
|
||||
GraphicsDevice.CopyAllocatorPool.Enqueue(currentCommandList.NativeCommandAllocator, GraphicsDevice.NextCopyFenceValue - 1);
|
||||
break;
|
||||
default:
|
||||
throw new NotSupportedException("This command list type is not supported.");
|
||||
}
|
||||
|
||||
currentCommandList.NativeCommandList.Dispose();
|
||||
}
|
||||
|
||||
public void DrawIndexedInstanced(int indexCountPerInstance, int instanceCount, int startIndexLocation = 0, int baseVertexLocation = 0, int startInstanceLocation = 0)
|
||||
{
|
||||
currentCommandList.NativeCommandList.DrawIndexedInstanced(indexCountPerInstance, instanceCount, startIndexLocation, baseVertexLocation, startInstanceLocation);
|
||||
}
|
||||
|
||||
public void DrawInstanced(int vertexCountPerInstance, int instanceCount, int startVertexLocation = 0, int startInstanceLocation = 0)
|
||||
{
|
||||
currentCommandList.NativeCommandList.DrawInstanced(vertexCountPerInstance, instanceCount, startVertexLocation, startInstanceLocation);
|
||||
}
|
||||
|
||||
public void ExecuteBundle(CompiledCommandList commandList)
|
||||
{
|
||||
if (currentCommandList != commandList && commandList.Builder.CommandListType == CommandListType.Bundle)
|
||||
{
|
||||
currentCommandList.NativeCommandList.ExecuteBundle(commandList.NativeCommandList);
|
||||
}
|
||||
}
|
||||
|
||||
public void Flush(bool wait = false)
|
||||
{
|
||||
GraphicsDevice.ExecuteCommandLists(wait, Close());
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
CommandAllocator commandAllocator = GetCommandAllocator();
|
||||
|
||||
currentCommandList.NativeCommandAllocator = commandAllocator;
|
||||
currentCommandList.NativeCommandList.Reset(currentCommandList.NativeCommandAllocator, null);
|
||||
|
||||
SetDescriptorHeaps(GraphicsDevice.ShaderResourceViewAllocator.DescriptorHeap);
|
||||
}
|
||||
|
||||
public void ResourceBarrierTransition(GraphicsResource resource, ResourceStates stateBefore, ResourceStates stateAfter)
|
||||
{
|
||||
currentCommandList.NativeCommandList.ResourceBarrierTransition(resource.NativeResource, stateBefore, stateAfter);
|
||||
}
|
||||
|
||||
public void SetDescriptorHeaps(params DescriptorHeap[] descriptorHeaps)
|
||||
{
|
||||
if (CommandListType != CommandListType.Copy)
|
||||
{
|
||||
currentCommandList.NativeCommandList.SetDescriptorHeaps(descriptorHeaps);
|
||||
}
|
||||
}
|
||||
|
||||
public void SetGraphicsRoot32BitConstant(int rootParameterIndex, int srcData, int destOffsetIn32BitValues)
|
||||
{
|
||||
currentCommandList.NativeCommandList.SetGraphicsRoot32BitConstant(rootParameterIndex, srcData, destOffsetIn32BitValues);
|
||||
}
|
||||
|
||||
public void SetGraphicsRootDescriptorTable(int rootParameterIndex, GraphicsResource resource)
|
||||
{
|
||||
SetGraphicsRootDescriptorTable(rootParameterIndex, resource.NativeGpuDescriptorHandle);
|
||||
}
|
||||
|
||||
public void SetGraphicsRootDescriptorTable(int rootParameterIndex, GpuDescriptorHandle baseDescriptor)
|
||||
{
|
||||
currentCommandList.NativeCommandList.SetGraphicsRootDescriptorTable(rootParameterIndex, baseDescriptor);
|
||||
}
|
||||
|
||||
public void SetGraphicsRootSignature(RootSignature rootSignature)
|
||||
{
|
||||
currentCommandList.NativeCommandList.SetGraphicsRootSignature(rootSignature);
|
||||
}
|
||||
|
||||
public void SetComputeRoot32BitConstant(int rootParameterIndex, int srcData, int destOffsetIn32BitValues)
|
||||
{
|
||||
currentCommandList.NativeCommandList.SetComputeRoot32BitConstant(rootParameterIndex, srcData, destOffsetIn32BitValues);
|
||||
}
|
||||
|
||||
public void SetComputeRootDescriptorTable(int rootParameterIndex, GraphicsResource resource)
|
||||
{
|
||||
SetComputeRootDescriptorTable(rootParameterIndex, resource.NativeGpuDescriptorHandle);
|
||||
}
|
||||
|
||||
public void SetComputeRootDescriptorTable(int rootParameterIndex, GpuDescriptorHandle baseDescriptor)
|
||||
{
|
||||
currentCommandList.NativeCommandList.SetComputeRootDescriptorTable(rootParameterIndex, baseDescriptor);
|
||||
}
|
||||
|
||||
public void SetComputeRootSignature(RootSignature rootSignature)
|
||||
{
|
||||
currentCommandList.NativeCommandList.SetComputeRootSignature(rootSignature);
|
||||
}
|
||||
|
||||
public void SetComputeRootUnorderedAccessView(int rootParameterIndex, GraphicsResource resource)
|
||||
{
|
||||
currentCommandList.NativeCommandList.SetComputeRootUnorderedAccessView(rootParameterIndex, resource.NativeResource.GPUVirtualAddress);
|
||||
}
|
||||
|
||||
public void SetIndexBuffer(IndexBufferView? indexBufferView)
|
||||
{
|
||||
currentCommandList.NativeCommandList.SetIndexBuffer(indexBufferView);
|
||||
}
|
||||
|
||||
public void SetPipelineState(PipelineState pipelineState)
|
||||
{
|
||||
if (pipelineState.IsCompute)
|
||||
{
|
||||
SetComputeRootSignature(pipelineState.RootSignature);
|
||||
}
|
||||
else
|
||||
{
|
||||
SetGraphicsRootSignature(pipelineState.RootSignature);
|
||||
}
|
||||
|
||||
currentCommandList.NativeCommandList.PipelineState = pipelineState.NativePipelineState;
|
||||
}
|
||||
|
||||
public void SetRenderTargets(Texture? depthStencilView, params Texture[] renderTargetViews)
|
||||
{
|
||||
DepthStencilBuffer = depthStencilView;
|
||||
|
||||
if (renderTargetViews.Length > MaxRenderTargetCount)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(renderTargetViews), renderTargetViews.Length, $"The maximum number of render targets is {MaxRenderTargetCount}.");
|
||||
}
|
||||
|
||||
if (RenderTargets.Length != renderTargetViews.Length)
|
||||
{
|
||||
RenderTargets = new Texture[renderTargetViews.Length];
|
||||
}
|
||||
|
||||
renderTargetViews.CopyTo(RenderTargets, 0);
|
||||
|
||||
CpuDescriptorHandle[] renderTargetDescriptors = new CpuDescriptorHandle[renderTargetViews.Length];
|
||||
|
||||
for (int i = 0; i < renderTargetViews.Length; i++)
|
||||
{
|
||||
//ResourceBarrierTransition(renderTargetViews[i], ResourceStates.Present, ResourceStates.RenderTarget);
|
||||
renderTargetDescriptors[i] = renderTargetViews[i].NativeCpuDescriptorHandle;
|
||||
}
|
||||
|
||||
currentCommandList.NativeCommandList.SetRenderTargets(renderTargetDescriptors, depthStencilView?.NativeCpuDescriptorHandle);
|
||||
}
|
||||
|
||||
public void SetScissorRectangles(params RawRectangle[] scissorRectangles)
|
||||
{
|
||||
if (scissorRectangles.Length > MaxViewportAndScissorRectangleCount)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(scissorRectangles), scissorRectangles.Length, $"The maximum number of scissor rectangles is {MaxViewportAndScissorRectangleCount}.");
|
||||
}
|
||||
|
||||
if (ScissorRectangles.Length != scissorRectangles.Length)
|
||||
{
|
||||
ScissorRectangles = new RawRectangle[scissorRectangles.Length];
|
||||
}
|
||||
|
||||
scissorRectangles.CopyTo(ScissorRectangles, 0);
|
||||
|
||||
currentCommandList.NativeCommandList.SetScissorRectangles(scissorRectangles);
|
||||
}
|
||||
|
||||
public void SetVertexBuffers(int startSlot, params VertexBufferView[] vertexBufferViews)
|
||||
{
|
||||
currentCommandList.NativeCommandList.SetVertexBuffers(startSlot, vertexBufferViews);
|
||||
}
|
||||
|
||||
public void SetViewports(params RawViewportF[] viewports)
|
||||
{
|
||||
if (viewports.Length > MaxViewportAndScissorRectangleCount)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(viewports), viewports.Length, $"The maximum number of viewporst is {MaxViewportAndScissorRectangleCount}.");
|
||||
}
|
||||
|
||||
if (Viewports.Length != viewports.Length)
|
||||
{
|
||||
Viewports = new RawViewportF[viewports.Length];
|
||||
}
|
||||
|
||||
viewports.CopyTo(Viewports, 0);
|
||||
|
||||
currentCommandList.NativeCommandList.SetViewports(viewports);
|
||||
}
|
||||
|
||||
private CommandAllocator GetCommandAllocator() => CommandListType switch
|
||||
{
|
||||
CommandListType.Bundle => GraphicsDevice.BundleAllocatorPool.GetCommandAllocator(),
|
||||
CommandListType.Compute => GraphicsDevice.ComputeAllocatorPool.GetCommandAllocator(),
|
||||
CommandListType.Copy => GraphicsDevice.CopyAllocatorPool.GetCommandAllocator(),
|
||||
CommandListType.Direct => GraphicsDevice.DirectAllocatorPool.GetCommandAllocator(),
|
||||
_ => throw new NotSupportedException("This command list type is not supported.")
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System;
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public enum CommandListType
|
||||
{
|
||||
Direct,
|
||||
Bundle,
|
||||
Compute,
|
||||
Copy,
|
||||
VideoDecode,
|
||||
VideoProcess
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public sealed class CompiledCommandList
|
||||
{
|
||||
internal CompiledCommandList(CommandList builder, CommandAllocator nativeCommandAllocator, GraphicsCommandList nativeCommandList)
|
||||
{
|
||||
Builder = builder;
|
||||
NativeCommandAllocator = nativeCommandAllocator;
|
||||
NativeCommandList = nativeCommandList;
|
||||
}
|
||||
|
||||
internal CommandList Builder { get; set; }
|
||||
|
||||
internal CommandAllocator NativeCommandAllocator { get; set; }
|
||||
|
||||
internal GraphicsCommandList NativeCommandList { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using SharpDX;
|
||||
using SharpDX.DXGI;
|
||||
using Windows.UI.Core;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public class CoreWindowSwapChainGraphicsPresenter : SwapChainGraphicsPresenter
|
||||
{
|
||||
private readonly CoreWindow coreWindow;
|
||||
|
||||
public CoreWindowSwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters, CoreWindow coreWindow)
|
||||
: base(device, presentationParameters, CreateSwapChain(device, presentationParameters, coreWindow))
|
||||
{
|
||||
this.coreWindow = coreWindow;
|
||||
}
|
||||
|
||||
private static SwapChain3 CreateSwapChain(GraphicsDevice device, PresentationParameters presentationParameters, CoreWindow coreWindow)
|
||||
{
|
||||
SwapChainDescription1 swapChainDescription = new SwapChainDescription1
|
||||
{
|
||||
Width = presentationParameters.BackBufferWidth,
|
||||
Height = presentationParameters.BackBufferHeight,
|
||||
SampleDescription = new SampleDescription(1, 0),
|
||||
Stereo = presentationParameters.Stereo,
|
||||
Usage = Usage.RenderTargetOutput,
|
||||
BufferCount = BufferCount,
|
||||
Scaling = Scaling.Stretch,
|
||||
SwapEffect = SwapEffect.FlipSequential,
|
||||
Format = (Format)presentationParameters.BackBufferFormat,
|
||||
Flags = SwapChainFlags.None,
|
||||
AlphaMode = AlphaMode.Unspecified
|
||||
};
|
||||
|
||||
using Factory4 factory = new Factory4();
|
||||
using ComObject window = new ComObject(coreWindow);
|
||||
using SwapChain1 tempSwapChain = new SwapChain1(factory, device.NativeDirectCommandQueue, window, ref swapChainDescription);
|
||||
|
||||
return tempSwapChain.QueryInterface<SwapChain3>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using System;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
internal sealed class DescriptorAllocator : IDisposable
|
||||
{
|
||||
private const int DescriptorsPerHeap = 4096;
|
||||
|
||||
private readonly object allocatorLock = new object();
|
||||
private readonly int descriptorSize;
|
||||
|
||||
private CpuDescriptorHandle currentCpuHandle;
|
||||
private GpuDescriptorHandle currentGpuHandle;
|
||||
private int remainingHandles;
|
||||
|
||||
public DescriptorAllocator(GraphicsDevice device, DescriptorHeapType descriptorHeapType, DescriptorHeapFlags descriptorHeapFlags = DescriptorHeapFlags.None, int descriptorCount = DescriptorsPerHeap)
|
||||
{
|
||||
if (descriptorCount < 1 || descriptorCount > DescriptorsPerHeap)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(descriptorCount), $"Descriptor count must be between 1 and {DescriptorsPerHeap}.");
|
||||
}
|
||||
|
||||
descriptorSize = device.NativeDevice.GetDescriptorHandleIncrementSize(descriptorHeapType);
|
||||
|
||||
DescriptorHeapDescription rtvHeapDescription = new DescriptorHeapDescription
|
||||
{
|
||||
DescriptorCount = descriptorCount,
|
||||
Flags = descriptorHeapFlags,
|
||||
Type = descriptorHeapType
|
||||
};
|
||||
|
||||
DescriptorHeap = device.NativeDevice.CreateDescriptorHeap(rtvHeapDescription);
|
||||
|
||||
remainingHandles = descriptorCount;
|
||||
currentCpuHandle = DescriptorHeap.CPUDescriptorHandleForHeapStart;
|
||||
currentGpuHandle = DescriptorHeap.GPUDescriptorHandleForHeapStart;
|
||||
}
|
||||
|
||||
public DescriptorHeap DescriptorHeap { get; }
|
||||
|
||||
public (CpuDescriptorHandle, GpuDescriptorHandle) Allocate(int count)
|
||||
{
|
||||
if (count < 1 || (count > remainingHandles && remainingHandles != 0))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(count), "Count must be between 1 and the remaining handles if the remaining handles are not 0.");
|
||||
}
|
||||
|
||||
lock (allocatorLock)
|
||||
{
|
||||
if (remainingHandles == 0)
|
||||
{
|
||||
remainingHandles = DescriptorHeap.Description.DescriptorCount;
|
||||
currentCpuHandle = DescriptorHeap.CPUDescriptorHandleForHeapStart;
|
||||
currentGpuHandle = DescriptorHeap.GPUDescriptorHandleForHeapStart;
|
||||
}
|
||||
|
||||
CpuDescriptorHandle cpuDescriptorHandle = currentCpuHandle;
|
||||
GpuDescriptorHandle gpuDescriptorHandle = currentGpuHandle;
|
||||
|
||||
currentCpuHandle += descriptorSize * count;
|
||||
currentGpuHandle += descriptorSize * count;
|
||||
remainingHandles -= count;
|
||||
|
||||
return (cpuDescriptorHandle, gpuDescriptorHandle);
|
||||
}
|
||||
}
|
||||
|
||||
public (CpuDescriptorHandle, GpuDescriptorHandle) AllocateSlot(int slot)
|
||||
{
|
||||
if (slot < 0 || slot > DescriptorHeap.Description.DescriptorCount - 1)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(slot), "Slot must be between 0 and the descript count - 1.");
|
||||
}
|
||||
|
||||
lock (allocatorLock)
|
||||
{
|
||||
CpuDescriptorHandle cpuDescriptorHandle = DescriptorHeap.CPUDescriptorHandleForHeapStart + descriptorSize * slot;
|
||||
GpuDescriptorHandle gpuDescriptorHandle = DescriptorHeap.GPUDescriptorHandleForHeapStart + descriptorSize * slot;
|
||||
|
||||
return (cpuDescriptorHandle, gpuDescriptorHandle);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
DescriptorHeap.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using SharpDX;
|
||||
using SharpDX.DXGI;
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using Windows.Graphics.DirectX.Direct3D11;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
internal static class Direct3DInterop
|
||||
{
|
||||
private static readonly Guid ID3D11Resource = new Guid("DC8E63F3-D12B-4952-B47B-5E45026A862D");
|
||||
|
||||
[ComImport]
|
||||
[Guid("A9B3D012-3DF2-4EE3-B8D1-8695F457D3C1")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
[ComVisible(true)]
|
||||
private interface IDirect3DDxgiInterfaceAccess : IDisposable
|
||||
{
|
||||
IntPtr GetInterface([In] ref Guid iid);
|
||||
}
|
||||
|
||||
internal static IDirect3DDevice CreateDirect3DDevice(Device dxgiDevice)
|
||||
{
|
||||
Result result = CreateDirect3D11DeviceFromDXGIDevice(dxgiDevice.NativePointer, out IntPtr graphicsDevice);
|
||||
|
||||
if (result.Failure) throw new InvalidOperationException(result.Code.ToString());
|
||||
|
||||
IDirect3DDevice d3DInteropDevice = (IDirect3DDevice)Marshal.GetObjectForIUnknown(graphicsDevice);
|
||||
Marshal.Release(graphicsDevice);
|
||||
|
||||
return d3DInteropDevice;
|
||||
}
|
||||
|
||||
internal static IDirect3DSurface CreateDirect3DSurface(Surface dxgiSurface)
|
||||
{
|
||||
Result result = CreateDirect3D11SurfaceFromDXGISurface(dxgiSurface.NativePointer, out IntPtr graphicsSurface);
|
||||
|
||||
if (result.Failure) throw new InvalidOperationException(result.Code.ToString());
|
||||
|
||||
IDirect3DSurface d3DSurface = (IDirect3DSurface)Marshal.GetObjectForIUnknown(graphicsSurface);
|
||||
Marshal.Release(graphicsSurface);
|
||||
|
||||
return d3DSurface;
|
||||
}
|
||||
|
||||
internal static Device CreateDXGIDevice(IDirect3DDevice direct3DDevice)
|
||||
{
|
||||
IDirect3DDxgiInterfaceAccess dxgiDeviceInterfaceAccess = (IDirect3DDxgiInterfaceAccess)direct3DDevice;
|
||||
IntPtr device = dxgiDeviceInterfaceAccess.GetInterface(ID3D11Resource);
|
||||
|
||||
return new Device(device);
|
||||
}
|
||||
|
||||
internal static Surface CreateDXGISurface(IDirect3DSurface direct3DSurface)
|
||||
{
|
||||
IDirect3DDxgiInterfaceAccess dxgiSurfaceInterfaceAccess = (IDirect3DDxgiInterfaceAccess)direct3DSurface;
|
||||
IntPtr surface = dxgiSurfaceInterfaceAccess.GetInterface(ID3D11Resource);
|
||||
|
||||
return new Surface(surface);
|
||||
}
|
||||
|
||||
[DllImport("d3d11.dll", EntryPoint = "CreateDirect3D11DeviceFromDXGIDevice",
|
||||
SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
|
||||
private static extern Result CreateDirect3D11DeviceFromDXGIDevice(IntPtr dxgiDevice, out IntPtr graphicsDevice);
|
||||
|
||||
[DllImport("d3d11.dll", EntryPoint = "CreateDirect3D11SurfaceFromDXGISurface",
|
||||
SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
|
||||
private static extern Result CreateDirect3D11SurfaceFromDXGISurface(IntPtr dxgiSurface, out IntPtr graphicsSurface);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<LangVersion>8.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="SharpDX.Direct2D1" Version="4.2.1-beta0-gab36f12303" />
|
||||
<PackageReference Include="SharpDX.Direct3D11" Version="4.2.1-beta0-gab36f12303" />
|
||||
<PackageReference Include="SharpDX.Direct3D12" Version="4.2.1-beta0-gab36f12303" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DirectX12GameEngine.Core\DirectX12GameEngine.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,318 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using DirectX12GameEngine.Core;
|
||||
using SharpDX.Direct3D;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public sealed class GraphicsDevice : IDisposable, ICollector
|
||||
{
|
||||
private readonly AutoResetEvent fenceEvent = new AutoResetEvent(false);
|
||||
private SharpDX.Direct3D11.Device? nativeDirect3D11Device;
|
||||
|
||||
public GraphicsDevice(FeatureLevel minFeatureLevel = FeatureLevel.Level_11_0, bool enableDebugLayer = false)
|
||||
{
|
||||
#if DEBUG
|
||||
if (enableDebugLayer)
|
||||
{
|
||||
DebugInterface.Get().EnableDebugLayer();
|
||||
}
|
||||
#endif
|
||||
FeatureLevel = minFeatureLevel < FeatureLevel.Level_11_0 ? FeatureLevel.Level_11_0 : minFeatureLevel;
|
||||
|
||||
NativeDevice = new Device(null, FeatureLevel);
|
||||
|
||||
NativeComputeCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Compute));
|
||||
NativeCopyCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Copy));
|
||||
NativeDirectCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Direct));
|
||||
|
||||
BundleAllocatorPool = new CommandAllocatorPool(this, CommandListType.Bundle);
|
||||
ComputeAllocatorPool = new CommandAllocatorPool(this, CommandListType.Compute);
|
||||
CopyAllocatorPool = new CommandAllocatorPool(this, CommandListType.Copy);
|
||||
DirectAllocatorPool = new CommandAllocatorPool(this, CommandListType.Direct);
|
||||
|
||||
NativeComputeFence = NativeDevice.CreateFence(0, FenceFlags.None);
|
||||
NativeCopyFence = NativeDevice.CreateFence(0, FenceFlags.None);
|
||||
NativeDirectFence = NativeDevice.CreateFence(0, FenceFlags.None);
|
||||
|
||||
DepthStencilViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.DepthStencilView, descriptorCount: 1);
|
||||
RenderTargetViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.RenderTargetView, descriptorCount: 2);
|
||||
ShaderResourceViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, DescriptorHeapFlags.ShaderVisible);
|
||||
|
||||
CommandList = new CommandList(this, CommandListType.Direct);
|
||||
CommandList.Close();
|
||||
}
|
||||
|
||||
public CommandList CommandList { get; }
|
||||
|
||||
public ICollection<IDisposable> Disposables { get; } = new List<IDisposable>();
|
||||
|
||||
public FeatureLevel FeatureLevel { get; }
|
||||
|
||||
public GraphicsPresenter? Presenter { get; set; }
|
||||
|
||||
internal Queue<CommandList> CopyCommandLists { get; } = new Queue<CommandList>();
|
||||
|
||||
internal Device NativeDevice { get; }
|
||||
|
||||
internal SharpDX.Direct3D11.Device NativeDirect3D11Device => NativeDirect3D11Device ?? (nativeDirect3D11Device = SharpDX.Direct3D11.Device.CreateFromDirect3D12(
|
||||
NativeDevice, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, null, null, NativeDirectCommandQueue));
|
||||
|
||||
internal DescriptorAllocator DepthStencilViewAllocator { get; set; }
|
||||
|
||||
internal DescriptorAllocator RenderTargetViewAllocator { get; set; }
|
||||
|
||||
internal DescriptorAllocator ShaderResourceViewAllocator { get; set; }
|
||||
|
||||
internal CommandAllocatorPool BundleAllocatorPool { get; }
|
||||
|
||||
internal CommandAllocatorPool ComputeAllocatorPool { get; }
|
||||
|
||||
internal CommandAllocatorPool CopyAllocatorPool { get; }
|
||||
|
||||
internal CommandAllocatorPool DirectAllocatorPool { get; }
|
||||
|
||||
internal CommandQueue NativeComputeCommandQueue { get; }
|
||||
|
||||
internal CommandQueue NativeCopyCommandQueue { get; }
|
||||
|
||||
internal CommandQueue NativeDirectCommandQueue { get; }
|
||||
|
||||
internal Fence NativeComputeFence { get; }
|
||||
|
||||
internal Fence NativeCopyFence { get; }
|
||||
|
||||
internal Fence NativeDirectFence { get; }
|
||||
|
||||
internal long NextComputeFenceValue { get; private set; } = 1;
|
||||
|
||||
internal long NextCopyFenceValue { get; private set; } = 1;
|
||||
|
||||
internal long NextDirectFenceValue { get; private set; } = 1;
|
||||
|
||||
public void CopyDescriptors(int numDestDescriptorRanges, CpuDescriptorHandle[] destDescriptorRangeStartsRef, int[] destDescriptorRangeSizesRef, int numSrcDescriptorRanges, CpuDescriptorHandle[] srcDescriptorRangeStartsRef, int[] srcDescriptorRangeSizesRef, DescriptorHeapType descriptorHeapsType)
|
||||
{
|
||||
NativeDevice.CopyDescriptors(numDestDescriptorRanges, destDescriptorRangeStartsRef, destDescriptorRangeSizesRef, numSrcDescriptorRanges, srcDescriptorRangeStartsRef, srcDescriptorRangeSizesRef, descriptorHeapsType);
|
||||
}
|
||||
|
||||
public (CpuDescriptorHandle, GpuDescriptorHandle) CopyDescriptorsToOneDescriptorHandle(IEnumerable<GraphicsResource> resources)
|
||||
{
|
||||
return CopyDescriptorsToOneDescriptorHandle(resources.Select(t => t.NativeCpuDescriptorHandle).ToArray());
|
||||
}
|
||||
|
||||
public (CpuDescriptorHandle, GpuDescriptorHandle) CopyDescriptorsToOneDescriptorHandle(CpuDescriptorHandle[] descriptors)
|
||||
{
|
||||
if (descriptors.Length == 0) return default;
|
||||
|
||||
int[] srcDescriptorRangeStarts = new int[descriptors.Length];
|
||||
//Array.Fill(srcDescriptorRangeStarts, 1);
|
||||
|
||||
for (int i = 0; i < srcDescriptorRangeStarts.Length; i++)
|
||||
{
|
||||
srcDescriptorRangeStarts[i] = 1;
|
||||
}
|
||||
|
||||
var (cpuDescriptorHandle, gpuDescriptorHandle) = ShaderResourceViewAllocator.Allocate(descriptors.Length);
|
||||
|
||||
CopyDescriptors(
|
||||
1, new[] { cpuDescriptorHandle }, new[] { descriptors.Length },
|
||||
descriptors.Length, descriptors, srcDescriptorRangeStarts,
|
||||
DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
|
||||
|
||||
return (cpuDescriptorHandle, gpuDescriptorHandle);
|
||||
}
|
||||
|
||||
public RootSignature CreateRootSignature(RootSignatureDescription rootSignatureDescription)
|
||||
{
|
||||
return NativeDevice.CreateRootSignature(rootSignatureDescription.Serialize());
|
||||
}
|
||||
|
||||
public RootSignature CreateRootSignature(byte[] bytecode)
|
||||
{
|
||||
return NativeDevice.CreateRootSignature(bytecode);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
NativeDirectCommandQueue.Signal(NativeDirectFence, NextDirectFenceValue);
|
||||
NativeDirectCommandQueue.Wait(NativeDirectFence, NextDirectFenceValue);
|
||||
|
||||
CommandList.Dispose();
|
||||
|
||||
DepthStencilViewAllocator.Dispose();
|
||||
RenderTargetViewAllocator.Dispose();
|
||||
ShaderResourceViewAllocator.Dispose();
|
||||
|
||||
BundleAllocatorPool.Dispose();
|
||||
ComputeAllocatorPool.Dispose();
|
||||
CopyAllocatorPool.Dispose();
|
||||
DirectAllocatorPool.Dispose();
|
||||
|
||||
NativeComputeCommandQueue.Dispose();
|
||||
NativeCopyCommandQueue.Dispose();
|
||||
NativeDirectCommandQueue.Dispose();
|
||||
|
||||
NativeComputeFence.Dispose();
|
||||
NativeDirectFence.Dispose();
|
||||
NativeDirectFence.Dispose();
|
||||
|
||||
foreach (CommandList commandList in CopyCommandLists)
|
||||
{
|
||||
commandList.Dispose();
|
||||
}
|
||||
|
||||
foreach (IDisposable disposable in Disposables)
|
||||
{
|
||||
disposable.Dispose();
|
||||
}
|
||||
|
||||
nativeDirect3D11Device?.Dispose();
|
||||
|
||||
NativeDevice.Dispose();
|
||||
}
|
||||
|
||||
public void ExecuteCommandLists(bool wait, params CompiledCommandList[] commandLists)
|
||||
{
|
||||
Fence fence = commandLists[0].Builder.CommandListType switch
|
||||
{
|
||||
CommandListType.Direct => NativeDirectFence,
|
||||
CommandListType.Compute => NativeComputeFence,
|
||||
CommandListType.Copy => NativeCopyFence,
|
||||
_ => throw new NotSupportedException("This command list type is not supported.")
|
||||
};
|
||||
|
||||
long fenceValue = ExecuteCommandLists(commandLists);
|
||||
|
||||
if (wait)
|
||||
{
|
||||
WaitForFence(fence, fenceValue);
|
||||
}
|
||||
}
|
||||
|
||||
public long ExecuteCommandLists(params CompiledCommandList[] commandLists)
|
||||
{
|
||||
CommandAllocatorPool commandAllocatorPool;
|
||||
CommandQueue commandQueue;
|
||||
Fence fence;
|
||||
long fenceValue;
|
||||
|
||||
switch (commandLists[0].Builder.CommandListType)
|
||||
{
|
||||
case CommandListType.Compute:
|
||||
commandAllocatorPool = ComputeAllocatorPool;
|
||||
commandQueue = NativeComputeCommandQueue;
|
||||
|
||||
fence = NativeComputeFence;
|
||||
fenceValue = NextComputeFenceValue;
|
||||
NextDirectFenceValue++;
|
||||
break;
|
||||
case CommandListType.Copy:
|
||||
commandAllocatorPool = CopyAllocatorPool;
|
||||
commandQueue = NativeCopyCommandQueue;
|
||||
|
||||
fence = NativeCopyFence;
|
||||
fenceValue = NextCopyFenceValue;
|
||||
NextCopyFenceValue++;
|
||||
break;
|
||||
case CommandListType.Direct:
|
||||
commandAllocatorPool = DirectAllocatorPool;
|
||||
commandQueue = NativeDirectCommandQueue;
|
||||
|
||||
fence = NativeDirectFence;
|
||||
fenceValue = NextDirectFenceValue;
|
||||
NextDirectFenceValue++;
|
||||
break;
|
||||
default:
|
||||
throw new NotSupportedException("This command list type is not supported.");
|
||||
}
|
||||
|
||||
SharpDX.Direct3D12.CommandList[] nativeCommandLists = new SharpDX.Direct3D12.CommandList[commandLists.Length];
|
||||
|
||||
for (int i = 0; i < commandLists.Length; i++)
|
||||
{
|
||||
nativeCommandLists[i] = commandLists[i].NativeCommandList;
|
||||
commandAllocatorPool.Enqueue(commandLists[i].NativeCommandAllocator, fenceValue);
|
||||
}
|
||||
|
||||
commandQueue.ExecuteCommandLists(nativeCommandLists);
|
||||
commandQueue.Signal(fence, fenceValue);
|
||||
|
||||
return fenceValue;
|
||||
}
|
||||
|
||||
public CommandList GetOrCreateCopyCommandList()
|
||||
{
|
||||
CommandList commandList;
|
||||
|
||||
lock (CopyCommandLists)
|
||||
{
|
||||
if (CopyCommandLists.Count > 0)
|
||||
{
|
||||
commandList = CopyCommandLists.Dequeue();
|
||||
commandList.Reset();
|
||||
}
|
||||
else
|
||||
{
|
||||
commandList = new CommandList(this, CommandListType.Copy);
|
||||
}
|
||||
}
|
||||
|
||||
return commandList;
|
||||
}
|
||||
|
||||
public void EnqueueCopyCommandList(CommandList commandList)
|
||||
{
|
||||
lock (CopyCommandLists)
|
||||
{
|
||||
CopyCommandLists.Enqueue(commandList);
|
||||
}
|
||||
}
|
||||
|
||||
internal bool IsFenceComplete(Fence fence, long fenceValue)
|
||||
{
|
||||
return fenceValue <= fence.CompletedValue;
|
||||
}
|
||||
|
||||
internal void WaitForFence(Fence fence, long fenceValue)
|
||||
{
|
||||
if (IsFenceComplete(fence, fenceValue)) return;
|
||||
|
||||
lock (fence)
|
||||
{
|
||||
fence.SetEventOnCompletion(fenceValue, fenceEvent.SafeWaitHandle.DangerousGetHandle());
|
||||
fenceEvent.WaitOne();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal class D3DXUtilities
|
||||
{
|
||||
public const int ComponentMappingMask = 0x7;
|
||||
|
||||
public const int ComponentMappingShift = 3;
|
||||
|
||||
public const int ComponentMappingAlwaysSetBitAvoidingZeromemMistakes = 1 << (ComponentMappingShift * 4);
|
||||
|
||||
public static int ComponentMapping(int src0, int src1, int src2, int src3)
|
||||
{
|
||||
return ((src0) & ComponentMappingMask)
|
||||
| (((src1) & ComponentMappingMask) << ComponentMappingShift)
|
||||
| (((src2) & ComponentMappingMask) << (ComponentMappingShift * 2))
|
||||
| (((src3) & ComponentMappingMask) << (ComponentMappingShift * 3))
|
||||
| ComponentMappingAlwaysSetBitAvoidingZeromemMistakes;
|
||||
}
|
||||
|
||||
public static int DefaultComponentMapping()
|
||||
{
|
||||
return ComponentMapping(0, 1, 2, 3);
|
||||
}
|
||||
|
||||
public static int ComponentMapping(int ComponentToExtract, int Mapping)
|
||||
{
|
||||
return (Mapping >> (ComponentMappingShift * ComponentToExtract)) & ComponentMappingMask;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public abstract class GraphicsPresenter : IDisposable
|
||||
{
|
||||
protected GraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters)
|
||||
{
|
||||
GraphicsDevice = device;
|
||||
PresentationParameters = presentationParameters;
|
||||
|
||||
DepthStencilBuffer = CreateDepthStencilBuffer();
|
||||
}
|
||||
|
||||
public abstract Texture BackBuffer { get; }
|
||||
|
||||
public GraphicsDevice GraphicsDevice { get; }
|
||||
|
||||
public abstract object NativePresenter { get; }
|
||||
|
||||
public PresentationParameters PresentationParameters { get; }
|
||||
|
||||
public Texture DepthStencilBuffer { get; protected set; }
|
||||
|
||||
public virtual void BeginDraw(CommandList commandList)
|
||||
{
|
||||
}
|
||||
|
||||
public virtual void Dispose()
|
||||
{
|
||||
DepthStencilBuffer.Dispose();
|
||||
}
|
||||
|
||||
public abstract void Present();
|
||||
|
||||
public void Resize(int width, int height)
|
||||
{
|
||||
PresentationParameters.BackBufferWidth = width;
|
||||
PresentationParameters.BackBufferHeight = height;
|
||||
|
||||
ResizeBackBuffer(width, height);
|
||||
ResizeDepthStencilBuffer(width, height);
|
||||
}
|
||||
|
||||
protected virtual Texture CreateDepthStencilBuffer()
|
||||
{
|
||||
return Texture.New2D(GraphicsDevice,
|
||||
PresentationParameters.BackBufferWidth, PresentationParameters.BackBufferHeight, PresentationParameters.DepthStencilFormat,
|
||||
TextureFlags.DepthStencil, 1, PresentationParameters.Stereo ? 2 : 1);
|
||||
}
|
||||
|
||||
protected abstract void ResizeBackBuffer(int width, int height);
|
||||
|
||||
protected abstract void ResizeDepthStencilBuffer(int width, int height);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System;
|
||||
using SharpDX.Direct3D12;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public abstract class GraphicsResource : IDisposable
|
||||
{
|
||||
protected GraphicsResource()
|
||||
{
|
||||
}
|
||||
|
||||
protected GraphicsResource(GraphicsDevice device)
|
||||
{
|
||||
AttachToGraphicsDevice(device);
|
||||
}
|
||||
|
||||
#nullable disable
|
||||
public GraphicsDevice GraphicsDevice { get; private set; }
|
||||
#nullable restore
|
||||
|
||||
public IntPtr MappedResource { get; private set; }
|
||||
|
||||
#nullable disable
|
||||
protected internal Resource NativeResource { get; set; }
|
||||
#nullable restore
|
||||
|
||||
protected internal CpuDescriptorHandle NativeCpuDescriptorHandle { get; protected set; }
|
||||
|
||||
protected internal GpuDescriptorHandle NativeGpuDescriptorHandle { get; protected set; }
|
||||
|
||||
public void AttachToGraphicsDevice(GraphicsDevice device)
|
||||
{
|
||||
GraphicsDevice = device;
|
||||
}
|
||||
|
||||
public virtual void Dispose()
|
||||
{
|
||||
NativeResource.Dispose();
|
||||
}
|
||||
|
||||
public IntPtr Map(int subresource)
|
||||
{
|
||||
IntPtr mappedResource = NativeResource.Map(subresource);
|
||||
MappedResource = mappedResource;
|
||||
return mappedResource;
|
||||
}
|
||||
|
||||
public void Unmap(int subresource)
|
||||
{
|
||||
NativeResource.Unmap(subresource);
|
||||
MappedResource = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public enum GraphicsHeapType
|
||||
{
|
||||
Default = 1,
|
||||
Upload = 2,
|
||||
Readback = 3,
|
||||
Custom = 4
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using SharpDX.DXGI;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public class HwndSwapChainGraphicsPresenter : SwapChainGraphicsPresenter
|
||||
{
|
||||
private readonly WindowHandle windowHandle;
|
||||
|
||||
public HwndSwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters, WindowHandle windowHandle)
|
||||
: base(device, presentationParameters, CreateSwapChain(device, presentationParameters, windowHandle))
|
||||
{
|
||||
this.windowHandle = windowHandle;
|
||||
}
|
||||
|
||||
private static SwapChain3 CreateSwapChain(GraphicsDevice device, PresentationParameters presentationParameters, WindowHandle windowHandle)
|
||||
{
|
||||
SwapChainDescription1 swapChainDescription = new SwapChainDescription1
|
||||
{
|
||||
Width = presentationParameters.BackBufferWidth,
|
||||
Height = presentationParameters.BackBufferHeight,
|
||||
SampleDescription = new SampleDescription(1, 0),
|
||||
Stereo = presentationParameters.Stereo,
|
||||
Usage = Usage.RenderTargetOutput,
|
||||
BufferCount = BufferCount,
|
||||
Scaling = Scaling.Stretch,
|
||||
SwapEffect = SwapEffect.FlipSequential,
|
||||
Format = (Format)presentationParameters.BackBufferFormat,
|
||||
Flags = SwapChainFlags.None,
|
||||
AlphaMode = AlphaMode.Unspecified
|
||||
};
|
||||
|
||||
using Factory4 factory = new Factory4();
|
||||
using SwapChain1 tempSwapChain = new SwapChain1(factory, device.NativeDirectCommandQueue, windowHandle.Handle, ref swapChainDescription);
|
||||
|
||||
return tempSwapChain.QueryInterface<SwapChain3>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using SharpDX.DXGI;
|
||||
using Windows.Graphics.Imaging;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public sealed class Image : IDisposable
|
||||
{
|
||||
public Memory<byte> Data { get; }
|
||||
|
||||
public ImageDescription Description { get; }
|
||||
|
||||
public int Width => Description.Width;
|
||||
|
||||
public int Height => Description.Height;
|
||||
|
||||
internal Image()
|
||||
{
|
||||
}
|
||||
|
||||
internal Image(ImageDescription description, Memory<byte> data)
|
||||
{
|
||||
Description = description;
|
||||
Data = data;
|
||||
}
|
||||
|
||||
public static async Task<Image> LoadAsync(string filePath)
|
||||
{
|
||||
using FileStream stream = File.OpenRead(filePath);
|
||||
return await LoadAsync(stream);
|
||||
}
|
||||
|
||||
public static async Task<Image> LoadAsync(Stream stream)
|
||||
{
|
||||
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream.AsRandomAccessStream());
|
||||
|
||||
PixelDataProvider pixelDataProvider = await decoder.GetPixelDataAsync(
|
||||
decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, new BitmapTransform(),
|
||||
ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
|
||||
|
||||
byte[] imageBuffer = pixelDataProvider.DetachPixelData();
|
||||
|
||||
PixelFormat pixelFormat = decoder.BitmapPixelFormat switch
|
||||
{
|
||||
BitmapPixelFormat.Rgba8 => PixelFormat.R8G8B8A8_UNorm,
|
||||
BitmapPixelFormat.Bgra8 => PixelFormat.B8G8R8A8_UNorm,
|
||||
_ => throw new NotSupportedException("This format is not supported.")
|
||||
};
|
||||
|
||||
ImageDescription description = ImageDescription.New2D((int)decoder.PixelWidth, (int)decoder.OrientedPixelHeight, pixelFormat);
|
||||
|
||||
return new Image(description, imageBuffer);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public struct ImageDescription
|
||||
{
|
||||
public TextureDimension Dimension;
|
||||
|
||||
public int Width;
|
||||
|
||||
public int Height;
|
||||
|
||||
public int Depth;
|
||||
|
||||
public int ArraySize;
|
||||
|
||||
public int MipLevels;
|
||||
|
||||
public PixelFormat Format;
|
||||
|
||||
public static ImageDescription New2D(int width, int height, PixelFormat format, int mipCount = 1, int arraySize = 1)
|
||||
{
|
||||
return new ImageDescription
|
||||
{
|
||||
Dimension = TextureDimension.Texture2D,
|
||||
Width = width,
|
||||
Height = height,
|
||||
Depth = 1,
|
||||
ArraySize = arraySize,
|
||||
Format = format,
|
||||
MipLevels = mipCount,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using SharpDX.Direct3D;
|
||||
using SharpDX.Direct3D12;
|
||||
using SharpDX.DXGI;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public sealed class PipelineState
|
||||
{
|
||||
public PipelineState(GraphicsDevice device, ComputePipelineStateDescription pipelineStateDescription)
|
||||
{
|
||||
IsCompute = true;
|
||||
RootSignature = pipelineStateDescription.RootSignaturePointer;
|
||||
NativePipelineState = device.NativeDevice.CreateComputePipelineState(pipelineStateDescription);
|
||||
}
|
||||
|
||||
public PipelineState(GraphicsDevice device, RootSignature rootSignature, ShaderBytecode computeShader)
|
||||
: this(device, CreateComputePipelineStateDescription(rootSignature, computeShader))
|
||||
{
|
||||
}
|
||||
|
||||
public PipelineState(GraphicsDevice device, GraphicsPipelineStateDescription pipelineStateDescription)
|
||||
{
|
||||
IsCompute = false;
|
||||
RootSignature = pipelineStateDescription.RootSignature;
|
||||
NativePipelineState = device.NativeDevice.CreateGraphicsPipelineState(pipelineStateDescription);
|
||||
}
|
||||
|
||||
public PipelineState(GraphicsDevice device, InputElement[] inputElements, RootSignature rootSignature, ShaderBytecode vertexShader, ShaderBytecode pixelShader, ShaderBytecode hullShader = default, ShaderBytecode domainShader = default, ShaderBytecode geometryShader = default, RasterizerStateDescription? rasterizerStateDescription = null)
|
||||
: this(device, CreateGraphicsPipelineStateDescription(device, inputElements, rootSignature, vertexShader, pixelShader, hullShader, domainShader, geometryShader, rasterizerStateDescription))
|
||||
{
|
||||
}
|
||||
|
||||
public RootSignature RootSignature { get; }
|
||||
|
||||
internal bool IsCompute { get; }
|
||||
|
||||
internal SharpDX.Direct3D12.PipelineState NativePipelineState { get; }
|
||||
|
||||
private static ComputePipelineStateDescription CreateComputePipelineStateDescription(RootSignature rootSignature, ShaderBytecode computeShader)
|
||||
{
|
||||
return new ComputePipelineStateDescription
|
||||
{
|
||||
RootSignaturePointer = rootSignature,
|
||||
ComputeShader = computeShader
|
||||
};
|
||||
}
|
||||
|
||||
private static GraphicsPipelineStateDescription CreateGraphicsPipelineStateDescription(GraphicsDevice device, InputElement[] inputElements, RootSignature rootSignature, ShaderBytecode vertexShader, ShaderBytecode pixelShader, ShaderBytecode hullShader, ShaderBytecode domainShader, ShaderBytecode geometryShader, RasterizerStateDescription? rasterizerStateDescription)
|
||||
{
|
||||
RasterizerStateDescription rasterizerDescription = rasterizerStateDescription ?? RasterizerStateDescription.Default();
|
||||
rasterizerDescription.IsFrontCounterClockwise = true;
|
||||
rasterizerDescription.CullMode = CullMode.None;
|
||||
|
||||
BlendStateDescription blendStateDescription = BlendStateDescription.Default();
|
||||
RenderTargetBlendDescription[] renderTargetDescriptions = blendStateDescription.RenderTarget;
|
||||
|
||||
for (int i = 0; i < renderTargetDescriptions.Length; i++)
|
||||
{
|
||||
renderTargetDescriptions[i].IsBlendEnabled = true;
|
||||
renderTargetDescriptions[i].SourceBlend = BlendOption.SourceAlpha;
|
||||
renderTargetDescriptions[i].DestinationBlend = BlendOption.InverseSourceAlpha;
|
||||
}
|
||||
|
||||
DepthStencilStateDescription depthStencilStateDescription = DepthStencilStateDescription.Default();
|
||||
|
||||
GraphicsPipelineStateDescription pipelineStateDescription = new GraphicsPipelineStateDescription
|
||||
{
|
||||
InputLayout = new InputLayoutDescription(inputElements),
|
||||
RootSignature = rootSignature,
|
||||
VertexShader = vertexShader,
|
||||
PixelShader = pixelShader,
|
||||
HullShader = hullShader,
|
||||
DomainShader = domainShader,
|
||||
GeometryShader = geometryShader,
|
||||
RasterizerState = rasterizerDescription,
|
||||
BlendState = blendStateDescription,
|
||||
DepthStencilState = depthStencilStateDescription,
|
||||
SampleMask = int.MaxValue,
|
||||
PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
|
||||
RenderTargetCount = 1,
|
||||
SampleDescription = new SampleDescription(1, 0),
|
||||
StreamOutput = new StreamOutputDescription()
|
||||
};
|
||||
|
||||
Texture? depthStencilBuffer = device.CommandList.DepthStencilBuffer;
|
||||
|
||||
if (depthStencilBuffer != null)
|
||||
{
|
||||
pipelineStateDescription.DepthStencilFormat = (Format)depthStencilBuffer.Description.Format;
|
||||
}
|
||||
|
||||
for (int i = 0; i < device.CommandList.RenderTargets.Length; i++)
|
||||
{
|
||||
pipelineStateDescription.RenderTargetFormats[i] = (Format)device.CommandList.RenderTargets[i].Description.Format;
|
||||
}
|
||||
|
||||
return pipelineStateDescription;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public enum PixelFormat
|
||||
{
|
||||
Unknown = 0,
|
||||
R32G32B32A32_Typeless = 1,
|
||||
R32G32B32A32_Float = 2,
|
||||
R32G32B32A32_UInt = 3,
|
||||
R32G32B32A32_SInt = 4,
|
||||
R32G32B32_Typeless = 5,
|
||||
R32G32B32_Float = 6,
|
||||
R32G32B32_UInt = 7,
|
||||
R32G32B32_SInt = 8,
|
||||
R16G16B16A16_Typeless = 9,
|
||||
R16G16B16A16_Float = 10,
|
||||
R16G16B16A16_UNorm = 11,
|
||||
R16G16B16A16_UInt = 12,
|
||||
R16G16B16A16_SNorm = 13,
|
||||
R16G16B16A16_SInt = 14,
|
||||
R32G32_Typeless = 15,
|
||||
R32G32_Float = 16,
|
||||
R32G32_UInt = 17,
|
||||
R32G32_SInt = 18,
|
||||
R32G8X24_Typeless = 19,
|
||||
D32_Float_S8X24_UInt = 20,
|
||||
R32_Float_X8X24_Typeless = 21,
|
||||
X32_Typeless_G8X24_UInt = 22,
|
||||
R10G10B10A2_Typeless = 23,
|
||||
R10G10B10A2_UNorm = 24,
|
||||
R10G10B10A2_UInt = 25,
|
||||
R11G11B10_Float = 26,
|
||||
R8G8B8A8_Typeless = 27,
|
||||
R8G8B8A8_UNorm = 28,
|
||||
R8G8B8A8_UNorm_SRgb = 29,
|
||||
R8G8B8A8_UInt = 30,
|
||||
R8G8B8A8_SNorm = 31,
|
||||
R8G8B8A8_SInt = 32,
|
||||
R16G16_Typeless = 33,
|
||||
R16G16_Float = 34,
|
||||
R16G16_UNorm = 35,
|
||||
R16G16_UInt = 36,
|
||||
R16G16_SNorm = 37,
|
||||
R16G16_SInt = 38,
|
||||
R32_Typeless = 39,
|
||||
D32_Float = 40,
|
||||
R32_Float = 41,
|
||||
R32_UInt = 42,
|
||||
R32_SInt = 43,
|
||||
R24G8_Typeless = 44,
|
||||
D24_UNorm_S8_UInt = 45,
|
||||
R24_UNorm_X8_Typeless = 46,
|
||||
X24_Typeless_G8_UInt = 47,
|
||||
R8G8_Typeless = 48,
|
||||
R8G8_UNorm = 49,
|
||||
R8G8_UInt = 50,
|
||||
R8G8_SNorm = 51,
|
||||
R8G8_SInt = 52,
|
||||
R16_Typeless = 53,
|
||||
R16_Float = 54,
|
||||
D16_UNorm = 55,
|
||||
R16_UNorm = 56,
|
||||
R16_UInt = 57,
|
||||
R16_SNorm = 58,
|
||||
R16_SInt = 59,
|
||||
R8_Typeless = 60,
|
||||
R8_UNorm = 61,
|
||||
R8_UInt = 62,
|
||||
R8_SNorm = 63,
|
||||
R8_SInt = 64,
|
||||
A8_UNorm = 65,
|
||||
R1_UNorm = 66,
|
||||
R9G9B9E5_Sharedexp = 67,
|
||||
R8G8_B8G8_UNorm = 68,
|
||||
G8R8_G8B8_UNorm = 69,
|
||||
BC1_Typeless = 70,
|
||||
BC1_UNorm = 71,
|
||||
BC1_UNorm_SRgb = 72,
|
||||
BC2_Typeless = 73,
|
||||
BC2_UNorm = 74,
|
||||
BC2_UNorm_SRgb = 75,
|
||||
BC3_Typeless = 76,
|
||||
BC3_UNorm = 77,
|
||||
BC3_UNorm_SRgb = 78,
|
||||
BC4_Typeless = 79,
|
||||
BC4_UNorm = 80,
|
||||
BC4_SNorm = 81,
|
||||
BC5_Typeless = 82,
|
||||
BC5_UNorm = 83,
|
||||
BC5_SNorm = 84,
|
||||
B5G6R5_UNorm = 85,
|
||||
B5G5R5A1_UNorm = 86,
|
||||
B8G8R8A8_UNorm = 87,
|
||||
B8G8R8X8_UNorm = 88,
|
||||
R10G10B10_Xr_Bias_A2_UNorm = 89,
|
||||
B8G8R8A8_Typeless = 90,
|
||||
B8G8R8A8_UNorm_SRgb = 91,
|
||||
B8G8R8X8_Typeless = 92,
|
||||
B8G8R8X8_UNorm_SRgb = 93,
|
||||
BC6H_Typeless = 94,
|
||||
BC6H_Uf16 = 95,
|
||||
BC6H_Sf16 = 96,
|
||||
BC7_Typeless = 97,
|
||||
BC7_UNorm = 98,
|
||||
BC7_UNorm_SRgb = 99,
|
||||
AYUV = 100,
|
||||
Y410 = 101,
|
||||
Y416 = 102,
|
||||
NV12 = 103,
|
||||
P010 = 104,
|
||||
P016 = 105,
|
||||
Opaque420 = 106,
|
||||
YUY2 = 107,
|
||||
Y210 = 108,
|
||||
Y216 = 109,
|
||||
NV11 = 110,
|
||||
AI44 = 111,
|
||||
IA44 = 112,
|
||||
P8 = 113,
|
||||
A8P8 = 114,
|
||||
B4G4R4A4_UNorm = 115,
|
||||
P208 = 130,
|
||||
V208 = 131,
|
||||
V408 = 132
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using SharpDX.DXGI;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public class PresentationParameters
|
||||
{
|
||||
public PresentationParameters()
|
||||
{
|
||||
}
|
||||
|
||||
public PresentationParameters(int backBufferWidth, int backBufferHeight)
|
||||
: this(backBufferWidth, backBufferHeight, PixelFormat.B8G8R8A8_UNorm)
|
||||
{
|
||||
}
|
||||
|
||||
public PresentationParameters(int backBufferWidth, int backBufferHeight, PixelFormat backBufferFomat)
|
||||
{
|
||||
BackBufferWidth = backBufferWidth;
|
||||
BackBufferHeight = backBufferHeight;
|
||||
BackBufferFormat = backBufferFomat;
|
||||
}
|
||||
|
||||
public int BackBufferWidth { get; set; }
|
||||
|
||||
public int BackBufferHeight { get; set; }
|
||||
|
||||
public PixelFormat BackBufferFormat { get; set; } = PixelFormat.B8G8R8A8_UNorm;
|
||||
|
||||
public PixelFormat DepthStencilFormat { get; set; } = PixelFormat.D32_Float;
|
||||
|
||||
public PresentParameters PresentParameters { get; set; }
|
||||
|
||||
public bool Stereo { get; set; }
|
||||
|
||||
public int SyncInterval { get; set; } = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using System.Numerics;
|
||||
using SharpDX.Direct3D12;
|
||||
using SharpDX.DXGI;
|
||||
|
||||
using Resource = SharpDX.Direct3D12.Resource;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public class SwapChainGraphicsPresenter : GraphicsPresenter
|
||||
{
|
||||
protected const int BufferCount = 2;
|
||||
|
||||
private readonly Texture[] renderTargets = new Texture[BufferCount];
|
||||
|
||||
public SwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters, SwapChain3 swapChain)
|
||||
: base(device, presentationParameters)
|
||||
{
|
||||
SwapChain = swapChain;
|
||||
|
||||
if (GraphicsDevice.RenderTargetViewAllocator.DescriptorHeap.Description.DescriptorCount != BufferCount)
|
||||
{
|
||||
GraphicsDevice.RenderTargetViewAllocator.Dispose();
|
||||
GraphicsDevice.RenderTargetViewAllocator = new DescriptorAllocator(GraphicsDevice, DescriptorHeapType.RenderTargetView, descriptorCount: BufferCount);
|
||||
}
|
||||
|
||||
CreateRenderTargets();
|
||||
}
|
||||
|
||||
public override Texture BackBuffer => renderTargets[SwapChain.CurrentBackBufferIndex];
|
||||
|
||||
public Matrix3x2 MatrixTransform { get => SwapChain.MatrixTransform.ToMatrix3x2(); set => SwapChain.MatrixTransform = value.ToMatrix3x2(); }
|
||||
|
||||
public override object NativePresenter => SwapChain;
|
||||
|
||||
protected SwapChain3 SwapChain { get; }
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
SwapChain.Dispose();
|
||||
|
||||
foreach (Texture renderTarget in renderTargets)
|
||||
{
|
||||
renderTarget.Dispose();
|
||||
}
|
||||
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
public override void Present()
|
||||
{
|
||||
SwapChain.Present(PresentationParameters.SyncInterval, PresentFlags.None, PresentationParameters.PresentParameters);
|
||||
}
|
||||
|
||||
protected override void ResizeBackBuffer(int width, int height)
|
||||
{
|
||||
for (int i = 0; i < BufferCount; i++)
|
||||
{
|
||||
renderTargets[i].Dispose();
|
||||
}
|
||||
|
||||
SwapChain.ResizeBuffers(BufferCount, width, height, (Format)PresentationParameters.BackBufferFormat, SwapChainFlags.None);
|
||||
|
||||
CreateRenderTargets();
|
||||
}
|
||||
|
||||
protected override void ResizeDepthStencilBuffer(int width, int height)
|
||||
{
|
||||
DepthStencilBuffer.Dispose();
|
||||
DepthStencilBuffer = CreateDepthStencilBuffer();
|
||||
}
|
||||
|
||||
private void CreateRenderTargets()
|
||||
{
|
||||
for (int i = 0; i < BufferCount; i++)
|
||||
{
|
||||
renderTargets[i] = new Texture(GraphicsDevice).InitializeFrom(SwapChain.GetBackBuffer<Resource>(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static class MatrixExtensions
|
||||
{
|
||||
public static unsafe SharpDX.Mathematics.Interop.RawMatrix3x2 ToMatrix3x2(this Matrix3x2 value)
|
||||
{
|
||||
return *(SharpDX.Mathematics.Interop.RawMatrix3x2*)&value;
|
||||
}
|
||||
|
||||
public static unsafe Matrix3x2 ToMatrix3x2(this SharpDX.Mathematics.Interop.RawMatrix3x2 value)
|
||||
{
|
||||
return *(Matrix3x2*)&value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Tasks;
|
||||
using SharpDX.Direct3D12;
|
||||
using SharpDX.DXGI;
|
||||
|
||||
using Resource = SharpDX.Direct3D12.Resource;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public sealed class Texture : GraphicsResource
|
||||
{
|
||||
public Texture()
|
||||
{
|
||||
}
|
||||
|
||||
internal Texture(GraphicsDevice device) : base(device)
|
||||
{
|
||||
}
|
||||
|
||||
public TextureDescription Description { get; private set; }
|
||||
|
||||
public int Width => Description.Width;
|
||||
|
||||
public int Height => Description.Height;
|
||||
|
||||
public static async Task<Texture> LoadAsync(GraphicsDevice device, string filePath)
|
||||
{
|
||||
using FileStream stream = File.OpenRead(filePath);
|
||||
return await LoadAsync(device, stream);
|
||||
}
|
||||
|
||||
public static async Task<Texture> LoadAsync(GraphicsDevice device, Stream stream)
|
||||
{
|
||||
using Image image = await Image.LoadAsync(stream);
|
||||
return New2D(device, image.Data.Span, image.Width, image.Height, image.Description.Format); ;
|
||||
}
|
||||
|
||||
public static Texture New(GraphicsDevice device, TextureDescription description)
|
||||
{
|
||||
return new Texture(device).InitializeFrom(description);
|
||||
}
|
||||
|
||||
public static Texture New2D(GraphicsDevice device, int width, int height, PixelFormat format, TextureFlags textureFlags = TextureFlags.ShaderResource, int mipCount = 1, int arraySize = 1, int multisampleCount = 1, GraphicsHeapType heapType = GraphicsHeapType.Default)
|
||||
{
|
||||
return New(device, TextureDescription.New2D(width, height, format, textureFlags, mipCount, arraySize, multisampleCount, heapType));
|
||||
}
|
||||
|
||||
public static Texture New2D<T>(GraphicsDevice device, Span<T> data, int width, int height, PixelFormat format, TextureFlags textureFlags = TextureFlags.ShaderResource, int mipCount = 1, int arraySize = 1, int multisampleCount = 1, GraphicsHeapType heapType = GraphicsHeapType.Default) where T : unmanaged
|
||||
{
|
||||
Texture texture = New2D(device, width, height, format, textureFlags, mipCount, arraySize, multisampleCount, heapType);
|
||||
texture.Recreate(data);
|
||||
|
||||
return texture;
|
||||
}
|
||||
|
||||
public unsafe void Recreate<T>(Span<T> data) where T : unmanaged
|
||||
{
|
||||
Resource uploadResource = GraphicsDevice.NativeDevice.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, NativeResource.Description, ResourceStates.CopyDestination);
|
||||
using Texture textureUploadBuffer = new Texture(GraphicsDevice).InitializeFrom(uploadResource);
|
||||
|
||||
fixed (T* pointer = data)
|
||||
{
|
||||
textureUploadBuffer.NativeResource.WriteToSubresource(0, null, (IntPtr)pointer, ((Format)Description.Format).SizeOfInBytes() * Width, data.Length * Unsafe.SizeOf<T>());
|
||||
}
|
||||
|
||||
CommandList copyCommandList = GraphicsDevice.GetOrCreateCopyCommandList();
|
||||
|
||||
copyCommandList.CopyResource(textureUploadBuffer, this);
|
||||
copyCommandList.Flush(true);
|
||||
|
||||
GraphicsDevice.EnqueueCopyCommandList(copyCommandList);
|
||||
}
|
||||
|
||||
public Texture InitializeFrom(TextureDescription description)
|
||||
{
|
||||
ResourceStates resourceStates = ResourceStates.Common;
|
||||
|
||||
if (description.HeapType == GraphicsHeapType.Upload)
|
||||
{
|
||||
resourceStates = ResourceStates.GenericRead;
|
||||
}
|
||||
else if (description.HeapType == GraphicsHeapType.Readback)
|
||||
{
|
||||
resourceStates = ResourceStates.CopyDestination;
|
||||
}
|
||||
|
||||
NativeResource ??= GraphicsDevice.NativeDevice.CreateCommittedResource(
|
||||
new HeapProperties((HeapType)description.HeapType), HeapFlags.None,
|
||||
ConvertToNativeDescription(description), resourceStates);
|
||||
|
||||
Description = description;
|
||||
|
||||
(NativeCpuDescriptorHandle, NativeGpuDescriptorHandle) = description.Flags switch
|
||||
{
|
||||
TextureFlags.DepthStencil => CreateDepthStencilView(),
|
||||
TextureFlags.RenderTarget => CreateRenderTargetView(),
|
||||
TextureFlags.ShaderResource => CreateShaderResourceView(),
|
||||
TextureFlags.UnorderedAccess => CreateUnorderedAccessView(),
|
||||
_ => default
|
||||
};
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
internal Texture InitializeFrom(Resource resource)
|
||||
{
|
||||
NativeResource = resource;
|
||||
|
||||
TextureDescription description = ConvertFromNativeDescription(resource.Description);
|
||||
|
||||
return InitializeFrom(description);
|
||||
}
|
||||
|
||||
internal static ResourceFlags GetBindFlagsFromTextureFlags(TextureFlags flags)
|
||||
{
|
||||
ResourceFlags result = ResourceFlags.None;
|
||||
|
||||
if (flags.HasFlag(TextureFlags.RenderTarget))
|
||||
{
|
||||
result |= ResourceFlags.AllowRenderTarget;
|
||||
}
|
||||
|
||||
if (flags.HasFlag(TextureFlags.UnorderedAccess))
|
||||
{
|
||||
result |= ResourceFlags.AllowUnorderedAccess;
|
||||
//result |= ResourceFlags.AllowSimultaneousAccess;
|
||||
}
|
||||
|
||||
if (flags.HasFlag(TextureFlags.DepthStencil))
|
||||
{
|
||||
result |= ResourceFlags.AllowDepthStencil;
|
||||
|
||||
if (!flags.HasFlag(TextureFlags.ShaderResource))
|
||||
{
|
||||
result |= ResourceFlags.DenyShaderResource;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static TextureDescription ConvertFromNativeDescription(ResourceDescription description, bool isShaderResource = false)
|
||||
{
|
||||
TextureDescription textureDescription = new TextureDescription()
|
||||
{
|
||||
Dimension = TextureDimension.Texture2D,
|
||||
Width = (int)description.Width,
|
||||
Height = description.Height,
|
||||
Depth = 1,
|
||||
MultisampleCount = description.SampleDescription.Count,
|
||||
Format = (PixelFormat)description.Format,
|
||||
MipLevels = description.MipLevels,
|
||||
HeapType = GraphicsHeapType.Default,
|
||||
ArraySize = description.DepthOrArraySize,
|
||||
Flags = TextureFlags.None
|
||||
};
|
||||
|
||||
if (description.Flags.HasFlag(ResourceFlags.AllowRenderTarget))
|
||||
{
|
||||
textureDescription.Flags |= TextureFlags.RenderTarget;
|
||||
}
|
||||
|
||||
if (description.Flags.HasFlag(ResourceFlags.AllowUnorderedAccess))
|
||||
{
|
||||
textureDescription.Flags |= TextureFlags.UnorderedAccess;
|
||||
}
|
||||
|
||||
if (description.Flags.HasFlag(ResourceFlags.AllowDepthStencil))
|
||||
{
|
||||
textureDescription.Flags |= TextureFlags.DepthStencil;
|
||||
}
|
||||
|
||||
if (!description.Flags.HasFlag(ResourceFlags.DenyShaderResource) && isShaderResource)
|
||||
{
|
||||
textureDescription.Flags |= TextureFlags.ShaderResource;
|
||||
}
|
||||
|
||||
return textureDescription;
|
||||
}
|
||||
|
||||
private static ResourceDescription ConvertToNativeDescription(TextureDescription description)
|
||||
{
|
||||
return description.Dimension switch
|
||||
{
|
||||
TextureDimension.Texture2D => ResourceDescription.Texture2D((Format)description.Format, description.Width, description.Height, (short)description.ArraySize, (short)description.MipLevels, description.MultisampleCount, 0, GetBindFlagsFromTextureFlags(description.Flags)),
|
||||
_ => throw new NotSupportedException()
|
||||
};
|
||||
}
|
||||
|
||||
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateDepthStencilView()
|
||||
{
|
||||
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.DepthStencilViewAllocator.Allocate(1);
|
||||
GraphicsDevice.NativeDevice.CreateDepthStencilView(NativeResource, null, cpuHandle);
|
||||
|
||||
return (cpuHandle, gpuHandle);
|
||||
}
|
||||
|
||||
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateRenderTargetView()
|
||||
{
|
||||
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.RenderTargetViewAllocator.Allocate(1);
|
||||
GraphicsDevice.NativeDevice.CreateRenderTargetView(NativeResource, null, cpuHandle);
|
||||
|
||||
return (cpuHandle, gpuHandle);
|
||||
}
|
||||
|
||||
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateShaderResourceView()
|
||||
{
|
||||
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
|
||||
GraphicsDevice.NativeDevice.CreateShaderResourceView(NativeResource, null, cpuHandle);
|
||||
|
||||
return (cpuHandle, gpuHandle);
|
||||
}
|
||||
|
||||
private (CpuDescriptorHandle, GpuDescriptorHandle) CreateUnorderedAccessView()
|
||||
{
|
||||
(CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
|
||||
|
||||
GraphicsDevice.NativeDevice.CreateUnorderedAccessView(NativeResource, null, null, cpuHandle);
|
||||
|
||||
return (cpuHandle, gpuHandle);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public struct TextureDescription
|
||||
{
|
||||
public TextureDimension Dimension;
|
||||
|
||||
public int Width;
|
||||
|
||||
public int Height;
|
||||
|
||||
public int Depth;
|
||||
|
||||
public int ArraySize;
|
||||
|
||||
public int MipLevels;
|
||||
|
||||
public PixelFormat Format;
|
||||
|
||||
public int MultisampleCount;
|
||||
|
||||
public GraphicsHeapType HeapType;
|
||||
|
||||
public TextureFlags Flags;
|
||||
|
||||
public static TextureDescription New2D(int width, int height, PixelFormat format, TextureFlags textureFlags = TextureFlags.ShaderResource, int mipCount = 1, int arraySize = 1, int multisampleCount = 1, GraphicsHeapType heapType = GraphicsHeapType.Default)
|
||||
{
|
||||
return new TextureDescription
|
||||
{
|
||||
Dimension = TextureDimension.Texture2D,
|
||||
Width = width,
|
||||
Height = height,
|
||||
Depth = 1,
|
||||
ArraySize = arraySize,
|
||||
MultisampleCount = multisampleCount,
|
||||
Flags = textureFlags,
|
||||
Format = format,
|
||||
MipLevels = mipCount,
|
||||
HeapType = heapType,
|
||||
};
|
||||
}
|
||||
|
||||
public static implicit operator TextureDescription(ImageDescription description)
|
||||
{
|
||||
return new TextureDescription()
|
||||
{
|
||||
Dimension = description.Dimension,
|
||||
Width = description.Width,
|
||||
Height = description.Height,
|
||||
Depth = description.Depth,
|
||||
ArraySize = description.ArraySize,
|
||||
MipLevels = description.MipLevels,
|
||||
Format = description.Format,
|
||||
Flags = TextureFlags.ShaderResource,
|
||||
MultisampleCount = 1,
|
||||
HeapType = GraphicsHeapType.Default
|
||||
};
|
||||
}
|
||||
|
||||
public static implicit operator ImageDescription(TextureDescription description)
|
||||
{
|
||||
return new ImageDescription()
|
||||
{
|
||||
Dimension = description.Dimension,
|
||||
Width = description.Width,
|
||||
Height = description.Height,
|
||||
Depth = description.Depth,
|
||||
ArraySize = description.ArraySize,
|
||||
MipLevels = description.MipLevels,
|
||||
Format = description.Format,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public enum TextureDimension
|
||||
{
|
||||
Texture1D,
|
||||
Texture2D,
|
||||
Texture3D,
|
||||
TextureCube
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
[Flags]
|
||||
public enum TextureFlags
|
||||
{
|
||||
None = 0,
|
||||
RenderTarget = 1,
|
||||
DepthStencil = 2,
|
||||
UnorderedAccess = 4,
|
||||
ShaderResource = 8
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public class WindowHandle
|
||||
{
|
||||
public WindowHandle(IntPtr handle)
|
||||
{
|
||||
Handle = handle;
|
||||
}
|
||||
|
||||
public IntPtr Handle { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using SharpDX;
|
||||
using SharpDX.DXGI;
|
||||
using Windows.UI.Xaml.Controls;
|
||||
|
||||
namespace DirectX12GameEngine.Graphics
|
||||
{
|
||||
public class XamlSwapChainGraphicsPresenter : SwapChainGraphicsPresenter
|
||||
{
|
||||
private readonly SwapChainPanel swapChainPanel;
|
||||
|
||||
public XamlSwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters, SwapChainPanel swapChainPanel)
|
||||
: base(device, presentationParameters, CreateSwapChain(device, presentationParameters, swapChainPanel))
|
||||
{
|
||||
this.swapChainPanel = swapChainPanel;
|
||||
}
|
||||
|
||||
protected override void ResizeBackBuffer(int width, int height)
|
||||
{
|
||||
MatrixTransform = new System.Numerics.Matrix3x2
|
||||
{
|
||||
M11 = 1.0f / swapChainPanel.CompositionScaleX,
|
||||
M22 = 1.0f / swapChainPanel.CompositionScaleY
|
||||
};
|
||||
|
||||
base.ResizeBackBuffer(width, height);
|
||||
}
|
||||
|
||||
private static SwapChain3 CreateSwapChain(GraphicsDevice device, PresentationParameters presentationParameters, SwapChainPanel swapChainPanel)
|
||||
{
|
||||
SwapChainDescription1 swapChainDescription = new SwapChainDescription1
|
||||
{
|
||||
Width = presentationParameters.BackBufferWidth,
|
||||
Height = presentationParameters.BackBufferHeight,
|
||||
SampleDescription = new SampleDescription(1, 0),
|
||||
Stereo = presentationParameters.Stereo,
|
||||
Usage = Usage.RenderTargetOutput,
|
||||
BufferCount = BufferCount,
|
||||
Scaling = Scaling.Stretch,
|
||||
SwapEffect = SwapEffect.FlipSequential,
|
||||
Format = (Format)presentationParameters.BackBufferFormat,
|
||||
Flags = SwapChainFlags.None,
|
||||
AlphaMode = AlphaMode.Unspecified
|
||||
};
|
||||
|
||||
swapChainDescription.AlphaMode = AlphaMode.Premultiplied;
|
||||
|
||||
using Factory4 factory = new Factory4();
|
||||
using ISwapChainPanelNative nativePanel = ComObject.As<ISwapChainPanelNative>(swapChainPanel);
|
||||
using SwapChain1 tempSwapChain = new SwapChain1(factory, device.NativeDirectCommandQueue, ref swapChainDescription);
|
||||
|
||||
SwapChain3 swapChain = tempSwapChain.QueryInterface<SwapChain3>();
|
||||
nativePanel.SwapChain = swapChain;
|
||||
|
||||
swapChain.MatrixTransform = new SharpDX.Mathematics.Interop.RawMatrix3x2
|
||||
{
|
||||
M11 = 1.0f / swapChainPanel.CompositionScaleX,
|
||||
M22 = 1.0f / swapChainPanel.CompositionScaleY
|
||||
};
|
||||
|
||||
return swapChain;
|
||||
}
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする