Exemplo n.º 1
0
 public uint SubmitCommandList(ID3D12GraphicsCommandList4 pCmdList, ID3D12CommandQueue pCmdQueue, ID3D12Fence pFence, uint fenceValue)
 {
     pCmdList.Close();
     pCmdQueue.ExecuteCommandList(pCmdList);
     fenceValue++;
     pCmdQueue.Signal(pFence, fenceValue);
     return(fenceValue);
 }
Exemplo n.º 2
0
        private IDXGISwapChain3 CreateSwapChain(IDXGIFactory4 factory, ID3D12CommandQueue commandQueue, Format format)
        {
            SwapChainDescription1 desc = new SwapChainDescription1();

            desc.Format                  = format;
            desc.Width                   = Window.Width;
            desc.Height                  = Window.Height;
            desc.BufferCount             = DefaultSwapChainBuffers;
            desc.Usage                   = Usage.RenderTargetOutput;
            desc.SwapEffect              = SwapEffect.FlipDiscard;
            desc.SampleDescription       = new SampleDescription();
            desc.SampleDescription.Count = 1;

            var swapChain = factory.CreateSwapChainForHwnd(commandQueue, (IntPtr)Window.Handle, desc);

            return(swapChain.QueryInterface <IDXGISwapChain3>());
        }
Exemplo n.º 3
0
        /// <summary>
        /// Creates a new <see cref="GraphicsDevice"/> instance for the input <see cref="ID3D12Device"/>
        /// </summary>
        /// <param name="device">The <see cref="ID3D12Device"/> to use for the new <see cref="GraphicsDevice"/> instance</param>
        /// <param name="description">The available info for the new <see cref="GraphicsDevice"/> instance</param>
        public GraphicsDevice(ID3D12Device device, AdapterDescription description)
        {
            NativeDevice  = device;
            Description   = description;
            WavefrontSize = 64;

            NativeComputeCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Compute));
            NativeCopyCommandQueue    = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Copy));
            NativeDirectCommandQueue  = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct));

            ComputeAllocatorPool = new CommandAllocatorPool(this, CommandListType.Compute);
            CopyAllocatorPool    = new CommandAllocatorPool(this, CommandListType.Copy);
            DirectAllocatorPool  = new CommandAllocatorPool(this, CommandListType.Direct);

            NativeComputeFence = NativeDevice.CreateFence(0);
            NativeCopyFence    = NativeDevice.CreateFence(0);
            NativeDirectFence  = NativeDevice.CreateFence(0);

            ShaderResourceViewAllocator = new DescriptorAllocator(this);
        }
