public static SharpDX.Direct2D1.Bitmap Test(SharpDX.Direct2D1.DeviceContext dc, ImagingFactory factory, System.Windows.Media.Imaging.BitmapSource src) { // PixelFormat settings/conversion if (src.Format != System.Windows.Media.PixelFormats.Bgra32) { // Convert BitmapSource FormatConvertedBitmap fcb = new FormatConvertedBitmap(); fcb.BeginInit(); fcb.Source = src; fcb.DestinationFormat = PixelFormats.Bgra32; fcb.EndInit(); src = fcb; } SharpDX.Direct2D1.Bitmap retval = null; try { int stride = src.PixelWidth * (src.Format.BitsPerPixel + 7) / 8; int bufferSize = stride * src.PixelHeight; byte[] buffer = new byte[bufferSize]; src.CopyPixels(Int32Rect.Empty, buffer, stride, 0); GCHandle pinnedArray = GCHandle.Alloc(buffer, GCHandleType.Pinned); IntPtr pointer = pinnedArray.AddrOfPinnedObject(); SharpDX.DataStream datastream = new SharpDX.DataStream(pointer, bufferSize, true, true); var bmpProps1 = new SharpDX.Direct2D1.BitmapProperties1(dc.PixelFormat, dc.Factory.DesktopDpi.Width, dc.Factory.DesktopDpi.Height); retval = new SharpDX.Direct2D1.Bitmap1(dc, new SharpDX.Size2(src.PixelWidth, src.PixelHeight), datastream, stride, bmpProps1); pinnedArray.Free(); } catch (Exception e) { } return(retval); }
private void InitializeBackBuffer(D2D.DeviceContext deviceContext, SharpDX.Size2F size) { this.backBitmap?.Dispose(); Size2 pixelSize = Helpers.GetPixelSize(size, this.Factory.DesktopDpi); var p = new D2D.BitmapProperties1( new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied), this.Factory.DesktopDpi.Width, this.Factory.DesktopDpi.Height, D2D.BitmapOptions.Target); var desc = new D3D11.Texture2DDescription() { ArraySize = 1, BindFlags = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource, CpuAccessFlags = D3D11.CpuAccessFlags.None, Format = DXGI.Format.B8G8R8A8_UNorm, MipLevels = 1, OptionFlags = D3D11.ResourceOptionFlags.Shared, Usage = D3D11.ResourceUsage.Default, SampleDescription = new DXGI.SampleDescription(1, 0), Width = pixelSize.Width, Height = pixelSize.Height, }; using (var buffer = new D3D11.Texture2D(this.Device, desc)) using (var surface = buffer.QueryInterface <DXGI.Surface>()) { this.backBitmap = new D2D.Bitmap1(this.DeviceContext, surface, p); } this.DeviceContext.Target = this.backBitmap; }
private void CreateResources() { this.backBuffer = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(this.swapChain, 0); this.backBuffer.DebugName = "BackBuffer"; using (var surface = this.backBuffer.QueryInterface <DXGI.Surface>()) { var properties = new D2D.BitmapProperties( new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied), this.factory2d.DesktopDpi.Width, this.factory2d.DesktopDpi.Height); this.backBitmap = new D2D.Bitmap(this.deviceContext2D, surface, properties); if (this.renderBitmap != null) { this.backBitmap.CopyFromBitmap(this.renderBitmap); } } if (this.renderBitmap != null) { this.renderBitmap.Dispose(); this.renderBuffer.Dispose(); } var p = new D2D.BitmapProperties1( new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied), this.factory2d.DesktopDpi.Width, this.factory2d.DesktopDpi.Height, D2D.BitmapOptions.Target); var pixelSize = Helpers.GetPixelSize(this.backBitmap.Size, this.factory2d.DesktopDpi); var desc = new D3D11.Texture2DDescription() { ArraySize = 1, BindFlags = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource, CpuAccessFlags = D3D11.CpuAccessFlags.None, Format = DXGI.Format.B8G8R8A8_UNorm, MipLevels = 1, OptionFlags = D3D11.ResourceOptionFlags.Shared, Usage = D3D11.ResourceUsage.Default, SampleDescription = new DXGI.SampleDescription(1, 0), Width = pixelSize.Width, Height = pixelSize.Height, }; this.renderBuffer = new D3D11.Texture2D(this.device, desc); using (var surface = this.renderBuffer.QueryInterface <DXGI.Surface>()) { this.renderBitmap = new D2D.Bitmap1(this.deviceContext2D, surface, p); } this.renderBitmap.CopyFromBitmap(this.backBitmap); }
/// <summary> /// Creates all resources /// </summary> private void CreateResources(int viewWidth, int viewHeight, DpiScaling dpiScaling, bool forceInit) { // Calculate the screen size in device independent units Size2F scaledScreenSize = new Size2F( (float)viewWidth / dpiScaling.ScaleFactorX, (float)viewHeight / dpiScaling.ScaleFactorY); // Cancel here if the device does not support 2D rendering if ((!forceInit) && (!m_device.Supports2D)) { return; } if (!m_device.IsUsingFallbackMethodFor2D) { // Create the render target using (DXGI.Surface dxgiSurface = m_renderTarget3D.QueryInterface <DXGI.Surface>()) { D2D.BitmapProperties1 bitmapProperties = new D2D.BitmapProperties1(); bitmapProperties.DpiX = dpiScaling.DpiX; bitmapProperties.DpiY = dpiScaling.DpiY; bitmapProperties.BitmapOptions = D2D.BitmapOptions.Target | D2D.BitmapOptions.CannotDraw; bitmapProperties.PixelFormat = new D2D.PixelFormat(GraphicsHelper.DEFAULT_TEXTURE_FORMAT, D2D.AlphaMode.Premultiplied); m_renderTargetBitmap = new SharpDX.Direct2D1.Bitmap1(m_device.DeviceContextD2D, dxgiSurface, bitmapProperties); m_renderTarget2D = m_device.DeviceContextD2D; m_graphics2D = new Graphics2D(m_device, m_device.DeviceContextD2D, scaledScreenSize); } } else { using (DXGI.Surface dxgiSurface = m_renderTarget3D.QueryInterface <DXGI.Surface>()) { m_renderTarget2D = new D2D.RenderTarget( m_device.Core.FactoryD2D, dxgiSurface, new D2D.RenderTargetProperties() { MinLevel = D2D.FeatureLevel.Level_10, Type = D2D.RenderTargetType.Default, Usage = D2D.RenderTargetUsage.ForceBitmapRemoting, PixelFormat = new D2D.PixelFormat(GraphicsHelper.DEFAULT_TEXTURE_FORMAT, D2D.AlphaMode.Premultiplied), DpiX = dpiScaling.DpiX, DpiY = dpiScaling.DpiY }); m_graphics2D = new Graphics2D(m_device, m_renderTarget2D, scaledScreenSize); return; } } }
public static void CreateDeviceContextCPUBitmap( Direct2D1.DeviceContext target, int width, int height) { var props = new Direct2D1.BitmapProperties1 { BitmapOptions = Direct2D1.BitmapOptions.Target | Direct2D1.BitmapOptions.GdiCompatible, PixelFormat = new Direct2D1.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, Direct2D1.AlphaMode.Premultiplied) }; using (var bitmap = new Direct2D1.Bitmap1(target, new Size2(width, height), props)) { target.Target = bitmap; } }
public RenderController(IntPtr windowHandle) { writeFactory = new SharpDX.DirectWrite.Factory(); SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device ( DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport ); device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>(); SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface <SharpDX.DXGI.Device2>(); SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter; SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>(); SwapChainDescription1 description = new SwapChainDescription1() { Width = 0, Height = 0, Format = Format.B8G8R8A8_UNorm, Stereo = false, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 2, Scaling = Scaling.None, SwapEffect = SwapEffect.FlipSequential, }; swapChain = new SwapChain1(dxgiFactory2, device, windowHandle, ref description); backBuffer = Surface.FromSwapChain(swapChain, 0); d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); properties = new BitmapProperties1 ( new SharpDX.Direct2D1.PixelFormat ( SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied ), 0, 0, BitmapOptions.Target | BitmapOptions.CannotDraw ); d2dTarget = new Bitmap1(d2dContext, backBuffer, properties); d2dContext.Target = d2dTarget; canDraw = true; }
public static void CreateDeviceSwapChainBitmap( DXGI.SwapChain1 swapChain, Direct2D1.DeviceContext target) { using (var surface = swapChain.GetBackBuffer <DXGI.Surface>(0)) { var props = new Direct2D1.BitmapProperties1 { BitmapOptions = Direct2D1.BitmapOptions.Target | Direct2D1.BitmapOptions.CannotDraw, PixelFormat = new Direct2D1.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, Direct2D1.AlphaMode.Ignore) }; using (var bitmap = new Direct2D1.Bitmap1(target, surface, props)) { target.Target = bitmap; } } }
public void ReSize(double width, double height) { Width = width; Height = height; DX_Core.DisposeSwapChain(ref com); DX_Core.CreateD3DInstance(ref com); lock (DX_Core.D2D) { BitmapBuffer.Dispose(); if (gaussian != null) { gaussian.Dispose(); gaussian = null; } var bp = new D2D1.BitmapProperties1( new D2D1.PixelFormat(Dxgi.Format.B8G8R8A8_UNorm, D2D1.AlphaMode.Premultiplied), com.dpi, com.dpi, D2D1.BitmapOptions.Target); BitmapBuffer = new D2D1.Bitmap1(DX_Core.D2D.d2dContext, new Size2((int)width, (int)height), bp); } }
public DXBitmapExportContext(int width, int height, float displayScale = 1, int dpi = 72, bool disposeBitmap = true) : base(width, height, dpi) { _disposeBitmap = disposeBitmap; if (_default3DDevice == null) { _default3DDevice = new d3d.Device(DriverType.Hardware, d3d.DeviceCreationFlags.VideoSupport | d3d.DeviceCreationFlags.BgraSupport); // default3DDevice = new d3d.Device(DriverType.Warp, d3d.DeviceCreationFlags.BgraSupport); _default3DDevice1 = _default3DDevice.QueryInterface <d3d.Device1>(); _dxgiDevice = _default3DDevice1.QueryInterface <dxgi.Device>(); // get a reference to DXGI device _device2D = new d2.Device(_dxgiDevice); // initialize the DeviceContext - it will be the D2D render target _deviceContext = new d2.DeviceContext(_device2D, d2.DeviceContextOptions.None); } // specify a pixel format that is supported by both and WIC _pixelFormat = new d2.PixelFormat(dxgi.Format.B8G8R8A8_UNorm, d2.AlphaMode.Premultiplied); // create the d2d bitmap description using default flags var bitmapProps = new d2.BitmapProperties1(_pixelFormat, Dpi, Dpi, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw); // create our d2d bitmap where all drawing will happen _bitmap = new d2.Bitmap1(_deviceContext, new Size2(width, height), bitmapProps); // associate bitmap with the d2d context _deviceContext.Target = _bitmap; _deviceContext.BeginDraw(); _deviceContext.Clear(new Color4 { Alpha = 0, Blue = 0, Green = 0, Red = 0 }); _canvas = new DXCanvas(_deviceContext) { DisplayScale = displayScale }; }
public SharpDX.Direct2D1.Bitmap1 CreateRenderTarget( float width, float height, float dpi = DEFAULT_DPI, SharpDX.DXGI.Format format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode alpha = AlphaMode.Premultiplied) { var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1() { BitmapOptions = BitmapOptions.Target, DpiX = dpi, DpiY = dpi, PixelFormat = new SharpDX.Direct2D1.PixelFormat(format, alpha) }; var pixelWidth = SizeDipsToPixels(width, dpi); var pixelHeight = SizeDipsToPixels(height, dpi); var bitmap = new SharpDX.Direct2D1.Bitmap1(d2dResourceCreationDeviceContext, new Size2(pixelWidth, pixelHeight), bitmapProperties); return(bitmap); }
public SwapChain(double width, double height) { Width = width; Height = height; com = new SwapChainComponent(); com.panel = this; com.dpi = DisplayInformation.GetForCurrentView().LogicalDpi; DX_Core.CreateD3DInstance(ref com); DX_Child = new List <UIElement>(); this.PointerPressed += PointerOperation; this.PointerMoved += PointerOperation; this.PointerReleased += PointerOperation; this.PointerEntered += PointerOperation; this.PointerExited += PointerOperation; this.PointerWheelChanged += PointerOperation; var bp = new D2D1.BitmapProperties1( new D2D1.PixelFormat(Dxgi.Format.B8G8R8A8_UNorm, D2D1.AlphaMode.Premultiplied), com.dpi, com.dpi, D2D1.BitmapOptions.Target); lock (DX_Core.D2D) BitmapBuffer = new D2D1.Bitmap1(DX_Core.D2D.d2dContext, new Size2((int)width, (int)height), bp); ThreadManage.StartLoop(this); }
static void Main() { // input and output files are supposed to be in the program folder var inputPath = "Input.png"; var outputPath = "Output.png"; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // INITIALIZATION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // initialize the D3D device which will allow to render to image any graphics - 3D or 2D var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, d3d.DeviceCreationFlags.VideoSupport | d3d.DeviceCreationFlags.BgraSupport | d3d.DeviceCreationFlags.Debug); // take out the Debug flag for better performance var d3dDevice = defaultDevice.QueryInterface <d3d.Device1>(); // get a reference to the Direct3D 11.1 device var dxgiDevice = d3dDevice.QueryInterface <dxgi.Device>(); // get a reference to DXGI device var d2dDevice = new d2.Device(dxgiDevice); // initialize the D2D device var imagingFactory = new wic.ImagingFactory2(); // initialize the WIC factory // initialize the DeviceContext - it will be the D2D render target and will allow all rendering operations var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None); var dwFactory = new dw.Factory(); // specify a pixel format that is supported by both D2D and WIC var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied); // if in D2D was specified an R-G-B-A format - use the same for wic var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // IMAGE LOADING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ var decoder = new wic.PngBitmapDecoder(imagingFactory); // we will load a PNG image var inputStream = new wic.WICStream(imagingFactory, inputPath, NativeFileAccess.Read); // open the image file for reading decoder.Initialize(inputStream, wic.DecodeOptions.CacheOnLoad); // decode the loaded image to a format that can be consumed by D2D var formatConverter = new wic.FormatConverter(imagingFactory); formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat); // load the base image into a D2D Bitmap //var inputBitmap = d2.Bitmap1.FromWicBitmap(d2dContext, formatConverter, new d2.BitmapProperties1(d2PixelFormat)); // store the image size - output will be of the same size var inputImageSize = formatConverter.Size; var pixelWidth = inputImageSize.Width; var pixelHeight = inputImageSize.Height; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // EFFECT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Effect 1 : BitmapSource - take decoded image data and get a BitmapSource from it var bitmapSourceEffect = new d2.Effects.BitmapSource(d2dContext); bitmapSourceEffect.WicBitmapSource = formatConverter; // Effect 2 : GaussianBlur - give the bitmapsource a gaussian blurred effect var gaussianBlurEffect = new d2.Effects.GaussianBlur(d2dContext); gaussianBlurEffect.SetInput(0, bitmapSourceEffect.Output, true); gaussianBlurEffect.StandardDeviation = 5f; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // OVERLAY TEXT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ var textFormat = new dw.TextFormat(dwFactory, "Arial", 15f); // create the text format of specified font configuration // draw a long text to show the automatic line wrapping var textToDraw = "Some long text to show the drawing of preformatted " + "glyphs using DirectWrite on the Direct2D surface." + " Notice the automatic wrapping of line if it exceeds desired width."; // create the text layout - this improves the drawing performance for static text // as the glyph positions are precalculated var textLayout = new dw.TextLayout(dwFactory, textToDraw, textFormat, 300f, 1000f); var textBrush = new d2.SolidColorBrush(d2dContext, Color.LightGreen); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // RENDER TARGET SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // create the d2d bitmap description using default flags (from SharpDX samples) and 96 DPI var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw); // the render target var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(pixelWidth, pixelHeight), d2dBitmapProps); d2dContext.Target = d2dRenderTarget; // associate bitmap with the d2d context // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // DRAWING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // slow preparations - fast drawing: d2dContext.BeginDraw(); d2dContext.DrawImage(gaussianBlurEffect); d2dContext.DrawTextLayout(new Vector2(5f, 5f), textLayout, textBrush); d2dContext.EndDraw(); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // IMAGE SAVING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // delete the output file if it already exists if (System.IO.File.Exists(outputPath)) { System.IO.File.Delete(outputPath); } // use the appropiate overload to write either to stream or to a file var stream = new wic.WICStream(imagingFactory, outputPath, NativeFileAccess.Write); // select the image encoding format HERE var encoder = new wic.PngBitmapEncoder(imagingFactory); encoder.Initialize(stream); var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder); bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(pixelWidth, pixelHeight); bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat); // this is the trick to write D2D1 bitmap to WIC var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice); imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96, 0, 0, pixelWidth, pixelHeight)); bitmapFrameEncode.Commit(); encoder.Commit(); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // CLEANUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // dispose everything and free used resources bitmapFrameEncode.Dispose(); encoder.Dispose(); stream.Dispose(); textBrush.Dispose(); textLayout.Dispose(); textFormat.Dispose(); formatConverter.Dispose(); gaussianBlurEffect.Dispose(); bitmapSourceEffect.Dispose(); d2dRenderTarget.Dispose(); inputStream.Dispose(); decoder.Dispose(); d2dContext.Dispose(); dwFactory.Dispose(); imagingFactory.Dispose(); d2dDevice.Dispose(); dxgiDevice.Dispose(); d3dDevice.Dispose(); defaultDevice.Dispose(); // show the result System.Diagnostics.Process.Start(outputPath); }
/// <summary> /// Creates the D2D render target from the associated swap chain. /// </summary> private void CreateD2DRenderTarget() { var renderTarget = _presenter.BackBuffer; var dpi = DisplayProperties.LogicalDpi; // 1. Use same format as the underlying render target with premultiplied alpha mode // 2. Use correct DPI // 3. Deny drawing direct calls and specify that this is a render target. var bitmapProperties = new D2D.BitmapProperties1(new SharpDX.Direct2D1.PixelFormat(renderTarget.Format, D2D.AlphaMode.Premultiplied), dpi, dpi, D2D.BitmapOptions.CannotDraw | D2D.BitmapOptions.Target); // create the bitmap render target and assign it to the device context _bitmapTarget = _disposeCollector.Collect(new D2D.Bitmap1(_d2dDeviceContext, renderTarget, bitmapProperties)); _d2dDeviceContext.Target = _bitmapTarget; }
/// <summary> /// 使用 DirectX 在該表面上繪圖 /// 只會在 updateRect 參數中指定的更新區域進行繪圖。 /// </summary> /// <param name="updateRect"></param> public void BeginDraw(Windows.Foundation.Rect updateRect) { // Express target area as a native RECT type. var updateRectNative = new Rectangle { Left = (int)updateRect.Left, Top = (int)updateRect.Top, Right = (int)updateRect.Right, Bottom = (int)updateRect.Bottom }; // Query for ISurfaceImageSourceNative interface. using (var sisNative = ComObject.QueryInterface<ISurfaceImageSourceNative>(this)) { // Begin drawing - returns a target surface and an offset to use as the top left origin when drawing. try { Point offset; using (var surface = sisNative.BeginDraw(updateRectNative, out offset)) { var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1( new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), 96, 96, SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw); // Create render target. using (var bitmap = new Bitmap1(d2dContext, surface, bitmapProperties)) { // Set context's render target. d2dContext.Target = bitmap; } // Begin drawing using D2D context. d2dContext.BeginDraw(); // Apply a clip and transform to constrain updates to the target update area. // This is required to ensure coordinates within the target surface remain // consistent by taking into account the offset returned by BeginDraw, and // can also improve performance by optimizing the area that is drawn by D2D. // Apps should always account for the offset output parameter returned by // BeginDraw, since it may not match the passed updateRect input parameter's location. d2dContext.PushAxisAlignedClip( new RectangleF( (offset.X), (offset.Y), (offset.X + (float)updateRect.Width), (offset.Y + (float)updateRect.Height) ), AntialiasMode.Aliased ); d2dContext.Transform = Matrix3x2.Translation(offset.X, offset.Y); } } catch (SharpDXException ex) { if (ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceRemoved || ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceReset) { // If the device has been removed or reset, attempt to recreate it and continue drawing. CreateDeviceResources(); BeginDraw(updateRect); } else { throw; } } } }
/// <summary> /// main thread /// </summary> /// <param name="panel"></param> /// <param name="dpi"></param> internal static void CreateD3DInstance(ref SwapChainComponent com) { int width = (int)com.panel.Width; int height = (int)com.panel.Height; dpi = (int)com.dpi; com.port = new Viewport(0, 0, width, height, 0, 1); D2D.d3dContext.Rasterizer.SetViewport(com.port); var multisampleDesc = new Dxgi.SampleDescription(1, 0); var desc = new Dxgi.SwapChainDescription1() { // Automatic sizing AlphaMode = Dxgi.AlphaMode.Premultiplied, Width = width, Height = height, Format = Dxgi.Format.B8G8R8A8_UNorm, Stereo = false, SampleDescription = multisampleDesc, Usage = Dxgi.Usage.RenderTargetOutput, BufferCount = 2, SwapEffect = Dxgi.SwapEffect.FlipSequential, Scaling = Dxgi.Scaling.Stretch }; using (var dxgiDevice2 = D2D.d3dDevice.QueryInterface <Dxgi.Device2>()) using (var dxgiAdapter = dxgiDevice2.Adapter) using (var dxgiFactory2 = dxgiAdapter.GetParent <Dxgi.Factory2>()) using (com.NativePanel = ComObject.As <Dxgi.ISwapChainPanelNative>(com.panel)) { com.swapChain = new Dxgi.SwapChain1(dxgiFactory2, dxgiDevice2, ref desc, null); com.NativePanel.SwapChain = com.swapChain; dxgiDevice2.MaximumFrameLatency = 1; } using (com.backbuffer = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(com.swapChain, 0)) com.TargetView = new D3D11.RenderTargetView(D2D.d3dDevice, com.backbuffer); using (com.depthbuffer = new D3D11.Texture2D(D2D.d3dDevice, new D3D11.Texture2DDescription() { Format = Dxgi.Format.D24_UNorm_S8_UInt, ArraySize = 1, MipLevels = 1, Width = width, Height = height, SampleDescription = multisampleDesc, Usage = D3D11.ResourceUsage.Default, BindFlags = D3D11.BindFlags.DepthStencil, })) com.StencilView = new D3D11.DepthStencilView(D2D.d3dDevice, com.depthbuffer); D2D.d3dContext.OutputMerger.SetTargets(com.StencilView, com.TargetView); var bitmapProperties = new D2D1.BitmapProperties1( new D2D1.PixelFormat(Dxgi.Format.B8G8R8A8_UNorm, D2D1.AlphaMode.Premultiplied), com.dpi, com.dpi, D2D1.BitmapOptions.Target | D2D1.BitmapOptions.CannotDraw); using (var dxgiBackBuffer = com.swapChain.GetBackBuffer <Dxgi.Surface>(0)) { com.Bitmap = new D2D1.Bitmap1(D2D.d2dContext, dxgiBackBuffer, bitmapProperties); } D2D.d2dContext.Target = com.Bitmap; D2D.d2dContext.TextAntialiasMode = D2D1.TextAntialiasMode.Cleartype; }
/// <summary> /// Create the swap chain and render targets, which depend on the size of the window. /// </summary> /// <param name="window"></param> private void CreateSizeResources(Tesseract gameEngine) { // Get the 2D context reference var context2D = gameEngine.DeviceManager.Context2D; // Release all buffers before resizing the swap chain RemoveAndDispose(ref BackBuffer); RemoveAndDispose(ref RenderTargetView); RemoveAndDispose(ref DepthStencilView); RemoveAndDispose(ref DepthBuffer); RemoveAndDispose(ref RenderTarget); context2D.Target = null; // If a swap chain already exists, resize it instead of creating a new one int scHeight = (int)(gameEngine.WindowManager.WindowBounds.Height * gameEngine.DeviceManager.DPI / 96); int scWidth = (int)(gameEngine.WindowManager.WindowBounds.Width * gameEngine.DeviceManager.DPI / 96); if (SwapChain != null) { SwapChain.ResizeBuffers( SwapChain.Description1.BufferCount, scWidth, scHeight, SwapChain.Description.ModeDescription.Format, SwapChain.Description.Flags); } // Otherwise, create a new swap chain else { CreateSwapChain(gameEngine.WindowManager.Window.Handle, scWidth, scHeight); } // Create a back buffer, which will be used as the final 3D render target BackBuffer = ToDispose(Texture2D.FromSwapChain<Texture2D>(SwapChain, 0)); var bbDescription = BackBuffer.Description; // Set up render target resources RenderTargetView = ToDispose(new RenderTargetView(Device3D, BackBuffer)); RenderTargetBounds = new Rectangle(0, 0, bbDescription.Width, bbDescription.Height); // Create a viewport descriptor of the render size Viewport = new ViewportF(RenderTargetBounds); Context3D.Rasterizer.SetViewport(Viewport); // Create a decription structure for the depth/stencil buffer DepthBuffer = ToDispose(new Texture2D(Device3D, new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.DepthStencil, Format = Format.D32_Float_S8X24_UInt, Height = RenderTargetBounds.Height, MipLevels = 1, SampleDescription = SwapChain.Description.SampleDescription, Width = RenderTargetBounds.Width, })); // Create a view interface for the depth/stencil buffer DepthStencilView = ToDispose(new DepthStencilView( Device3D, DepthBuffer, new DepthStencilViewDescription() { Dimension = (SwapChain.Description.SampleDescription.Count > 1 || SwapChain.Description.SampleDescription.Quality > 0) ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D })); Context3D.OutputMerger.SetTargets(DepthStencilView, RenderTargetView); // Set up the Direct2D render target, which will render to the swap chain associated with the window var bitmapProperties = new BitmapProperties1( new PixelFormat(SwapChain.Description.ModeDescription.Format, SharpDX.Direct2D1.AlphaMode.Premultiplied), gameEngine.DeviceManager.DPI, gameEngine.DeviceManager.DPI, BitmapOptions.Target | BitmapOptions.CannotDraw); // Get a Direct2D surface from the DXGI back buffer to use as the render target using (var dxgiBackBuffer = SwapChain.GetBackBuffer<Surface>(0)) { RenderTarget = ToDispose(new Bitmap1(context2D, dxgiBackBuffer, bitmapProperties)); } // Set the render target context2D.Target = RenderTarget; // Set the text anti-aliasing mode to grayscale to ensure proper rendering of text on intermediate surfaces context2D.TextAntialiasMode = TextAntialiasMode.Grayscale; }
public SharpDX.Direct2D1.Bitmap1 CreateRenderTarget( float width, float height, float dpi = DEFAULT_DPI, SharpDX.DXGI.Format format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode alpha = AlphaMode.Premultiplied) { var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1() { BitmapOptions = BitmapOptions.Target, DpiX = dpi, DpiY = dpi, PixelFormat = new SharpDX.Direct2D1.PixelFormat(format, alpha) }; var pixelWidth = SizeDipsToPixels(width, dpi); var pixelHeight = SizeDipsToPixels(height, dpi); var bitmap = new SharpDX.Direct2D1.Bitmap1(d2dResourceCreationDeviceContext, new Size2(pixelWidth, pixelHeight), bitmapProperties); return bitmap; }
public DeviceManager() { try { // 创建 Dierect3D 设备。 this.d3DDevice = new D3D11Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport); this.dxgiDevice = d3DDevice.QueryInterface<D3D11Device1>().QueryInterface<DXGIDevice>(); // 创建 Direct2D 设备和工厂。 this.d2DDevice = new D2D1Device(dxgiDevice); this.d2DContext = new DeviceContext(d2DDevice, DeviceContextOptions.None); this.d2DFactory = this.d2DContext.Factory; this.wicFactory = new ImagingFactory2(); } catch { this.ClearResources(); try { // 创建 D3D 设备异常,则尝试 Direct2D 单线程工厂。 this.d2DFactory = new Factory(FactoryType.SingleThreaded); this.wicFactory = new ImagingFactory(); } catch { this.ClearResources(); } } if (this.d2DFactory != null) { Dpi = d2DFactory.DesktopDpi; BitmapProps1 = new BitmapProperties1(D2PixelFormat, Dpi.Width, Dpi.Height, BitmapOptions.Target); } }
public static MemoryStream Resize(System.IO.Stream source, int maxwidth, int maxheight, Action beforeDrawImage, Action afterDrawImage) { // initialize the D3D device which will allow to render to image any graphics - 3D or 2D var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Warp, d3d.DeviceCreationFlags.BgraSupport | d3d.DeviceCreationFlags.SingleThreaded | d3d.DeviceCreationFlags.PreventThreadingOptimizations); var d3dDevice = defaultDevice.QueryInterface<d3d.Device1>(); // get a reference to the Direct3D 11.1 device var dxgiDevice = d3dDevice.QueryInterface<dxgi.Device>(); // get a reference to DXGI device var d2dDevice = new d2.Device(dxgiDevice); // initialize the D2D device var imagingFactory = new wic.ImagingFactory2(); // initialize the WIC factory // initialize the DeviceContext - it will be the D2D render target and will allow all rendering operations var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None); var dwFactory = new dw.Factory(); // specify a pixel format that is supported by both D2D and WIC var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied); // if in D2D was specified an R-G-B-A format - use the same for wic var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // IMAGE LOADING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ var decoder = new wic.BitmapDecoder(imagingFactory,source, wic.DecodeOptions.CacheOnLoad); // decode the loaded image to a format that can be consumed by D2D var formatConverter = new wic.FormatConverter(imagingFactory); formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat); // store the image size - output will be of the same size var inputImageSize = formatConverter.Size; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // RENDER TARGET SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // create the d2d bitmap description using default flags (from SharpDX samples) and 96 DPI var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw); //Calculate size var resultSize = MathUtil.ScaleWithin(inputImageSize.Width,inputImageSize.Height,maxwidth,maxheight); var newWidth = resultSize.Item1; var newHeight = resultSize.Item2; // the render target var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(newWidth, newHeight), d2dBitmapProps); d2dContext.Target = d2dRenderTarget; // associate bitmap with the d2d context var bitmapSourceEffect = new d2.Effects.BitmapSourceEffect(d2dContext); bitmapSourceEffect.WicBitmapSource = formatConverter; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // DRAWING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ beforeDrawImage(); // slow preparations - fast drawing: d2dContext.BeginDraw(); d2dContext.Transform = Matrix3x2.Scaling(new Vector2((float)(newWidth / (float)inputImageSize.Width), (float)(newHeight / (float)inputImageSize.Height))); d2dContext.DrawImage(bitmapSourceEffect, d2.InterpolationMode.HighQualityCubic); d2dContext.EndDraw(); afterDrawImage(); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // IMAGE SAVING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ var ms = new MemoryStream(); // use the appropiate overload to write either to stream or to a file var stream = new wic.WICStream(imagingFactory,ms); // select the image encoding format HERE var encoder = new wic.JpegBitmapEncoder(imagingFactory); encoder.Initialize(stream); var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder); bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(newWidth, newHeight); bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat); // this is the trick to write D2D1 bitmap to WIC var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice); imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96, 0, 0, newWidth, newHeight)); bitmapFrameEncode.Commit(); encoder.Commit(); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // CLEANUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // dispose everything and free used resources bitmapFrameEncode.Dispose(); encoder.Dispose(); stream.Dispose(); formatConverter.Dispose(); bitmapSourceEffect.Dispose(); d2dRenderTarget.Dispose(); decoder.Dispose(); d2dContext.Dispose(); dwFactory.Dispose(); imagingFactory.Dispose(); d2dDevice.Dispose(); dxgiDevice.Dispose(); d3dDevice.Dispose(); defaultDevice.Dispose(); return ms; }
/// <summary> /// Now that we have a CoreWindow object, the DirectX device/context can be created. /// </summary> /// <param name="entryPoint"></param> public async void Load(string entryPoint) { // Get the default hardware device and enable debugging. Don't care about the available feature level. // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop. SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport); // Query the default device for the supported device and context interfaces. device = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>(); d3dContext = device.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>(); // Query for the adapter and more advanced DXGI objects. SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface<SharpDX.DXGI.Device2>(); SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter; SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>(); // Description for our swap chain settings. SwapChainDescription1 description = new SwapChainDescription1() { // 0 means to use automatic buffer sizing. Width = 0, Height = 0, // 32 bit RGBA color. Format = Format.B8G8R8A8_UNorm, // No stereo (3D) display. Stereo = false, // No multisampling. SampleDescription = new SampleDescription(1, 0), // Use the swap chain as a render target. Usage = Usage.RenderTargetOutput, // Enable double buffering to prevent flickering. BufferCount = 2, // No scaling. Scaling = Scaling.None, // Flip between both buffers. SwapEffect = SwapEffect.FlipSequential, }; // Generate a swap chain for our window based on the specified description. swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(device, new ComObject(window), ref description, null); // Get the default Direct2D device and create a context. SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); // Specify the properties for the bitmap that we will use as the target of our Direct2D operations. // We want a 32-bit BGRA surface with premultiplied alpha. BitmapProperties1 properties = new BitmapProperties1(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw); // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target. Surface backBuffer = swapChain.GetBackBuffer<Surface>(0); d2dTarget = new Bitmap1(d2dContext, backBuffer, properties); // Create the DirectWrite factory objet. SharpDX.DirectWrite.Factory fontFactory = new SharpDX.DirectWrite.Factory(); // Create a TextFormat object that will use the Segoe UI font with a size of 24 DIPs. textFormat = new TextFormat(fontFactory, "Segoe UI", 24.0f); // Create two TextLayout objects for rendering the moving text. textLayout1 = new TextLayout(fontFactory, "This is an example of a moving TextLayout object with snapped pixel boundaries.", textFormat, 400.0f, 200.0f); textLayout2 = new TextLayout(fontFactory, "This is an example of a moving TextLayout object with no snapped pixel boundaries.", textFormat, 400.0f, 200.0f); // Vertical offset for the moving text. layoutY = 0.0f; // Create the brushes for the text background and text color. backgroundBrush = new SolidColorBrush(d2dContext, Color.White); textBrush = new SolidColorBrush(d2dContext, Color.Black); }
void Resize() { d2dDeviceContext.Target = null; d2dSurface.Dispose(); swapChain.ResizeBuffers(0, 0, 0, Format.Unknown, SwapChainFlags.None); Surface1 dxgiSurface = swapChain.GetBackBuffer<Surface1>(0); var props = new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, D2D.AlphaMode.Ignore), d2dDeviceContext.DotsPerInch.Width, d2dDeviceContext.DotsPerInch.Height, BitmapOptions.Target | BitmapOptions.CannotDraw); d2dSurface = new Bitmap1(d2dDeviceContext, dxgiSurface, props); dxgiSurface.Dispose(); d2dDeviceContext.Target = d2dSurface; }
/// <summary> /// Now that we have a CoreWindow object, the DirectX device/context can be created. /// </summary> /// <param name="entryPoint"></param> public void Load(string entryPoint) { // Get the default hardware device and enable debugging. Don't care about the available feature level. // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop. SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport); // Query the default device for the supported device and context interfaces. device = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>(); d3dContext = device.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>(); // Query for the adapter and more advanced DXGI objects. SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface<SharpDX.DXGI.Device2>(); SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter; SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>(); // Description for our swap chain settings. SwapChainDescription1 description = new SwapChainDescription1() { // 0 means to use automatic buffer sizing. Width = 0, Height = 0, // 32 bit RGBA color. Format = Format.B8G8R8A8_UNorm, // No stereo (3D) display. Stereo = false, // No multisampling. SampleDescription = new SampleDescription(1, 0), // Use the swap chain as a render target. Usage = Usage.RenderTargetOutput, // Enable double buffering to prevent flickering. BufferCount = 2, // No scaling. Scaling = Scaling.None, // Flip between both buffers. SwapEffect = SwapEffect.FlipSequential, }; // Generate a swap chain for our window based on the specified description. swapChain = new SwapChain1(dxgiFactory2, device, new ComObject(window), ref description); // Get the default Direct2D device and create a context. SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); // Specify the properties for the bitmap that we will use as the target of our Direct2D operations. // We want a 32-bit BGRA surface with premultiplied alpha. BitmapProperties1 properties = new BitmapProperties1(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw); // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target. Surface backBuffer = swapChain.GetBackBuffer<Surface>(0); d2dTarget = new Bitmap1(d2dContext, backBuffer, properties); // Load bitmap images playerBitmap = this.LoadBitmapFromContentFile("/Assets/Bitmaps/player.png"); terrainBitmap = this.LoadBitmapFromContentFile("/Assets/Bitmaps/terrain.png"); // Create hue rotation effect hueRotationEffect = new SharpDX.Direct2D1.Effects.HueRotation(d2dContext); // Create image shadow effect shadowEffect = new SharpDX.Direct2D1.Effects.Shadow(d2dContext); // Create image transform effect affineTransformEffect = new SharpDX.Direct2D1.Effects.AffineTransform2D(d2dContext); affineTransformEffect.SetInputEffect(0, shadowEffect); affineTransformEffect.TransformMatrix = Matrix3x2.Translation(terrainBitmap.PixelSize.Width * 0.25f, terrainBitmap.PixelSize.Height * 0.25f); // Create composite effect compositeEffect = new SharpDX.Direct2D1.Effects.Composite(d2dContext); compositeEffect.InputCount = 2; compositeEffect.SetInputEffect(0, affineTransformEffect); // Create tiling brush for terrain bitmap terrainBrush = new ImageBrush(d2dContext, terrainBitmap, new ImageBrushProperties() { ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap, SourceRectangle = new RectangleF(0, 0, terrainBitmap.Size.Width, terrainBitmap.Size.Height), }); // Create rendertarget for drawing the tiling brush brushTarget = new Bitmap1(d2dContext, new Size2((int)(terrainBitmap.Size.Width * 10), (int)terrainBitmap.Size.Height), new BitmapProperties1() { PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), BitmapOptions = BitmapOptions.Target }); }
static void Main() { // input and output files are supposed to be in the program folder var inputPath = "Input.png"; var outputPath = "Output.png"; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // INITIALIZATION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // initialize the D3D device which will allow to render to image any graphics - 3D or 2D var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, d3d.DeviceCreationFlags.VideoSupport | d3d.DeviceCreationFlags.BgraSupport | d3d.DeviceCreationFlags.Debug); // take out the Debug flag for better performance var d3dDevice = defaultDevice.QueryInterface<d3d.Device1>(); // get a reference to the Direct3D 11.1 device var dxgiDevice = d3dDevice.QueryInterface<dxgi.Device>(); // get a reference to DXGI device var d2dDevice = new d2.Device(dxgiDevice); // initialize the D2D device var imagingFactory = new wic.ImagingFactory2(); // initialize the WIC factory // initialize the DeviceContext - it will be the D2D render target and will allow all rendering operations var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None); var dwFactory = new dw.Factory(); // specify a pixel format that is supported by both D2D and WIC var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied); // if in D2D was specified an R-G-B-A format - use the same for wic var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // IMAGE LOADING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ var decoder = new wic.PngBitmapDecoder(imagingFactory); // we will load a PNG image var inputStream = new wic.WICStream(imagingFactory, inputPath, NativeFileAccess.Read); // open the image file for reading decoder.Initialize(inputStream, wic.DecodeOptions.CacheOnLoad); // decode the loaded image to a format that can be consumed by D2D var formatConverter = new wic.FormatConverter(imagingFactory); formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat); // load the base image into a D2D Bitmap //var inputBitmap = d2.Bitmap1.FromWicBitmap(d2dContext, formatConverter, new d2.BitmapProperties1(d2PixelFormat)); // store the image size - output will be of the same size var inputImageSize = formatConverter.Size; var pixelWidth = inputImageSize.Width; var pixelHeight = inputImageSize.Height; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // EFFECT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Effect 1 : BitmapSource - take decoded image data and get a BitmapSource from it var bitmapSourceEffect = new d2.Effects.BitmapSource(d2dContext); bitmapSourceEffect.WicBitmapSource = formatConverter; // Effect 2 : GaussianBlur - give the bitmapsource a gaussian blurred effect var gaussianBlurEffect = new d2.Effects.GaussianBlur(d2dContext); gaussianBlurEffect.SetInput(0, bitmapSourceEffect.Output, true); gaussianBlurEffect.StandardDeviation = 5f; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // OVERLAY TEXT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ var textFormat = new dw.TextFormat(dwFactory, "Arial", 15f); // create the text format of specified font configuration // draw a long text to show the automatic line wrapping var textToDraw = "Some long text to show the drawing of preformatted " + "glyphs using DirectWrite on the Direct2D surface." + " Notice the automatic wrapping of line if it exceeds desired width."; // create the text layout - this improves the drawing performance for static text // as the glyph positions are precalculated var textLayout = new dw.TextLayout(dwFactory, textToDraw, textFormat, 300f, 1000f); var textBrush = new d2.SolidColorBrush(d2dContext, Color.LightGreen); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // RENDER TARGET SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // create the d2d bitmap description using default flags (from SharpDX samples) and 96 DPI var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw); // the render target var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(pixelWidth, pixelHeight), d2dBitmapProps); d2dContext.Target = d2dRenderTarget; // associate bitmap with the d2d context // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // DRAWING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // slow preparations - fast drawing: d2dContext.BeginDraw(); d2dContext.DrawImage(gaussianBlurEffect); d2dContext.DrawTextLayout(new Vector2(5f, 5f), textLayout, textBrush); d2dContext.EndDraw(); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // IMAGE SAVING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // delete the output file if it already exists if (System.IO.File.Exists(outputPath)) System.IO.File.Delete(outputPath); // use the appropiate overload to write either to stream or to a file var stream = new wic.WICStream(imagingFactory, outputPath, NativeFileAccess.Write); // select the image encoding format HERE var encoder = new wic.PngBitmapEncoder(imagingFactory); encoder.Initialize(stream); var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder); bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(pixelWidth, pixelHeight); bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat); // this is the trick to write D2D1 bitmap to WIC var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice); imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96, 0, 0, pixelWidth, pixelHeight)); bitmapFrameEncode.Commit(); encoder.Commit(); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // CLEANUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // dispose everything and free used resources bitmapFrameEncode.Dispose(); encoder.Dispose(); stream.Dispose(); textBrush.Dispose(); textLayout.Dispose(); textFormat.Dispose(); formatConverter.Dispose(); gaussianBlurEffect.Dispose(); bitmapSourceEffect.Dispose(); d2dRenderTarget.Dispose(); inputStream.Dispose(); decoder.Dispose(); d2dContext.Dispose(); dwFactory.Dispose(); imagingFactory.Dispose(); d2dDevice.Dispose(); dxgiDevice.Dispose(); d3dDevice.Dispose(); defaultDevice.Dispose(); // show the result System.Diagnostics.Process.Start(outputPath); }
/// <summary> /// Now that we have a CoreWindow object, the DirectX device/context can be created. /// </summary> /// <param name="entryPoint"></param> public void Load(string entryPoint) { // Get the default hardware device and enable debugging. Don't care about the available feature level. // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop. SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport); // Query the default device for the supported device and context interfaces. device = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>(); d3dContext = device.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>(); // Query for the adapter and more advanced DXGI objects. SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface<SharpDX.DXGI.Device2>(); SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter; SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>(); // Description for our swap chain settings. SwapChainDescription1 description = new SwapChainDescription1() { // 0 means to use automatic buffer sizing. Width = 0, Height = 0, // 32 bit RGBA color. Format = Format.B8G8R8A8_UNorm, // No stereo (3D) display. Stereo = false, // No multisampling. SampleDescription = new SampleDescription(1, 0), // Use the swap chain as a render target. Usage = Usage.RenderTargetOutput, // Enable double buffering to prevent flickering. BufferCount = 2, // No scaling. Scaling = Scaling.None, // Flip between both buffers. SwapEffect = SwapEffect.FlipSequential, }; // Generate a swap chain for our window based on the specified description. swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(device, new ComObject(window), ref description, null); // Get the default Direct2D device and create a context. SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); // Specify the properties for the bitmap that we will use as the target of our Direct2D operations. // We want a 32-bit BGRA surface with premultiplied alpha. BitmapProperties1 properties = new BitmapProperties1(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw); // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target. Surface backBuffer = swapChain.GetBackBuffer<Surface>(0); d2dTarget = new Bitmap1(d2dContext, backBuffer, properties); // Create a solid color brush. solidBrush = new SolidColorBrush(d2dContext, Color.Coral); // Create a linear gradient brush. // Note that the StartPoint and EndPoint values are set as absolute coordinates of the surface you are drawing to, // NOT the geometry we will apply the brush. linearGradientBrush = new LinearGradientBrush(d2dContext, new LinearGradientBrushProperties() { StartPoint = new Vector2(50, 0), EndPoint = new Vector2(450, 0), }, new GradientStopCollection(d2dContext, new GradientStop[] { new GradientStop() { Color = Color.Blue, Position = 0, }, new GradientStop() { Color = Color.Green, Position = 1, } })); // Create a radial gradient brush. // The center is specified in absolute coordinates, too. radialGradientBrush = new RadialGradientBrush(d2dContext, new RadialGradientBrushProperties() { Center = new Vector2(250, 525), RadiusX = 100, RadiusY = 100, }, new GradientStopCollection(d2dContext, new GradientStop[] { new GradientStop() { Color = Color.Yellow, Position = 0, }, new GradientStop() { Color = Color.Red, Position = 1, } })); }
public SharpRender(RenderForm form) { this.form = form; var adapters = new DXGI.Factory1().Adapters; DXGI.Adapter myadapter = null; for (int i = 0; i < adapters.Length; ++i) { Logger.Log(string.Format("Adapter Found: [{0}] " + "{1}\tDeviceId={5}" + "{1}\tLuid={6}" + "{1}\tVendorId={10}" + "{1}\tSubsystemId={9}" + "{1}\tDescription={4}" + "{1}\tRevision={7}" + "{1}\tDedicatedSystemMemory={2}" + "{1}\tDedicatedVideoMemory={3}" + "{1}\tSharedSystemMemory={8}" + "", i, Environment.NewLine, adapters[i].Description.DedicatedSystemMemory, adapters[i].Description.DedicatedVideoMemory, adapters[i].Description.Description, adapters[i].Description.DeviceId, adapters[i].Description.Luid, adapters[i].Description.Revision, adapters[i].Description.SharedSystemMemory, adapters[i].Description.SubsystemId, adapters[i].Description.VendorId)); var outputs = adapters[i].Outputs; for (int j = 0; j < outputs.Length; ++j) { Logger.Log(string.Format("Output Found: [{0},{1}]" + "{2}\tDeviceName={4}" + "{2}\tIsAttachedToDesktop={5}" + "{2}\tMonitorHandle={6}" + "{2}\tDesktopBounds={3}" + "{2}\tRotation={7}" + "", i, j, Environment.NewLine, (Rectangle)outputs[j].Description.DesktopBounds, outputs[j].Description.DeviceName, outputs[j].Description.IsAttachedToDesktop, outputs[j].Description.MonitorHandle, outputs[j].Description.Rotation)); } if (outputs.Length > 0 && myadapter == null) { myadapter = adapters[i]; } } d3device = new Direct3D11.Device( myadapter, Direct3D11.DeviceCreationFlags.BgraSupport); //SharpDX.Direct3D.DriverType.Hardware, //Direct3D11.DeviceCreationFlags.BgraSupport | //Direct3D11.DeviceCreationFlags.Debug); defDevice = d3device.QueryInterface <Direct3D11.Device1>(); dxgiDevice2 = defDevice.QueryInterface <DXGI.Device2>(); dxgiAdapter = dxgiDevice2.Adapter; dxgiFactory2 = dxgiAdapter.GetParent <DXGI.Factory2>(); var scDescription = new DXGI.SwapChainDescription1() { Width = 0, Height = 0, Format = DXGI.Format.B8G8R8A8_UNorm, Stereo = false, SampleDescription = new DXGI.SampleDescription(1, 0), Usage = DXGI.Usage.RenderTargetOutput, BufferCount = 2, Scaling = DXGI.Scaling.None, SwapEffect = DXGI.SwapEffect.FlipSequential }; swapChain = new DXGI.SwapChain1(dxgiFactory2, defDevice, form.Handle, ref scDescription, null, null); d2dDevice = new Direct2D1.Device(dxgiDevice2); d2dContext = new Direct2D1.DeviceContext(d2dDevice, Direct2D1.DeviceContextOptions.None); fac = new Direct2D1.Factory(Direct2D1.FactoryType.SingleThreaded); var dpi = fac.DesktopDpi; var bMProperties = new Direct2D1.BitmapProperties1( new Direct2D1.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, Direct2D1.AlphaMode.Premultiplied), dpi.Width, dpi.Height, Direct2D1.BitmapOptions.CannotDraw | Direct2D1.BitmapOptions.Target); bb = swapChain.GetBackBuffer <DXGI.Surface>(0); target = new Direct2D1.Bitmap1(d2dContext, bb, bMProperties); d2dContext.Target = target; wrFactory = new DirectWrite.Factory(); brush = new Direct2D1.SolidColorBrush(d2dContext, c(Color.White)); }
static void over() { var inputPath = "Input.png"; var outputPath = "output.png"; // 그래픽을 랜더링할 장비를 추가 - 3D or 2D var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, d3d.DeviceCreationFlags.VideoSupport | d3d.DeviceCreationFlags.BgraSupport | d3d.DeviceCreationFlags.None); var d3dDevice = defaultDevice.QueryInterface <d3d.Device1>(); //get a refer to the D3D 11.1 device var dxgiDevice = d3dDevice.QueryInterface <dxgi.Device1>(); //get a refer to the DXGI device var d2dDevice = new d2.Device(dxgiDevice); // DeviceContext를 초기화. D2D 렌더링 타겟이 될 것이고 모든 렌더링 작업을 허용 var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None); var dwFactory = new dw.Factory(); //D2D, WIC 둘 다 지원되는 픽셀 형식 지정 var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied); //RGBA형식 사용 var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA; //이미지 로딩 var imagingFactory = new wic.ImagingFactory2(); var decoder = new wic.PngBitmapDecoder(imagingFactory); var inputStream = new wic.WICStream(imagingFactory, inputPath, NativeFileAccess.Read); decoder.Initialize(inputStream, wic.DecodeOptions.CacheOnLoad); //다이렉트2D가 사용할수 있도록 디코딩 var formatConverter = new wic.FormatConverter(imagingFactory); formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat); //기본 이미지를 D2D이미지로 로드 //var inputBitmap = d2.Bitmap1.FromWicBitmap(d2dContext, formatConverter, new d2.BitmapProperties1(d2PixelFormat)); //이미지 크기 저장 var inputImageSize = formatConverter.Size; var pixelWidth = inputImageSize.Width; var pixelHeight = inputImageSize.Height; //Effect1 : BitpmapSource - 디코딩된 이미지 데이터를 가져오고 BitmapSource 가져오기 var bitmapSourceEffect = new d2.Effects.BitmapSource(d2dContext); bitmapSourceEffect.WicBitmapSource = formatConverter; // Effect 2 : GaussianBlur - bitmapsource에 가우시안블러 효과 적용 var gaussianBlurEffect = new d2.Effects.GaussianBlur(d2dContext); gaussianBlurEffect.SetInput(0, bitmapSourceEffect.Output, true); gaussianBlurEffect.StandardDeviation = 5f; //overlay text setup var textFormat = new dw.TextFormat(dwFactory, "Arial", 15f); //draw a long text to show the automatic line wrapping var textToDraw = "sime ling text..." + "text" + "dddd"; //create the text layout - this imroves the drawing performance for static text // as the glyph positions are precalculated //윤곽선 글꼴 데이터에서 글자 하나의 모양에 대한 기본 단위를 글리프(glyph)라고 한다 var textLayout = new dw.TextLayout(dwFactory, textToDraw, textFormat, 300f, 1000f); SharpDX.Mathematics.Interop.RawColor4 color = new SharpDX.Mathematics.Interop.RawColor4(255, 255, 255, 1); var textBrush = new d2.SolidColorBrush(d2dContext, color); //여기서부터 다시 //render target setup //create the d2d bitmap description using default flags and 96 DPI var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw); //the render target var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(pixelWidth, pixelHeight), d2dBitmapProps); d2dContext.Target = d2dRenderTarget; //associate bitmap with the d2d context //Drawing //slow preparations - fast drawing d2dContext.BeginDraw(); d2dContext.DrawImage(gaussianBlurEffect, new SharpDX.Mathematics.Interop.RawVector2(100f, 100f)); d2dContext.DrawTextLayout(new SharpDX.Mathematics.Interop.RawVector2(50f, 50f), textLayout, textBrush); d2dContext.EndDraw(); //Image save //delete the output file if it already exists if (System.IO.File.Exists(outputPath)) { System.IO.File.Delete(outputPath); } //use the appropiate overload to write either to tream or to a file var stream = new wic.WICStream(imagingFactory, outputPath, NativeFileAccess.Write); //select the image encoding format HERE var encoder = new wic.PngBitmapEncoder(imagingFactory); encoder.Initialize(stream); var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder); bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(pixelWidth, pixelHeight); bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat); //this is the trick to write d2d1 bitmap to WIC var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice); imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96, 0, 0, pixelWidth, pixelHeight)); bitmapFrameEncode.Commit(); encoder.Commit(); //cleanup //dispose everything and free used resources bitmapFrameEncode.Dispose(); encoder.Dispose(); stream.Dispose(); textBrush.Dispose(); textLayout.Dispose(); textFormat.Dispose(); formatConverter.Dispose(); //gaussianBlurEffect.Dispose(); bitmapSourceEffect.Dispose(); d2dRenderTarget.Dispose(); inputStream.Dispose(); decoder.Dispose(); d2dContext.Dispose(); dwFactory.Dispose(); imagingFactory.Dispose(); d2dDevice.Dispose(); dxgiDevice.Dispose(); d3dDevice.Dispose(); defaultDevice.Dispose(); //save System.Diagnostics.Process.Start(outputPath); }
void InitializeDirect2D() { d3dDevice = new D3D.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport); dxgiDevice = d3dDevice.QueryInterface<DXGI.Device1>(); var desc = new SwapChainDescription1() { Width = 0, Height = 0, Format = Format.B8G8R8A8_UNorm, Stereo = false, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 3, Scaling = Scaling.None, SwapEffect = SwapEffect.FlipSequential, Flags = SwapChainFlags.None }; DXGI.Factory2 dxgiFactory = dxgiDevice.Adapter.GetParent<DXGI.Factory2>(); swapChain = new SwapChain1(dxgiFactory, d3dDevice, Child.Handle, ref desc); swapChain.BackgroundColor = Color4.White; dxgiFactory.Dispose(); d2dFactory = new D2D.Factory1(FactoryType.SingleThreaded); d2dDevice = new D2D.Device(d2dFactory, dxgiDevice); d2dDeviceContext = new D2D.DeviceContext(d2dDevice, DeviceContextOptions.None); d2dDeviceContext.TextAntialiasMode = TextAntialiasMode.Cleartype; //d2dDeviceContext.DotsPerInch = new Size2F(96, 96); var props = new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, D2D.AlphaMode.Ignore), d2dDeviceContext.DotsPerInch.Width, d2dDeviceContext.DotsPerInch.Height, BitmapOptions.Target | BitmapOptions.CannotDraw); Surface1 dxgiSurface = swapChain.GetBackBuffer<Surface1>(0); d2dSurface = new Bitmap1(d2dDeviceContext, dxgiSurface, props); dxgiSurface.Dispose(); d2dDeviceContext.Target = d2dSurface; VertexFillBrush = new SolidColorBrush(d2dDeviceContext, new Color4(1, 0.5f, 0, 1)); VertexDrawBrush = new SolidColorBrush(d2dDeviceContext, new Color4(0.2f, 0.2f, 0.2f, 1)); EdgeDrawBrush = new SolidColorBrush(d2dDeviceContext, Color4.Black); RasterDrawBrush = new SolidColorBrush(d2dDeviceContext, new Color4(0.5f, 0.5f, 0.5f, 1)); }