public static void Run() { var factory = new Factory1(); // 0: Intel 1: Nvidia 2: CPU var adapter = factory.Adapters1[1]; var device = new D3DDevice(adapter); var gpuName = adapter.Description.Description; var _64MB = new byte[64 * 1024 * 1024]; var buffer = new DXDynamicVertexBuffer(device); for (int i = 64; i <= 2048; i += 64) { buffer.Reset(_64MB); var result = MessageBox.Show(i + " MB! Flush?", "Memory Test - " + gpuName, MessageBoxButtons.YesNoCancel); if (result == DialogResult.Yes) { device.ImmediateContext.Flush(); } else if (result == DialogResult.No) { continue; } else { break; } } buffer.Dispose(); device.Dispose(); adapter.Dispose(); factory.Dispose(); }
private bool disposedValue = false; // 要检测冗余调用 protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: 释放托管状态(托管对象)。 factory.Dispose(); adapter.Dispose(); device.Dispose(); output.Dispose(); output1.Dispose(); screenTexture.Dispose(); } // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。 // TODO: 将大型字段设置为 null。 factory = null; adapter = null; device = null; output = null; output1 = null; screenTexture = null; disposedValue = true; } }
/// <summary> /// Dispose all /// </summary> public void close() { duplicatedOutput.Dispose(); screenTexture.Dispose(); output1.Dispose(); output.Dispose(); device.Dispose(); adapter.Dispose(); factory.Dispose(); }
protected virtual void Dispose(bool disposing) { DestroyOutputDuplicator(); screenTexture?.Dispose(); screen?.Dispose(); output?.Dispose(); device?.Dispose(); adapter?.Dispose(); factory?.Dispose(); }
private void Cleanup() { _duplicatedOutput?.Dispose(); _screenTexture?.Dispose(); _output1?.Dispose(); _output?.Dispose(); _device?.Dispose(); _adapter?.Dispose(); _factory?.Dispose(); }
public void TestDXGI() { // Force to load DXGI assembly var factory = new Factory1(); factory.Dispose(); // Look for DXGI descriptor SharpDX.DXGI.ResultCode.DeviceRemoved var descriptor = ResultDescriptor.Find(0x887A0005); Assert.AreEqual(descriptor.NativeApiCode, "DXGI_ERROR_DEVICE_REMOVED"); }
public void Dispose() { _factory?.Dispose(); _adapter?.Dispose(); _device?.Dispose(); _output?.Dispose(); _output6?.Dispose(); _duplicatedOutput?.Dispose(); _screenTexture?.Dispose(); GC.SuppressFinalize(this); }
public void Dispose() { duplicatedOutput?.Dispose(); output1?.Dispose(); output?.Dispose(); device?.Dispose(); adapter?.Dispose(); factory?.Dispose(); CurrentFrame?.Dispose(); PreviousFrame?.Dispose(); }
public void Dispose() { _duplicatedOutput?.Dispose(); _output1?.Dispose(); _output?.Dispose(); _stagingTexture?.Dispose(); _smallerTexture?.Dispose(); _smallerTextureView?.Dispose(); _device?.Dispose(); _adapter?.Dispose(); _factory?.Dispose(); _lastCapturedFrame = null; _disposed = true; }
public void Dispose() { try { // If there are any errors, that means the items are disposed or not yet newed up. We should be fine moving on. Texture.Dispose(); OutputDuplication.Dispose(); _output1.ReleaseOwnership(); _output.ReleaseOwnership(); _output1.Dispose(); _output.Dispose(); Device.Dispose(); _adapter.Dispose(); _factory.Dispose(); } catch { } }
public static void PrintAdapterInfo() { Factory1 factory1 = new Factory1(); Adapter1[] nAdapters = factory1.Adapters1; for (int i = 0; i < nAdapters.Length; i++) { Adapter1 adapter = factory1.Adapters1[i]; Debug.WriteLine(adapter.Description1.Description); Debug.WriteLine(adapter.Description1.DedicatedVideoMemory / 1024 / 1024 + "MB video memory."); // Output[] displays = adapter.Outputs; // foreach (var display in displays) // { // Debug.WriteLine(display.Description.DeviceName); // display.Dispose(); // } Debug.WriteLine($"Adapter {SharpDX.Direct3D11.Device.GetSupportedFeatureLevel(adapter).ToString()}"); adapter.Dispose(); } factory1.Dispose(); }
private void DisposeNative() { factory?.Dispose(); factory = null; if (renderBitmaps != null) { for (var i = 0; i < renderBitmaps.Length; i++) { renderBitmaps[i]?.Dispose(); renderBitmaps[i] = null; } renderBitmaps = null; } if (inputs != null) { for (var i = 0; i < inputs.Length; i++) { inputs[i]?.Dispose(); inputs[i] = null; } inputs = null; } }
private void DisposeNative() { _factory?.Dispose(); _factory = null; if (_renderBitmaps != null) { for (var i = 0; i < _renderBitmaps.Length; i++) { _renderBitmaps[i]?.Dispose(); _renderBitmaps[i] = null; } _renderBitmaps = null; } if (_inputs != null) { for (var i = 0; i < _inputs.Length; i++) { _inputs[i]?.Dispose(); _inputs[i] = null; } _inputs = null; } }
public bool Initialize(DSystemConfiguration configuration, IntPtr windowHandle) { try { #region Environment Configuration VerticalSyncEnabled = DSystemConfiguration.VerticalSyncEnabled; var factory = new Factory1(); var adapter = factory.GetAdapter1(0); var monitor = adapter.GetOutput(0); var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); var rational = new Rational(0, 1); if (VerticalSyncEnabled) { foreach (var mode in modes) { if (mode.Width == configuration.Width && mode.Height == configuration.Height) { rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator); break; } } } var adapterDescription = adapter.Description; VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; VideoCardDescription = string.Format("VideoCard: {0}", adapterDescription.Description.Trim('\0')); monitor.Dispose(); adapter.Dispose(); factory.Dispose(); #endregion #region Initialize swap chain and d3d device var swapChainDesc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm) { Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrder.Unspecified }, Usage = Usage.RenderTargetOutput, OutputHandle = windowHandle, SampleDescription = new SampleDescription(1, 0), IsWindowed = !DSystemConfiguration.FullScreen, Flags = SwapChainFlags.None, SwapEffect = SwapEffect.Discard }; SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; #endregion #region Initialize buffers var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0); RenderTargetView = new RenderTargetView(device, backBuffer); backBuffer.Dispose(); var depthBufferDesc = new Texture2DDescription() { Width = configuration.Width, Height = configuration.Height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; DepthStencilBuffer = new Texture2D(device, depthBufferDesc); #endregion #region Initialize Depth Enabled Stencil var depthStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; DepthStencilState = new DepthStencilState(Device, depthStencilDesc); #endregion #region Initialize Output Merger DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1); var depthStencilViewDesc = new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc); DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView); #endregion #region Initialize Raster State var rasterDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }; RasterState = new RasterizerState(Device, rasterDesc); var rasterDescWireFrame = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = FillMode.Wireframe, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }; RasterStateWirefram = new RasterizerState(Device, rasterDescWireFrame); // Setup a raster description which turns off back face culling. var rasterNoCullDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.None, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; // Create the no culling rasterizer state. RasterStateNoCulling = new RasterizerState(Device, rasterNoCullDesc); #endregion #region Initialize Rasterizer DeviceContext.Rasterizer.State = RasterState; ViewPort = new ViewportF(0.0f, 0.0f, (float)configuration.Width, (float)configuration.Height, 0.0f, 1.0f); DeviceContext.Rasterizer.SetViewport(ViewPort); #endregion #region Initialize matrices ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)configuration.Width / (float)configuration.Height), DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth); WorldMatrix = Matrix.Identity; OrthoMatrix = Matrix.OrthoLH(configuration.Width, configuration.Height, DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth); #endregion #region Initialize Depth Disabled Stencil var depthDisabledStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; DepthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc); #endregion #region Initialize Blend States var blendStateDesc = new BlendStateDescription(); blendStateDesc.AlphaToCoverageEnable = false; blendStateDesc.IndependentBlendEnable = false; blendStateDesc.RenderTarget[0].IsBlendEnabled = true; blendStateDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].SourceBlend = BlendOption.One; blendStateDesc.RenderTarget[0].DestinationBlend = BlendOption.One; blendStateDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; AlphaEnableBlendingState = new BlendState(device, blendStateDesc); blendStateDesc.RenderTarget[0].IsBlendEnabled = false; blendStateDesc.AlphaToCoverageEnable = false; AlphaDisableBlendingState = new BlendState(device, blendStateDesc); #endregion return(true); } catch (Exception) { return(false); } }
private byte[] CaptureToBuffer(out int width, out int height) { // # of graphics card adapter const int numAdapter = 0; // # of output device (i.e. monitor) const int numOutput = 0; const string outputFileName = "ScreenCapture.bmp"; // Create DXGI Factory1 var factory = new Factory1(); var adapter = factory.GetAdapter1(numAdapter); // Create device from Adapter var device = new Device(adapter); // Get DXGI.Output var output = adapter.GetOutput(numOutput); var output1 = output.QueryInterface <Output1>(); // Width/Height of desktop to capture width = ((SharpDX.Rectangle)output.Description.DesktopBounds).Width; height = ((SharpDX.Rectangle)output.Description.DesktopBounds).Height; byte[] buffer = null; // Create Staging texture CPU-accessible var textureDesc = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = width, Height = height, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; var screenTexture = new Texture2D(device, textureDesc); // Duplicate the output var duplicatedOutput = output1.DuplicateOutput(device); bool captureDone = false; for (int i = 0; !captureDone; i++) { try { SharpDX.DXGI.Resource screenResource; OutputDuplicateFrameInformation duplicateFrameInformation; // Try to get duplicated frame within given time duplicatedOutput.AcquireNextFrame(10000, out duplicateFrameInformation, out screenResource); if (i > 0) { // copy resource into memory that can be accessed by the CPU using (var screenTexture2D = screenResource.QueryInterface <Texture2D>()) device.ImmediateContext.CopyResource(screenTexture2D, screenTexture); // Get the desktop capture texture var mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, MapFlags.None); buffer = new byte[width * height * 4]; Marshal.Copy(mapSource.DataPointer, buffer, 0, buffer.Length); device.ImmediateContext.UnmapSubresource(screenTexture, 0); // Capture done captureDone = true; } screenResource.Dispose(); duplicatedOutput.ReleaseFrame(); } catch (SharpDXException e) { if (e.ResultCode.Code != SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code) { throw e; } } } duplicatedOutput.Dispose(); screenTexture.Dispose(); output1.Dispose(); output.Dispose(); device.Dispose(); adapter.Dispose(); factory.Dispose(); // TODO: We should cleanp up all allocated COM objects here return(buffer); }
public bool Initialize(DSystemConfiguration configuration, IntPtr windowHandle) { try { #region Environment Configuration // Store the vsync setting. VerticalSyncEnabled = DSystemConfiguration.VerticalSyncEnabled; // Create a DirectX graphics interface factory. var factory = new Factory1(); // Use the factory to create an adapter for the primary graphics interface (video card). var adapter = factory.GetAdapter1(0); // Get the primary adapter output (monitor). var monitor = adapter.GetOutput(0); // Get modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor). var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); // Now go through all the display modes and find the one that matches the screen width and height. // When a match is found store the the refresh rate for that monitor, if vertical sync is enabled. // Otherwise we use maximum refresh rate. var rational = new Rational(0, 1); if (VerticalSyncEnabled) { foreach (var mode in modes) { if (mode.Width == configuration.Width && mode.Height == configuration.Height) { rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator); break; } } } // Get the adapter (video card) description. var adapterDescription = adapter.Description; // Store the dedicated video card memory in megabytes. VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; // Convert the name of the video card to a character array and store it. VideoCardDescription = adapterDescription.Description.Trim('\0'); // Release the adapter output. monitor.Dispose(); // Release the adapter. adapter.Dispose(); // Release the factory. factory.Dispose(); #endregion #region Initialize swap chain and d3d device // Initialize the swap chain description. var swapChainDesc = new SwapChainDescription() { // Set to a single back buffer. BufferCount = 1, // Set the width and height of the back buffer. ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm), // Set the usage of the back buffer. Usage = Usage.RenderTargetOutput, // Set the handle for the window to render to. OutputHandle = windowHandle, // Turn multisampling off. SampleDescription = new SampleDescription(1, 0), // Set to full screen or windowed mode. IsWindowed = !DSystemConfiguration.FullScreen, // Don't set the advanced flags. Flags = SwapChainFlags.None, // Discard the back buffer content after presenting. SwapEffect = SwapEffect.Discard }; // Create the swap chain, Direct3D device, and Direct3D device context. SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; #endregion #region Initialize buffers // Get the pointer to the back buffer. var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0); // Create the render target view with the back buffer pointer. RenderTargetView = new RenderTargetView(device, backBuffer); // Release pointer to the back buffer as we no longer need it. backBuffer.Dispose(); #endregion #region Initialize Depth Enabled Stencil #endregion #region Initialize Output Merger // Bind the render target view and depth stencil buffer to the output render pipeline. DeviceContext.OutputMerger.SetTargets(RenderTargetView); // Removed DepthStencilView, from method input arguments #endregion #region Initialize Raster State #endregion #region Initialize Rasterizer // Setup and create the viewport for rendering. DeviceContext.Rasterizer.SetViewport(0, 0, configuration.Width, configuration.Height, 0, 1); #endregion #region Initialize matrices // Setup and create the projection matrix. ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)configuration.Width / (float)configuration.Height), DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth); // Initialize the world matrix to the identity matrix. WorldMatrix = Matrix.Identity; #endregion #region Initialize Depth Disabled Stencil #endregion #region Initialize Blend States #endregion return(true); } catch (Exception) { return(false); } }
public void Run() { var form = new RenderForm("2d and 3d combined...it's like magic"); form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) { form.Close(); } }; // DirectX DXGI 1.1 factory var factory1 = new Factory1(); // The 1st graphics adapter var adapter1 = factory1.GetAdapter1(0); // --------------------------------------------------------------------------------------------- // Setup direct 3d version 11. It's context will be used to combine the two elements // --------------------------------------------------------------------------------------------- var description = new SwapChainDescription { BufferCount = 1, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, Flags = SwapChainFlags.AllowModeSwitch }; Device11 device11; SwapChain swapChain; Device11.CreateWithSwapChain(adapter1, DeviceCreationFlags.None, description, out device11, out swapChain); // create a view of our render target, which is the backbuffer of the swap chain we just created RenderTargetView renderTargetView; using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0)) renderTargetView = new RenderTargetView(device11, resource); // setting a viewport is required if you want to actually see anything var context = device11.ImmediateContext; var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height); context.OutputMerger.SetTargets(renderTargetView); context.Rasterizer.SetViewports(viewport); // // Create the DirectX11 texture2D. This texture will be shared with the DirectX10 device. // // The DirectX10 device will be used to render text onto this texture. // DirectX11 will then draw this texture (blended) onto the screen. // The KeyedMutex flag is required in order to share this resource between the two devices. var textureD3D11 = new Texture2D(device11, new Texture2DDescription { Width = form.ClientSize.Width, Height = form.ClientSize.Height, MipLevels = 1, ArraySize = 1, Format = Format.B8G8R8A8_UNorm, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.SharedKeyedmutex }); // --------------------------------------------------------------------------------------------- // Setup a direct 3d version 10.1 adapter // --------------------------------------------------------------------------------------------- var device10 = new Device10(adapter1, SharpDX.Direct3D10.DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0); // --------------------------------------------------------------------------------------------- // Setup Direct 2d // --------------------------------------------------------------------------------------------- // Direct2D Factory var factory2D = new SharpDX.Direct2D1.Factory(FactoryType.SingleThreaded, DebugLevel.Information); // Here we bind the texture we've created on our direct3d11 device through the direct3d10 // to the direct 2d render target.... var sharedResource = textureD3D11.QueryInterface <SharpDX.DXGI.Resource>(); var textureD3D10 = device10.OpenSharedResource <SharpDX.Direct3D10.Texture2D>(sharedResource.SharedHandle); var surface = textureD3D10.AsSurface(); var rtp = new RenderTargetProperties { MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_10, Type = RenderTargetType.Hardware, PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied) }; var renderTarget2D = new RenderTarget(factory2D, surface, rtp); var solidColorBrush = new SolidColorBrush(renderTarget2D, Colors.Red); // --------------------------------------------------------------------------------------------------- // Setup the rendering data // --------------------------------------------------------------------------------------------------- // Load Effect. This includes both the vertex and pixel shaders. // Also can include more than one technique. ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile( "effectDx11.fx", "fx_5_0", ShaderFlags.EnableStrictness); var effect = new Effect(device11, shaderByteCode); // create triangle vertex data, making sure to rewind the stream afterward var verticesTriangle = new DataStream(VertexPositionColor.SizeInBytes * 3, true, true); verticesTriangle.Write(new VertexPositionColor(new Vector3(0.0f, 0.5f, 0.5f), new Color4(1.0f, 0.0f, 0.0f, 1.0f))); verticesTriangle.Write(new VertexPositionColor(new Vector3(0.5f, -0.5f, 0.5f), new Color4(0.0f, 1.0f, 0.0f, 1.0f))); verticesTriangle.Write(new VertexPositionColor(new Vector3(-0.5f, -0.5f, 0.5f), new Color4(0.0f, 0.0f, 1.0f, 1.0f))); verticesTriangle.Position = 0; // create the triangle vertex layout and buffer var layoutColor = new InputLayout(device11, effect.GetTechniqueByName("Color").GetPassByIndex(0).Description.Signature, VertexPositionColor.inputElements); var vertexBufferColor = new Buffer(device11, verticesTriangle, (int)verticesTriangle.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); verticesTriangle.Close(); // create overlay vertex data, making sure to rewind the stream afterward // Top Left of screen is -1, +1 // Bottom Right of screen is +1, -1 var verticesText = new DataStream(VertexPositionTexture.SizeInBytes * 4, true, true); verticesText.Write(new VertexPositionTexture(new Vector3(-1, 1, 0), new Vector2(0, 0f))); verticesText.Write(new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 0))); verticesText.Write(new VertexPositionTexture(new Vector3(-1, -1, 0), new Vector2(0, 1))); verticesText.Write(new VertexPositionTexture(new Vector3(1, -1, 0), new Vector2(1, 1))); verticesText.Position = 0; // create the overlay vertex layout and buffer var layoutOverlay = new InputLayout(device11, effect.GetTechniqueByName("Overlay").GetPassByIndex(0).Description.Signature, VertexPositionTexture.inputElements); var vertexBufferOverlay = new Buffer(device11, verticesText, (int)verticesText.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); verticesText.Close(); // Think of the shared textureD3D10 as an overlay. // The overlay needs to show the 2d content but let the underlying triangle (or whatever) // show thru, which is accomplished by blending. var bsd = new BlendStateDescription(); bsd.RenderTarget[0].IsBlendEnabled = true; bsd.RenderTarget[0].SourceBlend = BlendOption.SourceColor; bsd.RenderTarget[0].DestinationBlend = BlendOption.BlendFactor; bsd.RenderTarget[0].BlendOperation = BlendOperation.Add; bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.One; bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; var blendStateTransparent = new BlendState(device11, bsd); // --------------------------------------------------------------------------------------------------- // Create and tesselate an ellipse // --------------------------------------------------------------------------------------------------- var center = new DrawingPointF(form.ClientSize.Width / 2.0f, form.ClientSize.Height / 2.0f); var ellipse = new EllipseGeometry(factory2D, new Ellipse(center, form.ClientSize.Width / 2.0f, form.ClientSize.Height / 2.0f)); // Populate a PathGeometry from Ellipse tessellation var tesselatedGeometry = new PathGeometry(factory2D); _geometrySink = tesselatedGeometry.Open(); // Force RoundLineJoin otherwise the tesselated looks buggy at line joins _geometrySink.SetSegmentFlags(PathSegment.ForceRoundLineJoin); // Tesselate the ellipse to our TessellationSink ellipse.Tessellate(1, this); _geometrySink.Close(); // --------------------------------------------------------------------------------------------------- // Acquire the mutexes. These are needed to assure the device in use has exclusive access to the surface // --------------------------------------------------------------------------------------------------- var device10Mutex = textureD3D10.QueryInterface <KeyedMutex>(); var device11Mutex = textureD3D11.QueryInterface <KeyedMutex>(); // --------------------------------------------------------------------------------------------------- // Main rendering loop // --------------------------------------------------------------------------------------------------- bool first = true; RenderLoop .Run(form, () => { if (first) { form.Activate(); first = false; } // clear the render target to black context.ClearRenderTargetView(renderTargetView, Colors.DarkSlateGray); // Draw the triangle context.InputAssembler.InputLayout = layoutColor; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferColor, VertexPositionColor.SizeInBytes, 0)); context.OutputMerger.BlendState = null; var currentTechnique = effect.GetTechniqueByName("Color"); for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass) { using (var effectPass = currentTechnique.GetPassByIndex(pass)) { System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass"); effectPass.Apply(context); } context.Draw(3, 0); } ; // Draw Ellipse on the shared Texture2D device10Mutex.Acquire(0, 100); renderTarget2D.BeginDraw(); renderTarget2D.Clear(Colors.Black); renderTarget2D.DrawGeometry(tesselatedGeometry, solidColorBrush); renderTarget2D.DrawEllipse(new Ellipse(center, 200, 200), solidColorBrush, 20, null); renderTarget2D.EndDraw(); device10Mutex.Release(0); // Draw the shared texture2D onto the screen, blending the 2d content in device11Mutex.Acquire(0, 100); var srv = new ShaderResourceView(device11, textureD3D11); effect.GetVariableByName("g_Overlay").AsShaderResource().SetResource(srv); context.InputAssembler.InputLayout = layoutOverlay; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferOverlay, VertexPositionTexture.SizeInBytes, 0)); context.OutputMerger.BlendState = blendStateTransparent; currentTechnique = effect.GetTechniqueByName("Overlay"); for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass) { using (var effectPass = currentTechnique.GetPassByIndex(pass)) { System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass"); effectPass.Apply(context); } context.Draw(4, 0); } srv.Dispose(); device11Mutex.Release(0); swapChain.Present(0, PresentFlags.None); }); // dispose everything vertexBufferColor.Dispose(); vertexBufferOverlay.Dispose(); layoutColor.Dispose(); layoutOverlay.Dispose(); effect.Dispose(); shaderByteCode.Dispose(); renderTarget2D.Dispose(); swapChain.Dispose(); device11.Dispose(); device10.Dispose(); textureD3D10.Dispose(); textureD3D11.Dispose(); factory1.Dispose(); adapter1.Dispose(); sharedResource.Dispose(); factory2D.Dispose(); surface.Dispose(); solidColorBrush.Dispose(); blendStateTransparent.Dispose(); device10Mutex.Dispose(); device11Mutex.Dispose(); }
public bool Initialize(DSystemConfiguration configuration, IntPtr windowHandle) { try { #region Environment Configuration var factory = new Factory1(); //Aquire GPU var adapter = factory.GetAdapter1(0); //Aquire monitor var monitor = adapter.GetOutput(0); //Get modes supporting RGB with interaced var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); var adapterDescription = adapter.Description; VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; VideoCardDescription = adapterDescription.Description.Trim('\0'); monitor.Dispose(); adapter.Dispose(); factory.Dispose(); #endregion #region Initialize swap chain and d3d device // Initialize the swap chain description. var swapChainDesc = new SwapChainDescription() { // Set to a single back buffer. BufferCount = 1, ModeDescription = new ModeDescription(configuration.Width, configuration.Height, new Rational(0, 1), Format.R8G8B8A8_UNorm) { Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrder.Unspecified }, // Set the usage of the back buffer. Usage = Usage.RenderTargetOutput, // Set the handle for the window to render to. OutputHandle = windowHandle, // Turn multisampling off. SampleDescription = new SampleDescription(1, 0), // Set to full screen or windowed mode. IsWindowed = !DSystemConfiguration.FullScreen, // Don't set the advanced flags. Flags = SwapChainFlags.None, // Discard the back buffer content after presenting. SwapEffect = SwapEffect.Discard }; // Create the swap chain, Direct3D device, and Direct3D device context. SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; #endregion #region Initialize buffers // Get the pointer to the back buffer. var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0); // Create the render target view with the back buffer pointer. RenderTargetView = new RenderTargetView(device, backBuffer); // Release pointer to the back buffer as we no longer need it. backBuffer.Dispose(); // Initialize and set up the description of the depth buffer. var depthBufferDesc = new Texture2DDescription() { Width = configuration.Width, Height = configuration.Height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; // Create the texture for the depth buffer using the filled out description. DepthStencilBuffer = new Texture2D(device, depthBufferDesc); #endregion #region Initialize Depth Enabled Stencil // Initialize and set up the description of the stencil state. var depthStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, // Stencil operation if pixel front-facing. FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, // Stencil operation if pixel is back-facing. BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; // Create the depth stencil state. DepthStencilState = new DepthStencilState(Device, depthStencilDesc); #endregion #region Initialize Output Merger // Set the depth stencil state. DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1); // Initialize and set up the depth stencil view. var depthStencilViewDesc = new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; // Create the depth stencil view. DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc); // Bind the render target view and depth stencil buffer to the output render pipeline. DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView); #endregion #region Initialize Raster State // Setup the raster description which will determine how and what polygon will be drawn. var rasterDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; RasterState = new RasterizerState(Device, rasterDesc); #endregion #region Initialize Rasterizer DeviceContext.Rasterizer.State = RasterState; ViewPort = new ViewportF(0.0f, 0.0f, (float)configuration.Width, (float)configuration.Height, 0.0f, 1.0f); DeviceContext.Rasterizer.SetViewport(ViewPort); #endregion #region Initialize matrices ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)configuration.Width / (float)configuration.Height), DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth); WorldMatrix = Matrix.Identity; #endregion #region Initialize Depth Disabled Stencil var depthDisabledStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; DepthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc); #endregion #region Initialize Blend States var blendStateDesc = new BlendStateDescription(); blendStateDesc.RenderTarget[0].IsBlendEnabled = true; blendStateDesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; blendStateDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; blendStateDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; blendStateDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; AlphaEnableBlendingState = new BlendState(device, blendStateDesc); blendStateDesc.RenderTarget[0].IsBlendEnabled = false; AlphaDisableBlendingState = new BlendState(device, blendStateDesc); #endregion return(true); } catch { throw new DDeviceNotInitialized(); } }
public bool Initialize(DSystemConfiguration configuration, IntPtr windowHandle) { try { #region Environment Configuration // Store the vsync setting. VerticalSyncEnabled = DSystemConfiguration.VerticalSyncEnabled; // Create a DirectX graphics interface factory. var factory = new Factory1(); // Use the factory to create an adapter for the primary graphics interface (video card). var adapter = factory.GetAdapter1(0); // Get the primary adapter output (monitor). var monitor = adapter.GetOutput(0); // Get modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor). var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); // Now go through all the display modes and find the one that matches the screen width and height. // When a match is found store the the refresh rate for that monitor, if vertical sync is enabled. // Otherwise we use maximum refresh rate. var rational = new Rational(0, 1); if (VerticalSyncEnabled) { foreach (var mode in modes) { if (mode.Width == configuration.Width && mode.Height == configuration.Height) { rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator); break; } } } // Get the adapter (video card) description. var adapterDescription = adapter.Description; // Store the dedicated video card memory in megabytes. VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; // Convert the name of the video card to a character array and store it. VideoCardDescription = adapterDescription.Description.Trim('\0'); // Release the adapter output. monitor.Dispose(); // Release the adapter. adapter.Dispose(); // Release the factory. factory.Dispose(); #endregion #region Initialize swap chain and d3d device // Initialize the swap chain description. var swapChainDesc = new SwapChainDescription() { // Set to a single back buffer. BufferCount = 1, // Set the width and height of the back buffer. ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm) { Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrder.Unspecified }, // Set the usage of the back buffer. Usage = Usage.RenderTargetOutput, // Set the handle for the window to render to. OutputHandle = windowHandle, // Turn multisampling off. SampleDescription = new SampleDescription(1, 0), // Set to full screen or windowed mode. IsWindowed = !DSystemConfiguration.FullScreen, // Don't set the advanced flags. Flags = SwapChainFlags.None, // Discard the back buffer content after presenting. SwapEffect = SwapEffect.Discard }; // Create the swap chain, Direct3D device, and Direct3D device context. SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; #endregion #region Initialize buffers // Get the pointer to the back buffer. var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0); // Create the render target view with the back buffer pointer. RenderTargetView = new RenderTargetView(device, backBuffer); // Release pointer to the back buffer as we no longer need it. backBuffer.Dispose(); // Initialize and set up the description of the depth buffer. var depthBufferDesc = new Texture2DDescription() { Width = configuration.Width, Height = configuration.Height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; // Create the texture for the depth buffer using the filled out description. DepthStencilBuffer = new Texture2D(device, depthBufferDesc); #endregion #region Initialize Depth Enabled Stencil // Initialize and set up the description of the stencil state. var depthStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, // Stencil operation if pixel front-facing. FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, // Stencil operation if pixel is back-facing. BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; // Create the depth stencil state. DepthStencilState = new DepthStencilState(Device, depthStencilDesc); #endregion #region Initialize Output Merger // Set the depth stencil state. DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1); // Initialize and set up the depth stencil view. var depthStencilViewDesc = new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; // Create the depth stencil view. DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc); // Bind the render target view and depth stencil buffer to the output render pipeline. DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView); #endregion #region Initialize Raster State // Setup the raster description which will determine how and what polygon will be drawn. var rasterDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, #region Tut 24 EX 2: for Clip Planning wqith raised camera nd culling off. // CullMode = CullMode.None, #endregion CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; // Create the rasterizer state from the description we just filled out. RasterState = new RasterizerState(Device, rasterDesc); #endregion #region Initialize Rasterizer // Now set the rasterizer state. DeviceContext.Rasterizer.State = RasterState; ViewPort = new ViewportF(0.0f, 0.0f, (float)configuration.Width, (float)configuration.Height, 0.0f, 1.0f); // Setup and create the viewport for rendering. DeviceContext.Rasterizer.SetViewport(ViewPort); #endregion #region Initialize matrices // Initialize the world matrix to the identity matrix. WorldMatrix = Matrix.Identity; // Create an orthographic projection matrix for 2D rendering. OrthoMatrix = Matrix.OrthoLH(configuration.Width, configuration.Height, DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth); #endregion #region Initialize Depth Disabled Stencil // Now create a second depth stencil state which turns off the Z buffer for 2D rendering. Added in Tutorial 11 // The difference is that DepthEnable is set to false. // All other parameters are the same as the other depth stencil state. var depthDisabledStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, // Stencil operation if pixel front-facing. FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, // Stencil operation if pixel is back-facing. BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; // Create the depth stencil state. DepthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc); #endregion #region Initialize Blend States #endregion return(true); } catch (Exception) { return(false); } }
public bool Initialize(DSystemConfiguration configuration, IntPtr windowHandle) { try { VerticalSyncEnabled = DSystemConfiguration.VerticalSyncEnabled; var factory = new Factory1(); var adapter = factory.GetAdapter1(0); var monitor = adapter.GetOutput(0); var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); var rational = new Rational(0, 1); if (VerticalSyncEnabled) { foreach (var mode in modes) { if (mode.Width == configuration.Width && mode.Height == configuration.Height) { rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator); break; } } } var adapterDescription = adapter.Description; VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; VideoCardDescription = adapterDescription.Description; monitor.Dispose(); adapter.Dispose(); factory.Dispose(); var swapChainDesc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, OutputHandle = windowHandle, SampleDescription = new SampleDescription(1, 0), IsWindowed = !DSystemConfiguration.FullScreen, Flags = SwapChainFlags.None, SwapEffect = SwapEffect.Discard }; SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0); RenderTargetView = new RenderTargetView(device, backBuffer); backBuffer.Dispose(); Texture2DDescription depthBufferDesc = new Texture2DDescription() { Width = configuration.Width, Height = configuration.Height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; DepthStencilBuffer = new Texture2D(device, depthBufferDesc); DepthStencilStateDescription depthStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; DepthStencilState = new DepthStencilState(Device, depthStencilDesc); DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1); DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc); DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView); RasterizerStateDescription rasterDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; RasterState = new RasterizerState(Device, rasterDesc); DeviceContext.Rasterizer.State = RasterState; DeviceContext.Rasterizer.SetViewport(0, 0, configuration.Width, configuration.Height, 0, 1); ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)configuration.Width / (float)configuration.Height), DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth); WorldMatrix = Matrix.Identity; return(true); } catch { return(false); } }
public bool Init(IntPtr WindowHandle) { var factory = new Factory1(); var adapter = factory.GetAdapter1(0); var monitor = adapter.GetOutput(0); var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); var rational = new Rational(0, 1); if (ToolkitSettings.VSync) { foreach (var mode in modes) { if (mode.Width == ToolkitSettings.Width && mode.Height == ToolkitSettings.Height) { rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator); break; } } } var adapterDescription = adapter.Description; VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; VideoCardDescription = adapterDescription.Description.Trim('\0'); monitor.Dispose(); adapter.Dispose(); factory.Dispose(); var swapChainDesc = new SwapChainDescription() { BufferCount = 2, ModeDescription = new ModeDescription(ToolkitSettings.Width, ToolkitSettings.Height, rational, Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, OutputHandle = WindowHandle, SampleDescription = new SampleDescription(1, 0), IsWindowed = true, Flags = SwapChainFlags.None, SwapEffect = SwapEffect.Discard }; SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0); m_RenderTargetView = new RenderTargetView(device, backBuffer); backBuffer.Dispose(); var depthBufferDesc = new Texture2DDescription() { Width = ToolkitSettings.Width, Height = ToolkitSettings.Height, MipLevels = 0, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; m_depthStencilBuffer = new Texture2D(device, depthBufferDesc); var depthStencilDecs = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always, }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; DepthStencilState = new DepthStencilState(Device, depthStencilDecs); DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1); var depthStencilViewDesc = new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; BlendStateDescription bsd = new BlendStateDescription() { AlphaToCoverageEnable = false,//true, IndependentBlendEnable = false, }; bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; bsd.RenderTarget[0].BlendOperation = BlendOperation.Add; bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.One; bsd.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; bsd.RenderTarget[0].IsBlendEnabled = true; bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.Zero; bsd.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; //bsDefault = new BlendState(device, bsd); bsd.AlphaToCoverageEnable = true; BlendState bsAlpha = new BlendState(device, bsd); DeviceContext.OutputMerger.BlendState = bsAlpha; m_DepthStencilView = new DepthStencilView(Device, m_depthStencilBuffer, depthStencilViewDesc); DeviceContext.OutputMerger.SetTargets(m_DepthStencilView, m_RenderTargetView); m_RSDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = true, CullMode = CullMode.Back, DepthBias = 10, DepthBiasClamp = .0f, IsDepthClipEnabled = false, FillMode = FillMode.Solid, IsFrontCounterClockwise = true, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; m_RSCullSolid = new RasterizerState(Device, m_RSDesc); m_RSDesc.CullMode = CullMode.None; m_RSSolid = new RasterizerState(Device, m_RSDesc); m_RSDesc.FillMode = FillMode.Wireframe; m_RSWireFrame = new RasterizerState(Device, m_RSDesc); m_RSDesc.CullMode = CullMode.Back; m_RSCullWireFrame = new RasterizerState(Device, m_RSDesc); UpdateRasterizer(); return(true); }
/// <summary> /// Duplicates the output of the specified monitor on the specified graphics adapter. /// </summary> /// <param name="whichGraphicsCardAdapter">The adapter which contains the desired outputs.</param> /// <param name="whichOutputDevice">The output device to duplicate (i.e. monitor). Begins with zero, which seems to correspond to the primary monitor.</param> public DesktopDuplicator(int whichGraphicsCardAdapter, int whichOutputDevice) { //SharpDX.Configuration.EnableObjectTracking = true; this.mWhichOutputDevice = whichOutputDevice; Adapter1 adapter = null; try { adapter = new Factory1().GetAdapter1(whichGraphicsCardAdapter); } catch (SharpDXException) { throw new DesktopDuplicationException("Could not find the specified graphics card adapter."); } this.mDevice = new Device(adapter); Output output = null; try { output = adapter.GetOutput(whichOutputDevice); } catch (SharpDXException) { throw new DesktopDuplicationException("Could not find the specified output device."); } var output1 = output.QueryInterface <Output1>(); this.mOutputDesc = output.Description; this.mTextureDesc = new Texture2DDescription() { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = this.mOutputDesc.DesktopBounds.GetWidth(), Height = this.mOutputDesc.DesktopBounds.GetHeight(), OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; try { this.mDeskDupl = output1.DuplicateOutput(mDevice); } catch (SharpDXException ex) { if (ex.ResultCode.Code == SharpDX.DXGI.ResultCode.NotCurrentlyAvailable.Result.Code) { output.Dispose(); output1.Dispose(); adapter.Dispose(); throw new DesktopDuplicationException("There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again."); } } output.Dispose(); output1.Dispose(); adapter.Dispose(); }
public void Start() { const int numAdapter = 0; // Change the output number to select a different desktop const int numOutput = 0; var factory = new Factory1(); var adapter = factory.GetAdapter1(numAdapter); var device = new SharpDX.Direct3D11.Device(adapter); var output = adapter.GetOutput(numOutput); var output1 = output.QueryInterface <Output1>(); width = output.Description.DesktopBounds.Right; height = output.Description.DesktopBounds.Bottom; var textureDesc = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = width, Height = height, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; var screenTexture = new Texture2D(device, textureDesc); var duplicatedOutput = output1.DuplicateOutput(device); timer = new Timer((Object stateInfo) => { try { SharpDX.DXGI.Resource screenResource; OutputDuplicateFrameInformation duplicateFrameInformation; duplicatedOutput.AcquireNextFrame(1000 / FPS, out duplicateFrameInformation, out screenResource); using (var screenTexture2D = screenResource.QueryInterface <Texture2D>()) device.ImmediateContext.CopyResource(screenTexture2D, screenTexture); screenResource.Dispose(); duplicatedOutput.ReleaseFrame(); var mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None); IntPtr[] planes = { mapSource.DataPointer }; int[] strides = { mapSource.RowPitch }; using (var frame = VideoFrame.CreateYuv420pFrameFromBuffer(PixelFormat.FormatArgb32, width, height, planes, strides)) { frameConsumer.Consume(frame); } device.ImmediateContext.UnmapSubresource(screenTexture, 0); } catch (SharpDXException) { } }, null, 0, 1000 / FPS); output1.Dispose(); output.Dispose(); adapter.Dispose(); factory.Dispose(); }
public bool Initialize(int screenWidth, int screenHeight, bool vsync, IntPtr hwnd, bool fullscreen, float screenDepth, float screenNear) { try { var factory = new Factory1(); var adapter = factory.GetAdapter1(0); var adapterOutput = adapter.GetOutput(0); var displayModeList = adapterOutput.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); _vsync_enabled = vsync; var rational = new Rational(0, 1); if (_vsync_enabled) { foreach (var mode in displayModeList) { if (mode.Width == screenWidth && mode.Height == screenHeight) { rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator); break; } } } VideoCardMemory = adapter.Description.DedicatedVideoMemory >> 10 >> 10; VideoCardDescription = adapter.Description.Description.Trim('\0'); SharpDX.Direct3D11.Device.CreateWithSwapChain( DriverType.Hardware, DeviceCreationFlags.None, new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(screenWidth, screenHeight, rational, Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, OutputHandle = hwnd, SampleDescription = new SampleDescription(1, 0), IsWindowed = fullscreen, Flags = SwapChainFlags.None, SwapEffect = SwapEffect.Discard }, out var device, out _swapChain); Device = device; DeviceContext = Device.ImmediateContext; BackBuffer = Texture2D.FromSwapChain <Texture2D>(_swapChain, 0); _renderTargetView = new RenderTargetView(Device, BackBuffer); DepthStencilBuffer = new Texture2D(Device, new Texture2DDescription() { Width = screenWidth, Height = screenHeight, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); _depthStencilState = new DepthStencilState(Device, new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }); DeviceContext.OutputMerger.SetDepthStencilState(_depthStencilState, 1); DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }); DeviceContext.OutputMerger.SetTargets(DepthStencilView, _renderTargetView); _rasterState = new RasterizerState(Device, new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }); DeviceContext.Rasterizer.State = _rasterState; DeviceContext.Rasterizer.SetViewport(0, 0, screenWidth, screenHeight, 0, 1); ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)screenWidth / (float)screenHeight), screenNear, screenDepth); WorldMatrix = Matrix.Identity; OrthoMatrix = Matrix.OrthoLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth); _depthDisabledStencilState = new DepthStencilState(Device, new DepthStencilStateDescription() { IsDepthEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }); var blendStateDesc = new BlendStateDescription(); blendStateDesc.RenderTarget[0].IsBlendEnabled = true; blendStateDesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; blendStateDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; blendStateDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; blendStateDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _alphaEnableBlendingState = new BlendState(Device, blendStateDesc); blendStateDesc.RenderTarget[0].IsBlendEnabled = false; _alphaDisableBlendingState = new BlendState(Device, blendStateDesc); factory.Dispose(); return(true); } catch { return(false); } }
public static Bitmap CaptureScreen() { // # of graphics card adapter const int numAdapter = 0; // # of output device (i.e. monitor) const int numOutput = 1; // Create DXGI Factory1 var factory = new Factory1(); var adapter = factory.GetAdapter1(numAdapter); // Create device from Adapter var device = new Device(adapter); // Get DXGI.Output var output = adapter.GetOutput(numOutput); var output1 = output.QueryInterface <Output1>(); // Width/Height of desktop to capture int width = ((Rectangle)output.Description.DesktopBounds).Width; //width = 1024; int height = ((Rectangle)output.Description.DesktopBounds).Height; //height = 1024; // Create Staging texture CPU-accessible var textureDesc = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = width, Height = height, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; var screenTexture = new Texture2D(device, textureDesc); // Duplicate the output var duplicatedOutput = output1.DuplicateOutput(device); bool captureDone = false; Bitmap bitmap = null; for (int i = 0; !captureDone; i++) { try { SharpDX.DXGI.Resource screenResource; OutputDuplicateFrameInformation duplicateFrameInformation; // Try to get duplicated frame within given time duplicatedOutput.AcquireNextFrame(10000, out duplicateFrameInformation, out screenResource); if (i > 0) { // copy resource into memory that can be accessed by the CPU using (var screenTexture2D = screenResource.QueryInterface <Texture2D>()) device.ImmediateContext.CopyResource(screenTexture2D, screenTexture); // Get the desktop capture texture var mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, MapFlags.None); // Create Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height, PixelFormat.Format32bppArgb); var boundsRect = new System.Drawing.Rectangle(0, 0, width, height); // Copy pixels from screen capture Texture to GDI bitmap var mapDest = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat); var sourcePtr = mapSource.DataPointer; var destPtr = mapDest.Scan0; for (int y = 0; y < height; y++) { // Copy a single line Utilities.CopyMemory(destPtr, sourcePtr, width * 4); // Advance pointers sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch); destPtr = IntPtr.Add(destPtr, mapDest.Stride); } // Release source and dest locks bitmap.UnlockBits(mapDest); device.ImmediateContext.UnmapSubresource(screenTexture, 0); // Capture done captureDone = true; } screenResource.Dispose(); duplicatedOutput.ReleaseFrame(); } catch (SharpDXException e) { if (e.ResultCode.Code != SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code) { throw e; } } } duplicatedOutput.Dispose(); screenTexture.Dispose(); output1.Dispose(); output.Dispose(); device.Dispose(); adapter.Dispose(); factory.Dispose(); return(bitmap); }
public bool Initialize(DSystemConfiguration configuration, IntPtr windowHandle) { try { #region Environment Configuration // Store the vsync setting. VerticalSyncEnabled = DSystemConfiguration.VerticalSyncEnabled; // Create a DirectX graphics interface factory. var factory = new Factory1(); // Use the factory to create an adapter for the primary graphics interface (video card). var adapter = factory.GetAdapter1(0); // Get the primary adapter output (monitor). var monitor = adapter.GetOutput(0); // Get modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor). var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); // Now go through all the display modes and find the one that matches the screen width and height. // When a match is found store the the refresh rate for that monitor, if vertical sync is enabled. // Otherwise we use maximum refresh rate. var rational = new Rational(0, 1); if (VerticalSyncEnabled) { foreach (var mode in modes) { if (mode.Width == configuration.Width && mode.Height == configuration.Height) { rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator); break; } } } // Get the adapter (video card) description. var adapterDescription = adapter.Description; // Store the dedicated video card memory in megabytes. VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; // Convert the name of the video card to a character array and store it. VideoCardDescription = adapterDescription.Description.Trim('\0'); // Release the adapter output. monitor.Dispose(); // Release the adapter. adapter.Dispose(); // Release the factory. factory.Dispose(); #endregion #region Initialize swap chain and d3d device // Initialize the swap chain description. var swapChainDesc = new SwapChainDescription() { // Set to a single back buffer. BufferCount = 1, // Set the width and height of the back buffer. ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm), // Set the usage of the back buffer. Usage = Usage.RenderTargetOutput, // Set the handle for the window to render to. OutputHandle = windowHandle, // Turn multisampling off. SampleDescription = new SampleDescription(1, 0), // Set to full screen or windowed mode. IsWindowed = !DSystemConfiguration.FullScreen, // Don't set the advanced flags. Flags = SwapChainFlags.None, // Discard the back buffer content after presenting. SwapEffect = SwapEffect.Discard }; // Create the swap chain, Direct3D device, and Direct3D device context. SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; #endregion #region Initialize buffers // Get the pointer to the back buffer. var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0); // Create the render target view with the back buffer pointer. RenderTargetView = new RenderTargetView(device, backBuffer); // Release pointer to the back buffer as we no longer need it. backBuffer.Dispose(); // Initialize and set up the description of the depth buffer. var depthBufferDesc = new Texture2DDescription() { Width = configuration.Width, Height = configuration.Height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; // Create the texture for the depth buffer using the filled out description. DepthStencilBuffer = new Texture2D(device, depthBufferDesc); #endregion #region Initialize Depth Enabled Stencil #endregion #region Initialize Output Merger // Initialize and set up the depth stencil view. var depthStencilViewDesc = new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; // Create the depth stencil view. DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc); // Bind the render target view and depth stencil buffer to the output render pipeline. DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView); #endregion #region Initialize Raster State // Setup the raster description which will determine how and what polygon will be drawn. var rasterDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; // Create the rasterizer state from the description we just filled out. RasterState = new RasterizerState(Device, rasterDesc); #endregion #region Initialize Rasterizer // Now set the rasterizer state. DeviceContext.Rasterizer.State = RasterState; // Setup and create the viewport for rendering. DeviceContext.Rasterizer.SetViewport(0, 0, configuration.Width, configuration.Height, 0, 1); #endregion #region Initialize matrices // Setup and create the projection matrix. ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)configuration.Width / (float)configuration.Height), DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth); // Initialize the world matrix to the identity matrix. WorldMatrix = Matrix.Identity; #endregion #region Initialize Depth Disabled Stencil #endregion #region Initialize Blend States // Create an alpha enabled blend state description. var blendStateDesc = new BlendStateDescription(); blendStateDesc.RenderTarget[0].IsBlendEnabled = true; blendStateDesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; blendStateDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; blendStateDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; blendStateDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; // Create the blend state using the description. AlphaEnableBlendingState = new BlendState(device, blendStateDesc); // Modify the description to create an disabled blend state description. blendStateDesc.RenderTarget[0].IsBlendEnabled = false; // Create the blend state using the description. AlphaDisableBlendingState = new BlendState(device, blendStateDesc); #endregion return(true); } catch (Exception) { return(false); } }
public bool Initialize(int screenWidth, int screenHeight, bool vSync, IntPtr hwnd, bool fullScreen, float screenDepth, float screenNear) { try { vSyncEnabled = vSync; Rational refreshRate = new Rational(0, 0); var factory = new Factory1(); var adapter = factory.Adapters[0]; var adapterOutput = adapter.Outputs[0]; var modes = adapterOutput.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); for (int i = 0; i < modes.Length; i++) { if (modes[i].Width == screenWidth) { if (modes[i].Height == screenHeight) { refreshRate = modes[i].RefreshRate; } } } VideoCardMemory = adapter.Description.DedicatedVideoMemory / 1024 / 1024; VideoCardDescription = adapter.Description.Description; adapterOutput.Dispose(); adapter.Dispose(); factory.Dispose(); var swapChainDescription = new SwapChainDescription { BufferCount = 1, ModeDescription = { Width = screenWidth, Height = screenHeight, Format = Format.R8G8B8A8_UNorm, RefreshRate = vSyncEnabled ? refreshRate : new Rational(0, 0), ScanlineOrdering = DisplayModeScanlineOrder.Unspecified, Scaling = DisplayModeScaling.Unspecified }, Usage = Usage.RenderTargetOutput, OutputHandle = hwnd, SampleDescription = { Count = 1, Quality = 0 }, IsWindowed = !fullScreen, SwapEffect = SwapEffect.Discard, Flags = SwapChainFlags.None }; var featureLevel = FeatureLevel.Level_11_0; Device device; Device.CreateWithSwapChain( DriverType.Hardware, DeviceCreationFlags.Debug, new[] { featureLevel }, swapChainDescription, out device, out swapChain ); Device = device; DeviceContext = device.ImmediateContext; using (var backBuffer = swapChain.GetBackBuffer <Texture2D>(0)) { renderTargetView = new RenderTargetView(device, backBuffer); } var depthBufferDescription = new Texture2DDescription { Width = screenWidth, Height = screenHeight, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; depthStencilBuffer = new Texture2D(device, depthBufferDescription); var depthStencilStateDescription = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; depthStencilState = new DepthStencilState(device, depthStencilStateDescription); var depthStencilViewDescription = new DepthStencilViewDescription { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = { MipSlice = 0 } }; depthStencilView = new DepthStencilView(device, depthStencilBuffer, depthStencilViewDescription); DeviceContext.OutputMerger.SetRenderTargets(depthStencilView, renderTargetView); var rasterizerStateDescription = new RasterizerStateDescription { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }; rasterizerState = new RasterizerState(device, rasterizerStateDescription); DeviceContext.Rasterizer.State = rasterizerState; var viewport = new Viewport { Width = screenWidth, Height = screenHeight, MinDepth = 0.0f, MaxDepth = 1.0f, X = 0, Y = 0 }; DeviceContext.Rasterizer.SetViewport(viewport); var fieldOfView = MathUtil.Pi / 4.0f; var screenAspect = (float)screenWidth / screenHeight; Projection = Matrix.PerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth); World = Matrix.Identity; Orthogonal = Matrix.OrthoLH(screenWidth, screenHeight, screenNear, screenDepth); } catch { return(false); } return(true); }
public void Dispose() { try { //Clean Up event Delegates if (ScreenSize_Updated != null) { //Remove all Events associated to this control (That haven't been unsubscribed !) foreach (Delegate d in ScreenSize_Updated.GetInvocationList()) { ScreenSize_Updated -= (ScreenSizeUpdated)d; } } //Dispo State repo RenderStatesRepo.Dispose(); if (_renderForm != null) { _renderForm.ResizeBegin -= _renderForm_ResizeBegin; _renderForm.ResizeEnd -= _renderForm_ResizeEnd; _renderForm.Resize -= _renderForm_Resize; _renderForm.LostFocus -= GameWindow_LostFocus; _renderForm.GotFocus -= GameWindow_GotFocus; } //Dispose the created states if (BackBufferTex != null) { BackBufferTex.Dispose(); } if (_dx11factory != null) { _dx11factory.Dispose(); } if (_depthStencil != null) { _depthStencil.Dispose(); } if (_renderTarget != null) { _renderTarget.Dispose(); } if (_swapChain != null) { _swapChain.Dispose(); } foreach (var dc in _registeredDC) { dc.Dispose(); } //The ImmediatContext is automaticaly disposed by the Device Device.Dispose(); } catch (Exception e) { logger.Error("Error logged at Engine disposal time {0}", e.Message); } }
public bool Init(IntPtr WindowHandle) { var factory = new Factory1(); var adapter = factory.GetAdapter1(0); var monitor = adapter.GetOutput(0); var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); var rational = new Rational(0, 1); var adapterDescription = adapter.Description; //VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; //VideoCardDescription = adapterDescription.Description.Trim('\0'); monitor.Dispose(); adapter.Dispose(); factory.Dispose(); var swapChainDesc = new SwapChainDescription() { BufferCount = 2, ModeDescription = new ModeDescription(1920, 1080, rational, Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, OutputHandle = WindowHandle, SampleDescription = new SampleDescription(1, 0), IsWindowed = true, Flags = SwapChainFlags.None, SwapEffect = SwapEffect.Discard }; SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0); m_RenderTargetView = new RenderTargetView(device, backBuffer); backBuffer.Dispose(); BlendStateDescription bsd = new BlendStateDescription() { AlphaToCoverageEnable = false,//true, IndependentBlendEnable = false, }; bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; bsd.RenderTarget[0].BlendOperation = BlendOperation.Add; bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.One; bsd.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; bsd.RenderTarget[0].IsBlendEnabled = true; bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.Zero; bsd.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; //bsDefault = new BlendState(device, bsd); bsd.AlphaToCoverageEnable = true; BlendState bsAlpha = new BlendState(device, bsd); DeviceContext.OutputMerger.BlendState = bsAlpha; BuildDepthStencilView(1920, 1080); m_RSDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = false, FillMode = FillMode.Solid, IsFrontCounterClockwise = true, IsMultisampleEnabled = true, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; m_RSCullSolid = new RasterizerState(Device, m_RSDesc); m_RSDesc.CullMode = CullMode.None; m_RSSolid = new RasterizerState(Device, m_RSDesc); m_RSDesc.FillMode = FillMode.Wireframe; m_RSWireFrame = new RasterizerState(Device, m_RSDesc); m_RSDesc.CullMode = CullMode.Back; m_RSCullWireFrame = new RasterizerState(Device, m_RSDesc); UpdateRasterizer(); return(true); }
/// <summary> /// WPF用初期化 /// </summary> /// <param name="width"></param> /// <param name="height"></param> static public void InitializeForWPF(int width, int height) { #if false Factory1 factory = new Factory1(); Adapter adapter = GetAdapter(factory); //D3dDevice = new DxDevice(DriverType.Hardware, DeviceCreationFlags.None, FeatureLevel.Level_11_0); D3dDevice = new DxDevice(adapter, DeviceCreationFlags.None, FeatureLevel.Level_11_0); D3dDeviceContext = D3dDevice.ImmediateContext; factory.Dispose(); #else #if DEBUG DeviceCreationFlags flags = DeviceCreationFlags.Debug; #else DeviceCreationFlags flags = DeviceCreationFlags.None; #endif D3D11Device = new DxDevice(DriverType.Hardware, flags, FeatureLevel.Level_11_0); D3D11ImmediateContext = D3D11Device.ImmediateContext; #endif ImmediateContext = new GraphicsContext(D3D11ImmediateContext); // カラーバッファ defaultColorBuffer_ = new Texture(new Texture.InitDesc { width = width, height = height, //format = Format.R8G8B8A8_UNorm, format = Format.B8G8R8A8_UNorm, bindFlag = TextureBuffer.BindFlag.IsRenderTarget, optionFlags = ResourceOptionFlags.Shared, }); defaultRenderTarget_ = defaultColorBuffer_.RenderTargetView; // デプスバッファ defaultDepthStencil_ = new Texture(new Texture.InitDesc { width = width, height = height, //format = Format.R24G8_Typeless, format = Format.R32_Typeless, bindFlag = TextureBuffer.BindFlag.IsDepthStencil, }); var viewport = new Viewport(0.0f, 0.0f, width, height); TargetWidth = width; TargetHeight = height; D3D11ImmediateContext.OutputMerger.SetTargets(defaultDepthStencil_.DepthStencilView, defaultRenderTarget_); D3D11ImmediateContext.Rasterizer.SetViewports(viewport); // トポロジーをトライアングルリスト固定でセットしておく D3D11ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; // カメラの初期化 Camera3D = new Camera(); float aspect = (float)width / height; Camera3D.InitializePerspective(new Vector3(10, 0, 0), new Vector3(0, 0, 0), new Vector3(0, 1, 0), Math.DegToRad(45.0f), 0.1f, 1000.0f, aspect); CurrentDrawCamera = Camera3D; // レンダーステート InitializeRasterizerState(); InitializeBlendState(); InitializeDepthStencilState(); InitializeSamplerState(); InitializeQuery(); }