private void LoadAssets()
        {
            DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0 } };

            StaticSamplerDescription sampler = new StaticSamplerDescription()
            {
                Filter = Filter.MinimumMinMagMipPoint,
                AddressU = TextureAddressMode.Border,
                AddressV = TextureAddressMode.Border,
                AddressW = TextureAddressMode.Border,
                MipLODBias = 0,
                MaxAnisotropy = 0,
                ComparisonFunc = Comparison.Never,
                BorderColor = StaticBorderColor.TransparentBlack,
                MinLOD = 0.0f,
                MaxLOD = float.MaxValue,
                ShaderRegister = 0,
                RegisterSpace = 0,
                ShaderVisibility = ShaderVisibility.Pixel,
            };

            RootParameter[] rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.Pixel, ranges) };

            RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters, new StaticSamplerDescription[] { sampler });
            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.CompileFromFile("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.CompileFromFile("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

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                    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).
            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 = new DepthStencilStateDescription() { IsDepthEnabled = false, 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);

            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);

            // Create the vertex buffer.
            float aspectRatio = viewport.Width / viewport.Height;

            // Define the geometry for a triangle.
            Vertex[] triangleVertices = new Vertex[]
            {
                    new Vertex() {position=new Vector3(0.0f, 0.25f * aspectRatio, 0.0f ),uv=new Vector2(0.5f, 0.0f) },
                    new Vertex() {position=new Vector3(0.25f, -0.25f * aspectRatio, 0.0f),uv=new Vector2(1.0f, 1.0f) },
                    new Vertex() {position=new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f),uv=new Vector2(0.0f, 1.0f) },
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            Resource textureUploadHeap;

            // Create the texture.
            // Describe and create a Texture2D.
            ResourceDescription textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight);
            texture = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, textureDesc, ResourceStates.CopyDestination);

            long uploadBufferSize = GetRequiredIntermediateSize(this.texture, 0, 1);

            // Create the GPU upload buffer.
            textureUploadHeap = device.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight), ResourceStates.GenericRead);

            // Copy data to the intermediate upload heap and then schedule a copy
            // from the upload heap to the Texture2D.
            byte[] textureData = GenerateTextureData();

            GCHandle handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
            IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);
            textureUploadHeap.WriteToSubresource(0, null, ptr, TexturePixelSize * TextureWidth, textureData.Length);
            handle.Free();

            commandList.CopyTextureRegion(new TextureCopyLocation(texture, 0), 0, 0, 0, new TextureCopyLocation(textureUploadHeap, 0), null);

            commandList.ResourceBarrierTransition(this.texture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource);

            // Describe and create a SRV for the texture.
            ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription()
            {
                Shader4ComponentMapping = D3DXUtilities.DefaultComponentMapping(),
                Format = textureDesc.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
            };
            srvDesc.Texture2D.MipLevels = 1;

            device.CreateShaderResourceView(this.texture, srvDesc, shaderRenderViewHeap.CPUDescriptorHandleForHeapStart);

            // 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.
            commandList.Close();

            commandQueue.ExecuteCommandList(commandList);

            // Create synchronization objects.
            fence = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;

            // Create an event handle to use for frame synchronization.
            fenceEvent = new AutoResetEvent(false);

            WaitForPreviousFrame();

            //release temp texture
            textureUploadHeap.Dispose();
        }
