private void BuildResource()
        {
            // Note, compressed formats cannot be used for UAV. We get error like:
            // ERROR: ID3D11Device::CreateTexture2D: The format (0x4d, BC3_UNORM)
            // cannot be bound as an UnorderedAccessView, or cast to a format that
            // could be bound as an UnorderedAccessView. Therefore this format
            // does not support D3D11_BIND_UNORDERED_ACCESS.

            var texDesc = new ResourceDescription
            {
                Dimension         = ResourceDimension.Texture2D,
                Alignment         = 0,
                Width             = Width,
                Height            = Height,
                DepthOrArraySize  = 6,
                MipLevels         = 1,
                Format            = _format,
                SampleDescription = new SampleDescription(1, 0),
                Layout            = TextureLayout.Unknown,
                Flags             = ResourceFlags.AllowRenderTarget
            };

            var optClear = new ClearValue
            {
                Format = _format,
                Color  = Color.LightSteelBlue.ToVector4()
            };

            Resource = _device.CreateCommittedResource(
                new HeapProperties(HeapType.Default),
                HeapFlags.None,
                texDesc,
                ResourceStates.GenericRead,
                optClear);
        }
        private void BuildResource()
        {
            var texDesc = new ResourceDescription
            {
                Dimension         = ResourceDimension.Texture2D,
                Alignment         = 0,
                Width             = Width,
                Height            = Height,
                DepthOrArraySize  = 1,
                MipLevels         = 1,
                Format            = Format,
                SampleDescription = new SampleDescription(1, 0),
                Layout            = TextureLayout.Unknown,
                Flags             = ResourceFlags.AllowDepthStencil
            };

            var optClear = new ClearValue
            {
                Format       = Format.D24_UNorm_S8_UInt,
                DepthStencil = new DepthStencilValue
                {
                    Depth   = 1.0f,
                    Stencil = 0
                }
            };

            Resource = _device.CreateCommittedResource(
                new HeapProperties(HeapType.Default),
                HeapFlags.None,
                texDesc,
                ResourceStates.GenericRead,
                optClear);
        }
 /// <summary>
 /// Initialize new instance of <see cref="RenderPassBeginningAccess"/> struct.
 /// </summary>
 /// <param name="type">The type of access being requested.</param>
 /// <param name="clearValue">Appropriate when Type is <see cref="RenderPassBeginningAccessType.Clear"/>. The clear value to which resource(s) should be cleared.</param>
 public RenderPassBeginningAccess(RenderPassBeginningAccessType type, ClearValue clearValue)
 {
     Type  = type;
     Clear = new RenderPassBeginningAccessClearParameters {
         ClearValue = clearValue
     };
 }
    public Result CreateCommittedResource1 <T>(
        HeapProperties heapProperties,
        HeapFlags heapFlags,
        ResourceDescription description,
        ResourceStates initialResourceState,
        ID3D12ProtectedResourceSession protectedSession,
        ClearValue optimizedClearValue,
        out T?resource) where T : ID3D12Resource1
    {
        Result result = CreateCommittedResource1(ref heapProperties, heapFlags,
                                                 ref description,
                                                 initialResourceState,
                                                 optimizedClearValue,
                                                 protectedSession,
                                                 typeof(T).GUID, out IntPtr nativePtr);

        if (result.Failure)
        {
            resource = default;
            return(result);
        }

        resource = MarshallingHelpers.FromPointer <T>(nativePtr);
        return(result);
    }
Esempio n. 5
0
        /// <summary>
        /// Creates a depth texture.
        /// </summary>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public void CreateDepth(int width, int height)
        {
            Width  = width;
            Height = height;


            ClearValue depthOptimizedClearValue = new ClearValue()
            {
                Format       = Format.D32_Float,
                DepthStencil = new DepthStencilValue()
                {
                    Depth = 1.0F, Stencil = 0
                },
            };

            Resource = Device.NativeDevice.CreateCommittedResource(
                new HeapProperties(HeapType.Default),
                HeapFlags.None,
                ResourceDescription.Texture2D(
                    Format.D32_Float, Width, Height,
                    mipLevels: MipLevels,
                    flags: ResourceFlags.AllowDepthStencil),
                ResourceStates.DepthWrite,
                depthOptimizedClearValue);

            NativeDepthStencilView = Device.DepthStencilViewAllocator.Allocate(1);
            Device.NativeDevice.CreateDepthStencilView(Resource, null, NativeDepthStencilView);
        }
Esempio n. 6
0
        public unsafe void ClearRenderTargetDepthStencil(int layer, int layerCount, float depthValue, bool depthMask, int stencilValue, int stencilMask)
        {
            // TODO: Use stencilMask (fully)

            if (FramebufferParams == null || !FramebufferParams.HasDepthStencil)
            {
                return;
            }

            if (_renderPass == null)
            {
                CreateRenderPass();
            }

            BeginRenderPass();

            var clearValue = new ClearValue(null, new ClearDepthStencilValue(depthValue, (uint)stencilValue));
            var flags      = depthMask ? ImageAspectFlags.ImageAspectDepthBit : 0;

            if (stencilMask != 0)
            {
                flags |= ImageAspectFlags.ImageAspectStencilBit;
            }

            var attachment = new ClearAttachment(flags, 0, clearValue);
            var clearRect  = FramebufferParams.GetClearRect(ClearScissor, layer, layerCount);

            Gd.Api.CmdClearAttachments(CommandBuffer, 1, &attachment, 1, &clearRect);
        }
Esempio n. 7
0
        private void BuildResources()
        {
            var texDesc = new ResourceDescription
            {
                Dimension         = ResourceDimension.Texture2D,
                Alignment         = 0,
                Width             = _renderTargetWidth,
                Height            = _renderTargetHeight,
                DepthOrArraySize  = 1,
                MipLevels         = 1,
                Format            = NormalMapFormat,
                SampleDescription = new SampleDescription(1, 0),
                Layout            = TextureLayout.Unknown,
                Flags             = ResourceFlags.AllowRenderTarget
            };

            var optClear = new ClearValue
            {
                Format = NormalMapFormat,
                Color  = Vector4.UnitZ
            };

            _normalMap = _device.CreateCommittedResource(
                new HeapProperties(HeapType.Default),
                HeapFlags.None,
                texDesc,
                ResourceStates.GenericRead,
                optClear);

            // Ambient occlusion maps are at half resolution.
            texDesc.Width  = SsaoMapWidth;
            texDesc.Height = SsaoMapHeight;
            texDesc.Format = AmbientMapFormat;

            optClear = new ClearValue
            {
                Format = AmbientMapFormat,
                Color  = Vector4.One
            };

            _ambientMap0 = _device.CreateCommittedResource(
                new HeapProperties(HeapType.Default),
                HeapFlags.None,
                texDesc,
                ResourceStates.GenericRead,
                optClear);

            _ambientMap1 = _device.CreateCommittedResource(
                new HeapProperties(HeapType.Default),
                HeapFlags.None,
                texDesc,
                ResourceStates.GenericRead,
                optClear);
        }
        private void BuildDepthBuffer()
        {
            DescriptorHeapDescription descDescriptorHeapDSB = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Type            = DescriptorHeapType.DepthStencilView,
                Flags           = DescriptorHeapFlags.None
            };

            DescriptorHeap      descriptorHeapDSB = device.CreateDescriptorHeap(descDescriptorHeapDSB);
            ResourceDescription descDepth         = new ResourceDescription()
            {
                Dimension         = ResourceDimension.Texture2D,
                DepthOrArraySize  = 1,
                MipLevels         = 0,
                Flags             = ResourceFlags.AllowDepthStencil,
                Width             = (int)viewport.Width,
                Height            = (int)viewport.Height,
                Format            = Format.R32_Typeless,
                Layout            = TextureLayout.Unknown,
                SampleDescription = new SampleDescription()
                {
                    Count = 1
                }
            };

            ClearValue dsvClearValue = new ClearValue()
            {
                Format       = Format.D32_Float,
                DepthStencil = new DepthStencilValue()
                {
                    Depth   = 1.0f,
                    Stencil = 0
                }
            };

            Resource renderTargetDepth = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, descDepth, ResourceStates.GenericRead, dsvClearValue);

            DepthStencilViewDescription depthDSV = new DepthStencilViewDescription()
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Format    = Format.D32_Float,
                Texture2D = new DepthStencilViewDescription.Texture2DResource()
                {
                    MipSlice = 0
                }
            };

            device.CreateDepthStencilView(renderTargetDepth, depthDSV, descriptorHeapDSB.CPUDescriptorHandleForHeapStart);
            handleDSV = descriptorHeapDSB.CPUDescriptorHandleForHeapStart;
        }