Exemplo n.º 4
0
        private void InitDXR(IntPtr winHandle, int winWidth, int winHeight)
        {
            mHwnd = winHandle;
            this.mSwapChainRect = new Rect(0, 0, winWidth, winHeight);

            // Initialize the debug layer for debug builds
#if DEBUG
            if (D3D12.D3D12GetDebugInterface <ID3D12Debug>(out var pDx12Debug).Success)
            {
                pDx12Debug.EnableDebugLayer();
            }
#endif
            // Create the DXGI factory
            IDXGIFactory4 pDXGIFactory;
            DXGI.CreateDXGIFactory1 <IDXGIFactory4>(out pDXGIFactory);
            mpDevice    = this.context.CreateDevice(pDXGIFactory);
            mpCmdQueue  = this.context.CreateCommandQueue(mpDevice);
            mpSwapChain = this.context.CreateDXGISwapChain(pDXGIFactory, mHwnd, winWidth, winHeight, Format.R8G8B8A8_UNorm, mpCmdQueue);

            // Create a RTV descriptor heap
            mRtvHeap.Heap = this.context.CreateDescriptorHeap(mpDevice, kRtvHeapSize, DescriptorHeapType.RenderTargetView, false);

            // Create the per-frame objects
            this.mFrameObjects = new FrameObject[this.context.kDefaultSwapChainBuffers];
            for (int i = 0; i < this.context.kDefaultSwapChainBuffers; i++)
            {
                mFrameObjects[i].pCmdAllocator    = mpDevice.CreateCommandAllocator(CommandListType.Direct);
                mFrameObjects[i].pSwapChainBuffer = mpSwapChain.GetBuffer <ID3D12Resource>(i);
                mFrameObjects[i].rtvHandle        = context.CreateRTV(mpDevice, mFrameObjects[i].pSwapChainBuffer, mRtvHeap.Heap, ref mRtvHeap.usedEntries, Format.R8G8B8A8_UNorm_SRgb);
            }

            // Create the command-list
            var cmdList = mpDevice.CreateCommandList(0, CommandListType.Direct, mFrameObjects[0].pCmdAllocator, null);
            this.mpCmdList = cmdList.QueryInterface <ID3D12GraphicsCommandList4>();

            // Create a fence and the event
            this.mpFence     = mpDevice.CreateFence(0, FenceFlags.None);
            this.mFenceEvent = new EventWaitHandle(false, EventResetMode.AutoReset);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Creates a new <see cref="GraphicsDevice"/> instance for the input <see cref="ID3D12Device"/>
        /// </summary>
        /// <param name="device">The <see cref="ID3D12Device"/> to use for the new <see cref="GraphicsDevice"/> instance</param>
        /// <param name="description">The available info for the new <see cref="GraphicsDevice"/> instance</param>
        public GraphicsDevice(ID3D12Device device, AdapterDescription description)
        {
            NativeDevice  = device;
            Name          = description.Description;
            MemorySize    = description.DedicatedVideoMemory;
            ComputeUnits  = device.Options1.TotalLaneCount;
            WavefrontSize = device.Options1.WaveLaneCountMin;

            NativeComputeCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Compute));
            NativeCopyCommandQueue    = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Copy));
            NativeDirectCommandQueue  = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct));

            ComputeAllocatorPool = new CommandAllocatorPool(this, CommandListType.Compute);
            CopyAllocatorPool    = new CommandAllocatorPool(this, CommandListType.Copy);
            DirectAllocatorPool  = new CommandAllocatorPool(this, CommandListType.Direct);

            NativeComputeFence = NativeDevice.CreateFence(0);
            NativeCopyFence    = NativeDevice.CreateFence(0);
            NativeDirectFence  = NativeDevice.CreateFence(0);

            ShaderResourceViewAllocator = new DescriptorAllocator(NativeDevice);
        }
Exemplo n.º 6
0
        public IDXGISwapChain3 CreateDXGISwapChain(IDXGIFactory4 pFactory, IntPtr hwnd, int width, int height, Vortice.DXGI.Format format, ID3D12CommandQueue pCommandQueue)
        {
            SwapChainDescription1 swapChainDesc = new SwapChainDescription1();

            swapChainDesc.BufferCount       = kDefaultSwapChainBuffers;
            swapChainDesc.Width             = width;
            swapChainDesc.Height            = height;
            swapChainDesc.Format            = format;
            swapChainDesc.Usage             = Usage.RenderTargetOutput;
            swapChainDesc.SwapEffect        = SwapEffect.FlipDiscard;
            swapChainDesc.SampleDescription = new SampleDescription(1, 0);

            // CreateSwapChainForHwnd() doesn't accept IDXGISwapChain3 (Why MS? Why?)
            IDXGISwapChain1 pSwapChain  = pFactory.CreateSwapChainForHwnd(pCommandQueue, hwnd, swapChainDesc);
            IDXGISwapChain3 pSwapChain3 = pSwapChain.QueryInterface <IDXGISwapChain3>();

            return(pSwapChain3);
        }
Exemplo n.º 7
0
 public void Signal(ID3D12CommandQueue queue, ulong fenceValue)
 {
     queue.Signal(_fence, fenceValue);
 }
