Ejemplo n.º 1
0
        public byte[] GetData(Resource res, int subresource, Size3 size, int pixelByteSize)
        {
            var result      = new byte[size.Product * pixelByteSize];
            var data        = context.MapSubresource(res, subresource, MapMode.Read, MapFlags.None);
            int srcOffset   = 0;
            int dstOffset   = 0;
            int rowSize     = size.Width * pixelByteSize;
            int sliceOffset = data.SlicePitch - data.RowPitch * size.Height;

            Debug.Assert(rowSize <= data.RowPitch);

            for (int curZ = 0; curZ < size.Depth; ++curZ)
            {
                for (int curY = 0; curY < size.Height; ++curY)
                {
                    Marshal.Copy(data.DataPointer + srcOffset, result, dstOffset, rowSize);

                    srcOffset += data.RowPitch;
                    dstOffset += rowSize;
                }
                srcOffset += sliceOffset;
            }

            context.UnmapSubresource(res, subresource);

            return(result);
        }
Ejemplo n.º 2
0
        unsafe void DrawVertices(int[] indices, Vertex[] vertices, int bufferIndex)
        {
            if (bufferIndex != currentBufferIndex)
            {
                indexBuffer        = indexBuffers[bufferIndex];
                vertexBuffer       = vertexBuffers[bufferIndex];
                currentBufferIndex = bufferIndex;

                deviceContext.InputAssembler.SetIndexBuffer(indexBuffer, DXGI.Format.R32_UInt, 0);
                deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer, sizeof(Vertex), 0));
            }

            DataStream stream;

            deviceContext.MapSubresource(indexBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None, out stream);
            stream.Position = 0;
            stream.WriteRange(indices);
            deviceContext.UnmapSubresource(indexBuffer, 0);
            stream.Dispose();

            deviceContext.MapSubresource(vertexBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None, out stream);
            stream.Position = 0;
            stream.WriteRange(vertices);
            deviceContext.UnmapSubresource(vertexBuffer, 0);
            stream.Dispose();

            deviceContext.DrawIndexed(indices.Length, 0, 0);
        }
Ejemplo n.º 3
0
        public WaveSolution[] GetSolutionSet()
        {
            CloseCurrentBuffer();

            DataStream stream;

            WaveSolution[] read;
            ImmediateContext.MapSubresource(_waveSwapChain.CurrentBuffer, 0, D3D11.MapMode.Read, D3D11.MapFlags.None, out stream);

            read = stream.ReadRange <WaveSolution>(VertexCount);

            ImmediateContext.UnmapSubresource(_waveSwapChain.CurrentBuffer, 0);

            return(read);
        }
Ejemplo n.º 4
0
        public void Render()
        {
            if (!_isDirty)
            {
                return;
            }
            if (!IsEnabled)
            {
                return;
            }

            _wicRenderTarget.BeginDraw();
            _wicRenderTarget.Clear(_clearColor);
            _wicRenderTarget.DrawText(_text, _textFormat, _rect, _sceneColorBrush);
            _wicRenderTarget.EndDraw();

            var        bitmapLock = _wicBitmap.Lock(SharpDX.WIC.BitmapLockFlags.Read);
            DataStream stream;

            _immediateContext.MapSubresource(_renderTexture, 0, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out stream);
            stream.WriteRange(bitmapLock.Data.DataPointer, _bitmapSize);
            _immediateContext.UnmapSubresource(_renderTexture, 0);
            stream.Dispose();
            bitmapLock.Dispose();

            _isDirty = false;
        }
        /// <summary>
        /// Sets given content to the constant buffer.
        /// </summary>
        /// <param name="deviceContext">The context used for updating the constant buffer.</param>
        /// <param name="dataToSet">The data to set.</param>
        internal void SetData(D3D11.DeviceContext deviceContext, T dataToSet)
        {
            DataBox dataBox = deviceContext.MapSubresource(base.ConstantBuffer, 0, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None);

            SharpDX.Utilities.Write(dataBox.DataPointer, ref dataToSet);
            deviceContext.UnmapSubresource(base.ConstantBuffer, 0);
        }
        /// <summary>
        /// Triggers internal rendering within the resource (e. g. Render to Texture).
        /// </summary>
        /// <param name="renderState">Current render state.</param>
        public void Render(RenderState renderState)
        {
            D3D11.DeviceContext deviceContext = renderState.Device.DeviceImmediateContextD3D11;

            // Upload the last read video frame to texture buffer on the graphics device
            if (m_thumbnailFrame != null)
            {
                SharpDX.DataBox dataBox = deviceContext.MapSubresource(m_texture, 0, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None);
                try
                {
                    unsafe
                    {
                        int *frameBufferPointerNative   = (int *)m_thumbnailFrame.Pointer.ToPointer();
                        int *textureBufferPointerNative = (int *)dataBox.DataPointer.ToPointer();

                        // Performance optimization using MemCopy
                        //  see http://www.rolandk.de/wp/2015/05/wie-schnell-man-speicher-falsch-kopieren-kann/
                        for (int loopY = 0; loopY < m_videoHeight; loopY++)
                        {
                            IntPtr rowStartTexture = new IntPtr(textureBufferPointerNative + (dataBox.RowPitch / 4) * loopY);
                            IntPtr rowStartSource  = new IntPtr(frameBufferPointerNative + (m_videoWidth) * loopY);
                            CommonTools.CopyMemory(rowStartSource, rowStartTexture, (ulong)dataBox.RowPitch);
                        }
                    }
                }
                finally
                {
                    GraphicsHelper.SafeDispose(ref m_thumbnailFrame);
                    deviceContext.UnmapSubresource(m_texture, 0);
                }
            }
        }