Esempio n. 9
0
        private void CreateTargets(int width, int height)
        {
            //Viewport and scissorrect
            viewport.Width    = width;
            viewport.Height   = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right  = width;
            scissorRect.Bottom = height;

            // Create frame resources.
            CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;

            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer <Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtvHandle);
                rtvHandle += rtvDescriptorSize;
            }

            CpuDescriptorHandle dsvHandle = depthStencilViewHeap.CPUDescriptorHandleForHeapStart;

            ClearValue depthOptimizedClearValue = new ClearValue()
            {
                Format       = Format.D32_Float,
                DepthStencil = new DepthStencilValue()
                {
                    Depth = 1.0F, Stencil = 0
                },
            };

            depthTarget = device.CreateCommittedResource(
                new HeapProperties(HeapType.Default),
                HeapFlags.None,
                new ResourceDescription(ResourceDimension.Texture2D, 0, width, height, 1, 0, Format.D32_Float, 1, 0, TextureLayout.Unknown, ResourceFlags.AllowDepthStencil),
                ResourceStates.DepthWrite, depthOptimizedClearValue);

            var depthView = new DepthStencilViewDescription()
            {
                Format    = Format.D32_Float,
                Dimension = DepthStencilViewDimension.Texture2D,
                Flags     = DepthStencilViewFlags.None,
            };



            //bind depth buffer
            device.CreateDepthStencilView(depthTarget, null, dsvHandle);
        }
Esempio n. 10
0
        protected virtual ID3D12Resource *CreateDepthStencil()
        {
            ID3D12Resource *depthStencil;

            var heapProperties = new HeapProperties(HeapType.HeapTypeDefault);

            var resourceDesc = new ResourceDesc
                               (
                ResourceDimension.ResourceDimensionTexture2D,
                0ul,
                (ulong)Size.X,
                (uint)Size.Y,
                1,
                1,
                DepthBufferFormat,
                new SampleDesc()
            {
                Count = 1, Quality = 0
            },
                TextureLayout.TextureLayoutUnknown,
                ResourceFlags.ResourceFlagAllowDepthStencil
                               );

            var clearValue = new ClearValue(DepthBufferFormat, depthStencil: new DepthStencilValue(1.0f, 0));

            var iid = ID3D12Resource.Guid;

            SilkMarshal.ThrowHResult
            (
                D3DDevice->CreateCommittedResource
                (
                    &heapProperties, HeapFlags.HeapFlagNone, &resourceDesc, ResourceStates.ResourceStateDepthWrite,
                    &clearValue, &iid, (void **)&depthStencil
                )
            );

            var dsvDesc = new DepthStencilViewDesc
            {
                Format        = DepthBufferFormat,
                ViewDimension = DsvDimension.DsvDimensionTexture2D
            };

            D3DDevice->CreateDepthStencilView(depthStencil, &dsvDesc, DSVHeap->GetCPUDescriptorHandleForHeapStart());

            return(depthStencil);
        }
Esempio n. 11
0
        protected override void InitCommandBuffers()
        {
            for (int i = 0; i < bufferSize; i++)
            {
                var beginInfo = new CommandBufferBeginInfo
                {
                    Flags = CommandBufferUsageFlags.SimultaneousUse
                };
                commandBuffers[i].Begin(beginInfo);

                var clearColor = new ClearValue
                {
                    Color = new ClearColorValue(new float[] { 25 / 255f, 0.0f, 10 / 255f, 1.0f })
                };
                var renderPassInfo = new RenderPassBeginInfo
                {
                    RenderPass  = renderPass,
                    Framebuffer = framebuffers[i],
                    RenderArea  = new Rect2D
                    {
                        Offset = new Offset2D
                        {
                            X = 0,
                            Y = 0
                        },
                        Extent = extent
                    },
                    ClearValueCount = 1,
                    ClearValues     = new ClearValue[] { clearColor }
                };
                commandBuffers[i].CmdBeginRenderPass(renderPassInfo, SubpassContents.Inline);
                commandBuffers[i].CmdBindPipeline(PipelineBindPoint.Graphics, graphicsPipeline);

                commandBuffers[i].CmdBindVertexBuffer(0, vertexBuffer, 0);
                commandBuffers[i].CmdBindIndexBuffer(indexBuffer, 0, IndexType.Uint32);

                commandBuffers[i].CmdBindDescriptorSet(PipelineBindPoint.Graphics, pipelineLayout, 0, descriptorSets[i], null);

                commandBuffers[i].CmdDrawIndexed((uint)mesh.indices.Length, 1, 0, 0, 0);

                commandBuffers[i].CmdEndRenderPass();
                commandBuffers[i].End();
            }
        }
Esempio n. 12
0
        public void BeginBuffer(CommandBuffer cb,
                                int frameBufIndex, ClearValue cv)
        {
            CommandBufferBeginInfo cbbi = new CommandBufferBeginInfo();

            cbbi.Flags = CommandBufferUsages.SimultaneousUse;

            cb.Begin(cbbi);

            RenderPassBeginInfo rpbi = new RenderPassBeginInfo(
                mChainBuffers[frameBufIndex],
                new Rect2D(Offset2D.Zero, mDevices.GetChainExtent()), cv);

            //rpbi.ClearValues	=cv;

            cb.CmdBeginRenderPass(rpbi);

            cb.CmdBindPipeline(PipelineBindPoint.Graphics, mPipe);
        }
    public T CreateCommittedResource2 <T>(
        HeapProperties heapProperties,
        HeapFlags heapFlags,
        ResourceDescription1 description,
        ResourceStates initialResourceState,
        ClearValue optimizedClearValue,
        ID3D12ProtectedResourceSession protectedSession) where T : ID3D12Resource
    {
        CreateCommittedResource2(
            ref heapProperties,
            heapFlags,
            ref description,
            initialResourceState,
            optimizedClearValue,
            protectedSession,
            typeof(T).GUID, out IntPtr nativePtr).CheckError();

        return(MarshallingHelpers.FromPointer <T>(nativePtr));
    }
        private void BuildCubeDepthStencil()
        {
            _cubeDSV = DsvHeap.CPUDescriptorHandleForHeapStart + DsvDescriptorSize;

            // Create the depth/stencil buffer and view.
            var depthStencilDesc = new ResourceDescription
            {
                Dimension         = ResourceDimension.Texture2D,
                Alignment         = 0,
                Width             = CubeMapSize,
                Height            = CubeMapSize,
                DepthOrArraySize  = 1,
                MipLevels         = 1,
                Format            = DepthStencilFormat,
                SampleDescription = new SampleDescription(1, 0),
                Layout            = TextureLayout.Unknown,
                Flags             = ResourceFlags.AllowDepthStencil
            };

            var optClear = new ClearValue
            {
                Format       = DepthStencilFormat,
                DepthStencil = new DepthStencilValue
                {
                    Depth   = 1.0f,
                    Stencil = 0
                }
            };

            _cubeDepthStencilBuffer = Device.CreateCommittedResource(
                new HeapProperties(HeapType.Default),
                HeapFlags.None,
                depthStencilDesc,
                ResourceStates.Common,
                optClear);

            // Create descriptor to mip level 0 of entire resource using the format of the resource.
            Device.CreateDepthStencilView(_cubeDepthStencilBuffer, null, _cubeDSV);

            // Transition the resource from its initial state to be used as a depth buffer.
            CommandList.ResourceBarrierTransition(_cubeDepthStencilBuffer, ResourceStates.Common, ResourceStates.DepthWrite);
        }
        static public ClearValue GetDXGIFormatClearValue(Format format, Boolean depth)
        {
            ClearValue clearValue = new ClearValue();

            clearValue.Color.X = 0.0f;
            clearValue.Color.Y = 0.0f;
            clearValue.Color.Z = 0.0f;
            clearValue.Color.W = 0.0f;

            switch (format)
            {
            // special handling for format conversion
            case Format.R32_Typeless:
                format = depth ? Format.D32_Float : Format.R32_Float;
                break;
            }

            clearValue.Format = format;
            return(clearValue);
        }
Esempio n. 16
0
        public unsafe void ClearRenderTargetColor(int index, int layer, int layerCount, ColorF color)
        {
            if (FramebufferParams == null || !FramebufferParams.IsValidColorAttachment(index))
            {
                return;
            }

            if (_renderPass == null)
            {
                CreateRenderPass();
            }

            BeginRenderPass();

            var clearValue = new ClearValue(new ClearColorValue(color.Red, color.Green, color.Blue, color.Alpha));
            var attachment = new ClearAttachment(ImageAspectFlags.ImageAspectColorBit, (uint)index, clearValue);
            var clearRect  = FramebufferParams.GetClearRect(ClearScissor, layer, layerCount);

            Gd.Api.CmdClearAttachments(CommandBuffer, 1, &attachment, 1, &clearRect);
        }