Exemplo n.º 8
0
        public D3D12GraphicsDevice(IDXGIFactory4 factory)
        {
            DXGIFactory = factory;

            var adapters = DXGIFactory.EnumAdapters1();

            for (var i = 0; i < adapters.Length; i++)
            {
                var adapter = adapters[i];
                var desc    = adapter.Description1;

                // Don't select the Basic Render Driver adapter.
                if ((desc.Flags & AdapterFlags.Software) != AdapterFlags.None)
                {
                    continue;
                }

                if (D3D12CreateDevice(adapter, FeatureLevel.Level_11_0, out var device).Success)
                {
                    DXGIAdapter = adapter;
                    D3D12Device = device;
                }
            }

            if (D3D12Device == null)
            {
                // Create the Direct3D 12 with WARP adapter.
                DXGIAdapter = DXGIFactory.GetWarpAdapter <IDXGIAdapter1>();

                if (D3D12CreateDevice(DXGIAdapter, FeatureLevel.Level_11_0, out D3D12Device).Failure)
                {
                    throw new GraphicsException("Cannot create D3D12 device");
                }
            }

            if (Validation)
            {
                var infoQueue = D3D12Device.QueryInterfaceOrNull <ID3D12InfoQueue>();
                if (infoQueue != null)
                {
#if DEBUG
                    infoQueue.SetBreakOnSeverity(MessageSeverity.Corruption, true);
                    infoQueue.SetBreakOnSeverity(MessageSeverity.Error, true);
#endif

                    infoQueue.AddStorageFilterEntries(new DirectX.Direct3D12.Debug.InfoQueueFilter
                    {
                        DenyList = new DirectX.Direct3D12.Debug.InfoQueueFilterDescription
                        {
                            Ids = new[]
                            {
                                MessageId.ClearRenderTargetViewMismatchingClearValue,

                                // These happen when capturing with VS diagnostics
                                MessageId.MapInvalidNullRange,
                                MessageId.UnmapInvalidNullRange,
                            }
                        }
                    });
                    infoQueue.Dispose();
                }
            }

            // Init device features.
            InitializeFeatures();

            // Create command queue's.
            _graphicsCommandQueue = new CommandQueueD3D12(this, CommandQueueType.Graphics);
            _computeCommandQueue  = new CommandQueueD3D12(this, CommandQueueType.Compute);
            _copyCommandQueue     = new CommandQueueD3D12(this, CommandQueueType.Copy);

            // Create main graphics command queue.
            GraphicsQueue = D3D12Device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct));
            GraphicsQueue.SetName("Main GraphicsQueue");

            // Create ImmediateContext.
            for (int i = 0; i < RenderLatency; i++)
            {
                _deferredReleases[i] = new List <IUnknown>();
            }

            // Create the frame fence
            _frameFence = new FenceD3D12(this, 0);

            // Create descriptor allocators
            for (var i = 0; i < (int)DescriptorHeapType.Count; i++)
            {
                _descriptorAllocator[i] = new DescriptorAllocator(this, (DescriptorHeapType)i);
            }
        }
Exemplo n.º 9
0
    public HelloDml()
    {
        if (!IsSupported())
        {
            throw new InvalidOperationException("Direct3D12 is not supported on current OS");
        }

        bool validation = false;

#if DEBUG
        if (D3D12.D3D12GetDebugInterface(out ID3D12Debug? debug).Success)
        {
            debug !.EnableDebugLayer();
            debug !.Dispose();
            validation = true;
        }
#endif

        DXGIFactory = DXGI.CreateDXGIFactory2 <IDXGIFactory4>(validation);

        ID3D12Device2?device = default;

        for (int adapterIndex = 0; DXGIFactory.EnumAdapters1(adapterIndex, out IDXGIAdapter1 adapter).Success; adapterIndex++)
        {
            AdapterDescription1 desc = adapter.Description1;

            // Don't select the Basic Render Driver adapter.
            if ((desc.Flags & AdapterFlags.Software) != AdapterFlags.None)
            {
                adapter.Dispose();

                continue;
            }

            if (D3D12.D3D12CreateDevice(adapter, Vortice.Direct3D.FeatureLevel.Level_11_0, out device).Success)
            {
                adapter.Dispose();

                break;
            }
        }

        if (device == null)
        {
            throw new InvalidOperationException("Direct3D12 device could not be created");
        }

        D3D12Device = device !;

        CommandQueueDescription commandQueueDesc = new()
        {
            Type  = CommandListType.Direct,
            Flags = CommandQueueFlags.None,
        };

        D3D12CommandQueue     = D3D12Device.CreateCommandQueue(commandQueueDesc);
        D3D12CommandAllocator = D3D12Device.CreateCommandAllocator(CommandListType.Direct);
        D3D12CommandList      = D3D12Device.CreateCommandList <ID3D12GraphicsCommandList4>(CommandListType.Direct, D3D12CommandAllocator);

        var createFlags = CreateDeviceFlags.None;

#if DEBUG
        createFlags |= CreateDeviceFlags.Debug;
#endif
        DMLDevice = DMLCreateDevice(D3D12Device, createFlags);

        Console.WriteLine($"Highest supported feature level: {DMLDevice.HighestFeatureLevel}");
    }