Ejemplo n.º 7
0
        public void TakeSnapshot(string fileName)
        {
            Texture2D snapshotTexture;

            lock (device)
            {
                Utilities.Dispose(ref rtv);
                Utilities.Dispose(ref backBuffer);

                swapChain.ResizeBuffers(0, decoder.vDecoder.info.Width, decoder.vDecoder.info.Height, Format.Unknown, SwapChainFlags.None);
                backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
                rtv        = new RenderTargetView(device, backBuffer);
                context.Rasterizer.SetViewport(0, 0, backBuffer.Description.Width, backBuffer.Description.Height);

                for (int i = 0; i < swapChain.Description.BufferCount; i++)
                {
                    context.OutputMerger.SetRenderTargets(rtv);
                    context.ClearRenderTargetView(rtv, cfg.video._ClearColor);
                    context.Draw(6, 0);
                    swapChain.Present(cfg.video.VSync, PresentFlags.None);
                }

                snapshotTexture = new Texture2D(device, new Texture2DDescription()
                {
                    Usage             = ResourceUsage.Staging,
                    ArraySize         = 1,
                    MipLevels         = 1,
                    Width             = backBuffer.Description.Width,
                    Height            = backBuffer.Description.Height,
                    Format            = Format.B8G8R8A8_UNorm,
                    BindFlags         = BindFlags.None,
                    CpuAccessFlags    = CpuAccessFlags.Read,
                    OptionFlags       = ResourceOptionFlags.None,
                    SampleDescription = new SampleDescription(1, 0)
                });
                context.CopyResource(backBuffer, snapshotTexture);
                ResizeBuffers(null, null);
            }

            System.Drawing.Bitmap snapshotBitmap = new System.Drawing.Bitmap(snapshotTexture.Description.Width, snapshotTexture.Description.Height);
            DataBox db         = context.MapSubresource(snapshotTexture, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None);
            var     bitmapData = snapshotBitmap.LockBits(new System.Drawing.Rectangle(0, 0, snapshotBitmap.Width, snapshotBitmap.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var     sourcePtr  = db.DataPointer;
            var     destPtr    = bitmapData.Scan0;

            for (int y = 0; y < snapshotBitmap.Height; y++)
            {
                Utilities.CopyMemory(destPtr, sourcePtr, snapshotBitmap.Width * 4);

                sourcePtr = IntPtr.Add(sourcePtr, db.RowPitch);
                destPtr   = IntPtr.Add(destPtr, bitmapData.Stride);
            }
            snapshotBitmap.UnlockBits(bitmapData);
            context.UnmapSubresource(snapshotTexture, 0);
            snapshotTexture.Dispose();

            try { snapshotBitmap.Save(fileName); } catch (Exception) { }
            snapshotBitmap.Dispose();
        }
Ejemplo n.º 8
0
        public T[] GetData <T>(int count) where T : struct
        {
            _deviceContext.CopyResource(_buffer, _resultBuffer);

            SharpDX.DataStream stream;
            SharpDX.DataBox    box = _deviceContext.MapSubresource(_resultBuffer, 0, MapMode.Read, MapFlags.None, out stream);
            T[] result             = stream.ReadRange <T>(count);
            _deviceContext.UnmapSubresource(_buffer, 0);

            return(result);
        }
 public static int[] GetIntArrayFromByfferData(SharpDX.Direct3D11.DeviceContext dc, SharpDX.Direct3D11.Buffer histogramCPU)
 {
     try
     {
         var   databox  = dc.MapSubresource(histogramCPU, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None);
         int[] intArray = new int[databox.RowPitch / sizeof(int)];
         System.Runtime.InteropServices.Marshal.Copy(databox.DataPointer, intArray, 0, intArray.Length);
         return(intArray);
     }
     finally
     {
         dc.UnmapSubresource(histogramCPU, 0);
     }
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Triggers internal rendering within the resource (e. g. Render to Texture).
        /// </summary>
        /// <param name="renderState">Current render state.</param>
        public void Render(RenderState renderState)
        {
            D3D11.DeviceContext deviceContext = renderState.Device.DeviceImmediateContextD3D11;

            // Do nothing here if we have no new frame to render
            if (m_lastFrameTimestamp >= m_videoReader.CurrentFrameTimestamp)
            {
                return;
            }

            // Upload the last read video frame to texture buffer on the graphics device
            using (SeeingSharpMediaBuffer mediaBuffer = m_videoReader.GetCurrentFrame())
            {
                MF.MediaBuffer  mediaBufferNative = mediaBuffer.GetBuffer();
                SharpDX.DataBox dataBox           = deviceContext.MapSubresource(m_texture, 0, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None);
                try
                {
                    int    cbMaxLength;
                    int    cbCurrentLenght;
                    IntPtr mediaBufferPointer = mediaBufferNative.Lock(out cbMaxLength, out cbCurrentLenght);
                    try
                    {
                        unsafe
                        {
                            int *frameBufferPointerNative   = (int *)mediaBufferPointer.ToPointer();
                            int *textureBufferPointerNative = (int *)dataBox.DataPointer.ToPointer();

                            // Performance optimization using MemCopy
                            //  see http://www.rolandk.de/wp/2015/05/wie-schnell-man-speicher-falsch-kopieren-kann/
                            for (int loopY = 0; loopY < m_currentHeight; loopY++)
                            {
                                IntPtr rowStartTexture = new IntPtr(textureBufferPointerNative + (dataBox.RowPitch / 4) * loopY);
                                IntPtr rowStartSource  = new IntPtr(frameBufferPointerNative + (m_currentWidth) * loopY);
                                CommonTools.CopyMemory(rowStartSource, rowStartTexture, (ulong)dataBox.RowPitch);
                            }
                        }
                    }
                    finally
                    {
                        mediaBufferNative.Unlock();
                    }
                }
                finally
                {
                    deviceContext.UnmapSubresource(m_texture, 0);
                }
            }
        }
Ejemplo n.º 11
0
        private Stream DumpAndSaveImage()
        {
            var stream            = new MemoryStream();
            var textureSDRCpuCopy = new D3D11.Texture2D(d3dDevice, new D3D11.Texture2DDescription
            {
                Width             = description.CanvasRect.Width,
                Height            = description.CanvasRect.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = DXGI.Format.B8G8R8A8_UNorm_SRgb,
                Usage             = D3D11.ResourceUsage.Staging,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                BindFlags         = D3D11.BindFlags.None,
                CpuAccessFlags    = D3D11.CpuAccessFlags.Read,
                OptionFlags       = D3D11.ResourceOptionFlags.None,
            });

            DataStream rawSdrImageDataStream;

            d3dContext.CopyResource(textureSDRImage, textureSDRCpuCopy);

            var dataBox       = d3dContext.MapSubresource(textureSDRCpuCopy, 0, 0, D3D11.MapMode.Read, D3D11.MapFlags.None, out rawSdrImageDataStream);
            var dataRectangle = new DataRectangle
            {
                DataPointer = rawSdrImageDataStream.DataPointer,
                Pitch       = dataBox.RowPitch,
            };

            using (var bitmap = new WIC.Bitmap(wicFactory, description.CanvasRect.Width, description.CanvasRect.Height, WIC.PixelFormat.Format32bppBGRA, dataRectangle))
                using (var imageEncoder = new WIC.BmpBitmapEncoder(wicFactory, stream))
                    using (var encodeInstance = new WIC.BitmapFrameEncode(imageEncoder))
                    {
                        encodeInstance.Initialize();
                        encodeInstance.SetSize(bitmap.Size.Width, bitmap.Size.Height);
                        var pixelFormat = WIC.PixelFormat.Format24bppBGR;
                        encodeInstance.SetPixelFormat(ref pixelFormat);
                        encodeInstance.WriteSource(bitmap);
                        encodeInstance.Commit();
                        imageEncoder.Commit();
                        stream.Flush();
                    }

            d3dContext.UnmapSubresource(textureSDRCpuCopy, 0);
            rawSdrImageDataStream.Dispose();
            textureSDRCpuCopy.Dispose();

            return(stream);
        }
        /// <summary>
        /// Takes a screenshot and returns it as a gdi bitmap.
        /// </summary>
        public GDI.Bitmap TakeScreenshotGdi(GDI.Size size)
        {
            //Get and read data from the gpu (create copy helper texture on demand)
            if (_copyHelperTextureStaging == null)
            {
                _copyHelperTextureStaging = CreateStagingTexture(_d3d11Device, size);
            }
            _d3d11Context.CopyResource(_renderTexture, _copyHelperTextureStaging);

            //Prepare target bitmap
            var result = new GDI.Bitmap(size.Width, size.Height);

            var dataBox = _d3d11Context.MapSubresource(_copyHelperTextureStaging, 0, D3D11.MapMode.Read, D3D11.MapFlags.None);

            try
            {
                //Lock bitmap so it can be accessed for texture loading
                System.Drawing.Imaging.BitmapData bitmapData = result.LockBits(
                    new System.Drawing.Rectangle(0, 0, result.Width, result.Height),
                    System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                try
                {
                    //Copy bitmap data
                    memcpy(bitmapData.Scan0, dataBox.DataPointer, new UIntPtr((uint)(size.Width * size.Height * 4)));
                }
                finally
                {
                    result.UnlockBits(bitmapData);
                }
            }
            finally
            {
                _d3d11Context.UnmapSubresource(_copyHelperTextureStaging, 0);
            }

            return(result);
        }
Ejemplo n.º 13
0
 // TODO: Code that uses temporary resources (that calls this method) should be changed to use Managers and their interfaces
 internal void UnmapSubresource(Resource resourceRef, int subresource)
 {
     m_deviceContext.UnmapSubresource(resourceRef, subresource);
     CheckErrors();
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Copies to a stream using WIC. The format is converted if necessary.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="texture"></param>
        /// <param name="outputFormat"></param>
        /// <param name="stream"></param>
        public void ToStream(SharpDX.Direct3D11.DeviceContext context, Texture2D texture, ImageFormat outputFormat, Stream stream)
        {
            if (wicFactory == null)
            {
                wicFactory = ToDispose(new SharpDX.WIC.ImagingFactory2());
            }

            DataStream dataStream;
            var        dataBox = context.MapSubresource(
                texture,
                0,
                0,
                MapMode.Read,
                SharpDX.Direct3D11.MapFlags.None,
                out dataStream);

            try
            {
                var dataRectangle = new DataRectangle
                {
                    DataPointer = dataStream.DataPointer,
                    Pitch       = dataBox.RowPitch
                };

                var format = PixelFormatFromFormat(texture.Description.Format);

                if (format == Guid.Empty)
                {
                    return;
                }

                using (var bitmap = new SharpDX.WIC.Bitmap(
                           wicFactory,
                           texture.Description.Width,
                           texture.Description.Height,
                           format,
                           dataRectangle))
                {
                    stream.Position = 0;

                    SharpDX.WIC.BitmapEncoder bitmapEncoder = null;
                    switch (outputFormat)
                    {
                    case ImageFormat.Bitmap:
                        bitmapEncoder = new SharpDX.WIC.BmpBitmapEncoder(wicFactory, stream);
                        break;

                    case ImageFormat.Jpeg:
                        bitmapEncoder = new SharpDX.WIC.JpegBitmapEncoder(wicFactory, stream);
                        break;

                    case ImageFormat.Png:
                        bitmapEncoder = new SharpDX.WIC.PngBitmapEncoder(wicFactory, stream);
                        break;

                    default:
                        return;
                    }

                    try
                    {
                        using (var bitmapFrameEncode = new SharpDX.WIC.BitmapFrameEncode(bitmapEncoder))
                        {
                            bitmapFrameEncode.Initialize();
                            bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
                            var pixelFormat = format;
                            bitmapFrameEncode.SetPixelFormat(ref pixelFormat);

                            if (pixelFormat != format)
                            {
                                // IWICFormatConverter
                                var converter = new SharpDX.WIC.FormatConverter(wicFactory);
                                if (converter.CanConvert(format, pixelFormat))
                                {
                                    converter.Initialize(bitmap, SharpDX.WIC.PixelFormat.Format24bppBGR, SharpDX.WIC.BitmapDitherType.None, null, 0, SharpDX.WIC.BitmapPaletteType.MedianCut);
                                    bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
                                    bitmapFrameEncode.WriteSource(converter);
                                }
                                else
                                {
                                    this.DebugMessage(string.Format("Unable to convert Direct3D texture format {0} to a suitable WIC format", texture.Description.Format.ToString()));
                                    return;
                                }
                            }
                            else
                            {
                                bitmapFrameEncode.WriteSource(bitmap);
                            }
                            bitmapFrameEncode.Commit();
                            bitmapEncoder.Commit();
                        }
                    }
                    finally
                    {
                        bitmapEncoder.Dispose();
                    }
                }
            }
            finally
            {
                context.UnmapSubresource(texture, 0);
            }
        }
Ejemplo n.º 15
0
        private bool UpdateBuffers(SharpDX.Direct3D11.DeviceContext deviceContext, int positionX, int positionY)
        {
            // If the position we are rendering this bitmap to has not changed then don't update the vertex buffer since it currently has the correct parameters.
            if (PreviousPosX == positionX && PreviousPosY == positionY)
            {
                return(true);
            }

            // If it has changed then update the position it is being rendered to.
            PreviousPosX = positionX;
            PreviousPosY = positionY;

            //// Calculate the screen coordinates of the left side of the bitmap.
            float left = (-(ScreenWidth / 2)) + (float)positionX;  //
            // Calculate the screen coordinates of the right side of the bitmap.
            float right = left + BitmapWidth;
            // Calculate the screen coordinates of the top of the bitmap.
            float top = (ScreenHeight / 2) - (float)positionY;  //
            // Calculate the screen coordinates of the bottom of the bitmap.
            float bottom = top - BitmapHeight;

            // Create and load the vertex array.
            var vertices = new[]
            {
                new DVertexType()    // First triangle.
                {                    // Top left.
                    position = new Vector3(left, top, 0),
                    texture  = new Vector2(0, 0)
                },
                new DVertexType()
                {    // Bottom right.
                    position = new Vector3(right, bottom, 0),
                    texture  = new Vector2(1, 1)
                },
                new DVertexType()
                {   // Bottom left.
                    position = new Vector3(left, bottom, 0),
                    texture  = new Vector2(0, 1)
                },
                new DVertexType()   // Second triangle.
                {                   // Top left.
                    position = new Vector3(left, top, 0),
                    texture  = new Vector2(0, 0)
                },
                new DVertexType()
                {   // Top right.
                    position = new Vector3(right, top, 0),
                    texture  = new Vector2(1, 0)
                },
                new DVertexType()
                {   // Bottom right.
                    position = new Vector3(right, bottom, 0),
                    texture  = new Vector2(1, 1)
                }
            };

            DataStream mappedResource;

            #region Vertex Buffer
            // mappedResource = VertexBuffer.Map(MapMode.WriteDiscard);
            // Lock the vertex buffer so it can be written to.
            deviceContext.MapSubresource(VertexBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out mappedResource);

            // Copy the data into the vertex buffer.
            mappedResource.WriteRange <DVertexType>(vertices);

            // Unlock the vertex buffer.
            deviceContext.UnmapSubresource(VertexBuffer, 0);
            #endregion

            vertices = null;

            return(true);
        }