Esempio n. 17
0
        public unsafe void ClearRenderTargetColor(int index, uint componentMask, ColorF color)
        {
            // TODO: Use componentMask

            if (_framebuffer == null)
            {
                return;
            }

            if (_renderPass == null)
            {
                CreateRenderPass();
            }

            BeginRenderPass();

            var clearValue = new ClearValue(new ClearColorValue(color.Red, color.Green, color.Blue, color.Alpha));
            var attachment = new ClearAttachment(ImageAspectFlags.ImageAspectColorBit, (uint)index, clearValue);
            var clearRect  = FramebufferParams?.GetClearRect() ?? default;

            Gd.Api.CmdClearAttachments(CommandBuffer, 1, &attachment, 1, &clearRect);
        }
        private void LoadPipeline(RenderForm form)
        {
            int width = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            viewport.Width = width;
            viewport.Height = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right = width;
            scissorRect.Bottom = height;

            #if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
            #endif
            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);
            using (var factory = new Factory4())
            {
                // Describe and create the command queue.
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                // Describe and create the swap chain.
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount = FrameCount,
                    ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage = Usage.RenderTargetOutput,
                    SwapEffect = SwapEffect.FlipDiscard,
                    OutputHandle = form.Handle,
                    //Flags = SwapChainFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed = true
                };

                SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface<SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);

            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            // Create frame resources.
            CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer<Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtvHandle);
                rtvHandle += rtvDescriptorSize;
            }

            //create depth buffer;
            DescriptorHeapDescription dsvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.DepthStencilView
            };
            depthStencilViewHeap = device.CreateDescriptorHeap(dsvHeapDesc);
            CpuDescriptorHandle dsvHandle = depthStencilViewHeap.CPUDescriptorHandleForHeapStart;

            ClearValue depthOptimizedClearValue = new ClearValue()
            {
                Format = Format.D32_Float,
                DepthStencil = new DepthStencilValue() { Depth = 1.0F, Stencil = 0 },
            };

            depthTarget = device.CreateCommittedResource(
                new HeapProperties(HeapType.Default),
                HeapFlags.None,
                new ResourceDescription(ResourceDimension.Texture2D, 0, width, height, 1, 0, Format.D32_Float, 1, 0, TextureLayout.Unknown, ResourceFlags.AllowDepthStencil),
                ResourceStates.DepthWrite, depthOptimizedClearValue);

            var depthView = new DepthStencilViewDescription()
            {
                Format = Format.D32_Float,
                Dimension = DepthStencilViewDimension.Texture2D,
                Flags = DepthStencilViewFlags.None,
            };

            //bind depth buffer
            device.CreateDepthStencilView(depthTarget, null, dsvHandle);

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
            bundleAllocator = device.CreateCommandAllocator(CommandListType.Bundle);
        }
Esempio n. 19
0
        void RecordCommandBuffers()
        {
            var graphics_commandd_buffer_begin_info = new CommandBufferBeginInfo
            {
                sType            = StructureType.CommandBufferBeginInfo,             // VkStructureType                        sType
                pNext            = IntPtr.Zero,                                      // const void                            *pNext
                flags            = CommandBufferUsageFlagBits.SimultaneousUseBit,    // VkCommandBufferUsageFlagBits              flags
                pInheritanceInfo = (CommandBufferInheritanceInfo *)0                 // const VkCommandBufferInheritanceInfo  *pInheritanceInfo
            };

            var image_subresource_range = new ImageSubresourceRange
            {
                aspectMask     = ImageAspectFlagBits.ColorBit,       // VkImageAspectFlagBits             aspectMask
                baseMipLevel   = 0,                                  // uint32_t                       baseMipLevel
                layerCount     = 1,                                  // uint32_t                       levelCount
                baseArrayLayer = 0,                                  // uint32_t                       baseArrayLayer
                levelCount     = 1                                   // uint32_t                       layerCount
            };

            var clear_value = new ClearValue
            {
                color = new ClearColorValue(1.0f, 0.8f, 0.4f, 0.0f),                    // VkClearColorValue              color
            };

            ImageParameters[] swap_chain_images = GetSwapChain.Images;

            for (int i = 0; i < Vulkan.GraphicsCommandBuffers.Length; ++i)
            {
                vk.BeginCommandBuffer(Vulkan.GraphicsCommandBuffers[i], ref graphics_commandd_buffer_begin_info).CheckError();

                if (GetPresentQueue.Handle != GetGraphicsQueue.Handle)
                {
                    var barrier_from_present_to_draw = new ImageMemoryBarrier
                    {
                        sType                       = StructureType.ImageMemoryBarrier,                     // VkStructureType                sType
                        pNext                       = IntPtr.Zero,                                          // const void                    *pNext
                        sourceAccessMask            = AccessFlagBits.MemoryReadBit,                         // VkAccessFlagBits                  srcAccessMask
                        destinationAccessMask       = AccessFlagBits.ColorAttachmentWriteBit,               // VkAccessFlagBits                  dstAccessMask
                        oldLayout                   = ImageLayout.Undefined,                                // VkImageLayout                  oldLayout
                        newLayout                   = ImageLayout.PresentSourceKhr,                         // VkImageLayout                  newLayout
                        sourceQueueFamilyIndex      = GetPresentQueue.FamilyIndex,                          // uint32_t                       srcQueueFamilyIndex
                        destinationQueueFamilyIndex = GetGraphicsQueue.FamilyIndex,                         // uint32_t                       dstQueueFamilyIndex
                        image                       = swap_chain_images[i].Handle,                          // VkImage                        image
                        subresourceRange            = image_subresource_range                               // VkImageSubresourceRange        subresourceRange
                    };
                    vk.CmdPipelineBarrier(
                        Vulkan.GraphicsCommandBuffers[i],
                        PipelineStageFlagBits.ColorAttachmentOutputBit,
                        PipelineStageFlagBits.ColorAttachmentOutputBit,
                        (DependencyFlagBits)0,
                        0, (MemoryBarrier *)0,
                        0, (BufferMemoryBarrier *)0,
                        1, &barrier_from_present_to_draw);
                }

                var render_pass_begin_info = new RenderPassBeginInfo
                {
                    sType       = StructureType.RenderPassBeginInfo,               // VkStructureType                sType
                    pNext       = IntPtr.Zero,                                     // const void                    *pNext
                    renderPass  = Vulkan.RenderPass,                               // VkRenderPass                   renderPass
                    framebuffer = Vulkan.Framebuffers[i],                          // VkFramebuffer                  framebuffer
                    renderArea  = new Rect2D
                    {                                                              // VkRect2D                       renderArea
                        offset = new Offset2D
                        {                                                          // VkOffset2D                     offset
                            x = 0,                                                 // int32_t                        x
                            y = 0                                                  // int32_t                        y
                        },
                        extent = new Extent2D
                        {                                                               // VkExtent2D                     extent
                            width  = 300,                                               // int32_t                        width
                            height = 300,                                               // int32_t                        height
                        }
                    },
                    clearValueCount = 1,                                           // uint32_t                       clearValueCount
                    pClearValues    = &clear_value                                 // const VkClearValue            *pClearValues
                };

                vk.CmdBeginRenderPass(Vulkan.GraphicsCommandBuffers[i], ref render_pass_begin_info, SubpassContents.Inline);

                vk.CmdBindPipeline(Vulkan.GraphicsCommandBuffers[i], PipelineBindPoint.Graphics, Vulkan.GraphicsPipeline);

                vk.CmdDraw(Vulkan.GraphicsCommandBuffers[i], 3, 1, 0, 0);

                vk.CmdEndRenderPass(Vulkan.GraphicsCommandBuffers[i]);

                if (GetGraphicsQueue.Handle != GetPresentQueue.Handle)
                {
                    var barrier_from_draw_to_present = new ImageMemoryBarrier
                    {
                        sType                       = StructureType.ImageMemoryBarrier,                    // VkStructureType              sType
                        pNext                       = IntPtr.Zero,                                         // const void                  *pNext
                        sourceAccessMask            = AccessFlagBits.ColorAttachmentWriteBit,              // VkAccessFlagBits                srcAccessMask
                        destinationAccessMask       = AccessFlagBits.MemoryReadBit,                        // VkAccessFlagBits                dstAccessMask
                        oldLayout                   = ImageLayout.PresentSourceKhr,                        // VkImageLayout                oldLayout
                        newLayout                   = ImageLayout.PresentSourceKhr,                        // VkImageLayout                newLayout
                        sourceQueueFamilyIndex      = GetGraphicsQueue.FamilyIndex,                        // uint32_t                     srcQueueFamilyIndex
                        destinationQueueFamilyIndex = GetPresentQueue.FamilyIndex,                         // uint32_t                     dstQueueFamilyIndex
                        image                       = swap_chain_images[i].Handle,                         // VkImage                      image
                        subresourceRange            = image_subresource_range                              // VkImageSubresourceRange      subresourceRange
                    };
                    vk.CmdPipelineBarrier(
                        Vulkan.GraphicsCommandBuffers[i],
                        PipelineStageFlagBits.ColorAttachmentOutputBit,
                        PipelineStageFlagBits.BottomOfPipeBit,
                        (DependencyFlagBits)0,
                        0, (MemoryBarrier *)0,
                        0, (BufferMemoryBarrier *)0,
                        1, &barrier_from_draw_to_present);
                }
                vk.EndCommandBuffer(Vulkan.GraphicsCommandBuffers[i]).CheckError();
            }
        }