Пример #2
0
        public override ImageCapture CaptureRenderTarget(RenderTarget surface)
        {
            IntPtr texNativePtr = RenderDeviceD3D11.GetTextureNativePointer(surface.Texture);

            SharpDX.Direct3D12.Resource            texture = new SharpDX.Direct3D12.Resource(texNativePtr);
            SharpDX.Direct3D12.ResourceDescription texDesc = texture.Description;

            // Transition PIXEL_SHADER_RESOURCE -> COPY_SOURCE
            SharpDX.Direct3D12.ResourceBarrier barrier = new SharpDX.Direct3D12.ResourceBarrier();
            barrier.Type       = SharpDX.Direct3D12.ResourceBarrierType.Transition;
            barrier.Flags      = SharpDX.Direct3D12.ResourceBarrierFlags.None;
            barrier.Transition = new SharpDX.Direct3D12.ResourceTransitionBarrier(texture,
                                                                                  SharpDX.Direct3D12.ResourceStates.PixelShaderResource,
                                                                                  SharpDX.Direct3D12.ResourceStates.CopySource)
            {
                Subresource = 0
            };

            _commands.ResourceBarrier(barrier);

            long totalBytes;

            long[] rowSize = { 0 };
            _dev.GetCopyableFootprints(ref texDesc, 0, 1, 0, null, null, rowSize, out totalBytes);
            long pitch = (rowSize[0] + 255) & ~255;

            // Create staging texture
            SharpDX.Direct3D12.HeapProperties heap;
            heap.Type                 = SharpDX.Direct3D12.HeapType.Readback;
            heap.CPUPageProperty      = SharpDX.Direct3D12.CpuPageProperty.Unknown;
            heap.MemoryPoolPreference = SharpDX.Direct3D12.MemoryPool.Unknown;
            heap.CreationNodeMask     = 0;
            heap.VisibleNodeMask      = 0;

            SharpDX.Direct3D12.ResourceDescription desc;
            desc.Dimension         = SharpDX.Direct3D12.ResourceDimension.Buffer;
            desc.Alignment         = 0;
            desc.Width             = pitch * texDesc.Height * 4;
            desc.Height            = 1;
            desc.DepthOrArraySize  = 1;
            desc.MipLevels         = 1;
            desc.Format            = SharpDX.DXGI.Format.Unknown;
            desc.SampleDescription = new SampleDescription {
                Count = 1, Quality = 0
            };
            desc.Layout = SharpDX.Direct3D12.TextureLayout.RowMajor;
            desc.Flags  = SharpDX.Direct3D12.ResourceFlags.None;

            SharpDX.Direct3D12.Resource stagingTex = _dev.CreateCommittedResource(heap, SharpDX.Direct3D12.HeapFlags.None,
                                                                                  desc, SharpDX.Direct3D12.ResourceStates.CopyDestination, null);

            SharpDX.Direct3D12.TextureCopyLocation copySrc = new SharpDX.Direct3D12.TextureCopyLocation(texture, 0);
            SharpDX.Direct3D12.TextureCopyLocation copyDst = new SharpDX.Direct3D12.TextureCopyLocation(texture,
                                                                                                        new SharpDX.Direct3D12.PlacedSubResourceFootprint
            {
                Offset    = 0,
                Footprint = new SharpDX.Direct3D12.SubResourceFootprint
                {
                    Width    = (int)texDesc.Width,
                    Height   = (int)texDesc.Height,
                    Depth    = 1,
                    RowPitch = (int)pitch,
                    Format   = texDesc.Format
                }
            });

            // Wait GPU completion
            _commands.CopyTextureRegion(copyDst, 0, 0, 0, copySrc, null);
            _commands.Close();
            _queue.ExecuteCommandList(_commands);
            WaitForGpu();

            // Ensure image capture object is created with the appropriate size
            if (_imageCapture == null || _imageCapture.Width != desc.Width || _imageCapture.Height != desc.Height)
            {
                _imageCapture = new ImageCapture((uint)desc.Width, (uint)desc.Height);
            }

            // Map and copy to image
            byte[] dst = _imageCapture.Pixels;
            IntPtr src = stagingTex.Map(0);

            for (int i = 0; i < desc.Height; ++i)
            {
                int dstRow = i * (int)_imageCapture.Stride;
                int srcRow = i * (int)pitch;

                for (int j = 0; j < desc.Width; j++)
                {
                    // RGBA -> BGRA
                    dst[dstRow + 4 * j + 2] = Noesis.Marshal.ReadByte(src, srcRow + 4 * j + 0);
                    dst[dstRow + 4 * j + 1] = Noesis.Marshal.ReadByte(src, srcRow + 4 * j + 1);
                    dst[dstRow + 4 * j + 0] = Noesis.Marshal.ReadByte(src, srcRow + 4 * j + 2);
                    dst[dstRow + 4 * j + 3] = Noesis.Marshal.ReadByte(src, srcRow + 4 * j + 3);
                }
            }

            stagingTex.Unmap(0);

            return(_imageCapture);
        }