Exemplo n.º 10
0
        protected Application(bool useDirect3D12)
        {
            _wndProc = ProcessWindowMessage;
            var wndClassEx = new WNDCLASSEX
            {
                Size                  = Unsafe.SizeOf <WNDCLASSEX>(),
                Styles                = WindowClassStyles.CS_HREDRAW | WindowClassStyles.CS_VREDRAW | WindowClassStyles.CS_OWNDC,
                WindowProc            = _wndProc,
                InstanceHandle        = HInstance,
                CursorHandle          = LoadCursor(IntPtr.Zero, SystemCursor.IDC_ARROW),
                BackgroundBrushHandle = IntPtr.Zero,
                IconHandle            = IntPtr.Zero,
                ClassName             = WndClassName,
            };

            var atom = RegisterClassEx(ref wndClassEx);

            if (atom == 0)
            {
                throw new InvalidOperationException(
                          $"Failed to register window class. Error: {Marshal.GetLastWin32Error()}"
                          );
            }

            Window = new Window("Vortice", 800, 600);

            if (useDirect3D12 &&
                !ID3D12Device.IsSupported(null, FeatureLevel.Level_11_0))
            {
                useDirect3D12 = false;
            }

            var debugFactory = false;

#if DEBUG
            if (useDirect3D12)
            {
                if (D3D12GetDebugInterface <ID3D12Debug>(out var debug).Success)
                {
                    debug.EnableDebugLayer();
                    debugFactory = true;
                }
            }
#endif

            if (useDirect3D12)
            {
                if (CreateDXGIFactory2(debugFactory, out IDXGIFactory4 dxgiFactory4).Failure)
                {
                    throw new InvalidOperationException("Cannot create IDXGIFactory4");
                }

                _dxgiFactory = dxgiFactory4;
            }
            else
            {
                if (CreateDXGIFactory2(debugFactory, out _dxgiFactory).Failure)
                {
                    throw new InvalidOperationException("Cannot create IDXGIFactory4");
                }
            }

            if (useDirect3D12)
            {
                Debug.Assert(D3D12CreateDevice(null, FeatureLevel.Level_11_0, out _d3d12Device).Success);

                _d3d12CommandQueue = _d3d12Device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct, CommandQueuePriority.Normal));
            }
            else
            {
                var featureLevels = new FeatureLevel[]
                {
                    FeatureLevel.Level_11_1,
                    FeatureLevel.Level_11_0
                };
                Debug.Assert(ID3D11Device.TryCreate(
                                 null,
                                 DriverType.Hardware,
                                 DeviceCreationFlags.BgraSupport,
                                 featureLevels,
                                 out _d3d11Device,
                                 out _d3d11DeviceContext).Success);
            }

            var swapChainDesc = new SwapChainDescription1
            {
                BufferCount       = FrameCount,
                Width             = Window.Width,
                Height            = Window.Height,
                Format            = Format.B8G8R8A8_UNorm,
                Usage             = Vortice.Usage.RenderTargetOutput,
                SwapEffect        = SwapEffect.FlipDiscard,
                SampleDescription = new SampleDescription(1, 0)
            };

            SwapChain = DXGIFactory.CreateSwapChainForHwnd(_d3d12CommandQueue, Window.Handle, swapChainDesc);
            DXGIFactory.MakeWindowAssociation(Window.Handle, WindowAssociationFlags.IgnoreAltEnter);

            if (useDirect3D12)
            {
                SwapChain3  = SwapChain.QueryInterface <IDXGISwapChain3>();
                _frameIndex = SwapChain3.GetCurrentBackBufferIndex();
            }

            _rtvHeap           = _d3d12Device.CreateDescriptorHeap(new DescriptorHeapDescription(DescriptorHeapType.RenderTargetView, FrameCount));
            _rtvDescriptorSize = _d3d12Device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            // Create frame resources.
            {
                var rtvHandle = _rtvHeap.GetCPUDescriptorHandleForHeapStart();

                // Create a RTV for each frame.
                _renderTargets = new ID3D12Resource[FrameCount];
                for (var i = 0; i < FrameCount; i++)
                {
                    _renderTargets[i] = SwapChain.GetBuffer <ID3D12Resource>(i);
                    _d3d12Device.CreateRenderTargetView(_renderTargets[i], null, rtvHandle);
                    rtvHandle += _rtvDescriptorSize;
                }
            }

            _commandAllocator = _d3d12Device.CreateCommandAllocator(CommandListType.Direct);
            _commandList      = _d3d12Device.CreateCommandList(CommandListType.Direct, _commandAllocator);
            _commandList.Close();

            // Create synchronization objects.
            _d3d12Fence = _d3d12Device.CreateFence(0);
            _fenceValue = 1;
            _fenceEvent = new AutoResetEvent(false);
        }