Esempio n. 20
0
    public Result CreateReservedResource1 <T>(ResourceDescription description, ResourceStates initialState, ClearValue clearValue, ID3D12ProtectedResourceSession protectedResourceSession, out T?resource) where T : ID3D12Resource1
    {
        Result result = CreateReservedResource1(ref description, initialState, clearValue, protectedResourceSession, typeof(T).GUID, out IntPtr nativePtr);

        if (result.Failure)
        {
            resource = default;
            return(result);
        }

        resource = MarshallingHelpers.FromPointer <T>(nativePtr);
        return(result);
    }
Esempio n. 21
0
        public void Initialize(Int32 width, Int32 height, IntPtr outputHandle)
        {
            // provide a convinent syntax that ensures the correct use of IDisposable objects
            // only factory is enabled in this scope
            using (var factory = new Factory4())
            {
                m_Desc = new SwapChainDescription()
                {
                    BufferCount       = FrameCount,
                    ModeDescription   = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage             = Usage.RenderTargetOutput,
                    OutputHandle      = outputHandle,
                    SwapEffect        = SwapEffect.FlipDiscard,
                    SampleDescription = new SampleDescription(1, 0), //@TODO enable 4xMSAA
                    IsWindowed        = true,
                };

                using (var tempSwapChain = new SwapChain(factory, m_CommandListPoolRef.CommandQueue, m_Desc))
                // @TODO - temporary
                //CommandQueue cmdQueue = H1Global<H1ManagedRenderer>.Instance.m_CommandQueue;
                //using (var tempSwapChain = new SwapChain(factory, cmdQueue, m_Desc))
                {
                    m_DXGISwapChain = tempSwapChain.QueryInterface <SwapChain3>();
                }
            }

            // set the back buffer resources
            for (Int32 n = 0; n < FrameCount; ++n)
            {
                m_BackBuffers.Add(m_DXGISwapChain.GetBackBuffer <SharpDX.Direct3D12.Resource>(n));
            }

            // @TODO need to move this chunk of codes to SwapChain
            #region Temp
            //@TODO - temp
            //H1DX12Device deviceDX12 = m_CommandListPoolRef.Device;
            H1DX12Device deviceDX12 = H1Global <H1ManagedRenderer> .Instance.Dx12Device;

            // create RTV descriptor heap
            deviceDX12.RenderTargetDescriptorCache.Initialize(deviceDX12.Device, FrameCount, false, H1ViewType.RenderTargetView);

            // create DSV descriptor heap
            deviceDX12.DepthStencilDescriptorCache.Initialize(deviceDX12.Device, 1, false, H1ViewType.DepthStencilView);

            // create CBV descriptor heap
            //H1DescriptorHeap generalHeap = new H1DescriptorHeap();
            //generalHeap.Initialize(m_Device, 2, true, H1ViewType.ConstantBufferView);
            //m_GlobalDescriptorHeaps.Add(generalHeap);

            // create frame resource
            // 1. RTV
            for (Int32 n = 0; n < FrameCount; ++n)
            {
                // get available alloc cpu address (internally update cursor in H1DescriptorHeap)
                CpuDescriptorHandle         rtvHandle      = deviceDX12.RenderTargetDescriptorCache.GetAvailableAllocCpuAddress();
                SharpDX.Direct3D12.Resource resourceForRTV = GetBackBuffer(n);
                deviceDX12.Device.CreateRenderTargetView(resourceForRTV, null, rtvHandle);
            }

            // 2. DSV
            DepthStencilViewDescription dsvDesc = new DepthStencilViewDescription();
            dsvDesc.Format    = SharpDX.DXGI.Format.D32_Float;
            dsvDesc.Dimension = DepthStencilViewDimension.Texture2D;
            dsvDesc.Flags     = DepthStencilViewFlags.None;

            ClearValue depthOptimizedClearValue = new ClearValue();
            depthOptimizedClearValue.Format               = SharpDX.DXGI.Format.D32_Float;
            depthOptimizedClearValue.DepthStencil.Depth   = 1.0f;
            depthOptimizedClearValue.DepthStencil.Stencil = 0;

            m_DepthStencil = deviceDX12.Device.CreateCommittedResource(
                new HeapProperties(HeapType.Default),
                HeapFlags.None,
                ResourceDescription.Texture2D(SharpDX.DXGI.Format.D32_Float, width, height, 1, 0, 1, 0, ResourceFlags.AllowDepthStencil),
                ResourceStates.DepthWrite,
                depthOptimizedClearValue);

            CpuDescriptorHandle dsvHandle = deviceDX12.DepthStencilDescriptorCache.GetAvailableAllocCpuAddress();
            deviceDX12.Device.CreateDepthStencilView(m_DepthStencil, dsvDesc, dsvHandle);

            #endregion
        }
Esempio n. 22
0
        private void LoadPipeline(RenderForm form)
        {
            int width  = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            viewport.Width    = width;
            viewport.Height   = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right  = width;
            scissorRect.Bottom = height;

#if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
#endif
            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);
            using (var factory = new Factory4())
            {
                // Describe and create the command queue.
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);


                // Describe and create the swap chain.
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount     = FrameCount,
                    ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage           = Usage.RenderTargetOutput,
                    SwapEffect      = SwapEffect.FlipDiscard,
                    OutputHandle    = form.Handle,
                    //Flags = SwapChainFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed        = true
                };

                SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface <SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags           = DescriptorHeapFlags.None,
                Type            = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);

            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            // Create frame resources.
            CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer <Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtvHandle);
                rtvHandle += rtvDescriptorSize;
            }


            //create depth buffer;
            DescriptorHeapDescription dsvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags           = DescriptorHeapFlags.None,
                Type            = DescriptorHeapType.DepthStencilView
            };
            depthStencilViewHeap = device.CreateDescriptorHeap(dsvHeapDesc);
            CpuDescriptorHandle dsvHandle = depthStencilViewHeap.CPUDescriptorHandleForHeapStart;

            ClearValue depthOptimizedClearValue = new ClearValue()
            {
                Format       = Format.D32_Float,
                DepthStencil = new DepthStencilValue()
                {
                    Depth = 1.0F, Stencil = 0
                },
            };

            depthTarget = device.CreateCommittedResource(
                new HeapProperties(HeapType.Default),
                HeapFlags.None,
                new ResourceDescription(ResourceDimension.Texture2D, 0, width, height, 1, 0, Format.D32_Float, 1, 0, TextureLayout.Unknown, ResourceFlags.AllowDepthStencil),
                ResourceStates.DepthWrite, depthOptimizedClearValue);

            var depthView = new DepthStencilViewDescription()
            {
                Format    = Format.D32_Float,
                Dimension = DepthStencilViewDimension.Texture2D,
                Flags     = DepthStencilViewFlags.None,
            };

            //bind depth buffer
            device.CreateDepthStencilView(depthTarget, null, dsvHandle);

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
            bundleAllocator  = device.CreateCommandAllocator(CommandListType.Bundle);
        }
Esempio n. 23
0
 public T CreateReservedResource1 <T>(ResourceDescription description, ResourceStates initialState, ClearValue clearValue, ID3D12ProtectedResourceSession protectedResourceSession) where T : ID3D12Resource1
 {
     CreateReservedResource1(ref description, initialState, clearValue, protectedResourceSession, typeof(T).GUID, out IntPtr nativePtr).CheckError();
     return(MarshallingHelpers.FromPointer <T>(nativePtr));
 }
