public override void Dispose() { if (dx11Device != null) dx11Device.Dispose(); if (dx11Factory != null) dx11Factory.Dispose(); if (dx11Output != null) dx11Output.Dispose(); if (dx11DuplicatedOutput != null) dx11DuplicatedOutput.Dispose(); if (dx11ScreenTexture != null) dx11ScreenTexture.Dispose(); if (dx11ScreenResource != null) dx11ScreenResource.Dispose(); if (dx11ScreenSurface != null) dx11ScreenSurface.Dispose(); if (screenShot != null) screenShot.Dispose(); dx11Device = null; dx11Factory = null; dx11Output = null; dx11DuplicatedOutput = null; dx11ScreenTexture = null; dx11ScreenResource = null; dx11ScreenSurface = null; screenShot = null; bmpData = null; GC.SuppressFinalize(this); }
/// <summary> /// Initializes a new instance of the <see cref="RenderControl" /> class. /// </summary> public RenderControl() { SwapChainDescription swapCHainDesc = new SwapChainDescription { BufferCount = 2, Usage = Usage.RenderTargetOutput, OutputHandle = Handle, IsWindowed = true, ModeDescription = new ModeDescription( Width, Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(1, 0), Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard }; Device.CreateWithSwapChain( DriverType.Hardware, DeviceCreationFlags.BgraSupport, swapCHainDesc, out _device, out _swapChain); Debug.Assert(_swapChain != null, "_swapChain != null"); // ReSharper disable once AssignNullToNotNullAttribute _backBuffer = Surface.FromSwapChain(_swapChain, 0); Debug.Assert(_backBuffer != null, "_backBuffer != null"); Size2F dpi = DirectXResourceManager.FactoryD2D.DesktopDpi; RenderTarget renderTarget = new RenderTarget( DirectXResourceManager.FactoryD2D, _backBuffer, new RenderTargetProperties { DpiX = dpi.Width, DpiY = dpi.Height, MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT, PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Ignore), Type = RenderTargetType.Default, Usage = RenderTargetUsage.None }); _renderTargetContainer = RenderTargetContainer.CreateContainer(renderTarget, out _renderTargetRef); using (FactoryDXGI factory = _swapChain.GetParent<FactoryDXGI>()) { Debug.Assert(factory != null, "factory != null"); factory.MakeWindowAssociation(Handle, WindowAssociationFlags.IgnoreAltEnter); } _renderThread = new Thread(RenderLoop) { Name = "Render Thread", IsBackground = true }; }
/// <summary> /// Disposes of object resources. /// </summary> /// <param name="disposeManagedResources">If true, managed resources should be /// disposed of in addition to unmanaged resources.</param> protected virtual void Dispose(bool disposeManagedResources) { if (disposeManagedResources) { _d3d11Device.Dispose(); _dxgiDevice.Dispose(); _backBuffer.Dispose(); _targetBitmap.Dispose(); _backBuffer2.Dispose(); _targetBitmap2.Dispose(); _d2dDevice.Dispose(); swapChain.Dispose(); swapChain2.Dispose(); d2dContext.Dispose(); d2dContext2.Dispose(); dw_Factory.Dispose(); } _d3d11Device = null; _dxgiDevice = null; _backBuffer = null; _targetBitmap = null; _backBuffer2 = null; _targetBitmap2 = null; _d2dDevice = null; swapChain = null; swapChain2 = null; d2dContext = null; d2dContext2 = null; dw_Factory = null; }
internal void ReleaseDevices() { IsRendererSuppressed = true; RenderTarget.Dispose(); Backbuffer.Dispose(); RenderTargetSurface.Dispose(); RenderTargetView.Dispose(); D2DDeviceContext.Dispose(); D2DDevice.Dispose(); D2DFactory.Dispose(); DXGIDevice.Dispose(); D3DDevice.Dispose(); D3DDefaultDevice.Dispose(); SwapChain.Dispose(); SwapChain = null; RenderTarget = null; RenderTargetSurface = null; Backbuffer = null; RenderTargetView = null; D2DDeviceContext = null; D2DFactory = null; D2DDevice = null; DXGIDevice = null; D3DDevice = null; D3DDefaultDevice = null; }
public void Connect() { using (DXGI.Surface surface = Dxgi().SwapChain.GetBackBuffer <DXGI.Surface>(0)) using (var bitmap = new Bitmap1(Context, surface)) { Context.Target = bitmap; } }
public RenderTargetCanvas(DXGI.Surface surface, D2D1.RenderTargetProperties properties, Direct2DFactories factories = null) { if (surface == null) { throw new ArgumentNullException("surface"); } this.factories = factories ?? Direct2DFactories.Shared; Initialize(new D2D1.RenderTarget(this.factories.D2DFactory, surface, properties)); }
public void ConstructRenderAndResource(double width, double height) { float dpiX, dpiY; this.GetDpi(out dpiX, out dpiY); D2D.RenderTargetProperties prop = new D2D.RenderTargetProperties( D2D.RenderTargetType.Default, new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied), dpiX, dpiY, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT); D3D11.Texture2DDescription desc = new D3D11.Texture2DDescription(); desc.Width = (int)width; desc.Height = (int)height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = DXGI.Format.B8G8R8A8_UNorm; desc.SampleDescription = new DXGI.SampleDescription(1, 0); desc.Usage = D3D11.ResourceUsage.Default; desc.BindFlags = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource; desc.CpuAccessFlags = D3D11.CpuAccessFlags.None; desc.OptionFlags = D3D11.ResourceOptionFlags.Shared; this.d3d11Texture = new D3D11.Texture2D(this.device, desc); this.surface = this.d3d11Texture.QueryInterface <DXGI.Surface>(); DXGI.Resource resource = this.d3d11Texture.QueryInterface <DXGI.Resource>(); IntPtr handel = resource.SharedHandle; D3D9.Texture texture = new D3D9.Texture( this.device9, this.d3d11Texture.Description.Width, this.d3d11Texture.Description.Height, 1, D3D9.Usage.RenderTarget, D3D9.Format.A8R8G8B8, D3D9.Pool.Default, ref handel); this.surface9 = texture.GetSurfaceLevel(0); resource.Dispose(); texture.Dispose(); D2D.BitmapProperties bmpProp = new D2D.BitmapProperties(); bmpProp.DpiX = dpiX; bmpProp.DpiY = dpiY; bmpProp.PixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied); this.bmpd2d = new D2D.Bitmap(this.render, this.surface, bmpProp); this.cachedBitMap = new D2D.Bitmap(this.render, new Size2((int)width, (int)height), bmpProp); this.hasCache = false; this.render.Target = this.bmpd2d; this.renderSize = new Size(width, height); }
public void ResizeScreen1() { d2dContext.Target = null; _backBuffer.Dispose(); _targetBitmap.Dispose(); swapChain.ResizeBuffers(1, 0, 0, DXGI.Format.B8G8R8A8_UNorm, DXGI.SwapChainFlags.None); _backBuffer = DXGI.Surface.FromSwapChain(swapChain, 0); _targetBitmap = new D2D1.Bitmap1(d2dContext, _backBuffer); d2dContext.Target = _targetBitmap; }
public void ResizeScreen2() { d2dContext2.Target = null; _backBuffer2.Dispose(); _targetBitmap2.Dispose(); swapChain2.ResizeBuffers(1, 0, 0, DXGI.Format.B8G8R8A8_UNorm, DXGI.SwapChainFlags.None); _backBuffer2 = DXGI.Surface.FromSwapChain(swapChain2, 0); _targetBitmap2 = new D2D1.Bitmap1(d2dContext2, _backBuffer2); d2dContext2.Target = _targetBitmap2; }
/// <summary> /// Specialised constructor for use only by derived classes. /// </summary> /// <param name="device">The device.</param> /// <param name="texture">The texture.</param> protected internal Texture3D(GraphicsDevice device, Texture3D texture, ViewType viewType, int arraySlice, int mipMapSlice, PixelFormat viewFormat = PixelFormat.None) : base(device, texture, viewType, arraySlice, mipMapSlice, viewFormat) { // Copy the device child, but don't use NativeDeviceChild, as it is registering it for disposing. _nativeDeviceChild = texture._nativeDeviceChild; Resource = texture.Resource; NativeDescription = texture.NativeDescription; dxgiSurface = texture.dxgiSurface; NativeShaderResourceView = GetShaderResourceView(ViewType, ArraySlice, MipLevel); NativeUnorderedAccessView = GetUnorderedAccessView(ArraySlice, MipLevel); }
public void Create3dObjects() { //Create RenderWindow RenderWindowInstance = new ModelRenderWindow(); FormInstance = RenderWindowInstance.CreateWindow(1080,1240,FormStartPosition.CenterScreen); //Create SwapChain SwapChainCreator = new ModelSwapChainDesc(); SwapChainD = SwapChainCreator.CreateSwapChain(2, Usage.RenderTargetOutput, FormInstance.Handle, true, 0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm, 1,0,SwapChainFlags.AllowModeSwitch, SwapEffect.Discard); //Create Device Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, SwapChainD, out GraphicsDevice, out NewSwapChain); //Create Back buffer BackBuffer = Surface.FromSwapChain(NewSwapChain, 0); //Create Factory FactoryD2D FactoryInstance = new FactoryD2D(); //Create RenderTarget RenderTargetInstance = new ModelRenderTarget(); RenderTarget = RenderTargetInstance.CreateRenderTarget(SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT, new PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Ignore), RenderTargetType.Default, RenderTargetUsage.None, BackBuffer, FactoryInstance); RenderLoop.Run(FormInstance, () => { RenderTarget.BeginDraw(); RenderTarget.Transform = Matrix3x2.Identity; RenderTarget.Clear(Color.White); using (var brush = new SolidColorBrush(RenderTarget, Color.Red)) { //for (int x = 0; x < RenderTarget.Size.Width; x += 10) // RenderTarget.DrawLine(new Vector2(x, 0), new Vector2(x, RenderTarget.Size.Height), brush, 0.5f); //for (int y = 0; y < RenderTarget.Size.Height; y += 10) // RenderTarget.DrawLine(new Vector2(0, y), new Vector2(RenderTarget.Size.Width, y), brush, 0.5f); RenderTarget.DrawLine(new Vector2(300, 10), new Vector2(300, 300), brush,1.5f); // RenderTarget.FillRectangle(new RectangleF(RenderTarget.Size.Width / 2 - 50, RenderTarget.Size.Height / 2 - 50, 100, 100), brush); } // RenderTarget.DrawRectangle( // new RectangleF(RenderTarget.Size.Width / 2 - 100, RenderTarget.Size.Height / 2 - 100, 200, 200), // new SolidColorBrush(RenderTarget, Color.CornflowerBlue)); RenderTarget.EndDraw(); NewSwapChain.Present(0, PresentFlags.None); }); RenderTarget.Dispose(); NewSwapChain.Dispose(); GraphicsDevice.Dispose(); }
/// <summary> /// Initializes the graphics. /// </summary> public void Initialize() { var swapChainDesc = new SwapChainDescription { BufferCount = 2, Usage = Usage.RenderTargetOutput, OutputHandle = SGL.Components.Get <RenderTarget>().Handle, IsWindowed = true, ModeDescription = new ModeDescription(_graphicsDevice.BackBuffer.Width, _graphicsDevice.BackBuffer.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(1, 0), Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard }; _swapChainDesc = swapChainDesc; swapChainDesc.ModeDescription.Scaling = _graphicsDevice.BackBuffer.Scaling ? DisplayModeScaling.Stretched : DisplayModeScaling.Centered; Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, swapChainDesc, out device, out swapChain); _swapChain = swapChain; // Get back buffer in a Direct2D-compatible format (DXGI surface) SharpDX.DXGI.Surface backBuffer = SharpDX.DXGI.Surface.FromSwapChain(swapChain, 0); var renderTarget = new SharpDX.Direct2D1.RenderTarget(DirectXHelper.D2DFactory, backBuffer, new RenderTargetProperties { DpiX = 96, DpiY = 96, MinLevel = FeatureLevel.Level_DEFAULT, PixelFormat = new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Ignore), Type = RenderTargetType.Hardware, Usage = RenderTargetUsage.None }) { TextAntialiasMode = TextAntialiasMode.Cleartype }; DirectXHelper.RenderTarget = renderTarget; DirectXHelper.RenderTarget.AntialiasMode = SmoothingMode == SmoothingMode.AntiAlias ? AntialiasMode.Aliased : AntialiasMode.PerPrimitive; }
/// <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 override void Dispose() { if (dx11Device != null) { dx11Device.Dispose(); } if (dx11Factory != null) { dx11Factory.Dispose(); } if (dx11Output != null) { dx11Output.Dispose(); } if (dx11DuplicatedOutput != null) { dx11DuplicatedOutput.Dispose(); } if (dx11ScreenTexture != null) { dx11ScreenTexture.Dispose(); } if (dx11ScreenResource != null) { dx11ScreenResource.Dispose(); } if (dx11ScreenSurface != null) { dx11ScreenSurface.Dispose(); } if (screenShot != null) { screenShot.Dispose(); } dx11Device = null; dx11Factory = null; dx11Output = null; dx11DuplicatedOutput = null; dx11ScreenTexture = null; dx11ScreenResource = null; dx11ScreenSurface = null; screenShot = null; bmpData = null; GC.SuppressFinalize(this); }
private void InitializeDevices() { try { SwapChainDescription = new DXGI.SwapChainDescription(); SwapChainDescription.BufferCount = 2; SwapChainDescription.SampleDescription = new DXGI.SampleDescription(1, 0); SwapChainDescription.SwapEffect = DXGI.SwapEffect.Discard; SwapChainDescription.Usage = DXGI.Usage.BackBuffer | DXGI.Usage.RenderTargetOutput; SwapChainDescription.IsWindowed = true; SwapChainDescription.ModeDescription = new DXGI.ModeDescription(GameWindow.Current.WindowParameters.Width, GameWindow.Current.WindowParameters.Height, new DXGI.Rational(60, 1), DXGI.Format.B8G8R8A8_UNorm); SwapChainDescription.OutputHandle = GameWindowHandle; D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport, featureLevels, SwapChainDescription, out D3DDefaultDevice, out SwapChain); DXGI.Factory factory = SwapChain.GetParent <DXGI.Factory>(); factory.MakeWindowAssociation(GameWindowHandle, DXGI.WindowAssociationFlags.IgnoreAll); D3DDevice = D3DDefaultDevice.QueryInterface <D3D11.Device1>(); Backbuffer = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(SwapChain, 0); RenderTargetView = new D3D11.RenderTargetView(D3DDevice, Backbuffer); D3DDevice.ImmediateContext.Rasterizer.SetViewport(0, 0, GameWindow.Current.WindowParameters.Width, GameWindow.Current.WindowParameters.Height); D3DDevice.ImmediateContext.OutputMerger.SetTargets(RenderTargetView); DXGIDevice = D3DDevice.QueryInterface <DXGI.Device>(); D2DFactory = new D2D1.Factory1(D2D1.FactoryType.MultiThreaded); D2DDevice = new D2D1.Device(D2DFactory, DXGIDevice); D2DDeviceContext = new D2D1.DeviceContext(D2DDevice, D2D1.DeviceContextOptions.None); RenderTargetSurface = Backbuffer.QueryInterface <DXGI.Surface>(); RenderTarget = new D2D1.RenderTarget(D2DFactory, RenderTargetSurface, new D2D1.RenderTargetProperties(new D2D1.PixelFormat(DXGI.Format.Unknown, D2D1.AlphaMode.Premultiplied))); RenderTarget.AntialiasMode = D2D1.AntialiasMode.PerPrimitive; // Initialize debug drawings brushes DrawingBoundsBrush = new D2D1.SolidColorBrush(RenderTarget, new SharpDX.Color(1f, 1f, 0f)); CollisionBoxesBrush = new D2D1.SolidColorBrush(RenderTarget, new SharpDX.Color(1f, 0f, 0f)); RenderFrame = new RenderFrame(RenderTarget); Clock = Stopwatch.StartNew(); } catch (Exception ex) { throw new DeviceInitializationException("Unable to initialize DirectX device!", ex); } }
public void Resize() { canDraw = false; device.ImmediateContext.ClearState(); d2dTarget.Dispose(); d2dContext.Dispose(); backBuffer.Dispose(); swapChain.ResizeBuffers(2, 0, 0, Format.Unknown, SwapChainFlags.None); backBuffer = Surface.FromSwapChain(swapChain, 0); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); d2dTarget = new Bitmap1(d2dContext, backBuffer, properties); d2dContext.Target = d2dTarget; canDraw = true; }
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; }
/// <inheritdoc/> protected internal override bool OnRecreate() { // Dependency: wait for underlying texture to be recreated if (ParentTexture != null && ParentTexture.LifetimeState != GraphicsResourceLifetimeState.Active) { return(false); } base.OnRecreate(); // Only a view? if (ParentTexture != null) { // Copy the device child, but don't use NativeDeviceChild, as it is registering it for disposing. _nativeDeviceChild = ParentTexture._nativeDeviceChild; NativeResource = ParentTexture.NativeResource; NativeDescription = ((Texture2D)ParentTexture).NativeDescription; dxgiSurface = ((Texture2D)ParentTexture).dxgiSurface; return(true); } else { // Render Target / Depth Stencil are considered as "dynamic" if ((Description.Usage == GraphicsResourceUsage.Immutable || Description.Usage == GraphicsResourceUsage.Default) && (NativeDescription.BindFlags & (BindFlags.RenderTarget | BindFlags.DepthStencil)) == 0) { return(false); } NativeDeviceChild = new SharpDX.Direct3D11.Texture2D(GraphicsDevice.NativeDevice, NativeDescription); } // Recreate SRV/UAV NativeShaderResourceView = GetShaderResourceView(ViewType, ArraySlice, MipLevel); NativeUnorderedAccessView = GetUnorderedAccessView(ArraySlice, MipLevel); // If we have a depthStencilBufferForShaderResource, then we should override the default shader resource view if (TextureDepthStencilBuffer != null) { nativeShaderResourceView = TextureDepthStencilBuffer.nativeShaderResourceView; } return(true); }
public void Resize() { var size = Target.ClientSize; mDevice.Dispose(); mSurface.Dispose(); mSwapChain.ResizeBuffers(1, size.Width, size.Height, mSwapChainDesc.ModeDescription.Format, mSwapChainDesc.Flags); mSurface = dx.Surface.FromSwapChain(mSwapChain, 0); mDevice = new d2.DeviceContext(mSurface); mD3Device.ImmediateContext.ClearState(); base.Resized(); }
public void Resize(int width, int height) { ResolutionX = width; ResolutionY = height; MainCamera.renderTargetView?.Dispose(); MainCamera.depthStencilView?.Dispose(); D2DTarget?.Dispose(); D2DContext?.Dispose(); MainCamera.AspectRatio = width / (float)height; swapChain.ResizeBuffers(swapChain.Description.BufferCount, width, height, DXGI.Format.Unknown, DXGI.SwapChainFlags.None); D2DContext = new D2D1.DeviceContext(D2DDevice, D2D1.DeviceContextOptions.None); using (DXGI.Surface surface = swapChain.GetBackBuffer <DXGI.Surface>(0)) D2DTarget = new D2D1.Bitmap1(D2DContext, surface, new D2D1.BitmapProperties1(new D2D1.PixelFormat(DXGI.Format.R8G8B8A8_UNorm, D2D1.AlphaMode.Premultiplied), D2DFactory.DesktopDpi.Height, D2DFactory.DesktopDpi.Width, D2D1.BitmapOptions.CannotDraw | D2D1.BitmapOptions.Target) ); D2DContext.Target = D2DTarget; // render target using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0)) MainCamera.renderTargetView = new D3D11.RenderTargetView(Device, backBuffer); // depth buffer D3D11.Texture2DDescription depthDescription = new D3D11.Texture2DDescription() { Format = DXGI.Format.D32_Float, ArraySize = 1, MipLevels = 1, Width = width, Height = height, SampleDescription = new DXGI.SampleDescription(SampleCount, SampleQuality), Usage = D3D11.ResourceUsage.Default, BindFlags = D3D11.BindFlags.DepthStencil, CpuAccessFlags = D3D11.CpuAccessFlags.None, OptionFlags = D3D11.ResourceOptionFlags.None }; using (D3D11.Texture2D depthTexture = new D3D11.Texture2D(Device, depthDescription)) MainCamera.depthStencilView = new D3D11.DepthStencilView(Device, depthTexture); // viewport Viewport = new Viewport(0, 0, width, height); Context.Rasterizer.SetViewport(Viewport); }
public SharpDXDevice(Window window) { this.window = window; width = (int)window.ViewportSize.Width; height = (int)window.ViewportSize.Height; DxDevice.CreateWithSwapChain(DriverType.Hardware, #if DEBUG DeviceCreationFlags.Debug | #endif DeviceCreationFlags.BgraSupport, CreateSwapChainDescription(), out device, out swapChain); direct2DFactory = new D2dFactory(); backBuffer = Resource.FromSwapChain<Texture2D>(swapChain, 0); surface = backBuffer.QueryInterface<Surface>(); RenderTarget = new RenderTarget(direct2DFactory, surface, defaultRenderTargetProperties); window.ViewportSizeChanged += ResetDeviceToNewViewportSize; Screen = new ScreenSpace(window.ViewportSize); }
private void CreateRenderTarget(SharpDX.DXGI.Surface surface) { // Create a D2D render target which can draw into our offscreen D3D surface. // D2D uses device independant units, like WPF, at 96/inch. var properties = new SharpDX.Direct2D1.RenderTargetProperties(); properties.DpiX = 96; properties.DpiY = 96; properties.MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT; properties.PixelFormat = new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied); properties.Usage = SharpDX.Direct2D1.RenderTargetUsage.None; if (this.renderTarget != null) { this.renderTarget.Dispose(); } renderTarget = new SharpDX.Direct2D1.RenderTarget(factory2D, surface, properties); }
/// <summary> /// Disposes all loaded view resources. /// </summary> void IRenderLoopHost.OnRenderLoop_DisposeViewResources(EngineDevice engineDevice) { if (m_d3dImageSource != null) { this.Source = m_dummyBitmap; // Dispose the render target m_d3dImageSource.SetRenderTarget(null); m_d3dImageSource.Dispose(); m_d3dImageSource = null; } // Dispose all other resources m_renderTarget2DDxgi = GraphicsHelper.DisposeObject(m_renderTarget2DDxgi); m_renderTargetDepth = GraphicsHelper.DisposeObject(m_renderTargetDepth); m_depthBuffer = GraphicsHelper.DisposeObject(m_depthBuffer); m_renderTarget = GraphicsHelper.DisposeObject(m_renderTarget); m_backBufferForWpf = GraphicsHelper.DisposeObject(m_backBufferForWpf); m_backBufferD3D11 = GraphicsHelper.DisposeObject(m_backBufferD3D11); }
public void ResizeDevice(int width, int height) { lock (this) { if (width < 0) { throw new ArgumentOutOfRangeException("width", "Value must be positive."); } if (height < 0) { throw new ArgumentOutOfRangeException("height", "Value must be positive."); } if ((width <= this.width) && (height <= this.height)) { return; } DirectXHelpers.SafeDispose(ref this.texture); var texture = CreateTexture(Math.Max(width, this.width), Math.Max(height, this.height), true); this.texture = texture; DirectXHelpers.SafeDispose(ref this.shareableTexture); var shareableTexture = CreateTexture(Math.Max(width, this.width), Math.Max(height, this.height), false); this.shareableTexture = shareableTexture; CreateD3D9TextureFromD3D10Texture(shareableTexture); this.width = texture.Description.Width; this.height = texture.Description.Height; using (SharpDX.DXGI.Surface surface = texture.AsSurface()) { CreateRenderTarget(surface); } if (DeviceResized != null) { DeviceResized(this, EventArgs.Empty); } } }
public RenderTarget CreateRenderTarget(SharpDX.Direct2D1.FeatureLevel PFeatureLevel, PixelFormat PPixelFormat, RenderTargetType PRenderTargetType, RenderTargetUsage PRenderTargetUsage, Surface PBackBuffer, FactoryD2D PFactory) { this._FeatureLevel = PFeatureLevel; this._PixelFormat = PPixelFormat; this._RenderType = PRenderTargetType; this._RenderUsage = PRenderTargetUsage; _DPI = PFactory.DesktopDpi; _RenderTarget = new RenderTarget(PFactory, PBackBuffer, new RenderTargetProperties() { DpiX = _DPI.Width, DpiY = _DPI.Height, MinLevel = _FeatureLevel, PixelFormat = _PixelFormat, Type = _RenderType, Usage= _RenderUsage }); return _RenderTarget; }
private void CleanUpDeviceIndependentResources() { if (_deviceIndependedResourcesCreated) { OnCleanUpDeviceIndependentResources(); } if (_surface != null && !_surface.IsDisposed) { _surface.Dispose(); } _surface = null; if (_dc != null && !_dc.IsDisposed) { _dc.Dispose(); } _dc = null; if (_d2dDevice != null && !_d2dDevice.IsDisposed) { _d2dDevice.Dispose(); } _d2dDevice = null; if (_renderTarget != null && !_renderTarget.IsDisposed) { _renderTarget.Dispose(); } _renderTarget = null; if (_d2dFactory != null && !_d2dFactory.IsDisposed) { _d2dFactory.Dispose(); } _d2dFactory = null; }
protected virtual void InitRenderer() { mSwapChainDesc = new dx.SwapChainDescription() { BufferCount = 1, IsWindowed = true, OutputHandle = Target.Handle, SwapEffect = dx.SwapEffect.Discard, Usage = dx.Usage.RenderTargetOutput | dx.Usage.ShaderInput, Flags = dx.SwapChainFlags.None, ModeDescription = new dx.ModeDescription(0, 0, dx.Rational.Empty, dx.Format.B8G8R8A8_UNorm), SampleDescription = new dx.SampleDescription(1, 0) }; d3_11.Device.CreateWithSwapChain(d3.DriverType.Hardware, d3_11.DeviceCreationFlags.BgraSupport, mSwapChainDesc, out mD3Device, out mSwapChain); mSurface = dx.Surface.FromSwapChain(mSwapChain, 0); WriteFactory = new dWrite.Factory(); mDevice = new d2.DeviceContext(mSurface); mRenderCallback = new dWin.RenderLoop.RenderCallback(Render); }
public void InitScreen1(IntPtr handle) { d2dContext = new D2D1.DeviceContext(_d2dDevice, D2D1.DeviceContextOptions.None); d2dContextCdgText = new D2D1.DeviceContext(_d2dDevice, D2D1.DeviceContextOptions.None); // DXGI SwapChain DXGI.SwapChainDescription swapChainDesc = new DXGI.SwapChainDescription() { BufferCount = 1, Usage = DXGI.Usage.RenderTargetOutput, OutputHandle = handle, IsWindowed = true, ModeDescription = new DXGI.ModeDescription(0, 0, new DXGI.Rational(60, 1), DXGI.Format.B8G8R8A8_UNorm), SampleDescription = new DXGI.SampleDescription(1, 0), SwapEffect = DXGI.SwapEffect.Discard }; swapChain = new DXGI.SwapChain(_dxgiDevice.GetParent <DXGI.Adapter>().GetParent <DXGI.Factory>(), _d3d11Device, swapChainDesc); // BackBuffer _backBuffer = DXGI.Surface.FromSwapChain(swapChain, 0); //BackBuffer DeviceContext _targetBitmap = new D2D1.Bitmap1(d2dContext, _backBuffer); d2dContext.Target = _targetBitmap; // _dcBrush = new D2D1.SolidColorBrush(d2dContext, Color.Black); }
private void CreateDeviceIndependentResources() { _dxgiDevice = _d3dDevice.QueryInterface <SharpDX.DXGI.Device>(); _d2dDevice = new SharpDX.Direct2D1.Device(_dxgiDevice); _d2dFactory = _d2dDevice.Factory; var dpiX = _d2dFactory.DesktopDpi.Width; var dpiY = _d2dFactory.DesktopDpi.Height; _dc = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, DeviceContextOptions.None); _dc.PrimitiveBlend = PrimitiveBlend.SourceOver; var format = new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied); var properties = new BitmapProperties1(format, dpiX, dpiY, BitmapOptions.Target | BitmapOptions.CannotDraw); _surface = _swapChain.GetBackBuffer <Surface>(0); _renderTarget = new Bitmap1(_dc, _surface, properties); _dc.Target = _renderTarget; _dc.AntialiasMode = AntialiasMode.PerPrimitive; OnCreateDeviceIndependentResources(); this._deviceIndependedResourcesCreated = true; }
private Bitmap GetDX11ScreenShot() { try { screenShot = null; screenShot = new Bitmap(WIDTH, HEIGHT, this.pixelFormat); if (dx11DuplicatedOutput != null) { dx11DuplicatedOutput.AcquireNextFrame(NEXT_FRAME_TIMEOUT, out dx11DuplFrameInfo, out dx11ScreenResource); dx11Device.ImmediateContext .CopyResource(dx11ScreenResource.QueryInterface <SharpDX.Direct3D11.Resource>(), dx11ScreenTexture); // cast from texture to surface, so we can access its bytes dx11ScreenSurface = dx11ScreenTexture.QueryInterface <SharpDX.DXGI.Surface>(); // map the resource to access it dx11Map = dx11ScreenSurface.Map(SharpDX.DXGI.MapFlags.Read); bmpData = screenShot.LockBits(boundsRect, ImageLockMode.WriteOnly, screenShot.PixelFormat); var sourcePtr = dx11Map.DataPointer; var destPtr = bmpData.Scan0; for (int y = 0; y < HEIGHT; y++) { // Copy a single line Utilities.CopyMemory(destPtr, sourcePtr, ARGB_WIDTH); // Advance pointers sourcePtr = IntPtr.Add(sourcePtr, dx11Map.Pitch); destPtr = IntPtr.Add(destPtr, bmpData.Stride); } dx11Device.ImmediateContext.UnmapSubresource(dx11ScreenTexture, 0); screenShot.UnlockBits(bmpData); dx11ScreenSurface.Unmap(); dx11ScreenSurface.Dispose(); dx11ScreenResource.Dispose(); dx11DuplicatedOutput.ReleaseFrame(); } else { return(screenShot = null); } dx11ScreenSurface = null; bmpData = null; GC.Collect(); return(screenShot); } catch (SharpDX.SharpDXException e) { if (e.ResultCode.Code == SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code) { //screen does not changed LdpLog.Warning("DX11 surface timeout.. Recursion is coming:)"); return(GetDX11ScreenShot()); } else { return(screenShot = null); } } catch (Exception ex) { LdpLog.Error("GetDX11ScreenShot\n" + ex.Message); return(screenShot = null); } }
private void MainWindow_Loaded(object sender, RoutedEventArgs e) { // 根据 [Surface sharing between Windows graphics APIs - Win32 apps](https://docs.microsoft.com/en-us/windows/win32/direct3darticles/surface-sharing-between-windows-graphics-apis?WT.mc_id=WD-MVP-5003260 ) 文档 var width = ImageWidth; var height = ImageHeight; // 2021.12.23 不能在 x86 下运行,会炸掉。参阅 https://github.com/dotnet/Silk.NET/issues/731 var texture2DDesc = new D3D11.Texture2DDesc() { BindFlags = (uint)(D3D11.BindFlag.BindRenderTarget | D3D11.BindFlag.BindShaderResource), Format = DXGI.Format.FormatB8G8R8A8Unorm, // 最好使用此格式,否则还需要后续转换 Width = (uint)width, Height = (uint)height, MipLevels = 1, SampleDesc = new DXGI.SampleDesc(1, 0), Usage = D3D11.Usage.UsageDefault, MiscFlags = (uint)D3D11.ResourceMiscFlag.ResourceMiscShared, // The D3D11_RESOURCE_MISC_FLAG cannot be used when creating resources with D3D11_CPU_ACCESS flags. CPUAccessFlags = 0, //(uint) D3D11.CpuAccessFlag.None, ArraySize = 1 }; D3D11.ID3D11Device * pD3D11Device; D3D11.ID3D11DeviceContext *pD3D11DeviceContext; D3DFeatureLevel pD3DFeatureLevel = default; D3D11.D3D11 d3D11 = D3D11.D3D11.GetApi(); var hr = d3D11.CreateDevice((DXGI.IDXGIAdapter *)IntPtr.Zero, D3DDriverType.D3DDriverTypeHardware, Software: 0, Flags: (uint)D3D11.CreateDeviceFlag.CreateDeviceBgraSupport, (D3DFeatureLevel *)IntPtr.Zero, FeatureLevels: 0, // D3DFeatureLevel 的长度 SDKVersion: 7, (D3D11.ID3D11Device * *) & pD3D11Device, // 参阅 [C# 从零开始写 SharpDx 应用 聊聊功能等级](https://blog.lindexi.com/post/C-%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%86%99-SharpDx-%E5%BA%94%E7%94%A8-%E8%81%8A%E8%81%8A%E5%8A%9F%E8%83%BD%E7%AD%89%E7%BA%A7.html ) ref pD3DFeatureLevel, (D3D11.ID3D11DeviceContext * *) & pD3D11DeviceContext ); SilkMarshal.ThrowHResult(hr); Debugger.Launch(); Debugger.Break(); _pD3D11Device = pD3D11Device; _pD3D11DeviceContext = pD3D11DeviceContext; D3D11.ID3D11Texture2D *pD3D11Texture2D; hr = pD3D11Device->CreateTexture2D(ref texture2DDesc, (D3D11.SubresourceData *)IntPtr.Zero, &pD3D11Texture2D); SilkMarshal.ThrowHResult(hr); var renderTarget = pD3D11Texture2D; _pD3D11Texture2D = pD3D11Texture2D; DXGI.IDXGISurface *pDXGISurface; var dxgiSurfaceGuid = DXGI.IDXGISurface.Guid; renderTarget->QueryInterface(ref dxgiSurfaceGuid, (void **)&pDXGISurface); _pDXGISurface = pDXGISurface; var d2DFactory = new D2D.Factory(); var renderTargetProperties = new D2D.RenderTargetProperties(new D2D.PixelFormat(SharpDXDXGI.Format.Unknown, D2D.AlphaMode.Premultiplied)); var surface = new SharpDXDXGI.Surface(new IntPtr((void *)pDXGISurface)); _d2DRenderTarget = new D2D.RenderTarget(d2DFactory, surface, renderTargetProperties); SetRenderTarget(renderTarget); var viewport = new D3D11.Viewport(0, 0, width, height, 0, 1); pD3D11DeviceContext->RSSetViewports(NumViewports: 1, ref viewport); CompositionTarget.Rendering += CompositionTarget_Rendering; }
private Bitmap GetDX11ScreenShot() { try { screenShot = null; screenShot = new Bitmap(WIDTH, HEIGHT, this.pixelFormat); if (dx11DuplicatedOutput != null) { dx11DuplicatedOutput.AcquireNextFrame(NEXT_FRAME_TIMEOUT, out dx11DuplFrameInfo, out dx11ScreenResource); dx11Device.ImmediateContext .CopyResource(dx11ScreenResource.QueryInterface<SharpDX.Direct3D11.Resource>(), dx11ScreenTexture); // cast from texture to surface, so we can access its bytes dx11ScreenSurface = dx11ScreenTexture.QueryInterface<SharpDX.DXGI.Surface>(); // map the resource to access it dx11Map = dx11ScreenSurface.Map(SharpDX.DXGI.MapFlags.Read); bmpData = screenShot.LockBits(boundsRect, ImageLockMode.WriteOnly, screenShot.PixelFormat); var sourcePtr = dx11Map.DataPointer; var destPtr = bmpData.Scan0; for (int y = 0; y < HEIGHT; y++) { // Copy a single line Utilities.CopyMemory(destPtr, sourcePtr, ARGB_WIDTH); // Advance pointers sourcePtr = IntPtr.Add(sourcePtr, dx11Map.Pitch); destPtr = IntPtr.Add(destPtr, bmpData.Stride); } dx11Device.ImmediateContext.UnmapSubresource(dx11ScreenTexture, 0); screenShot.UnlockBits(bmpData); dx11ScreenSurface.Unmap(); dx11ScreenSurface.Dispose(); dx11ScreenResource.Dispose(); dx11DuplicatedOutput.ReleaseFrame(); } else return screenShot = null; dx11ScreenSurface = null; bmpData = null; GC.Collect(); return screenShot; } catch (SharpDX.SharpDXException e) { if (e.ResultCode.Code == SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code) { //screen does not changed LdpLog.Warning("DX11 surface timeout.. Recursion is coming:)"); return GetDX11ScreenShot(); } else { return screenShot = null; } } catch (Exception ex) { LdpLog.Error("GetDX11ScreenShot\n" + ex.Message); return screenShot = null; } }
/// <summary> /// 使用指定的渲染目标控件创建渲染目标。 /// </summary> /// <param name="control">渲染的目标控件。</param> public void CreateRenderTarget(Control control) { if (SupportD3D) { // 创建 Direct3D SwapChain。 SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = 1, Usage = Usage.RenderTargetOutput, OutputHandle = control.Handle, IsWindowed = true, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format), SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard }; this.swapChain = new SwapChain(dxgiDevice.GetParent<Adapter>().GetParent<DXGIFactory>(), d3DDevice, swapChainDesc); this.backBuffer = Surface.FromSwapChain(this.swapChain, 0); this.targetBitmap = new Bitmap1(this.d2DContext, backBuffer); this.renderTarget = new DeviceContext(this.d2DDevice, DeviceContextOptions.None); ((DeviceContext)this.renderTarget).Target = targetBitmap; } else { // 创建 Direct2D 工厂。 // 渲染参数。 RenderTargetProperties renderProps = new RenderTargetProperties { PixelFormat = D2PixelFormat, Usage = RenderTargetUsage.None, Type = RenderTargetType.Default }; // 渲染目标属性。 HwndRenderTargetProperties hwndProps = new HwndRenderTargetProperties() { Hwnd = control.Handle, PixelSize = new Size2(control.ClientSize.Width, control.ClientSize.Height), PresentOptions = PresentOptions.None }; // 渲染目标。 this.renderTarget = new WindowRenderTarget(d2DFactory, renderProps, hwndProps) { AntialiasMode = AntialiasMode.PerPrimitive }; } }
/// <summary> /// 调整渲染目标的尺寸。 /// </summary> /// <param name="control">渲染的目标控件。</param> public void ResizeRenderTarget(Control control) { if (this.swapChain == null) { ((WindowRenderTarget)this.renderTarget).Resize( new Size2(control.ClientSize.Width, control.ClientSize.Height)); } else { ((DeviceContext)this.renderTarget).Target = null; this.backBuffer.Dispose(); this.targetBitmap.Dispose(); this.swapChain.ResizeBuffers(1, 0, 0, Format, SwapChainFlags.None); this.backBuffer = Surface.FromSwapChain(this.swapChain, 0); this.targetBitmap = new Bitmap1(this.d2DContext, backBuffer); ((DeviceContext)this.renderTarget).Target = targetBitmap; } }
/// <summary> /// 清理所有正在使用的资源,并设置为 <c>null</c>。 /// </summary> private void ClearResources() { if (this.d3DDevice != null) { this.d3DDevice.Dispose(); this.d3DDevice = null; } if (this.dxgiDevice != null) { this.dxgiDevice.Dispose(); this.dxgiDevice = null; } if (this.swapChain != null) { this.swapChain.Dispose(); this.swapChain = null; } if (this.backBuffer != null) { this.backBuffer.Dispose(); this.backBuffer = null; } if (this.targetBitmap != null) { this.targetBitmap.Dispose(); this.swapChain = null; } if (this.d2DDevice != null) { this.d2DDevice.Dispose(); this.d2DDevice = null; } if (this.d2DContext != null) { this.d2DContext.Dispose(); this.d2DContext = null; } if (this.d2DFactory != null) { this.d2DFactory.Dispose(); this.d2DFactory = null; } if (this.renderTarget != null) { this.renderTarget.Dispose(); this.renderTarget = null; } if (this.wicFactory != null) { this.wicFactory.Dispose(); this.wicFactory = null; } }
void mediaEngine_PlaybackEvent(MediaEngineEvent mediaEvent, long param1, int param2) { if (mediaEvent == MediaEngineEvent.CanPlay) { if (this.mediaEngine.Error != null) { int a = 0; } if (this.mediaEngine.HasVideo()) { int width = 0; int height = 0; this.mediaEngine.GetNativeVideoSize(out width, out height); this.texture = new SharpDX.Direct3D11.Texture2D(this.context.D3DDevice, new SharpDX.Direct3D11.Texture2DDescription() { ArraySize = 1, Width = width, Height = height, Usage = SharpDX.Direct3D11.ResourceUsage.Default, Format = Format.B8G8R8A8_UNorm, CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None, BindFlags = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource, OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), MipLevels = 1, }); this.dxgiSurface = this.texture.QueryInterface<SharpDX.DXGI.Surface>(); this.textureView = new ShaderResourceView(this.context.D3DDevice, this.texture); ready = true; this.mediaEngine.Play(); } state = new RasterizerState(this.context.D3DDevice, new RasterizerStateDescription() { CullMode = CullMode.Back, FillMode = FillMode.Solid, DepthBias = 0, DepthBiasClamp = 0, IsDepthClipEnabled = true, IsMultisampleEnabled = true, SlopeScaledDepthBias = 0 }); } }
private void ResetDeviceToNewViewportSize(Size newSizeInPixel) { backBuffer.Dispose(); surface.Dispose(); RenderTarget.Dispose(); width = (int)newSizeInPixel.Width; height = (int)newSizeInPixel.Height; swapChain.ResizeBuffers(BackBufferCount, width, height, BackBufferFormat, SwapChainFlags.None); backBuffer = Resource.FromSwapChain<Texture2D>(swapChain, 0); surface = backBuffer.QueryInterface<Surface>(); RenderTarget = new RenderTarget(direct2DFactory, surface, defaultRenderTargetProperties); Screen = new ScreenSpace(newSizeInPixel); }
/// <summary> /// Creates an <see cref="SharpDX.Direct2D1.Bitmap"/> whose data is shared with another resource. /// </summary> /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param> /// <param name="surface">An <see cref="SharpDX.DXGI.Surface"/> that contains the data to share with the new ID2D1Bitmap. For more information, see the Remarks section.</param> /// <param name="bitmapProperties">The pixel format and DPI of the bitmap to create . The <see cref="SharpDX.DXGI.Format"/> portion of the pixel format must match the <see cref="SharpDX.DXGI.Format"/> of data or the method will fail, but the alpha modes don't have to match. To prevent a mismatch, you can pass NULL or the value obtained from the {{D2D1::PixelFormat}} helper function. The DPI settings do not have to match those of data. If both dpiX and dpiY are 0.0f, the default DPI, 96, is used.</param> /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmapFromDxgiSurface([In] IDXGISurface* surface,[In, Optional] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap1)</unmanaged> public Bitmap1(DeviceContext deviceContext, Surface surface, SharpDX.Direct2D1.BitmapProperties1 bitmapProperties) : base(IntPtr.Zero) { deviceContext.CreateBitmapFromDxgiSurface(surface, bitmapProperties, this); }
/// <summary> /// Creates an <see cref="SharpDX.Direct2D1.Bitmap"/> whose data is shared with another resource. /// </summary> /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param> /// <param name="surface">An <see cref="SharpDX.DXGI.Surface"/> that contains the data to share with the new ID2D1Bitmap. For more information, see the Remarks section.</param> /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmapFromDxgiSurface([In] IDXGISurface* surface,[In, Optional] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap1)</unmanaged> public Bitmap1(DeviceContext deviceContext, Surface surface) : base(IntPtr.Zero) { deviceContext.CreateBitmapFromDxgiSurface(surface, null, this); }
/// <summary> /// Raises the <see cref="E:System.Windows.Forms.Control.Layout" /> event. /// </summary> /// <param name="e">A <see cref="T:System.Windows.Forms.LayoutEventArgs" /> that contains the event data. </param> protected override void OnLayout(LayoutEventArgs e) { base.OnLayout(e); if (!_running) return; lock (_lock) { Debug.Assert(_renderTargetRef != null, "_renderTargetRef != null"); _renderTargetRef.Value = null; Interlocked.Exchange(ref _backBuffer, null)?.Dispose(); Debug.Assert(_swapChain != null, "_swapChain != null"); _swapChain.ResizeBuffers( 2, Width, Height, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch); // ReSharper disable once AssignNullToNotNullAttribute _backBuffer = Surface.FromSwapChain(_swapChain, 0); Debug.Assert(_backBuffer != null, "_backBuffer != null"); Size2F dpi = DirectXResourceManager.FactoryD2D.DesktopDpi; _renderTargetRef.Value = new RenderTarget( DirectXResourceManager.FactoryD2D, _backBuffer, new RenderTargetProperties { DpiX = dpi.Width, DpiY = dpi.Height, MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT, PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Ignore), Type = RenderTargetType.Default, Usage = RenderTargetUsage.None }); NeedsRender = true; } Thread.Yield(); }
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)); }
/// <summary> /// Creates a render target that draws to a DirectX Graphics Infrastructure (DXGI) surface. /// </summary> /// <remarks> /// To write to a Direct3D surface, you obtain an <see cref="SharpDX.DXGI.Surface"/> and pass it to the {{CreateDxgiSurfaceRenderTarget}} method to create a DXGI surface render target; you can then use the DXGI surface render target to draw 2-D content to the DXGI surface. A DXGI surface render target is a type of <see cref="SharpDX.Direct2D1.RenderTarget"/>. Like other Direct2D render targets, you can use it to create resources and issue drawing commands. The DXGI surface render target and the DXGI surface must use the same DXGI format. If you specify the {{DXGI_FORMAT_UNKOWN}} format when you create the render target, it will automatically use the surface's format.The DXGI surface render target does not perform DXGI surface synchronization. To work with Direct2D, the Direct3D device that provides the <see cref="SharpDX.DXGI.Surface"/> must be created with the D3D10_CREATE_DEVICE_BGRA_SUPPORT flag.For more information about creating and using DXGI surface render targets, see the {{Direct2D and Direct3D Interoperability Overview}}.When you create a render target and hardware acceleration is available, you allocate resources on the computer's GPU. By creating a render target once and retaining it as long as possible, you gain performance benefits. Your application should create render targets once and hold onto them for the life of the application or until the render target's {{EndDraw}} method returns the {{D2DERR_RECREATE_TARGET}} error. When you receive this error, you need to recreate the render target (and any resources it created). /// </remarks> /// <param name="factory">an instance of <see cref = "SharpDX.Direct2D1.Factory" /></param> /// <param name="dxgiSurface">The DXGI surface to bind this render target to</param> /// <param name="properties">The rendering mode, pixel format, remoting options, DPI information, and the minimum DirectX support required for hardware rendering. For information about supported pixel formats, see {{Supported Pixel Formats and Alpha Modes}}.</param> public RenderTarget(Factory factory, Surface dxgiSurface, RenderTargetProperties properties) : base(IntPtr.Zero) { factory.CreateDxgiSurfaceRenderTarget(dxgiSurface, ref properties, this); }