Esempio n. 24
0
        void loadDevice()
        {
            _resources = new GraphicsResource[0];

            _viewport.Width    = WIDTH;
            _viewport.Height   = HEIGHT;
            _viewport.MaxDepth = 1.0f;

            _scissorRect.Right  = WIDTH;
            _scissorRect.Bottom = HEIGHT;

#if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
#endif

            using (var factory = new Factory4())
            {
                _device = new Device(factory.GetAdapter(_adapterIndex), SharpDX.Direct3D.FeatureLevel.Level_12_1).QueryInterface <Device3>();
                // Describe and create the command queue.
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                _graphicsQueue = _device.CreateCommandQueue(queueDesc);


                // Describe and create the swap chain.
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount       = FRAME_COUNT,
                    ModeDescription   = new ModeDescription(WIDTH, HEIGHT, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage             = Usage.RenderTargetOutput,
                    SwapEffect        = SwapEffect.FlipDiscard,
                    OutputHandle      = _window.Handle,
                    Flags             = SwapChainFlags.AllowModeSwitch,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed        = true
                };

                SwapChain tempSwapChain = new SwapChain(factory, _graphicsQueue, swapChainDesc);
                _swapChain = tempSwapChain.QueryInterface <SwapChain3>();
                tempSwapChain.Dispose();
                _frameIndex = _swapChain.CurrentBackBufferIndex;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FRAME_COUNT,
                Flags           = DescriptorHeapFlags.None,
                Type            = DescriptorHeapType.RenderTargetView
            };

            _renderTargetViewHeap = _device.CreateDescriptorHeap(rtvHeapDesc);

            DescriptorHeapDescription _dsvHeapDescription = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Flags           = DescriptorHeapFlags.None,
                NodeMask        = 0,
                Type            = DescriptorHeapType.DepthStencilView
            };
            _depthStencilView = _device.CreateDescriptorHeap(_dsvHeapDescription);

            _rtvDescriptorSize = _device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            // Create frame resources.
            CpuDescriptorHandle rtvHandle = _renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FRAME_COUNT; n++)
            {
                _renderTargets[n] = _swapChain.GetBackBuffer <Resource>(n);
                _device.CreateRenderTargetView(_renderTargets[n], null, rtvHandle);
                rtvHandle += _rtvDescriptorSize;
            }

            //Initialize Depth/Stencil Buffer
            _depthStencilDesc = new ResourceDescription(ResourceDimension.Texture2D, 0,
                                                        _window.Width, _window.Height, 1, 1, Format.D24_UNorm_S8_UInt, 1, 0,
                                                        TextureLayout.Unknown, ResourceFlags.AllowDepthStencil);
            _depthStencilClear = new ClearValue()
            {
                DepthStencil = new DepthStencilValue()
                {
                    Depth   = 1.0f,
                    Stencil = 0
                },
                Format = Format.D24_UNorm_S8_UInt
            };
            _depthStencilBuffer = _device.CreateCommittedResource(new HeapProperties(HeapType.Default),
                                                                  HeapFlags.None, _depthStencilDesc, ResourceStates.Common, _depthStencilClear);

            //Create Descriptor to mip level 0 of the entire resource using format of the resouce
            _device.CreateDepthStencilView(_depthStencilBuffer, null, DepthStencilHandle);

            _commandAllocator       = _device.CreateCommandAllocator(CommandListType.Direct);
            _bundleCommandAllocator = _device.CreateCommandAllocator(CommandListType.Bundle);

            // Create the command list.
            _commandList       = _device.CreateCommandList(CommandListType.Direct, _commandAllocator, null);
            _bundleCommandList = _device.CreateCommandList(CommandListType.Bundle, _bundleCommandAllocator, null);

            _commandList.ResourceBarrier(new ResourceBarrier(new ResourceTransitionBarrier(_depthStencilBuffer,
                                                                                           ResourceStates.Common, ResourceStates.DepthWrite)));

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            _bundleCommandList.Close();
        }
Esempio n. 25
0
        protected virtual void OnResize()
        {
            Debug.Assert(Device != null);
            Debug.Assert(SwapChain != null);
            Debug.Assert(DirectCmdListAlloc != null);

            // Flush before changing any resources.
            FlushCommandQueue();

            CommandList.Reset(DirectCmdListAlloc, null);

            // Release the previous resources we will be recreating.
            foreach (Resource buffer in _swapChainBuffers)
            {
                buffer?.Dispose();
            }
            DepthStencilBuffer?.Dispose();

            // Resize the swap chain.
            SwapChain.ResizeBuffers(
                SwapChainBufferCount,
                ClientWidth, ClientHeight,
                BackBufferFormat,
                SwapChainFlags.AllowModeSwitch);

            CpuDescriptorHandle rtvHeapHandle = RtvHeap.CPUDescriptorHandleForHeapStart;

            for (int i = 0; i < SwapChainBufferCount; i++)
            {
                Resource backBuffer = SwapChain.GetBackBuffer <Resource>(i);
                _swapChainBuffers[i] = backBuffer;
                Device.CreateRenderTargetView(backBuffer, null, rtvHeapHandle);
                rtvHeapHandle += RtvDescriptorSize;
            }

            // Create the depth/stencil buffer and view.
            var depthStencilDesc = new ResourceDescription
            {
                Dimension         = ResourceDimension.Texture2D,
                Alignment         = 0,
                Width             = ClientWidth,
                Height            = ClientHeight,
                DepthOrArraySize  = 1,
                MipLevels         = 1,
                Format            = Format.R24G8_Typeless,
                SampleDescription = new SampleDescription
                {
                    Count   = MsaaCount,
                    Quality = MsaaQuality
                },
                Layout = TextureLayout.Unknown,
                Flags  = ResourceFlags.AllowDepthStencil
            };
            var optClear = new ClearValue
            {
                Format       = DepthStencilFormat,
                DepthStencil = new DepthStencilValue
                {
                    Depth   = 1.0f,
                    Stencil = 0
                }
            };

            DepthStencilBuffer = Device.CreateCommittedResource(
                new HeapProperties(HeapType.Default),
                HeapFlags.None,
                depthStencilDesc,
                ResourceStates.Common,
                optClear);

            var depthStencilViewDesc = new DepthStencilViewDescription
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Format    = DepthStencilFormat
            };
            // Create descriptor to mip level 0 of entire resource using a depth stencil format.
            CpuDescriptorHandle dsvHeapHandle = DsvHeap.CPUDescriptorHandleForHeapStart;

            Device.CreateDepthStencilView(DepthStencilBuffer, depthStencilViewDesc, dsvHeapHandle);

            // Transition the resource from its initial state to be used as a depth buffer.
            CommandList.ResourceBarrierTransition(DepthStencilBuffer, ResourceStates.Common, ResourceStates.DepthWrite);

            // Execute the resize commands.
            CommandList.Close();
            CommandQueue.ExecuteCommandList(CommandList);

            // Wait until resize is complete.
            FlushCommandQueue();

            Viewport         = new ViewportF(0, 0, ClientWidth, ClientHeight, 0.0f, 1.0f);
            ScissorRectangle = new RectangleF(0, 0, ClientWidth, ClientHeight);
        }
        private void BuildDepthBuffer()
        {
            DescriptorHeapDescription descDescriptorHeapDSB = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Type = DescriptorHeapType.DepthStencilView,
                Flags = DescriptorHeapFlags.None
            };

            DescriptorHeap descriptorHeapDSB = device.CreateDescriptorHeap(descDescriptorHeapDSB);
            ResourceDescription descDepth = new ResourceDescription()
            {
                Dimension = ResourceDimension.Texture2D,
                DepthOrArraySize = 1,
                MipLevels = 0,
                Flags = ResourceFlags.AllowDepthStencil,
                Width = (int)viewport.Width,
                Height = (int)viewport.Height,
                Format = Format.R32_Typeless,
                Layout = TextureLayout.Unknown,
                SampleDescription = new SampleDescription() { Count = 1 }
            };

            ClearValue dsvClearValue = new ClearValue()
            {
                Format = Format.D32_Float,
                DepthStencil = new DepthStencilValue()
                {
                    Depth = 1.0f,
                    Stencil = 0
                }
            };

            Resource renderTargetDepth = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, descDepth, ResourceStates.GenericRead, dsvClearValue);

            DepthStencilViewDescription depthDSV = new DepthStencilViewDescription()
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Format = Format.D32_Float,
                Texture2D = new DepthStencilViewDescription.Texture2DResource()
                {
                    MipSlice = 0
                }
            };

            device.CreateDepthStencilView(renderTargetDepth, depthDSV, descriptorHeapDSB.CPUDescriptorHandleForHeapStart);
            handleDSV = descriptorHeapDSB.CPUDescriptorHandleForHeapStart;
        }
Esempio n. 27
0
 public ID3D12Resource1 CreateReservedResource1(ResourceDescription description, ResourceStates initialState, ClearValue clearValue, ID3D12ProtectedResourceSession protectedResourceSession)
 {
     return(CreateReservedResource1(ref description, initialState, clearValue, protectedResourceSession, typeof(ID3D12Resource1).GUID));
 }
Esempio n. 28
0
        private void CreateTargets(int width, int height)
        {
            //Viewport and scissorrect
            viewport.Width = width;
            viewport.Height = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right = width;
            scissorRect.Bottom = height;

            // Create frame resources.
            CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer<Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtvHandle);
                rtvHandle += rtvDescriptorSize;
            }

            CpuDescriptorHandle dsvHandle = depthStencilViewHeap.CPUDescriptorHandleForHeapStart;

            ClearValue depthOptimizedClearValue = new ClearValue()
            {
                Format = Format.D32_Float,
                DepthStencil = new DepthStencilValue() { Depth = 1.0F, Stencil = 0 },
            };

            depthTarget = device.CreateCommittedResource(
                new HeapProperties(HeapType.Default),
                HeapFlags.None,
                new ResourceDescription(ResourceDimension.Texture2D, 0, width, height, 1, 0, Format.D32_Float, 1, 0, TextureLayout.Unknown, ResourceFlags.AllowDepthStencil),
                ResourceStates.DepthWrite, depthOptimizedClearValue);

            var depthView = new DepthStencilViewDescription()
            {
                Format = Format.D32_Float,
                Dimension = DepthStencilViewDimension.Texture2D,
                Flags = DepthStencilViewFlags.None,
            };

            //bind depth buffer
            device.CreateDepthStencilView(depthTarget, null, dsvHandle);
        }
        public static H1DX12Texture2D Create(Device device, Vector4 clearValue, H1Texture2D.Description desc, H1SubresourceData[] initialData)
        {
            // converting description to DX12 description
            ResourceDescription desc12 = new ResourceDescription
            {
                Format           = H1RHIDefinitionHelper.ConvertToFormat(desc.Format),
                Width            = Convert.ToInt32(desc.Width),
                Height           = Convert.ToInt32(desc.Height),
                DepthOrArraySize = Convert.ToInt16(desc.ArraySize),
                MipLevels        = Convert.ToInt16(desc.MipLevels),
                Flags            = ResourceFlags.None,
                Layout           = TextureLayout.Unknown,
                Dimension        = ResourceDimension.Texture2D,
            };

            desc12.SampleDescription.Count   = Convert.ToInt32(desc.SampleDesc.Count);
            desc12.SampleDescription.Quality = Convert.ToInt32(desc.SampleDesc.Quality);

            HeapProperties heapProperties  = new HeapProperties(HeapType.Default);
            ResourceStates resourceUsage   = ResourceStates.CopyDestination;
            ClearValue     value           = H1GlobalDX12Definitions.GetDXGIFormatClearValue(desc12.Format, (desc.BindFlags & Convert.ToUInt32(H1BindFlag.DepthStencil)) != 0);
            Boolean        allowClearValue = desc12.Dimension == ResourceDimension.Buffer;

            if (desc.Usage == H1Usage.Immutable)
            {
                heapProperties = new HeapProperties(HeapType.Default);
                resourceUsage  = ResourceStates.CopyDestination;
            }

            else if (desc.Usage == H1Usage.Staging)
            {
                heapProperties = new HeapProperties(HeapType.Readback);
                resourceUsage  = ResourceStates.CopyDestination;
            }

            else if (desc.Usage == H1Usage.Dynamic)
            {
                heapProperties = new HeapProperties(HeapType.Upload);
                resourceUsage  = ResourceStates.GenericRead;
            }

            if (desc.CPUAccessFlags != 0)
            {
                if (desc.CPUAccessFlags == Convert.ToUInt32(H1CPUAccessFlag.Write))
                {
                    heapProperties = new HeapProperties(HeapType.Upload);
                    resourceUsage  = ResourceStates.GenericRead;
                }

                else if (desc.CPUAccessFlags == Convert.ToUInt32(H1CPUAccessFlag.Read))
                {
                    heapProperties = new HeapProperties(HeapType.Readback);
                    resourceUsage  = ResourceStates.CopyDestination;
                }

                else
                {
                    return(null);
                }
            }

            if (clearValue != null)
            {
                if ((desc.BindFlags & Convert.ToUInt32(H1BindFlag.DepthStencil)) != 0)
                {
                    value.DepthStencil.Depth   = clearValue.X;
                    value.DepthStencil.Stencil = Convert.ToByte(clearValue.Y);
                }
                else
                {
                    value.Color = clearValue;
                }
            }

            if ((desc.BindFlags & Convert.ToUInt32(H1BindFlag.UnorderedAccess)) != 0)
            {
                desc12.Flags |= ResourceFlags.AllowUnorderedAccess;
                resourceUsage = ResourceStates.UnorderedAccess;
            }

            if ((desc.BindFlags & Convert.ToUInt32(H1BindFlag.DepthStencil)) != 0)
            {
                desc12.Flags   |= ResourceFlags.AllowDepthStencil;
                allowClearValue = true;
                resourceUsage   = ResourceStates.DepthWrite;
            }

            if ((desc.BindFlags & Convert.ToUInt32(H1BindFlag.RenderTarget)) != 0)
            {
                desc12.Flags   |= ResourceFlags.AllowRenderTarget;
                allowClearValue = true;
                resourceUsage   = ResourceStates.RenderTarget;
            }

            Resource resource = device.CreateCommittedResource(
                heapProperties,
                HeapFlags.None,
                desc12,
                resourceUsage,
                allowClearValue ? value : default(ClearValue?));

            H1DX12Texture2D newTexture = new H1DX12Texture2D();

            newTexture.m_Resource = new H1DX12Resource(resource, resourceUsage, resource.Description, initialData, Convert.ToUInt32(desc12.DepthOrArraySize * desc12.MipLevels));
            return(newTexture);
        }
        private void LoadAssets()
        {
            // Create the root signature description.
            var rootSignatureDesc = new RootSignatureDescription(

                RootSignatureFlags.AllowInputAssemblerInputLayout,
                // Root Parameters
                new[]
                {
                    new RootParameter(ShaderVisibility.All,
                        new []
                        {
                            new DescriptorRange()
                            {
                                RangeType = DescriptorRangeType.ShaderResourceView,
                                DescriptorCount = 1,
                                OffsetInDescriptorsFromTableStart = int.MinValue,
                                BaseShaderRegister = 0
                            },
                            new DescriptorRange()
                            {
                                RangeType = DescriptorRangeType.ConstantBufferView,
                                DescriptorCount = 1,
                                OffsetInDescriptorsFromTableStart = int.MinValue + 1,
                                BaseShaderRegister = 0
                            }
                        }),
                    new RootParameter(ShaderVisibility.Pixel,
                        new DescriptorRange()
                        {
                            RangeType = DescriptorRangeType.Sampler,
                            DescriptorCount = 1,
                            OffsetInDescriptorsFromTableStart = int.MinValue,
                            BaseShaderRegister = 0
                        }),
                });
                //// Samplers
                //new[]
                //{
                //    new StaticSamplerDescription(ShaderVisibility.Pixel, 0, 0)
                //    {
                //        Filter = Filter.MinimumMinMagMipPoint,
                //        AddressUVW = TextureAddressMode.Border,
                //    }
                //});

            rootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.
            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            #if DEBUG
            //var result = SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug);
            var geometryShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            var inputElementDescs = new[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("TEXCOORD",0,Format.R32G32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            var psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                GeometryShader = geometryShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    DepthComparison = Comparison.LessEqual,
                    DepthWriteMask = DepthWriteMask.All,
                    IsStencilEnabled = false
                },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);
            commandList.Close();

            // build vertex buffer

            var triangleVertices = new[]
            {
                //TOP
                new Vertex() {Position = new Vector3(-1f , 1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(1f , 1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(1f , 1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f , 1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                //BOTTOM
                new Vertex() {Position = new Vector3(-1f ,-1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                //LEFT
                new Vertex() {Position = new Vector3(-1f ,-1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(-1f , 1f , 1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f , 1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f ,-1f) , TexCoord = new Vector2(1f ,1f)} ,
                //RIGHT
                new Vertex() {Position = new Vector3(1f ,-1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(1f , 1f , 1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(1f , 1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f ,-1f) , TexCoord = new Vector2(0f ,1f)} ,
                //FRONT
                new Vertex() {Position = new Vector3(-1f , 1f , 1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(1f , 1f , 1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                //BACK
                new Vertex() {Position = new Vector3(-1f , 1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(1f , 1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f ,-1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f ,-1f) , TexCoord = new Vector2(0f ,1f)}
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            // build index buffer

            var triangleIndexes = new uint[]
            {
                0,1,2,
                0,2,3,

                4,6,5,
                4,7,6,

                8,9,10,
                8,10,11,

                12,14,13,
                12,15,14,

                16,18,17,
                16,19,18,

                20,21,22,
                20,22,23
            };

            int indexBufferSize = Utilities.SizeOf(triangleIndexes);

            indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead);
            IntPtr pIndexDataBegin = indexBuffer.Map(0);
            Utilities.Write(pIndexDataBegin, triangleIndexes, 0, triangleIndexes.Length);
            indexBuffer.Unmap(0);

            indexBufferView = new IndexBufferView();
            indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress;
            indexBufferView.SizeInBytes = indexBufferSize;
            indexBufferView.Format = Format.R32_UInt;

            // Create the texture.
            // Describe and create a Texture2D.
            var textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight, 1, 1, 1, 0, ResourceFlags.None, TextureLayout.Unknown, 0);
            texture = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, textureDesc, ResourceStates.GenericRead, null);

            // Copy data to the intermediate upload heap and then schedule a copy
            // from the upload heap to the Texture2D.
            byte[] textureData = Utilities.ReadStream(new FileStream("../../texture1.dds", FileMode.Open));

            texture.Name = "Texture";

            var handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
            var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);
            texture.WriteToSubresource(0, null, ptr, TextureWidth * 4, textureData.Length);
            handle.Free();

            // Describe and create a SRV for the texture.
            var srvDesc = new ShaderResourceViewDescription
            {
                Shader4ComponentMapping = ((((0) & 0x7) |(((1) & 0x7) << 3) |(((2) & 0x7) << (3 * 2)) |(((3) & 0x7) << (3 * 3)) | (1 << (3 * 4)))),

                Format = textureDesc.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D =
                {
                    MipLevels = 1,
                    MostDetailedMip = 0,
                    PlaneSlice = 0,
                    ResourceMinLODClamp = 0.0f
                },
            };

            device.CreateShaderResourceView(texture, srvDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart);

            SamplerStateDescription samplerDesc = new SamplerStateDescription
            {
                Filter = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                MaximumAnisotropy = 0,
                MaximumLod = float.MaxValue,
                MinimumLod = -float.MaxValue,
                MipLodBias = 0,
                ComparisonFunction = Comparison.Never
            };

            device.CreateSampler(samplerDesc, samplerViewHeap.CPUDescriptorHandleForHeapStart);

            // build constant buffer

            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead);

            var cbDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes = (Utilities.SizeOf<ConstantBufferData>() + 255) & ~255
            };
            var srvCbvStep = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            device.CreateConstantBufferView(cbDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart + srvCbvStep);

            constantBufferData = new ConstantBufferData
            {
                Project = Matrix.Identity
            };

            constantBufferPointer = constantBuffer.Map(0);
            Utilities.Write(constantBufferPointer, ref constantBufferData);

            // build depth buffer

            DescriptorHeapDescription descDescriptorHeapDSB = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Type = DescriptorHeapType.DepthStencilView,
                Flags = DescriptorHeapFlags.None
            };

            DescriptorHeap descriptorHeapDSB = device.CreateDescriptorHeap(descDescriptorHeapDSB);
            ResourceDescription descDepth = new ResourceDescription()
            {
                Dimension = ResourceDimension.Texture2D,
                DepthOrArraySize = 1,
                MipLevels = 0,
                Flags = ResourceFlags.AllowDepthStencil,
                Width = (int)viewport.Width,
                Height = (int)viewport.Height,
                Format = Format.R32_Typeless,
                Layout = TextureLayout.Unknown,
                SampleDescription = new SampleDescription() { Count = 1 }
            };

            ClearValue dsvClearValue = new ClearValue()
            {
                Format = Format.D32_Float,
                DepthStencil = new DepthStencilValue()
                {
                    Depth = 1.0f,
                    Stencil = 0
                }
            };

            Resource renderTargetDepth = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, descDepth, ResourceStates.GenericRead, dsvClearValue);

            DepthStencilViewDescription depthDSV = new DepthStencilViewDescription()
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Format = Format.D32_Float,
                Texture2D = new DepthStencilViewDescription.Texture2DResource()
                {
                    MipSlice = 0
                }
            };

            device.CreateDepthStencilView(renderTargetDepth, depthDSV, descriptorHeapDSB.CPUDescriptorHandleForHeapStart);
            handleDSV = descriptorHeapDSB.CPUDescriptorHandleForHeapStart;

            fence = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;
            fenceEvent = new AutoResetEvent(false);
        }
        private void LoadRenderTargetData()
        {
            // Define the geometry for a quad.
            Vertex[] quadBuffer = new Vertex[]
            {
                new Vertex()
                {
                    position = new Vector3(-1, -1, 0), textureCoordinate = new Vector3(0, 1, 0)
                },
                new Vertex()
                {
                    position = new Vector3(-1, 1, 0), textureCoordinate = new Vector3(0, 0, 0)
                },
                new Vertex()
                {
                    position = new Vector3(1, -1, 0), textureCoordinate = new Vector3(1, 1, 0)
                },

                new Vertex()
                {
                    position = new Vector3(-1, 1, 0), textureCoordinate = new Vector3(0, 0, 0)
                },
                new Vertex()
                {
                    position = new Vector3(1, 1, 0), textureCoordinate = new Vector3(1, 0, 0)
                },
                new Vertex()
                {
                    position = new Vector3(1, -1, 0), textureCoordinate = new Vector3(1, 1, 0)
                },
            };

            int vertexBufferSize = Utilities.SizeOf(quadBuffer);

            quadVertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            IntPtr pointer = quadVertexBuffer.Map(0);

            Utilities.Write(pointer, quadBuffer, 0, 6);
            quadVertexBuffer.Unmap(0);


            quadVertexBufferView = new VertexBufferView();
            quadVertexBufferView.BufferLocation = quadVertexBuffer.GPUVirtualAddress;
            quadVertexBufferView.StrideInBytes  = Utilities.SizeOf <Vertex>();
            quadVertexBufferView.SizeInBytes    = vertexBufferSize;


            //Render Target
            ClearValue renderTargetOptimizedClearValue = new ClearValue()
            {
                Format = Format.R8G8B8A8_UNorm,
                Color  = new Vector4(0, 0.2F, 0.4f, 1)
            };

            postProcessingRenderTarget = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None,
                                                                        new ResourceDescription(ResourceDimension.Texture2D, 0, TargetSize, TargetSize, 1, 0, Format.R8G8B8A8_UNorm, 1, 0, TextureLayout.Unknown, ResourceFlags.AllowRenderTarget), ResourceStates.RenderTarget, renderTargetOptimizedClearValue);

            CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart + device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView) * 2;

            device.CreateRenderTargetView(postProcessingRenderTarget, null, rtvHandle);


            //Shader Resource View
            int D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING = 5768;
            ShaderResourceViewDescription desc           = new ShaderResourceViewDescription
            {
                Dimension = ShaderResourceViewDimension.Texture2D,
                Format    = postProcessingRenderTarget.Description.Format,
                Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
            };

            desc.Texture2D.MipLevels           = 1;
            desc.Texture2D.MostDetailedMip     = 0;
            desc.Texture2D.ResourceMinLODClamp = 0;

            //Create Render Target View
            //position start after first constant buffer and textures
            device.CreateShaderResourceView(postProcessingRenderTarget, desc, resourceViewHeap.CPUDescriptorHandleForHeapStart + device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView) * renderTargetViewPosition);

            //Depth Target
            ClearValue depthOptimizedClearValue = new ClearValue()
            {
                Format       = Format.D32_Float,
                DepthStencil = new DepthStencilValue()
                {
                    Depth = 1.0F, Stencil = 0
                },
            };

            postProcessingDepthTarget = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None,
                                                                       new ResourceDescription(ResourceDimension.Texture2D, 0, TargetSize, TargetSize, 1, 0, Format.D32_Float, 1, 0, TextureLayout.Unknown, ResourceFlags.AllowDepthStencil), ResourceStates.DepthWrite, depthOptimizedClearValue);

            CpuDescriptorHandle dpsHandle = depthStencilViewHeap.CPUDescriptorHandleForHeapStart + device.GetDescriptorHandleIncrementSize(DescriptorHeapType.DepthStencilView);

            device.CreateDepthStencilView(postProcessingDepthTarget, null, dpsHandle);


            //Shader

#if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("postProcessing.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
#endif

#if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("postProcessing.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
#endif

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32B32_Float, 24, 0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout           = new InputLayoutDescription(inputElementDescs),
                RootSignature         = rootSignature,
                VertexShader          = vertexShader,
                PixelShader           = pixelShader,
                RasterizerState       = RasterizerStateDescription.Default(),
                BlendState            = BlendStateDescription.Default(),
                DepthStencilFormat    = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState     = DepthStencilStateDescription.Default(),
                SampleMask            = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount     = 1,
                Flags             = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput      = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            postProcessingPipelineState = device.CreateGraphicsPipelineState(psoDesc);

            //constant Buffer
            int constantBufferSize = (Utilities.SizeOf <PostProcessingData>() + 255) & ~255;
            postProcessingConstantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(constantBufferSize), ResourceStates.GenericRead);

            //constant buffer
            ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = postProcessingConstantBuffer.GPUVirtualAddress,
                SizeInBytes    = constantBufferSize
            };

            var heapPosition = resourceViewHeap.CPUDescriptorHandleForHeapStart + device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView) * renderTargetConstantBufferPosition;
            device.CreateConstantBufferView(cbvDesc, heapPosition);
        }
        private void LoadAssets()
        {
            // Create the root signature description.
            var rootSignatureDesc = new RootSignatureDescription(

                RootSignatureFlags.AllowInputAssemblerInputLayout,
                // Root Parameters
                new[]
            {
                new RootParameter(ShaderVisibility.All,
                                  new []
                {
                    new DescriptorRange()
                    {
                        RangeType       = DescriptorRangeType.ShaderResourceView,
                        DescriptorCount = 1,
                        OffsetInDescriptorsFromTableStart = int.MinValue,
                        BaseShaderRegister = 0
                    },
                    new DescriptorRange()
                    {
                        RangeType       = DescriptorRangeType.ConstantBufferView,
                        DescriptorCount = 1,
                        OffsetInDescriptorsFromTableStart = int.MinValue + 1,
                        BaseShaderRegister = 0
                    }
                }),
                new RootParameter(ShaderVisibility.Pixel,
                                  new DescriptorRange()
                {
                    RangeType       = DescriptorRangeType.Sampler,
                    DescriptorCount = 1,
                    OffsetInDescriptorsFromTableStart = int.MinValue,
                    BaseShaderRegister = 0
                }),
            });

            //// Samplers
            //new[]
            //{
            //    new StaticSamplerDescription(ShaderVisibility.Pixel, 0, 0)
            //    {
            //        Filter = Filter.MinimumMinMagMipPoint,
            //        AddressUVW = TextureAddressMode.Border,
            //    }
            //});

            rootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.
#if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
#endif

#if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
#endif

#if DEBUG
            //var result = SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug);
            var geometryShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
#else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
#endif

            // Define the vertex input layout.
            var inputElementDescs = new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            var psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout        = new InputLayoutDescription(inputElementDescs),
                RootSignature      = rootSignature,
                VertexShader       = vertexShader,
                GeometryShader     = geometryShader,
                PixelShader        = pixelShader,
                RasterizerState    = RasterizerStateDescription.Default(),
                BlendState         = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState  = new DepthStencilStateDescription()
                {
                    IsDepthEnabled   = true,
                    DepthComparison  = Comparison.LessEqual,
                    DepthWriteMask   = DepthWriteMask.All,
                    IsStencilEnabled = false
                },
                SampleMask            = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount     = 1,
                Flags             = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput      = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);
            commandList.Close();

            // build vertex buffer

            var triangleVertices = new[]
            {
                //TOP
                new Vertex()
                {
                    Position = new Vector3(-1f, 1f, 1f), TexCoord = new Vector2(1f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, 1f, 1f), TexCoord = new Vector2(0f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, 1f, -1f), TexCoord = new Vector2(0f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(-1f, 1f, -1f), TexCoord = new Vector2(1f, 0f)
                },
                //BOTTOM
                new Vertex()
                {
                    Position = new Vector3(-1f, -1f, 1f), TexCoord = new Vector2(1f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, -1f, 1f), TexCoord = new Vector2(0f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, -1f, -1f), TexCoord = new Vector2(0f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(-1f, -1f, -1f), TexCoord = new Vector2(1f, 0f)
                },
                //LEFT
                new Vertex()
                {
                    Position = new Vector3(-1f, -1f, 1f), TexCoord = new Vector2(0f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(-1f, 1f, 1f), TexCoord = new Vector2(0f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(-1f, 1f, -1f), TexCoord = new Vector2(1f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(-1f, -1f, -1f), TexCoord = new Vector2(1f, 1f)
                },
                //RIGHT
                new Vertex()
                {
                    Position = new Vector3(1f, -1f, 1f), TexCoord = new Vector2(1f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, 1f, 1f), TexCoord = new Vector2(1f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, 1f, -1f), TexCoord = new Vector2(0f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, -1f, -1f), TexCoord = new Vector2(0f, 1f)
                },
                //FRONT
                new Vertex()
                {
                    Position = new Vector3(-1f, 1f, 1f), TexCoord = new Vector2(1f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, 1f, 1f), TexCoord = new Vector2(0f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, -1f, 1f), TexCoord = new Vector2(0f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(-1f, -1f, 1f), TexCoord = new Vector2(1f, 1f)
                },
                //BACK
                new Vertex()
                {
                    Position = new Vector3(-1f, 1f, -1f), TexCoord = new Vector2(0f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, 1f, -1f), TexCoord = new Vector2(1f, 0f)
                },
                new Vertex()
                {
                    Position = new Vector3(1f, -1f, -1f), TexCoord = new Vector2(1f, 1f)
                },
                new Vertex()
                {
                    Position = new Vector3(-1f, -1f, -1f), TexCoord = new Vector2(0f, 1f)
                }
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes  = Utilities.SizeOf <Vertex>();
            vertexBufferView.SizeInBytes    = vertexBufferSize;

            // build index buffer

            var triangleIndexes = new uint[]
            {
                0, 1, 2,
                0, 2, 3,

                4, 6, 5,
                4, 7, 6,

                8, 9, 10,
                8, 10, 11,

                12, 14, 13,
                12, 15, 14,

                16, 18, 17,
                16, 19, 18,

                20, 21, 22,
                20, 22, 23
            };

            int indexBufferSize = Utilities.SizeOf(triangleIndexes);

            indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead);
            IntPtr pIndexDataBegin = indexBuffer.Map(0);
            Utilities.Write(pIndexDataBegin, triangleIndexes, 0, triangleIndexes.Length);
            indexBuffer.Unmap(0);

            indexBufferView = new IndexBufferView();
            indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress;
            indexBufferView.SizeInBytes    = indexBufferSize;
            indexBufferView.Format         = Format.R32_UInt;

            // Create the texture.
            // Describe and create a Texture2D.
            var textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight, 1, 1, 1, 0, ResourceFlags.None, TextureLayout.Unknown, 0);
            texture = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, textureDesc, ResourceStates.GenericRead, null);

            // Copy data to the intermediate upload heap and then schedule a copy
            // from the upload heap to the Texture2D.
            byte[] textureData = Utilities.ReadStream(new FileStream("../../texture1.dds", FileMode.Open));

            texture.Name = "Texture";

            var handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
            var ptr    = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);
            texture.WriteToSubresource(0, null, ptr, TextureWidth * 4, textureData.Length);
            handle.Free();

            // Describe and create a SRV for the texture.
            var srvDesc = new ShaderResourceViewDescription
            {
                Shader4ComponentMapping = ((((0) & 0x7) | (((1) & 0x7) << 3) | (((2) & 0x7) << (3 * 2)) | (((3) & 0x7) << (3 * 3)) | (1 << (3 * 4)))),

                Format    = textureDesc.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D =
                {
                    MipLevels           = 1,
                    MostDetailedMip     = 0,
                    PlaneSlice          = 0,
                    ResourceMinLODClamp = 0.0f
                },
            };

            device.CreateShaderResourceView(texture, srvDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart);

            SamplerStateDescription samplerDesc = new SamplerStateDescription
            {
                Filter             = Filter.MinMagMipLinear,
                AddressU           = TextureAddressMode.Clamp,
                AddressV           = TextureAddressMode.Clamp,
                AddressW           = TextureAddressMode.Clamp,
                MaximumAnisotropy  = 0,
                MaximumLod         = float.MaxValue,
                MinimumLod         = -float.MaxValue,
                MipLodBias         = 0,
                ComparisonFunction = Comparison.Never
            };

            device.CreateSampler(samplerDesc, samplerViewHeap.CPUDescriptorHandleForHeapStart);

            // build constant buffer

            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead);

            var cbDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes    = (Utilities.SizeOf <ConstantBufferData>() + 255) & ~255
            };
            var srvCbvStep = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            device.CreateConstantBufferView(cbDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart + srvCbvStep);

            constantBufferData = new ConstantBufferData
            {
                Project = Matrix.Identity
            };

            constantBufferPointer = constantBuffer.Map(0);
            Utilities.Write(constantBufferPointer, ref constantBufferData);

            // build depth buffer

            DescriptorHeapDescription descDescriptorHeapDSB = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Type            = DescriptorHeapType.DepthStencilView,
                Flags           = DescriptorHeapFlags.None
            };

            DescriptorHeap      descriptorHeapDSB = device.CreateDescriptorHeap(descDescriptorHeapDSB);
            ResourceDescription descDepth         = new ResourceDescription()
            {
                Dimension         = ResourceDimension.Texture2D,
                DepthOrArraySize  = 1,
                MipLevels         = 0,
                Flags             = ResourceFlags.AllowDepthStencil,
                Width             = (int)viewport.Width,
                Height            = (int)viewport.Height,
                Format            = Format.R32_Typeless,
                Layout            = TextureLayout.Unknown,
                SampleDescription = new SampleDescription()
                {
                    Count = 1
                }
            };

            ClearValue dsvClearValue = new ClearValue()
            {
                Format       = Format.D32_Float,
                DepthStencil = new DepthStencilValue()
                {
                    Depth   = 1.0f,
                    Stencil = 0
                }
            };

            Resource renderTargetDepth = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, descDepth, ResourceStates.GenericRead, dsvClearValue);

            DepthStencilViewDescription depthDSV = new DepthStencilViewDescription()
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Format    = Format.D32_Float,
                Texture2D = new DepthStencilViewDescription.Texture2DResource()
                {
                    MipSlice = 0
                }
            };

            device.CreateDepthStencilView(renderTargetDepth, depthDSV, descriptorHeapDSB.CPUDescriptorHandleForHeapStart);
            handleDSV = descriptorHeapDSB.CPUDescriptorHandleForHeapStart;

            fence      = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;
            fenceEvent = new AutoResetEvent(false);
        }