public D3D11RenderingPane( Factory dxgiFactory, SlimDX.Direct3D11.Device d3D11Device, DeviceContext d3D11DeviceContext, D3D11HwndDescription d3D11HwndDescription ) { mDxgiFactory = dxgiFactory; mD3D11Device = d3D11Device; mD3D11DeviceContext = d3D11DeviceContext; var swapChainDescription = new SwapChainDescription { BufferCount = 1, ModeDescription = new ModeDescription( d3D11HwndDescription.Width, d3D11HwndDescription.Height, new Rational( 60, 1 ), Format.R8G8B8A8_UNorm ), IsWindowed = true, OutputHandle = d3D11HwndDescription.Handle, SampleDescription = new SampleDescription( 1, 0 ), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; mSwapChain = new SwapChain( mDxgiFactory, mD3D11Device, swapChainDescription ); mDxgiFactory.SetWindowAssociation( d3D11HwndDescription.Handle, WindowAssociationFlags.IgnoreAll ); CreateD3D11Resources( d3D11HwndDescription.Width, d3D11HwndDescription.Height ); PauseRendering = false; }
public static void CreateDeviceSwapChainAndRenderTarget(Form form, out Device device, out SwapChain swapChain, out RenderTargetView renderTarget) { try { // the debug mode requires the sdk to be installed otherwise an exception is thrown device = new Device(DeviceCreationFlags.Debug); } catch (Direct3D10Exception) { device = new Device(DeviceCreationFlags.None); } var swapChainDescription = new SwapChainDescription(); var modeDescription = new ModeDescription(); var sampleDescription = new SampleDescription(); modeDescription.Format = Format.R8G8B8A8_UNorm; modeDescription.RefreshRate = new Rational(60, 1); modeDescription.Scaling = DisplayModeScaling.Unspecified; modeDescription.ScanlineOrdering = DisplayModeScanlineOrdering.Unspecified; modeDescription.Width = WIDTH; modeDescription.Height = HEIGHT; sampleDescription.Count = 1; sampleDescription.Quality = 0; swapChainDescription.ModeDescription = modeDescription; swapChainDescription.SampleDescription = sampleDescription; swapChainDescription.BufferCount = 1; swapChainDescription.Flags = SwapChainFlags.None; swapChainDescription.IsWindowed = true; swapChainDescription.OutputHandle = form.Handle; swapChainDescription.SwapEffect = SwapEffect.Discard; swapChainDescription.Usage = Usage.RenderTargetOutput; using (var factory = new Factory()) { swapChain = new SwapChain(factory, device, swapChainDescription); } using (var resource = swapChain.GetBuffer<Texture2D>(0)) { renderTarget = new RenderTargetView(device, resource); } var viewport = new Viewport { X = 0, Y = 0, Width = WIDTH, Height = HEIGHT, MinZ = 0.0f, MaxZ = 1.0f }; device.Rasterizer.SetViewports(viewport); device.OutputMerger.SetTargets(renderTarget); }
//------------------------------------------------------------------- // Constructor //------------------------------------------------------------------- public DrawDevice() { m_hwnd = IntPtr.Zero; m_pDevice = null; m_pSwapChain = null; m_d3dpp = null; m_Data = IntPtr.Zero; m_format = Format.X8R8G8B8; m_width = 0; m_height = 0; m_lDefaultStride = 0; m_PixelAR.Denominator = m_PixelAR.Numerator = 1; m_rcDest = Rectangle.Empty; VideoFormatDefs = new VideoFormatGUID[] { new VideoFormatGUID(MFMediaType.RGB32, TransformImage_RGB32, ARGB32_To_RGB32), new VideoFormatGUID(MFMediaType.RGB24, TransformImage_RGB24, ARGB32_To_RGB24), new VideoFormatGUID(MFMediaType.YUY2, TransformImage_YUY2, ARGB32_To_YUY2), new VideoFormatGUID(MFMediaType.NV12, TransformImage_NV12, ARGB32_To_NV12) }; m_convertFn = null; m_bmpconvertFn = null; }
/// <summary> /// Initializes a new instance of the <see cref="DeviceContext10"/> class. /// </summary> /// <param name="handle">The window handle to associate with the device.</param> /// <param name="settings">The settings used to configure the device.</param> internal DeviceContext10(IntPtr handle, DeviceSettings10 settings) { if (handle == IntPtr.Zero) throw new ArgumentException("Value must be a valid window handle.", "handle"); if (settings == null) throw new ArgumentNullException("settings"); this.settings = settings; factory = new Factory(); device = new Direct3D10.Device(factory.GetAdapter(settings.AdapterOrdinal), Direct3D10.DriverType.Hardware, settings.CreationFlags); swapChain = new SwapChain(factory, device, new SwapChainDescription { BufferCount = 1, Flags = SwapChainFlags.None, IsWindowed = true, ModeDescription = new ModeDescription(settings.Width, settings.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), OutputHandle = handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }); factory.SetWindowAssociation(handle, WindowAssociationFlags.IgnoreAll | WindowAssociationFlags.IgnoreAltEnter); }
public DX11SwapChain(DX11RenderContext context, IntPtr handle, Format format, SampleDescription sampledesc) { this.context = context; this.handle = handle; SwapChainDescription sd = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), format), IsWindowed = true, OutputHandle = handle, SampleDescription = sampledesc, SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput | Usage.ShaderInput, Flags = SwapChainFlags.None }; if (sd.SampleDescription.Count == 1 && context.IsFeatureLevel11) { sd.Usage |= Usage.UnorderedAccess; this.allowuav = true; } this.swapchain = new SwapChain(context.Device.Factory, context.Device, sd); this.Resource = Texture2D.FromSwapChain<Texture2D>(this.swapchain, 0); this.context.Factory.SetWindowAssociation(handle, WindowAssociationFlags.IgnoreAltEnter); this.RTV = new RenderTargetView(context.Device, this.Resource); this.SRV = new ShaderResourceView(context.Device, this.Resource); if (this.allowuav) { this.UAV = new UnorderedAccessView(context.Device, this.Resource); } this.desc = this.Resource.Description; }
private void InitalizeGraphics() { if (Window.RenderCanvasHandle == IntPtr.Zero) throw new InvalidOperationException("Window handle cannot be zero"); SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = 1, Flags = SwapChainFlags.None, IsWindowed = true, OutputHandle = Window.RenderCanvasHandle, SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, ModeDescription = new ModeDescription() { Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm, //Format = SlimDX.DXGI.Format.B8G8R8A8_UNorm, Width = Window.ClientSize.Width, Height = Window.ClientSize.Height, RefreshRate = new Rational(60, 1), Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrdering.Unspecified }, SampleDescription = new SampleDescription(1, 0) }; var giFactory = new SlimDX.DXGI.Factory(); var adapter = giFactory.GetAdapter(0); Device device; SwapChain swapChain; Device.CreateWithSwapChain(adapter, DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); _swapChain = swapChain; GraphicsDevice = device; // create a view of our render target, which is the backbuffer of the swap chain we just created using (var resource = SlimDX.Direct3D10.Resource.FromSwapChain<Texture2D>(swapChain, 0)) { _backBuffer = new RenderTargetView(device, resource); } // setting a viewport is required if you want to actually see anything var viewport = new Viewport(0, 0, Window.ClientSize.Width, Window.ClientSize.Height); device.OutputMerger.SetTargets(_backBuffer); device.Rasterizer.SetViewports(viewport); CreateDepthStencil(); LoadVisualizationEffect(); // Allocate a large buffer to write the PhysX visualization vertices into // There's more optimized ways of doing this, but for this sample a large buffer will do _userPrimitivesBuffer = new SlimDX.Direct3D10.Buffer(GraphicsDevice, VertexPositionColor.SizeInBytes * 50000, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None); var elements = new[] { new InputElement("Position", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("Color", 0, Format.R32G32B32A32_Float, 16, 0) }; _inputLayout = new InputLayout(GraphicsDevice, _visualizationEffect.RenderScenePass0.Description.Signature, elements); }
protected D3DApp(IntPtr hInstance) { AppInst = hInstance; MainWindowCaption = "D3D11 Application"; DriverType = DriverType.Hardware; ClientWidth = 800; ClientHeight = 600; Enable4XMsaa = false; Window = null; AppPaused = false; Minimized = false; Maximized = false; Resizing = false; Msaa4XQuality = 0; Device = null; ImmediateContext = null; SwapChain = null; DepthStencilBuffer = null; RenderTargetView = null; DepthStencilView = null; Viewport = new Viewport(); Timer = new GameTimer(); GD3DApp = this; }
public Renderer(int Width, int Height, IntPtr? OutputHandle) { if (Width < 1) Width = 1; if (Height < 1) Height = 1; bufferWidth = Width; bufferHeight = Height; deviceUsers++; if (device == null) device = new Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport, FeatureLevel.Level_11_0); if (OutputHandle.HasValue) { SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(BufferWidth, BufferHeight, new Rational(120, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = OutputHandle.Value, SampleDescription = BufferSampleDescription, SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, Flags = SwapChainFlags.AllowModeSwitch, }; swapChain = new SwapChain(device.Factory, Device, swapChainDesc); using (var factory = swapChain.GetParent<Factory>()) factory.SetWindowAssociation(OutputHandle.Value, WindowAssociationFlags.IgnoreAltEnter); } LightingSystem = new ForwardLighting(this); SetupRenderTargets(); LightingSystem.Initialize(); }
public override WriteableBitmap Initialize(Device device) { const int width = 600; const int height = 400; // Create device and swap chain. var swapChainPresenter = new WpfSwapChainPresenter(); _swapChain = device.CreateSwapChain(width, height, swapChainPresenter); _deviceContext = device.ImmediateContext; // Create RenderTargetView from the backbuffer. var backBuffer = Texture2D.FromSwapChain(_swapChain, 0); _renderTargetView = device.CreateRenderTargetView(backBuffer); // Create DepthStencilView. var depthStencilBuffer = device.CreateTexture2D(new Texture2DDescription { ArraySize = 1, MipLevels = 1, Width = width, Height = height, BindFlags = BindFlags.DepthStencil }); var depthStencilView = device.CreateDepthStencilView(depthStencilBuffer); // Prepare all the stages. _deviceContext.Rasterizer.SetViewports(new Viewport(0, 0, width, height, 0.0f, 1.0f)); _deviceContext.OutputMerger.SetTargets(depthStencilView, _renderTargetView); return swapChainPresenter.Bitmap; }
/// <summary> /// Create Direct3D device and swap chain /// </summary> public void InitDevice() { device = D3DDevice.CreateDeviceAndSwapChain(host.Handle); swapChain = device.SwapChain; // Create a render target view using (Texture2D pBuffer = swapChain.GetBuffer<Texture2D>(0)) { renderTargetView = device.CreateRenderTargetView(pBuffer); } device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { renderTargetView }, null); // Setup the viewport Viewport vp = new Viewport() { Width = (uint)host.ActualWidth, Height = (uint)host.ActualHeight, MinDepth = 0.0f, MaxDepth = 1.0f, TopLeftX = 0, TopLeftY = 0 }; device.RS.Viewports = new Viewport[] { vp }; }
public void TestException() { // Device is implicitly created with a DXGI Factory / Adapter var device = new Direct3D11.Device(DriverType.Hardware); // Create another DXGI Factory var factory = new SharpDX.DXGI.Factory1(); try { // This call should raise a DXGI_ERROR_INVALID_CALL: // The reason is the SwapChain must be created with a d3d device that was created with the same factory // Because we were creating the D3D11 device without a DXGI factory, it is associated with another factory. var swapChain = new SwapChain( factory, device, new SwapChainDescription() { BufferCount = 1, Flags = SwapChainFlags.None, IsWindowed = false, ModeDescription = new ModeDescription(1024, 768, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(1, 0), OutputHandle = IntPtr.Zero, SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }); } catch (SharpDXException exception) { Assert.AreEqual(exception.Descriptor.NativeApiCode, "DXGI_ERROR_INVALID_CALL"); } }
public override void Initialize() { using (var fac = new Factory()) { using (var tmpDevice = new Device(fac.GetAdapter(0), DriverType.Hardware, DeviceCreationFlags.None)) { using (var rf = new RenderForm()) { var desc = new SwapChainDescription { BufferCount = 1, Flags = SwapChainFlags.None, IsWindowed = true, ModeDescription = new ModeDescription(100, 100, new Rational(60, 1), Format.R8G8B8A8_UNorm), OutputHandle = rf.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; using (var sc = new SwapChain(fac, tmpDevice, desc)) { PresentPointer = Pulse.Magic.GetObjectVtableFunction(sc.ComPointer, VMT_PRESENT); ResetTargetPointer = Pulse.Magic.GetObjectVtableFunction(sc.ComPointer, VMT_RESIZETARGET); } } } } _presentDelegate = Pulse.Magic.RegisterDelegate<Direct3D10Present>(PresentPointer); _presentHook = Pulse.Magic.Detours.CreateAndApply(_presentDelegate, new Direct3D10Present(Callback), "D10Present"); }
public void AfterEngineInit() { // Basics. { var deviceDesc = new Device.Descriptor {DebugDevice = true}; renderDevice = new ClearSight.RendererDX12.Device(ref deviceDesc, ClearSight.RendererDX12.Device.FeatureLevel.Level_11_0); var descCQ = new CommandQueue.Descriptor() {Type = CommandListType.Graphics}; commandQueue = renderDevice.Create(ref descCQ); var wih = new WindowInteropHelper(window); var swapChainDesc = new SwapChain.Descriptor() { AssociatedGraphicsQueue = commandQueue, MaxFramesInFlight = 3, BufferCount = 3, Width = (uint) window.Width, Height = (uint) window.Height, Format = Format.R8G8B8A8_UNorm, SampleCount = 1, SampleQuality = 0, WindowHandle = wih.Handle, Fullscreen = false }; swapChain = renderDevice.Create(ref swapChainDesc); var commandListDesc = new CommandList.Descriptor() { Type = CommandListType.Graphics, AllocationPolicy = new CommandListInFlightFrameAllocationPolicy(CommandListType.Graphics, swapChain) }; commandList = renderDevice.Create(ref commandListDesc); } // Render targets. { var descHeapDesc = new DescriptorHeap.Descriptor() { Type = DescriptorHeap.Descriptor.ResourceDescriptorType.RenderTarget, NumResourceDescriptors = swapChain.Desc.BufferCount }; descHeapRenderTargets = renderDevice.Create(ref descHeapDesc); var rtvViewDesc = new RenderTargetViewDescription() { Format = swapChain.Desc.Format, Dimension = Dimension.Texture2D, Texture = new TextureSubresourceDesc(mipSlice: 0) }; for (uint i = 0; i < swapChain.Desc.BufferCount; ++i) { renderDevice.CreateRenderTargetView(descHeapRenderTargets, i, swapChain.BackbufferResources[i], ref rtvViewDesc); } } }
/// <summary> /// Create Direct3D device and swap chain /// </summary> protected void InitDevice() { device = D3DDevice.CreateDeviceAndSwapChain(directControl.Handle); swapChain = device.SwapChain; // Create a render target view using (Texture2D pBuffer = swapChain.GetBuffer<Texture2D>(0)) { renderTargetView = device.CreateRenderTargetView(pBuffer); } device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { renderTargetView }); // Setup the viewport Viewport vp = new Viewport() { Width = (uint)directControl.ClientSize.Width, Height = (uint)directControl.ClientSize.Height, MinDepth = 0.0f, MaxDepth = 1.0f, TopLeftX = 0, TopLeftY = 0 }; device.RS.Viewports = new Viewport[] { vp }; }
public RenderTarget(Device device, SwapChain swapChain) : this() { Texture = _disposer.Add(Texture2D.FromSwapChain<Texture2D>(swapChain, 0)); RenderTargetView = _disposer.Add(new RenderTargetView(device, Texture)); ShaderResourceView = null; Viewport = new Viewport(0, 0, Width, Height, 0.0f, 1.0f); }
public SwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters) : base(device, presentationParameters) { PresentInterval = presentationParameters.PresentationInterval; // Initialize the swap chain swapChain = ToDispose(CreateSwapChain()); backBuffer = ToDispose(RenderTarget2D.New(device, swapChain.GetBackBuffer<Direct3D11.Texture2D>(0))); }
void InitDevice() { // create Direct 3D device device = D3DDevice.CreateDeviceAndSwapChain(renderHost.Handle); swapChain = device.SwapChain; // Create a render target view using (Texture2D pBuffer = swapChain.GetBuffer<Texture2D>(0)) { renderTargetView = device.CreateRenderTargetView(pBuffer); } // Create depth stencil texture Texture2DDescription descDepth = new Texture2DDescription() { Width = (uint)renderHost.ActualWidth, Height = (uint)renderHost.ActualHeight, MipLevels = 1, ArraySize = 1, Format = Format.D32Float, SampleDescription = new SampleDescription() { Count = 1, Quality = 0 }, BindingOptions = BindingOptions.DepthStencil, }; depthStencil = device.CreateTexture2D(descDepth); // Create the depth stencil view DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription() { Format = descDepth.Format, ViewDimension = DepthStencilViewDimension.Texture2D }; depthStencilView = device.CreateDepthStencilView(depthStencil, depthStencilViewDesc); // bind the views to the device device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { renderTargetView }, depthStencilView); // Setup the viewport Viewport vp = new Viewport() { Width = (uint)renderHost.ActualWidth, Height = (uint)renderHost.ActualHeight, MinDepth = 0.0f, MaxDepth = 1.0f, TopLeftX = 0, TopLeftY = 0 }; device.RS.Viewports = new Viewport[] { vp }; }
/// <summary> /// Create Direct3D device and swap chain /// </summary> protected void InitDevice() { device = D3DDevice.CreateDeviceAndSwapChain(directControl.Handle); swapChain = device.SwapChain; SetViews(); meshManager = new XMeshManager(device); mesh = meshManager.Open("Media\\Tiger\\tiger.x"); InitMatrices(); }
public SwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters) : base(device, presentationParameters) { PresentInterval = presentationParameters.PresentationInterval; // Initialize the swap chain swapChain = CreateSwapChain(); backBuffer = new Texture(device).InitializeFrom(swapChain.GetBackBuffer<SharpDX.Direct3D11.Texture2D>(0), Description.BackBufferFormat.IsSRgb()); // Reload should get backbuffer from swapchain as well //backBufferTexture.Reload = graphicsResource => ((Texture)graphicsResource).Recreate(swapChain.GetBackBuffer<SharpDX.Direct3D11.Texture>(0)); }
/// <summary> /// Create Direct3D device and swap chain /// </summary> public void InitDevice() { device = D3DDevice.CreateDeviceAndSwapChain(host.Handle); swapChain = device.SwapChain; SetViews(); meshManager = new XMeshManager(device); mesh = meshManager.Open("Media\\Tiger\\tiger.x"); InitMatrices(); needsResizing = false; }
private void InitializeResources() { /* Creates a new DXGI swap chain */ InternalSwapChain = new SwapChain(m_factory, m_device, new SwapChainDescription { BufferCount = 1, Flags = SwapChainFlags.None, IsWindowed = true, ModeDescription = new ModeDescription(m_width, m_height, new Rational(60, 1), Format.B8G8R8A8_UNorm), OutputHandle = m_hWnd, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput | Usage.ShaderInput }); }
//------------------------------------------------------------------- // Constructor //------------------------------------------------------------------- public DrawDevice() { hwnd = IntPtr.Zero; pDevice = null; pSwapChain = null; d3dpp = null; format = Format.X8R8G8B8; width = 0; height = 0; lDefaultStride = 0; pixelAR.Denominator = pixelAR.Numerator = 1; rcDest = Rectangle.Empty; m_convertFn = null; }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (DesignMode) return; // create swap chain, rendertarget var swapChainDesc = new SwapChainDescription() { BufferCount = 1, Usage = Usage.RenderTargetOutput, OutputHandle = videoPanel1.Handle, IsWindowed = true, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard, SampleDescription = new SampleDescription(1, 0), }; swapChain = new SwapChain(factory, device, swapChainDesc); // render target renderTarget = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); renderTargetView = new RenderTargetView(device, renderTarget); // depth buffer var depthBufferDesc = new Texture2DDescription() { Width = videoPanel1.Width, Height = videoPanel1.Height, MipLevels = 1, ArraySize = 1, Format = Format.D32_Float, // necessary? SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None }; depthStencil = new Texture2D(device, depthBufferDesc); depthStencilView = new DepthStencilView(device, depthStencil); // viewport viewport = new Viewport(0, 0, videoPanel1.Width, videoPanel1.Height, 0f, 1f); }
public static SwapChain3 CreateSwapchain(RenderForm form, CommandQueue queue,Config config) { using (var Factory = new Factory4()) { var swapChainDesc = new SwapChainDescription() { BufferCount = config.FrameCount, ModeDescription = new ModeDescription(config.Width, config.Height, new Rational(config.RefreshRate, 1), config.Format), Usage = Usage.RenderTargetOutput, SwapEffect = SwapEffect.FlipDiscard, OutputHandle = form.Handle, SampleDescription = new SampleDescription(config.SampleCount, config.SampleQuality), IsWindowed = true }; var tempSwapChain = new SwapChain(Factory, queue, swapChainDesc); var SwapChain = tempSwapChain.QueryInterface<SwapChain3>(); tempSwapChain.Dispose(); return SwapChain; } }
/// <summary> /// Create Direct3D device and swap chain /// </summary> protected void InitDevice() { device = D3DDevice1.CreateDeviceAndSwapChain1(host.Handle); swapChain = device.SwapChain; SetViews(); // Create the effect using (FileStream effectStream = File.OpenRead("Tutorial07.fxo")) { effect = device.CreateEffectFromCompiledBinary(new BinaryReader(effectStream)); } // Obtain the technique technique = effect.GetTechniqueByName("Render"); // Obtain the variables worldVariable = effect.GetVariableByName("World").AsMatrix; viewVariable = effect.GetVariableByName("View").AsMatrix; projectionVariable = effect.GetVariableByName("Projection").AsMatrix; meshColorVariable = effect.GetVariableByName("vMeshColor").AsVector; diffuseVariable = effect.GetVariableByName("txDiffuse").AsShaderResource; InitVertexLayout(); InitVertexBuffer(); InitIndexBuffer(); // Set primitive topology device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList; // Load the Texture using (FileStream stream = File.OpenRead("seafloor.png")) { textureRV = TextureLoader.LoadTexture(device, stream); } InitMatrices(); diffuseVariable.Resource = textureRV; needsResizing = false; }
// For WinForms tests public static void CreateHwndRenderSurface(IntPtr windowHandle, Device device, int width, int height, out Texture2D renderTexture, out SwapChain swapChain) { var swapChainDesc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = windowHandle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; using (var dxgiDevice = new SharpDX.DXGI.Device1(device.NativePointer)) using (var adapter = dxgiDevice.GetParent<SharpDX.DXGI.Adapter1>()) using (var factory = adapter.GetParent<Factory>()) { swapChain = new SwapChain(factory, device, swapChainDesc); } renderTexture = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); }
private static void Main() { RenderForm form = new RenderForm("OculusWrap SharpDX demo"); IntPtr sessionPtr; InputLayout inputLayout = null; Buffer contantBuffer = null; Buffer vertexBuffer = null; ShaderSignature shaderSignature = null; PixelShader pixelShader = null; ShaderBytecode pixelShaderByteCode = null; VertexShader vertexShader = null; ShaderBytecode vertexShaderByteCode = null; Texture2D mirrorTextureD3D = null; EyeTexture[] eyeTextures = null; DeviceContext immediateContext = null; DepthStencilState depthStencilState = null; DepthStencilView depthStencilView = null; Texture2D depthBuffer = null; RenderTargetView backBufferRenderTargetView = null; Texture2D backBuffer = null; SharpDX.DXGI.SwapChain swapChain = null; Factory factory = null; MirrorTexture mirrorTexture = null; Guid textureInterfaceId = new Guid("6f15aaf2-d208-4e89-9ab4-489535d34f9c"); // Interface ID of the Direct3D Texture2D interface. Result result; OvrWrap OVR = OvrWrap.Create(); // Define initialization parameters with debug flag. InitParams initializationParameters = new InitParams(); initializationParameters.Flags = InitFlags.Debug | InitFlags.RequestVersion; initializationParameters.RequestedMinorVersion = 17; // Initialize the Oculus runtime. string errorReason = null; try { result = OVR.Initialize(initializationParameters); if (result < Result.Success) { errorReason = result.ToString(); } } catch (Exception ex) { errorReason = ex.Message; } if (errorReason != null) { MessageBox.Show("Failed to initialize the Oculus runtime library:\r\n" + errorReason, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Use the head mounted display. sessionPtr = IntPtr.Zero; var graphicsLuid = new GraphicsLuid(); result = OVR.Create(ref sessionPtr, ref graphicsLuid); if (result < Result.Success) { MessageBox.Show("The HMD is not enabled: " + result.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var hmdDesc = OVR.GetHmdDesc(sessionPtr); try { // Create a set of layers to submit. eyeTextures = new EyeTexture[2]; // Create DirectX drawing device. SharpDX.Direct3D11.Device device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.Debug); // Create DirectX Graphics Interface factory, used to create the swap chain. factory = new SharpDX.DXGI.Factory4(); immediateContext = device.ImmediateContext; // Define the properties of the swap chain. SwapChainDescription swapChainDescription = new SwapChainDescription(); swapChainDescription.BufferCount = 1; swapChainDescription.IsWindowed = true; swapChainDescription.OutputHandle = form.Handle; swapChainDescription.SampleDescription = new SampleDescription(1, 0); swapChainDescription.Usage = Usage.RenderTargetOutput | Usage.ShaderInput; swapChainDescription.SwapEffect = SwapEffect.Sequential; swapChainDescription.Flags = SwapChainFlags.AllowModeSwitch; swapChainDescription.ModeDescription.Width = form.Width; swapChainDescription.ModeDescription.Height = form.Height; swapChainDescription.ModeDescription.Format = Format.R8G8B8A8_UNorm; swapChainDescription.ModeDescription.RefreshRate.Numerator = 0; swapChainDescription.ModeDescription.RefreshRate.Denominator = 1; // Create the swap chain. swapChain = new SwapChain(factory, device, swapChainDescription); // Retrieve the back buffer of the swap chain. backBuffer = swapChain.GetBackBuffer <Texture2D>(0); backBufferRenderTargetView = new RenderTargetView(device, backBuffer); // Create a depth buffer, using the same width and height as the back buffer. Texture2DDescription depthBufferDescription = new Texture2DDescription(); depthBufferDescription.Format = Format.D32_Float; depthBufferDescription.ArraySize = 1; depthBufferDescription.MipLevels = 1; depthBufferDescription.Width = form.Width; depthBufferDescription.Height = form.Height; depthBufferDescription.SampleDescription = new SampleDescription(1, 0); depthBufferDescription.Usage = ResourceUsage.Default; depthBufferDescription.BindFlags = BindFlags.DepthStencil; depthBufferDescription.CpuAccessFlags = CpuAccessFlags.None; depthBufferDescription.OptionFlags = ResourceOptionFlags.None; // Define how the depth buffer will be used to filter out objects, based on their distance from the viewer. DepthStencilStateDescription depthStencilStateDescription = new DepthStencilStateDescription(); depthStencilStateDescription.IsDepthEnabled = true; depthStencilStateDescription.DepthComparison = Comparison.Less; depthStencilStateDescription.DepthWriteMask = DepthWriteMask.Zero; // Create the depth buffer. depthBuffer = new Texture2D(device, depthBufferDescription); depthStencilView = new DepthStencilView(device, depthBuffer); depthStencilState = new DepthStencilState(device, depthStencilStateDescription); var viewport = new Viewport(0, 0, hmdDesc.Resolution.Width, hmdDesc.Resolution.Height, 0.0f, 1.0f); immediateContext.OutputMerger.SetDepthStencilState(depthStencilState); immediateContext.OutputMerger.SetRenderTargets(depthStencilView, backBufferRenderTargetView); immediateContext.Rasterizer.SetViewport(viewport); // Retrieve the DXGI device, in order to set the maximum frame latency. using (SharpDX.DXGI.Device1 dxgiDevice = device.QueryInterface <SharpDX.DXGI.Device1>()) { dxgiDevice.MaximumFrameLatency = 1; } var layerEyeFov = new LayerEyeFov(); layerEyeFov.Header.Type = LayerType.EyeFov; layerEyeFov.Header.Flags = LayerFlags.None; for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++) { EyeType eye = (EyeType)eyeIndex; var eyeTexture = new EyeTexture(); eyeTextures[eyeIndex] = eyeTexture; // Retrieve size and position of the texture for the current eye. eyeTexture.FieldOfView = hmdDesc.DefaultEyeFov[eyeIndex]; eyeTexture.TextureSize = OVR.GetFovTextureSize(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex], 1.0f); eyeTexture.RenderDescription = OVR.GetRenderDesc(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex]); eyeTexture.HmdToEyeViewOffset = eyeTexture.RenderDescription.HmdToEyePose.Position; eyeTexture.ViewportSize.Position = new Vector2i(0, 0); eyeTexture.ViewportSize.Size = eyeTexture.TextureSize; eyeTexture.Viewport = new Viewport(0, 0, eyeTexture.TextureSize.Width, eyeTexture.TextureSize.Height, 0.0f, 1.0f); // Define a texture at the size recommended for the eye texture. eyeTexture.Texture2DDescription = new Texture2DDescription(); eyeTexture.Texture2DDescription.Width = eyeTexture.TextureSize.Width; eyeTexture.Texture2DDescription.Height = eyeTexture.TextureSize.Height; eyeTexture.Texture2DDescription.ArraySize = 1; eyeTexture.Texture2DDescription.MipLevels = 1; eyeTexture.Texture2DDescription.Format = Format.R8G8B8A8_UNorm; eyeTexture.Texture2DDescription.SampleDescription = new SampleDescription(1, 0); eyeTexture.Texture2DDescription.Usage = ResourceUsage.Default; eyeTexture.Texture2DDescription.CpuAccessFlags = CpuAccessFlags.None; eyeTexture.Texture2DDescription.BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget; // Convert the SharpDX texture description to the Oculus texture swap chain description. TextureSwapChainDesc textureSwapChainDesc = SharpDXHelpers.CreateTextureSwapChainDescription(eyeTexture.Texture2DDescription); // Create a texture swap chain, which will contain the textures to render to, for the current eye. IntPtr textureSwapChainPtr; result = OVR.CreateTextureSwapChainDX(sessionPtr, device.NativePointer, ref textureSwapChainDesc, out textureSwapChainPtr); WriteErrorDetails(OVR, result, "Failed to create swap chain."); eyeTexture.SwapTextureSet = new TextureSwapChain(OVR, sessionPtr, textureSwapChainPtr); // Retrieve the number of buffers of the created swap chain. int textureSwapChainBufferCount; result = eyeTexture.SwapTextureSet.GetLength(out textureSwapChainBufferCount); WriteErrorDetails(OVR, result, "Failed to retrieve the number of buffers of the created swap chain."); // Create room for each DirectX texture in the SwapTextureSet. eyeTexture.Textures = new Texture2D[textureSwapChainBufferCount]; eyeTexture.RenderTargetViews = new RenderTargetView[textureSwapChainBufferCount]; // Create a texture 2D and a render target view, for each unmanaged texture contained in the SwapTextureSet. for (int textureIndex = 0; textureIndex < textureSwapChainBufferCount; textureIndex++) { // Retrieve the Direct3D texture contained in the Oculus TextureSwapChainBuffer. IntPtr swapChainTextureComPtr = IntPtr.Zero; result = eyeTexture.SwapTextureSet.GetBufferDX(textureIndex, textureInterfaceId, out swapChainTextureComPtr); WriteErrorDetails(OVR, result, "Failed to retrieve a texture from the created swap chain."); // Create a managed Texture2D, based on the unmanaged texture pointer. eyeTexture.Textures[textureIndex] = new Texture2D(swapChainTextureComPtr); // Create a render target view for the current Texture2D. eyeTexture.RenderTargetViews[textureIndex] = new RenderTargetView(device, eyeTexture.Textures[textureIndex]); } // Define the depth buffer, at the size recommended for the eye texture. eyeTexture.DepthBufferDescription = new Texture2DDescription(); eyeTexture.DepthBufferDescription.Format = Format.D32_Float; eyeTexture.DepthBufferDescription.Width = eyeTexture.TextureSize.Width; eyeTexture.DepthBufferDescription.Height = eyeTexture.TextureSize.Height; eyeTexture.DepthBufferDescription.ArraySize = 1; eyeTexture.DepthBufferDescription.MipLevels = 1; eyeTexture.DepthBufferDescription.SampleDescription = new SampleDescription(1, 0); eyeTexture.DepthBufferDescription.Usage = ResourceUsage.Default; eyeTexture.DepthBufferDescription.BindFlags = BindFlags.DepthStencil; eyeTexture.DepthBufferDescription.CpuAccessFlags = CpuAccessFlags.None; eyeTexture.DepthBufferDescription.OptionFlags = ResourceOptionFlags.None; // Create the depth buffer. eyeTexture.DepthBuffer = new Texture2D(device, eyeTexture.DepthBufferDescription); eyeTexture.DepthStencilView = new DepthStencilView(device, eyeTexture.DepthBuffer); // Specify the texture to show on the HMD. if (eyeIndex == 0) { layerEyeFov.ColorTextureLeft = eyeTexture.SwapTextureSet.TextureSwapChainPtr; layerEyeFov.ViewportLeft.Position = new Vector2i(0, 0); layerEyeFov.ViewportLeft.Size = eyeTexture.TextureSize; layerEyeFov.FovLeft = eyeTexture.FieldOfView; } else { layerEyeFov.ColorTextureRight = eyeTexture.SwapTextureSet.TextureSwapChainPtr; layerEyeFov.ViewportRight.Position = new Vector2i(0, 0); layerEyeFov.ViewportRight.Size = eyeTexture.TextureSize; layerEyeFov.FovRight = eyeTexture.FieldOfView; } } MirrorTextureDesc mirrorTextureDescription = new MirrorTextureDesc(); mirrorTextureDescription.Format = TextureFormat.R8G8B8A8_UNorm_SRgb; mirrorTextureDescription.Width = form.Width; mirrorTextureDescription.Height = form.Height; mirrorTextureDescription.MiscFlags = TextureMiscFlags.None; // Create the texture used to display the rendered result on the computer monitor. IntPtr mirrorTexturePtr; result = OVR.CreateMirrorTextureDX(sessionPtr, device.NativePointer, ref mirrorTextureDescription, out mirrorTexturePtr); WriteErrorDetails(OVR, result, "Failed to create mirror texture."); mirrorTexture = new MirrorTexture(OVR, sessionPtr, mirrorTexturePtr); // Retrieve the Direct3D texture contained in the Oculus MirrorTexture. IntPtr mirrorTextureComPtr = IntPtr.Zero; result = mirrorTexture.GetBufferDX(textureInterfaceId, out mirrorTextureComPtr); WriteErrorDetails(OVR, result, "Failed to retrieve the texture from the created mirror texture buffer."); // Create a managed Texture2D, based on the unmanaged texture pointer. mirrorTextureD3D = new Texture2D(mirrorTextureComPtr); #region Vertex and pixel shader // Create vertex shader. vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "VertexShaderPositionColor", "vs_4_0"); vertexShader = new VertexShader(device, vertexShaderByteCode); // Create pixel shader. pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "PixelShaderPositionColor", "ps_4_0"); pixelShader = new PixelShader(device, pixelShaderByteCode); shaderSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); // Specify that each vertex consists of a single vertex position and color. InputElement[] inputElements = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }; // Define an input layout to be passed to the vertex shader. inputLayout = new InputLayout(device, shaderSignature, inputElements); // Create a vertex buffer, containing our 3D model. vertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer, m_vertices); // Create a constant buffer, to contain our WorldViewProjection matrix, that will be passed to the vertex shader. contantBuffer = new Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); // Setup the immediate context to use the shaders and model we defined. immediateContext.InputAssembler.InputLayout = inputLayout; immediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; immediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, sizeof(float) * 4 * 2, 0)); immediateContext.VertexShader.SetConstantBuffer(0, contantBuffer); immediateContext.VertexShader.Set(vertexShader); immediateContext.PixelShader.Set(pixelShader); #endregion DateTime startTime = DateTime.Now; Vector3 position = new Vector3(0, 0, -1); #region Render loop RenderLoop.Run(form, () => { Vector3f[] hmdToEyeViewOffsets = { eyeTextures[0].HmdToEyeViewOffset, eyeTextures[1].HmdToEyeViewOffset }; double displayMidpoint = OVR.GetPredictedDisplayTime(sessionPtr, 0); TrackingState trackingState = OVR.GetTrackingState(sessionPtr, displayMidpoint, true); Posef[] eyePoses = new Posef[2]; // Calculate the position and orientation of each eye. OVR.CalcEyePoses(trackingState.HeadPose.ThePose, hmdToEyeViewOffsets, ref eyePoses); float timeSinceStart = (float)(DateTime.Now - startTime).TotalSeconds; for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++) { EyeType eye = (EyeType)eyeIndex; EyeTexture eyeTexture = eyeTextures[eyeIndex]; if (eyeIndex == 0) { layerEyeFov.RenderPoseLeft = eyePoses[0]; } else { layerEyeFov.RenderPoseRight = eyePoses[1]; } // Update the render description at each frame, as the HmdToEyeOffset can change at runtime. eyeTexture.RenderDescription = OVR.GetRenderDesc(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex]); // Retrieve the index of the active texture int textureIndex; result = eyeTexture.SwapTextureSet.GetCurrentIndex(out textureIndex); WriteErrorDetails(OVR, result, "Failed to retrieve texture swap chain current index."); immediateContext.OutputMerger.SetRenderTargets(eyeTexture.DepthStencilView, eyeTexture.RenderTargetViews[textureIndex]); immediateContext.ClearRenderTargetView(eyeTexture.RenderTargetViews[textureIndex], Color.Black); immediateContext.ClearDepthStencilView(eyeTexture.DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0); immediateContext.Rasterizer.SetViewport(eyeTexture.Viewport); // Retrieve the eye rotation quaternion and use it to calculate the LookAt direction and the LookUp direction. Quaternion rotationQuaternion = SharpDXHelpers.ToQuaternion(eyePoses[eyeIndex].Orientation); Matrix rotationMatrix = Matrix.RotationQuaternion(rotationQuaternion); Vector3 lookUp = Vector3.Transform(new Vector3(0, -1, 0), rotationMatrix).ToVector3(); Vector3 lookAt = Vector3.Transform(new Vector3(0, 0, 1), rotationMatrix).ToVector3(); Vector3 viewPosition = position - eyePoses[eyeIndex].Position.ToVector3(); Matrix world = Matrix.Scaling(0.1f) * Matrix.RotationX(timeSinceStart / 10f) * Matrix.RotationY(timeSinceStart * 2 / 10f) * Matrix.RotationZ(timeSinceStart * 3 / 10f); Matrix viewMatrix = Matrix.LookAtLH(viewPosition, viewPosition + lookAt, lookUp); Matrix projectionMatrix = OVR.Matrix4f_Projection(eyeTexture.FieldOfView, 0.1f, 100.0f, ProjectionModifier.LeftHanded).ToMatrix(); projectionMatrix.Transpose(); Matrix worldViewProjection = world * viewMatrix * projectionMatrix; worldViewProjection.Transpose(); // Update the transformation matrix. immediateContext.UpdateSubresource(ref worldViewProjection, contantBuffer); // Draw the cube immediateContext.Draw(m_vertices.Length / 2, 0); // Commits any pending changes to the TextureSwapChain, and advances its current index result = eyeTexture.SwapTextureSet.Commit(); WriteErrorDetails(OVR, result, "Failed to commit the swap chain texture."); } result = OVR.SubmitFrame(sessionPtr, 0L, IntPtr.Zero, ref layerEyeFov); WriteErrorDetails(OVR, result, "Failed to submit the frame of the current layers."); immediateContext.CopyResource(mirrorTextureD3D, backBuffer); swapChain.Present(0, PresentFlags.None); }); #endregion } finally { if (immediateContext != null) { immediateContext.ClearState(); immediateContext.Flush(); } // Release all resources Dispose(inputLayout); Dispose(contantBuffer); Dispose(vertexBuffer); Dispose(shaderSignature); Dispose(pixelShader); Dispose(pixelShaderByteCode); Dispose(vertexShader); Dispose(vertexShaderByteCode); Dispose(mirrorTextureD3D); Dispose(mirrorTexture); Dispose(eyeTextures[0]); Dispose(eyeTextures[1]); Dispose(immediateContext); Dispose(depthStencilState); Dispose(depthStencilView); Dispose(depthBuffer); Dispose(backBufferRenderTargetView); Dispose(backBuffer); Dispose(swapChain); Dispose(factory); // Disposing the device, before the hmd, will cause the hmd to fail when disposing. // Disposing the device, after the hmd, will cause the dispose of the device to fail. // It looks as if the hmd steals ownership of the device and destroys it, when it's shutting down. // device.Dispose(); OVR.Destroy(sessionPtr); } }
protected abstract void CreateFromSwapChainImpl(SwapChain swapChain, uint backbufferIndex);
protected virtual void OnResize() { Debug.Assert(Device != null); Debug.Assert(SwapChain != null); Debug.Assert(DirectCmdListAlloc != null); // Flush before changing any resources. FlushCommandQueue(); CommandList.Reset(DirectCmdListAlloc, null); // Release the previous resources we will be recreating. foreach (Resource buffer in _swapChainBuffers) { buffer?.Dispose(); } DepthStencilBuffer?.Dispose(); // Resize the swap chain. SwapChain.ResizeBuffers( SwapChainBufferCount, ClientWidth, ClientHeight, BackBufferFormat, SwapChainFlags.AllowModeSwitch); CpuDescriptorHandle rtvHeapHandle = RtvHeap.CPUDescriptorHandleForHeapStart; for (int i = 0; i < SwapChainBufferCount; i++) { Resource backBuffer = SwapChain.GetBackBuffer <Resource>(i); _swapChainBuffers[i] = backBuffer; Device.CreateRenderTargetView(backBuffer, null, rtvHeapHandle); rtvHeapHandle += RtvDescriptorSize; } // Create the depth/stencil buffer and view. var depthStencilDesc = new ResourceDescription { Dimension = ResourceDimension.Texture2D, Alignment = 0, Width = ClientWidth, Height = ClientHeight, DepthOrArraySize = 1, MipLevels = 1, Format = Format.R24G8_Typeless, SampleDescription = new SampleDescription { Count = MsaaCount, Quality = MsaaQuality }, Layout = TextureLayout.Unknown, Flags = ResourceFlags.AllowDepthStencil }; var optClear = new ClearValue { Format = DepthStencilFormat, DepthStencil = new DepthStencilValue { Depth = 1.0f, Stencil = 0 } }; DepthStencilBuffer = Device.CreateCommittedResource( new HeapProperties(HeapType.Default), HeapFlags.None, depthStencilDesc, ResourceStates.Common, optClear); var depthStencilViewDesc = new DepthStencilViewDescription { Dimension = DepthStencilViewDimension.Texture2D, Format = DepthStencilFormat }; // Create descriptor to mip level 0 of entire resource using a depth stencil format. CpuDescriptorHandle dsvHeapHandle = DsvHeap.CPUDescriptorHandleForHeapStart; Device.CreateDepthStencilView(DepthStencilBuffer, depthStencilViewDesc, dsvHeapHandle); // Transition the resource from its initial state to be used as a depth buffer. CommandList.ResourceBarrierTransition(DepthStencilBuffer, ResourceStates.Common, ResourceStates.DepthWrite); // Execute the resize commands. CommandList.Close(); CommandQueue.ExecuteCommandList(CommandList); // Wait until resize is complete. FlushCommandQueue(); Viewport = new ViewportF(0, 0, ClientWidth, ClientHeight, 0.0f, 1.0f); ScissorRectangle = new RectangleF(0, 0, ClientWidth, ClientHeight); }
protected override void Draw(GameTimer gt) { CommandAllocator cmdListAlloc = CurrFrameResource.CmdListAlloc; // Reuse the memory associated with command recording. // We can only reset when the associated command lists have finished execution on the GPU. cmdListAlloc.Reset(); // A command list can be reset after it has been added to the command queue via ExecuteCommandList. // Reusing the command list reuses memory. CommandList.Reset(cmdListAlloc, _psos["opaque"]); CommandList.SetViewport(Viewport); CommandList.SetScissorRectangles(ScissorRectangle); // Indicate a state transition on the resource usage. CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.Present, ResourceStates.RenderTarget); // Clear the back buffer and depth buffer. CommandList.ClearRenderTargetView(CurrentBackBufferView, new Color(_mainPassCB.FogColor)); CommandList.ClearDepthStencilView(DepthStencilView, ClearFlags.FlagsDepth | ClearFlags.FlagsStencil, 1.0f, 0); // Specify the buffers we are going to render to. CommandList.SetRenderTargets(CurrentBackBufferView, DepthStencilView); CommandList.SetDescriptorHeaps(_descriptorHeaps.Length, _descriptorHeaps); CommandList.SetGraphicsRootSignature(_rootSignature); // Bind per-pass constant buffer. We only need to do this once per-pass. Resource passCB = CurrFrameResource.PassCB.Resource; CommandList.SetGraphicsRootConstantBufferView(2, passCB.GPUVirtualAddress); DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Opaque]); CommandList.PipelineState = _psos["alphaTested"]; DrawRenderItems(CommandList, _ritemLayers[RenderLayer.AlphaTested]); CommandList.PipelineState = _psos["transparent"]; DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Transparent]); // Indicate a state transition on the resource usage. CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.RenderTarget, ResourceStates.Present); // Done recording commands. CommandList.Close(); // Add the command list to the queue for execution. CommandQueue.ExecuteCommandList(CommandList); // Present the buffer to the screen. Presenting will automatically swap the back and front buffers. SwapChain.Present(0, PresentFlags.None); // Advance the fence value to mark commands up to this fence point. CurrFrameResource.Fence = ++CurrentFence; // Add an instruction to the command queue to set a new fence point. // Because we are on the GPU timeline, the new fence point won't be // set until the GPU finishes processing all the commands prior to this Signal(). CommandQueue.Signal(Fence, CurrentFence); }
/// <summary> /// This overload has been deprecated. Use one of the alternatives that does not take both an adapter and a driver type. /// </summary> internal static void CreateWithSwapChain(Adapter adapter, DriverType driverType, DeviceCreationFlags flags, SwapChainDescription swapChainDescription, FeatureLevel featureLevel, out Device1 device, out SwapChain swapChain) { D3D10.CreateDeviceAndSwapChain1(adapter, driverType, IntPtr.Zero, flags, featureLevel, D3D10.SdkVersion1, ref swapChainDescription, out swapChain, out device); }
public void Shutdown() { // Before shutting down set to windowed mode or when you release the swap chain it will throw an exception. if (SwapChain != null) { SwapChain.SetFullscreenState(false, null); } if (AlphaEnableBlendingState != null) { AlphaEnableBlendingState.Dispose(); AlphaEnableBlendingState = null; } if (AlphaDisableBlendingState != null) { AlphaDisableBlendingState.Dispose(); AlphaDisableBlendingState = null; } if (DepthDisabledStencilState != null) { DepthDisabledStencilState.Dispose(); DepthDisabledStencilState = null; } if (RasterState != null) { RasterState.Dispose(); RasterState = null; } if (DepthStencilView != null) { DepthStencilView.Dispose(); DepthStencilView = null; } if (DepthStencilState != null) { DepthStencilState.Dispose(); DepthStencilState = null; } if (DepthStencilBuffer != null) { DepthStencilBuffer.Dispose(); DepthStencilBuffer = null; } if (RenderTargetView != null) { RenderTargetView.Dispose(); RenderTargetView = null; } if (Device != null) { Device.Dispose(); Device = null; } if (SwapChain != null) { SwapChain.Dispose(); SwapChain = null; } }
protected override void Draw(GameTimer gt) { CommandAllocator cmdListAlloc = CurrFrameResource.CmdListAlloc; // Reuse the memory associated with command recording. // We can only reset when the associated command lists have finished execution on the GPU. cmdListAlloc.Reset(); // A command list can be reset after it has been added to the command queue via ExecuteCommandList. // Reusing the command list reuses memory. CommandList.Reset(cmdListAlloc, _psos["opaque"]); CommandList.SetDescriptorHeaps(_descriptorHeaps.Length, _descriptorHeaps); CommandList.SetGraphicsRootSignature(_rootSignature); // Bind all the materials used in this scene. For structured buffers, we can bypass the heap and // set as a root descriptor. Resource matBuffer = CurrFrameResource.MaterialBuffer.Resource; CommandList.SetGraphicsRootShaderResourceView(2, matBuffer.GPUVirtualAddress); // Bind null SRV for shadow map pass. CommandList.SetGraphicsRootDescriptorTable(3, _nullSrv); // Bind all the textures used in this scene. Observe // that we only have to specify the first descriptor in the table. // The root signature knows how many descriptors are expected in the table. CommandList.SetGraphicsRootDescriptorTable(4, _srvDescriptorHeap.GPUDescriptorHandleForHeapStart); DrawSceneToShadowMap(); CommandList.SetViewport(Viewport); CommandList.SetScissorRectangles(ScissorRectangle); // Indicate a state transition on the resource usage. CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.Present, ResourceStates.RenderTarget); // Clear the back buffer and depth buffer. CommandList.ClearRenderTargetView(CurrentBackBufferView, Color.LightSteelBlue); CommandList.ClearDepthStencilView(DepthStencilView, ClearFlags.FlagsDepth | ClearFlags.FlagsStencil, 1.0f, 0); // Specify the buffers we are going to render to. CommandList.SetRenderTargets(CurrentBackBufferView, DepthStencilView); Resource passCB = CurrFrameResource.PassCB.Resource; CommandList.SetGraphicsRootConstantBufferView(1, passCB.GPUVirtualAddress); // Bind the sky cube map. For our demos, we just use one "world" cube map representing the environment // from far away, so all objects will use the same cube map and we only need to set it once per-frame. // If we wanted to use "local" cube maps, we would have to change them per-object, or dynamically // index into an array of cube maps. GpuDescriptorHandle skyTexDescriptor = _srvDescriptorHeap.GPUDescriptorHandleForHeapStart; skyTexDescriptor += _skyTexHeapIndex * CbvSrvUavDescriptorSize; CommandList.SetGraphicsRootDescriptorTable(3, skyTexDescriptor); CommandList.PipelineState = _psos["opaque"]; DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Opaque]); CommandList.PipelineState = _psos["debug"]; DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Debug]); CommandList.PipelineState = _psos["sky"]; DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Sky]); // Indicate a state transition on the resource usage. CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.RenderTarget, ResourceStates.Present); // Done recording commands. CommandList.Close(); // Add the command list to the queue for execution. CommandQueue.ExecuteCommandList(CommandList); // Present the buffer to the screen. Presenting will automatically swap the back and front buffers. SwapChain.Present(0, PresentFlags.None); // Advance the fence value to mark commands up to this fence point. CurrFrameResource.Fence = ++CurrentFence; // Add an instruction to the command queue to set a new fence point. // Because we are on the GPU timeline, the new fence point won't be // set until the GPU finishes processing all the commands prior to this Signal(). CommandQueue.Signal(Fence, CurrentFence); }
private static MyRenderDeviceSettings CreateDeviceInternal(IntPtr windowHandle, MyRenderDeviceSettings?settingsToTry, bool forceDebugDevice) { if (Device != null) { Device.Dispose(); Device = null; } WIC = null; if (settingsToTry != null) { Log.WriteLine("CreateDevice - original settings"); Log.IncreaseIndent(); var originalSettings = settingsToTry.Value; LogSettings(ref originalSettings); } FeatureLevel[] featureLevels = { FeatureLevel.Level_11_0 }; DeviceCreationFlags flags = DeviceCreationFlags.None; //forceDebugDevice |= MyCompilationSymbols.IsDebugBuild; if (forceDebugDevice) { flags |= DeviceCreationFlags.Debug; } #if !XB1 WinApi.DEVMODE mode = new WinApi.DEVMODE(); WinApi.EnumDisplaySettings(null, WinApi.ENUM_REGISTRY_SETTINGS, ref mode); var settings = settingsToTry ?? new MyRenderDeviceSettings() { AdapterOrdinal = -1, BackBufferHeight = mode.dmPelsHeight, BackBufferWidth = mode.dmPelsWidth, WindowMode = MyWindowModeEnum.FullscreenWindow, RefreshRate = 60000, VSync = false, }; #else var settings = CreateXB1Settings(); #endif settings.AdapterOrdinal = ValidateAdapterIndex(settings.AdapterOrdinal); if (settings.AdapterOrdinal == -1) { throw new MyRenderException("No supported device detected!\nPlease apply windows updates and update to latest graphics drivers.", MyRenderExceptionEnum.GpuNotSupported); } m_settings = settings; Log.WriteLine("CreateDeviceInteral settings"); Log.IncreaseIndent(); LogSettings(ref m_settings); // If this line crashes cmd this: Dism /online /add-capability /capabilityname:Tools.Graphics.DirectX~~~~0.0.1.0 var factory = GetFactory(); var adapters = GetAdaptersList(); if (m_settings.AdapterOrdinal >= adapters.Length) { throw new MyRenderException("No supported device detected!\nPlease apply windows updates and update to latest graphics drivers.", MyRenderExceptionEnum.GpuNotSupported); } var adapterId = adapters[m_settings.AdapterOrdinal].AdapterDeviceId; if (adapterId >= factory.Adapters.Length) { throw new MyRenderException("Invalid adapter id binding!", MyRenderExceptionEnum.GpuNotSupported); } var adapter = factory.Adapters[adapterId]; Log.WriteLine("CreateDeviceInteral TweakSettingsAdapterAdHoc"); TweakSettingsAdapterAdHoc(adapter); Log.WriteLine("CreateDeviceInteral create device"); Device = new Device(adapter, flags, FeatureLevel.Level_11_0); Log.WriteLine("CreateDeviceInteral create ImagingFactory"); WIC = new ImagingFactory(); // HACK: This is required for Steam overlay to work. Apparently they hook only CreateDevice methods with DriverType argument. try { Log.WriteLine("CreateDeviceInteral Steam Overlay integration"); using (new Device(DriverType.Hardware, flags, FeatureLevel.Level_11_0)) { } Log.WriteLine("CreateDeviceInteral Steam Overlay OK"); } catch { Log.WriteLine("CreateDeviceInteral Steam Overlay Failed"); } Log.WriteLine("CreateDeviceInteral InitDebugOutput"); InitDebugOutput(forceDebugDevice); Log.WriteLine("CreateDeviceInteral RC Dispose"); if (RC != null) { RC.Dispose(); RC = null; } Log.WriteLine("CreateDeviceInteral RC Create"); RC = new MyRenderContext(); Log.WriteLine("CreateDeviceInteral RC Initialize"); RC.Initialize(Device.ImmediateContext); m_windowHandle = windowHandle; m_resolution = new Vector2I(m_settings.BackBufferWidth, m_settings.BackBufferHeight); Log.WriteLine("CreateDeviceInteral m_initializedOnce (" + m_initializedOnce + ")"); if (!m_initializedOnce) { InitSubsystemsOnce(); m_initializedOnce = true; } Log.WriteLine("CreateDeviceInteral m_initialized (" + m_initialized + ")"); if (!m_initialized) { OnDeviceReset(); InitSubsystems(); m_initialized = true; } Log.WriteLine("CreateDeviceInteral m_swapchain (" + m_swapchain + ")"); if (m_swapchain != null) { m_swapchain.Dispose(); m_swapchain = null; } Log.WriteLine("CreateDeviceInteral create swapchain"); if (m_swapchain == null) { //SharpDX.DXGI.Device d = Device.QueryInterface<SharpDX.DXGI.Device>(); //Adapter a = d.GetParent<Adapter>(); //var factory = a.GetParent<Factory>(); var scDesc = new SwapChainDescription(); scDesc.BufferCount = MyRender11Constants.BUFFER_COUNT; scDesc.Flags = SwapChainFlags.AllowModeSwitch; scDesc.IsWindowed = true; scDesc.ModeDescription.Format = MyRender11Constants.DX11_BACKBUFFER_FORMAT; scDesc.ModeDescription.Height = m_settings.BackBufferHeight; scDesc.ModeDescription.Width = m_settings.BackBufferWidth; scDesc.ModeDescription.RefreshRate.Numerator = m_settings.RefreshRate; scDesc.ModeDescription.RefreshRate.Denominator = 1000; scDesc.ModeDescription.Scaling = DisplayModeScaling.Unspecified; scDesc.ModeDescription.ScanlineOrdering = DisplayModeScanlineOrder.Progressive; scDesc.SampleDescription.Count = 1; scDesc.SampleDescription.Quality = 0; scDesc.OutputHandle = m_windowHandle; scDesc.Usage = Usage.RenderTargetOutput; scDesc.SwapEffect = SwapEffect.Discard; try { m_swapchain = new SwapChain(factory, Device, scDesc); } catch (Exception ex) { Log.WriteLine("SwapChain factory = " + factory); Log.WriteLine("SwapChain Device = " + Device); Log.WriteLine("SwapChainDescription.BufferCount = " + scDesc.BufferCount); Log.WriteLine("SwapChainDescription.Flags = " + scDesc.Flags); Log.WriteLine("SwapChainDescription.ModeDescription.Format = " + scDesc.ModeDescription.Format); Log.WriteLine("SwapChainDescription.ModeDescription.Height = " + scDesc.ModeDescription.Height); Log.WriteLine("SwapChainDescription.ModeDescription.Width = " + scDesc.ModeDescription.Width); Log.WriteLine("SwapChainDescription.ModeDescription.RefreshRate.Numerator = " + scDesc.ModeDescription.RefreshRate.Numerator); Log.WriteLine("SwapChainDescription.ModeDescription.RefreshRate.Denominator = " + scDesc.ModeDescription.RefreshRate.Denominator); Log.WriteLine("SwapChainDescription.ModeDescription.Scaling = " + scDesc.ModeDescription.Scaling); Log.WriteLine("SwapChainDescription.ModeDescription.ScanlineOrdering = " + scDesc.ModeDescription.ScanlineOrdering); Log.WriteLine("SwapChainDescription.SampleDescription.Count = " + scDesc.SampleDescription.Count); Log.WriteLine("SwapChainDescription.SampleDescription.Quality = " + scDesc.SampleDescription.Quality); Log.WriteLine("SwapChainDescription.BufferCount = " + scDesc.BufferCount); Log.WriteLine("SwapChainDescription.Usage = " + scDesc.Usage); Log.WriteLine("SwapChainDescription.SwapEffect = " + scDesc.SwapEffect); throw ex; } factory.MakeWindowAssociation(m_windowHandle, WindowAssociationFlags.IgnoreAll); } // we start with window always (DXGI recommended) Log.WriteLine("CreateDeviceInteral Apply Settings"); m_settings.WindowMode = MyWindowModeEnum.Window; ApplySettings(settings); Log.WriteLine("CreateDeviceInteral done (" + m_settings + ")"); return(m_settings); }
public DirectXCanvas() { InitializeComponent(); RenderCanvas = new RenderControl(); RenderForm.Child = RenderCanvas; SwapChainDesc = new SwapChainDescription() { BufferCount = 2, ModeDescription = new ModeDescription(RenderCanvas.ClientSize.Width, RenderCanvas.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = RenderCanvas.Handle, SampleDescription = new SampleDescription(4, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, }; SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, SwapChainDesc, out device, out swapChain); SwapChain = swapChain; RenderDevice = device; RenderFactory = SwapChain.GetParent <Factory>(); RenderFactory.MakeWindowAssociation(RenderCanvas.Handle, WindowAssociationFlags.IgnoreAll); RenderDevice.ImmediateContext.Rasterizer.State = new RasterizerState(RenderDevice, RasterizerDesc); WPConstantBuffer = SharpDX.Direct3D11.Buffer.Create(RenderDevice, BindFlags.ConstantBuffer, ref WP); DefaultFragment = LoadFragment(@"Basic.fx", new[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 8, 0) }); TextFragment = LoadFragment(@"Text.fx", new[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 8, 0), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 16, 0) }); Text = new TextManager(this); TextSamplerState = new SamplerState(device, TextSamplerDescription); BlendStateDescription blendDescription = new BlendStateDescription(); blendDescription.RenderTarget[0] = AlphaBlendStateDescription; AlphaBlendState = new BlendState(device, blendDescription); RenderCanvas.Paint += RenderCanvas_Paint; RenderCanvas.Resize += RenderCanvas_Resize; UnitView = SharpDX.Matrix.Scaling(2.0f, -2.0f, 1.0f); UnitView.TranslationVector = new Vector3(-1.0f, 1.0f, 0.0f); OnResize(); }
public void Reset( Device device ) { chain.Dispose( ); chain = new SwapChain( device, presentParams ); }
public RenderTarget( Device device, PresentParameters param ) { presentParams = param; renderWindow = presentParams.DeviceWindow; chain = new SwapChain( device, presentParams ); }
public static void Create(SwapChain p, RawRectangleF m)//parent,margin { if (sp != null) { ReSize(m); return; } SetNav(0); Parent = p; nav = new ListBox(); nav.Hrizon = true; int c = nav_data.Length; for (int i = 0; i < c; i++) { nav.Data.Add(nav_data[i].title[0]); } nav.SelectedIndex = 0; nav.ItemWidth = 60; nav.Forground = new RawColor4(0.8f, 0.8f, 0.8f, 1); nav.BorderColor = new RawColor4(0, 0, 0, 1); nav.Background = new RawColor4(0.6f, 0.4725f, 0.4725f, 0.8f); RoundBorder rb = new RoundBorder(); rb.RoundRect.RadiusX = 8; rb.RoundRect.RadiusY = 8; rb.Size = new Size2F(60, 20); rb.FillBrush = BrushManage.GetLinearA(); nav.FillTemplate = rb; nav.SelectChanged = (o) => { var lb = o as ListBox; if (lb.SelectedIndex < 0) { return; } if (lb.SelectedIndex >= 12) { return; } FilterPanel.Visble = false; for (int ss = 0; ss < sp.Data.Count; ss++) { (sp.Data[ss] as IDisposable).Dispose(); } sp.Data.Clear(); part = 0; TextBar[1].Text = "1"; SetNav(lb.SelectedIndex); }; nav.ItemClick = (o) => { ShowOrHideFilter(); }; FilterPanel = new UIViewPort(); FilterPanel.Visble = false; FilterPanel.GaussianBack = true; FilterPanel.Background = new RawColor4(0, 0.1f, 0.2f, 0.4f); sp = new GridPanel(); sp.ItemTemplate = DataMod.GetTemplate(); sp.BorderColor = new RawColor4(0, 0, 0, 1); create = true; sp.ItemClick = (o, e) => { if (sp.ClickIndex < 0) { return; } string href = (sp.Data[sp.ClickIndex] as DataMod).href; if (href != null) { VideoPage.SetAddress(href); } PageManageEx.CreateNewPage(PageTag.videopage); }; lock (p.DX_Child) { p.DX_Child.Add(sp); p.DX_Child.Add(nav); p.DX_Child.Add(FilterPanel); } CreateBar(p); ReSize(m); if (load) { Analyze(); } }
//static Border bk_ground; public static void Initial(SwapChain swap) { Swap = swap; PageManageEx.Initial(swap); PageManageEx.CreateNewPage(PageTag.main); }
public void Initialize(Int32 width, Int32 height, IntPtr outputHandle) { // provide a convinent syntax that ensures the correct use of IDisposable objects // only factory is enabled in this scope using (var factory = new Factory4()) { m_Desc = new SwapChainDescription() { BufferCount = FrameCount, ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, OutputHandle = outputHandle, SwapEffect = SwapEffect.FlipDiscard, SampleDescription = new SampleDescription(1, 0), //@TODO enable 4xMSAA IsWindowed = true, }; using (var tempSwapChain = new SwapChain(factory, m_CommandListPoolRef.CommandQueue, m_Desc)) // @TODO - temporary //CommandQueue cmdQueue = H1Global<H1ManagedRenderer>.Instance.m_CommandQueue; //using (var tempSwapChain = new SwapChain(factory, cmdQueue, m_Desc)) { m_DXGISwapChain = tempSwapChain.QueryInterface <SwapChain3>(); } } // set the back buffer resources for (Int32 n = 0; n < FrameCount; ++n) { m_BackBuffers.Add(m_DXGISwapChain.GetBackBuffer <SharpDX.Direct3D12.Resource>(n)); } // @TODO need to move this chunk of codes to SwapChain #region Temp //@TODO - temp //H1DX12Device deviceDX12 = m_CommandListPoolRef.Device; H1DX12Device deviceDX12 = H1Global <H1ManagedRenderer> .Instance.Dx12Device; // create RTV descriptor heap deviceDX12.RenderTargetDescriptorCache.Initialize(deviceDX12.Device, FrameCount, false, H1ViewType.RenderTargetView); // create DSV descriptor heap deviceDX12.DepthStencilDescriptorCache.Initialize(deviceDX12.Device, 1, false, H1ViewType.DepthStencilView); // create CBV descriptor heap //H1DescriptorHeap generalHeap = new H1DescriptorHeap(); //generalHeap.Initialize(m_Device, 2, true, H1ViewType.ConstantBufferView); //m_GlobalDescriptorHeaps.Add(generalHeap); // create frame resource // 1. RTV for (Int32 n = 0; n < FrameCount; ++n) { // get available alloc cpu address (internally update cursor in H1DescriptorHeap) CpuDescriptorHandle rtvHandle = deviceDX12.RenderTargetDescriptorCache.GetAvailableAllocCpuAddress(); SharpDX.Direct3D12.Resource resourceForRTV = GetBackBuffer(n); deviceDX12.Device.CreateRenderTargetView(resourceForRTV, null, rtvHandle); } // 2. DSV DepthStencilViewDescription dsvDesc = new DepthStencilViewDescription(); dsvDesc.Format = SharpDX.DXGI.Format.D32_Float; dsvDesc.Dimension = DepthStencilViewDimension.Texture2D; dsvDesc.Flags = DepthStencilViewFlags.None; ClearValue depthOptimizedClearValue = new ClearValue(); depthOptimizedClearValue.Format = SharpDX.DXGI.Format.D32_Float; depthOptimizedClearValue.DepthStencil.Depth = 1.0f; depthOptimizedClearValue.DepthStencil.Stencil = 0; m_DepthStencil = deviceDX12.Device.CreateCommittedResource( new HeapProperties(HeapType.Default), HeapFlags.None, ResourceDescription.Texture2D(SharpDX.DXGI.Format.D32_Float, width, height, 1, 0, 1, 0, ResourceFlags.AllowDepthStencil), ResourceStates.DepthWrite, depthOptimizedClearValue); CpuDescriptorHandle dsvHandle = deviceDX12.DepthStencilDescriptorCache.GetAvailableAllocCpuAddress(); deviceDX12.Device.CreateDepthStencilView(m_DepthStencil, dsvDesc, dsvHandle); #endregion }
public static Texture2D FromSwapChain(SwapChain swapChain, int index) { return(swapChain.GetBuffer(index)); }
/// <summary> /// Init device and required resources /// </summary> private void InitDevice() { // device creation device = D3DDevice.CreateDeviceAndSwapChain(host.Handle); swapChain = device.SwapChain; deviceContext = device.ImmediateContext; SetViews(); // vertex shader & layout // Open precompiled vertex shader // This file was compiled using: fxc Render.hlsl /T vs_4_0 /EVertShader /FoRender.vs using (Stream stream = Application.ResourceAssembly.GetManifestResourceStream("Microsoft.WindowsAPICodePack.Samples.Direct3D11.Render.vs")) { vertexShader = device.CreateVertexShader(stream); deviceContext.VS.Shader = vertexShader; // input layout is for the vert shader InputElementDescription inputElementDescription = new InputElementDescription(); inputElementDescription.SemanticName = "POSITION"; inputElementDescription.SemanticIndex = 0; inputElementDescription.Format = Format.R32G32B32Float; inputElementDescription.InputSlot = 0; inputElementDescription.AlignedByteOffset = 0; inputElementDescription.InputSlotClass = InputClassification.PerVertexData; inputElementDescription.InstanceDataStepRate = 0; stream.Position = 0; InputLayout inputLayout = device.CreateInputLayout( new InputElementDescription[] { inputElementDescription }, stream); deviceContext.IA.InputLayout = inputLayout; } // Open precompiled vertex shader // This file was compiled using: fxc Render.hlsl /T ps_4_0 /EPixShader /FoRender.ps using (Stream stream = Application.ResourceAssembly.GetManifestResourceStream("Microsoft.WindowsAPICodePack.Samples.Direct3D11.Render.ps")) { pixelShader = device.CreatePixelShader(stream); } deviceContext.PS.SetShader(pixelShader, null); // create some geometry to draw (1 triangle) SimpleVertexArray vertex = new SimpleVertexArray(); // put the vertices into a vertex buffer BufferDescription bufferDescription = new BufferDescription(); bufferDescription.Usage = Usage.Default; bufferDescription.ByteWidth = (uint)Marshal.SizeOf(vertex); bufferDescription.BindingOptions = BindingOptions.VertexBuffer; SubresourceData subresourceData = new SubresourceData(); IntPtr vertexData = Marshal.AllocCoTaskMem(Marshal.SizeOf(vertex)); Marshal.StructureToPtr(vertex, vertexData, false); subresourceData.SystemMemory = vertexData; vertexBuffer = device.CreateBuffer(bufferDescription, subresourceData); deviceContext.IA.SetVertexBuffers(0, new D3DBuffer[] { vertexBuffer }, new uint[] { 12 }, new uint[] { 0 }); deviceContext.IA.PrimitiveTopology = PrimitiveTopology.TriangleList; Marshal.FreeCoTaskMem(vertexData); }
public void End() { //Present the backbuffer to the screen SwapChain.Present(true); }
/// <summary> /// Initializes a new instance of the <see cref = "T:SharpDX.Direct3D10.Device1" /> class along with a new <see cref = "T:SharpDX.DXGI.SwapChain" /> used for rendering. /// </summary> /// <param name = "adapter">The video adapter on which the device should be created.</param> /// <param name = "flags">A list of runtime layers to enable.</param> /// <param name = "swapChainDescription">Details used to create the swap chain.</param> /// <param name="featureLevel">Desired feature level</param> /// <param name = "device">When the method completes, contains the created device instance.</param> /// <param name = "swapChain">When the method completes, contains the created swap chain instance.</param> /// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns> public static void CreateWithSwapChain(Adapter adapter, DeviceCreationFlags flags, SwapChainDescription swapChainDescription, FeatureLevel featureLevel, out Device1 device, out SwapChain swapChain) { CreateWithSwapChain(adapter, DriverType.Hardware, flags, swapChainDescription, featureLevel, out device, out swapChain); }
/// <summary> /// Our present hook that will grab a copy of the backbuffer when requested. Note: this supports multi-sampling (anti-aliasing) /// </summary> /// <param name="swapChainPtr"></param> /// <param name="syncInterval"></param> /// <param name="flags"></param> /// <returns>The HRESULT of the original method</returns> int PresentHook(IntPtr swapChainPtr, int syncInterval, PresentFlags flags) { if (swapChainPtr != _swapChainPointer) { _swapChain = SlimDX.DXGI.SwapChain.FromPointer(swapChainPtr); } SwapChain swapChain = _swapChain; { try { #region Screenshot Request if (this.Request != null) { try { this.DebugMessage("PresentHook: Request Start"); DateTime startTime = DateTime.Now; using (Texture2D texture = Texture2D.FromSwapChain <Texture2D>(swapChain, 0)) { #region Determine region to capture System.Drawing.Rectangle regionToCapture = new System.Drawing.Rectangle(0, 0, texture.Description.Width, texture.Description.Height); if (this.Request.RegionToCapture.Width > 0) { regionToCapture = this.Request.RegionToCapture; } #endregion var theTexture = texture; // If texture is multisampled, then we can use ResolveSubresource to copy it into a non-multisampled texture Texture2D textureResolved = null; if (texture.Description.SampleDescription.Count > 1) { this.DebugMessage("PresentHook: resolving multi-sampled texture"); // texture is multi-sampled, lets resolve it down to single sample textureResolved = new Texture2D(texture.Device, new Texture2DDescription() { CpuAccessFlags = CpuAccessFlags.None, Format = texture.Description.Format, Height = texture.Description.Height, Usage = ResourceUsage.Default, Width = texture.Description.Width, ArraySize = 1, SampleDescription = new SampleDescription(1, 0), // Ensure single sample BindFlags = BindFlags.None, MipLevels = 1, OptionFlags = texture.Description.OptionFlags }); // Resolve into textureResolved texture.Device.ResolveSubresource(texture, 0, textureResolved, 0, texture.Description.Format); // Make "theTexture" be the resolved texture theTexture = textureResolved; } // Create destination texture Texture2D textureDest = new Texture2D(texture.Device, new Texture2DDescription() { CpuAccessFlags = CpuAccessFlags.None, // CpuAccessFlags.Write | CpuAccessFlags.Read, Format = Format.R8G8B8A8_UNorm, // Supports BMP/PNG Height = regionToCapture.Height, Usage = ResourceUsage.Default, // ResourceUsage.Staging, Width = regionToCapture.Width, ArraySize = 1, //texture.Description.ArraySize, SampleDescription = new SampleDescription(1, 0), // texture.Description.SampleDescription, BindFlags = BindFlags.None, MipLevels = 1, //texture.Description.MipLevels, OptionFlags = texture.Description.OptionFlags }); // Copy the subresource region, we are dealing with a flat 2D texture with no MipMapping, so 0 is the subresource index theTexture.Device.CopySubresourceRegion(theTexture, 0, new ResourceRegion() { Top = regionToCapture.Top, Bottom = regionToCapture.Bottom, Left = regionToCapture.Left, Right = regionToCapture.Right, Front = 0, Back = 1 // Must be 1 or only black will be copied }, textureDest, 0, 0, 0, 0); // Note: it would be possible to capture multiple frames and process them in a background thread // Copy to memory and send back to host process on a background thread so that we do not cause any delay in the rendering pipeline Guid requestId = this.Request.RequestId; // this.Request gets set to null, so copy the RequestId for use in the thread ThreadPool.QueueUserWorkItem(delegate { //FileStream fs = new FileStream(@"c:\temp\temp.bmp", FileMode.Create); //Texture2D.ToStream(testSubResourceCopy, ImageFileFormat.Bmp, fs); DateTime startCopyToSystemMemory = DateTime.Now; using (MemoryStream ms = new MemoryStream()) { Texture2D.ToStream(textureDest, ImageFileFormat.Bmp, ms); ms.Position = 0; this.DebugMessage("PresentHook: Copy to System Memory time: " + (DateTime.Now - startCopyToSystemMemory).ToString()); DateTime startSendResponse = DateTime.Now; SendResponse(ms, requestId); this.DebugMessage("PresentHook: Send response time: " + (DateTime.Now - startSendResponse).ToString()); } // Free the textureDest as we no longer need it. textureDest.Dispose(); textureDest = null; this.DebugMessage("PresentHook: Full Capture time: " + (DateTime.Now - startTime).ToString()); }); // Make sure we free up the resolved texture if it was created if (textureResolved != null) { textureResolved.Dispose(); textureResolved = null; } } this.DebugMessage("PresentHook: Copy BackBuffer time: " + (DateTime.Now - startTime).ToString()); this.DebugMessage("PresentHook: Request End"); } finally { // Prevent the request from being processed a second time this.Request = null; } } #endregion #region Example: Draw overlay (after screenshot so we don't capture overlay as well) if (this.ShowOverlay) { using (Texture2D texture = Texture2D.FromSwapChain <SlimDX.Direct3D10.Texture2D>(swapChain, 0)) { if (_lastFrame != null) { FontDescription fd = new SlimDX.Direct3D10.FontDescription() { Height = 16, FaceName = "Times New Roman", IsItalic = false, Width = 0, MipLevels = 1, CharacterSet = SlimDX.Direct3D10.FontCharacterSet.Default, Precision = SlimDX.Direct3D10.FontPrecision.Default, Quality = SlimDX.Direct3D10.FontQuality.Antialiased, PitchAndFamily = FontPitchAndFamily.Default | FontPitchAndFamily.DontCare }; using (Font font = new Font(texture.Device, fd)) { DrawText(font, new Vector2(100, 100), String.Format("{0}", DateTime.Now), new Color4(System.Drawing.Color.Red.R, System.Drawing.Color.Red.G, System.Drawing.Color.Red.B, System.Drawing.Color.Red.A)); } } _lastFrame = DateTime.Now; } } #endregion } catch (Exception e) { // If there is an error we do not want to crash the hooked application, so swallow the exception this.DebugMessage("PresentHook: Exeception: " + e.GetType().FullName + ": " + e.Message); } // As always we need to call the original method, note that EasyHook has already repatched the original method // so calling it here will not cause an endless recursion to this function return(swapChain.Present(syncInterval, flags).Code); } }
/// <summary> /// Our present hook that will grab a copy of the backbuffer when requested. Note: this supports multi-sampling (anti-aliasing) /// </summary> /// <param name="swapChainPtr"></param> /// <param name="syncInterval"></param> /// <param name="flags"></param> /// <returns>The HRESULT of the original method</returns> int PresentHook(IntPtr swapChainPtr, int syncInterval, SharpDX.DXGI.PresentFlags flags) { this.Frame(); SwapChain swapChain = (SharpDX.DXGI.SwapChain)swapChainPtr; try { #region Screenshot Request if (this.Request != null) { this.DebugMessage("PresentHook: Request Start"); DateTime startTime = DateTime.Now; using (Texture2D texture = Texture2D.FromSwapChain <Texture2D>(swapChain, 0)) { #region Determine region to capture System.Drawing.Rectangle regionToCapture = new System.Drawing.Rectangle(0, 0, texture.Description.Width, texture.Description.Height); if (this.Request.RegionToCapture.Width > 0) { regionToCapture = this.Request.RegionToCapture; } #endregion var theTexture = texture; // If texture is multisampled, then we can use ResolveSubresource to copy it into a non-multisampled texture Texture2D textureResolved = null; if (texture.Description.SampleDescription.Count > 1) { this.DebugMessage("PresentHook: resolving multi-sampled texture"); // texture is multi-sampled, lets resolve it down to single sample textureResolved = new Texture2D(texture.Device, new Texture2DDescription() { CpuAccessFlags = CpuAccessFlags.None, Format = texture.Description.Format, Height = texture.Description.Height, Usage = ResourceUsage.Default, Width = texture.Description.Width, ArraySize = 1, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), // Ensure single sample BindFlags = BindFlags.None, MipLevels = 1, OptionFlags = texture.Description.OptionFlags }); // Resolve into textureResolved texture.Device.ImmediateContext.ResolveSubresource(texture, 0, textureResolved, 0, texture.Description.Format); // Make "theTexture" be the resolved texture theTexture = textureResolved; } // Create destination texture Texture2D textureDest = new Texture2D(texture.Device, new Texture2DDescription() { CpuAccessFlags = CpuAccessFlags.None, // CpuAccessFlags.Write | CpuAccessFlags.Read, Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm, // Supports BMP/PNG Height = regionToCapture.Height, Usage = ResourceUsage.Default, // ResourceUsage.Staging, Width = regionToCapture.Width, ArraySize = 1, //texture.Description.ArraySize, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), // texture.Description.SampleDescription, BindFlags = BindFlags.None, MipLevels = 1, //texture.Description.MipLevels, OptionFlags = texture.Description.OptionFlags }); // Copy the subresource region, we are dealing with a flat 2D texture with no MipMapping, so 0 is the subresource index theTexture.Device.ImmediateContext.CopySubresourceRegion(theTexture, 0, new ResourceRegion() { Top = regionToCapture.Top, Bottom = regionToCapture.Bottom, Left = regionToCapture.Left, Right = regionToCapture.Right, Front = 0, Back = 1 // Must be 1 or only black will be copied }, textureDest, 0, 0, 0, 0); // Note: it would be possible to capture multiple frames and process them in a background thread // Copy to memory and send back to host process on a background thread so that we do not cause any delay in the rendering pipeline Guid requestId = this.Request.RequestId; // this.Request gets set to null, so copy the RequestId for use in the thread ThreadPool.QueueUserWorkItem(delegate { //FileStream fs = new FileStream(@"c:\temp\temp.bmp", FileMode.Create); //Texture2D.ToStream(testSubResourceCopy, ImageFileFormat.Bmp, fs); DateTime startCopyToSystemMemory = DateTime.Now; using (MemoryStream ms = new MemoryStream()) { Texture2D.ToStream(textureDest.Device.ImmediateContext, textureDest, ImageFileFormat.Bmp, ms); ms.Position = 0; this.DebugMessage("PresentHook: Copy to System Memory time: " + (DateTime.Now - startCopyToSystemMemory).ToString()); DateTime startSendResponse = DateTime.Now; ProcessCapture(ms, requestId); this.DebugMessage("PresentHook: Send response time: " + (DateTime.Now - startSendResponse).ToString()); } // Free the textureDest as we no longer need it. textureDest.Dispose(); textureDest = null; this.DebugMessage("PresentHook: Full Capture time: " + (DateTime.Now - startTime).ToString()); }); // Prevent the request from being processed a second time this.Request = null; // Make sure we free up the resolved texture if it was created if (textureResolved != null) { textureResolved.Dispose(); textureResolved = null; } } this.DebugMessage("PresentHook: Copy BackBuffer time: " + (DateTime.Now - startTime).ToString()); this.DebugMessage("PresentHook: Request End"); } #endregion #if OVERLAYENGINE #region Draw overlay (after screenshot so we don't capture overlay as well) if (this.Config.ShowOverlay) { // Initialise Overlay Engine if (_swapChainPointer != swapChain.NativePointer || _overlayEngine == null) { if (_overlayEngine != null) { _overlayEngine.Dispose(); } _overlayEngine = new DX11.DXOverlayEngine(); _overlayEngine.Overlays.Add(new Capture.Hook.Common.Overlay { Elements = { //new Capture.Hook.Common.TextElement(new System.Drawing.Font("Times New Roman", 22)) { Text = "Test", Location = new System.Drawing.Point(200, 200), Color = System.Drawing.Color.Yellow, AntiAliased = false}, new Capture.Hook.Common.FramesPerSecond(new System.Drawing.Font("Arial", 16)) { Location = new System.Drawing.Point(5, 5), Color = System.Drawing.Color.Red, AntiAliased = true } } }); _overlayEngine.Initialise(swapChain); _swapChainPointer = swapChain.NativePointer; } // Draw Overlay(s) else if (_overlayEngine != null) { foreach (var overlay in _overlayEngine.Overlays) { overlay.Frame(); } _overlayEngine.Draw(); } } #endregion #endif } catch (Exception e) { // If there is an error we do not want to crash the hooked application, so swallow the exception this.DebugMessage("PresentHook: Exeception: " + e.GetType().FullName + ": " + e.ToString()); //return unchecked((int)0x8000FFFF); //E_UNEXPECTED } // As always we need to call the original method, note that EasyHook has already repatched the original method // so calling it here will not cause an endless recursion to this function swapChain.Present(syncInterval, flags); return(SharpDX.Result.Ok.Code); }
public DXGISwapChain(SwapChain swapchain) { m_swapChain = swapchain; }
/// <summary> /// Our present hook that will grab a copy of the backbuffer when requested. Note: this supports multi-sampling (anti-aliasing) /// </summary> /// <param name="swapChainPtr"></param> /// <param name="syncInterval"></param> /// <param name="flags"></param> /// <returns>The HRESULT of the original method</returns> int PresentHook(IntPtr swapChainPtr, int syncInterval, SharpDX.DXGI.PresentFlags flags) { this.Frame(); SwapChain swapChain = (SharpDX.DXGI.SwapChain)swapChainPtr; try { #region Screenshot Request if (this.Request != null) { this.DebugMessage("PresentHook: Request Start"); DateTime startTime = DateTime.Now; using (Texture2D currentRT = Texture2D.FromSwapChain <Texture2D>(swapChain, 0)) { #region Determine region to capture Rectangle captureRegion = new Rectangle(0, 0, currentRT.Description.Width, currentRT.Description.Height); if (this.Request.RegionToCapture.Width > 0) { captureRegion = new Rectangle(this.Request.RegionToCapture.Left, this.Request.RegionToCapture.Top, this.Request.RegionToCapture.Right, this.Request.RegionToCapture.Bottom); } else if (this.Request.Resize.HasValue) { captureRegion = new Rectangle(0, 0, this.Request.Resize.Value.Width, this.Request.Resize.Value.Height); } #endregion // Create / Recreate resources as necessary EnsureResources(currentRT.Device, currentRT.Description, captureRegion, Request); Texture2D sourceTexture = null; // If texture is multisampled, then we can use ResolveSubresource to copy it into a non-multisampled texture if (currentRT.Description.SampleDescription.Count > 1 || Request.Resize.HasValue) { if (Request.Resize.HasValue) { this.DebugMessage("PresentHook: resizing texture"); } else { this.DebugMessage("PresentHook: resolving multi-sampled texture"); } // Resolve into _resolvedRT if (_resolvedRTKeyedMutex != null) { _resolvedRTKeyedMutex.Acquire(0, int.MaxValue); } currentRT.Device.ImmediateContext.ResolveSubresource(currentRT, 0, _resolvedRT, 0, _resolvedRT.Description.Format); if (_resolvedRTKeyedMutex != null) { _resolvedRTKeyedMutex.Release(1); } if (Request.Resize.HasValue) { lock (_lock) { if (_resolvedRTKeyedMutex_Dev2 != null) { _resolvedRTKeyedMutex_Dev2.Acquire(1, int.MaxValue); } _saQuad.ShaderResource = _resolvedSRV; _saQuad.RenderTargetView = _resizedRTV; _saQuad.RenderTarget = _resizedRT; _saQuad.Render(); if (_resolvedRTKeyedMutex_Dev2 != null) { _resolvedRTKeyedMutex_Dev2.Release(0); } } // set sourceTexture to the resized RT sourceTexture = _resizedRT; } else { // Make sourceTexture be the resolved texture if (_resolvedRTShared != null) { sourceTexture = _resolvedRTShared; } else { sourceTexture = _resolvedRT; } } } else { // Copy the resource into the shared texture if (_resolvedRTKeyedMutex != null) { _resolvedRTKeyedMutex.Acquire(0, int.MaxValue); } currentRT.Device.ImmediateContext.CopySubresourceRegion(currentRT, 0, null, _resolvedRT, 0); if (_resolvedRTKeyedMutex != null) { _resolvedRTKeyedMutex.Release(1); } if (_resolvedRTShared != null) { sourceTexture = _resolvedRTShared; } else { sourceTexture = _resolvedRT; } } // Copy to memory and send back to host process on a background thread so that we do not cause any delay in the rendering pipeline _requestCopy = this.Request.Clone(); // this.Request gets set to null, so copy the Request for use in the thread // Prevent the request from being processed a second time this.Request = null; bool acquireLock = sourceTexture == _resolvedRTShared; ThreadPool.QueueUserWorkItem(new WaitCallback((o) => { // Acquire lock on second device if (acquireLock && _resolvedRTKeyedMutex_Dev2 != null) { _resolvedRTKeyedMutex_Dev2.Acquire(1, int.MaxValue); } lock (_lock) { // Copy the subresource region, we are dealing with a flat 2D texture with no MipMapping, so 0 is the subresource index sourceTexture.Device.ImmediateContext.CopySubresourceRegion(sourceTexture, 0, new ResourceRegion() { Top = captureRegion.Top, Bottom = captureRegion.Bottom, Left = captureRegion.Left, Right = captureRegion.Right, Front = 0, Back = 1 // Must be 1 or only black will be copied }, _finalRT, 0, 0, 0, 0); // Release lock upon shared surface on second device if (acquireLock && _resolvedRTKeyedMutex_Dev2 != null) { _resolvedRTKeyedMutex_Dev2.Release(0); } _finalRT.Device.ImmediateContext.End(_query); _queryIssued = true; while (_finalRT.Device.ImmediateContext.GetData(_query).ReadByte() != 1) { // Spin (usually only one cycle or no spin takes place) } DateTime startCopyToSystemMemory = DateTime.Now; try { DataBox db = default(DataBox); if (_requestCopy.Format == ImageFormat.PixelData) { db = _finalRT.Device.ImmediateContext.MapSubresource(_finalRT, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.DoNotWait); _finalRTMapped = true; } _queryIssued = false; try { using (MemoryStream ms = new MemoryStream()) { switch (_requestCopy.Format) { case ImageFormat.Bitmap: case ImageFormat.Jpeg: case ImageFormat.Png: ToStream(_finalRT.Device.ImmediateContext, _finalRT, _requestCopy.Format, ms); break; case ImageFormat.PixelData: if (db.DataPointer != IntPtr.Zero) { ProcessCapture(_finalRT.Description.Width, _finalRT.Description.Height, db.RowPitch, System.Drawing.Imaging.PixelFormat.Format32bppArgb, db.DataPointer, _requestCopy); } return; } ms.Position = 0; ProcessCapture(ms, _requestCopy); } } finally { this.DebugMessage("PresentHook: Copy to System Memory time: " + (DateTime.Now - startCopyToSystemMemory).ToString()); if (_finalRTMapped) { lock (_lock) { _finalRT.Device.ImmediateContext.UnmapSubresource(_finalRT, 0); _finalRTMapped = false; } } } } catch (SharpDX.SharpDXException exc) { // Catch DXGI_ERROR_WAS_STILL_DRAWING and ignore - the data isn't available yet } } })); // Note: it would be possible to capture multiple frames and process them in a background thread } this.DebugMessage("PresentHook: Copy BackBuffer time: " + (DateTime.Now - startTime).ToString()); this.DebugMessage("PresentHook: Request End"); } #endregion #region Draw overlay (after screenshot so we don't capture overlay as well) var displayOverlays = Overlays; if (this.Config.ShowOverlay && displayOverlays != null) { // Initialise Overlay Engine if (_swapChainPointer != swapChain.NativePointer || _overlayEngine == null || IsOverlayUpdatePending) { if (_overlayEngine != null) { _overlayEngine.Dispose(); } _overlayEngine = new DX11.DXOverlayEngine(); _overlayEngine.Overlays.AddRange((IEnumerable <IOverlay>)displayOverlays); _overlayEngine.Initialise(swapChain); _swapChainPointer = swapChain.NativePointer; IsOverlayUpdatePending = false; } // Draw Overlay(s) if (_overlayEngine != null) { foreach (var overlay in _overlayEngine.Overlays) { overlay.Frame(); } _overlayEngine.Draw(); } } #endregion } catch (Exception e) { // If there is an error we do not want to crash the hooked application, so swallow the exception this.DebugMessage("PresentHook: Exeception: " + e.GetType().FullName + ": " + e.ToString()); //return unchecked((int)0x8000FFFF); //E_UNEXPECTED } // As always we need to call the original method, note that EasyHook will automatically skip the hook and call the original method // i.e. calling it here will not cause a stack overflow into this function return(DXGISwapChain_PresentHook.Original(swapChainPtr, syncInterval, flags)); }
/// <summary> /// Initializes a new instance of the <see cref = "T:SharpDX.Direct3D10.Device1" /> class along with a new <see cref = "T:SharpDX.DXGI.SwapChain" /> used for rendering. /// </summary> /// <param name = "driverType">The type of device to create.</param> /// <param name = "flags">A list of runtime layers to enable.</param> /// <param name = "swapChainDescription">Details used to create the swap chain.</param> /// <param name="featureLevel">Desired feature level</param> /// <param name = "device">When the method completes, contains the created device instance.</param> /// <param name = "swapChain">When the method completes, contains the created swap chain instance.</param> /// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns> public static void CreateWithSwapChain(DriverType driverType, DeviceCreationFlags flags, SwapChainDescription swapChainDescription, FeatureLevel featureLevel, out Device1 device, out SwapChain swapChain) { CreateWithSwapChain(null, driverType, flags, swapChainDescription, featureLevel, out device, out swapChain); }
public void Dispose() { SwapChain.Dispose(); BackBufferTexture.Dispose(); }
/// <summary> /// スワップチェーンが変更された時に呼び出される /// </summary> /// <param name="device"></param> /// <param name="swapChain"></param> /// <param name="desc">変更後のスワップチェーン情報</param> internal void OnSwapChainResized(SharpDX.Direct3D11.Device device, SwapChain swapChain, SwapChainDescription desc) { }
public void Resize(int width, int height) { BackBufferTexture.Dispose(); SwapChain.ResizeBuffers(swapChainDescription1.BufferCount, width, height, Format.Unknown, SwapChainFlags.None); BackBufferTexture = Resource.FromSwapChain <Texture2D>(SwapChain, 0); }
/// <summary> /// Gets a swap chain back buffer. /// </summary> /// <typeparam name = "T">The type of the buffer.</typeparam> /// <param name = "swapChain">The swap chain to get the buffer from.</param> /// <param name = "index">The index of the desired buffer.</param> /// <returns>The buffer interface, or <c>null</c> on failure.</returns> public static T FromSwapChain <T>(SwapChain swapChain, int index) where T : Resource { return(swapChain.GetBackBuffer <T>(index)); }
static void RunDirectX(MainForm mainWnd, ref D3DDevice device, SwapChain swapChain, ref World blockWorld) { // Setup graphics pipeline // 0. Prepare buffers // Create vertex buffer var vertexData = blockWorld.Blocks; var vertexDataSize = Utilities.SizeOf(vertexData); var vertexBufferDesc = new BufferDescription() { /* Usage */ Usage = ResourceUsage.Default, /* ByteWidth */ SizeInBytes = vertexDataSize, /* BindFlags */ BindFlags = BindFlags.VertexBuffer, /* CPUAccessFlags */ CpuAccessFlags = CpuAccessFlags.None, /* MiscFlags */ OptionFlags = ResourceOptionFlags.None, /* StructureByteStride */ StructureByteStride = 0, }; var vertexBuffer = D3DBuffer.Create(device, vertexData, vertexBufferDesc); // Create constant buffer var constantData = new[] { Matrix.Identity }; var constantDataSize = constantData.Length * Utilities.SizeOf <Matrix>(); var constantBufferDesc = new BufferDescription() { /* Usage */ Usage = ResourceUsage.Default, /* ByteWidth */ SizeInBytes = constantDataSize, /* BindFlags */ BindFlags = BindFlags.ConstantBuffer, /* CPUAccessFlags */ CpuAccessFlags = CpuAccessFlags.None, /* MiscFlags */ OptionFlags = ResourceOptionFlags.None, /* StructureByteStride */ StructureByteStride = 0, }; var constantBuffer = D3DBuffer.Create(device, constantData, constantBufferDesc); var context = device.ImmediateContext; // 1. IA, VS, PS stage: Prepare shaders, bind buffers var vertexSize = Utilities.SizeOf <Vector4>() * 2; var vertexBuffers = new[] { vertexBuffer }; var vertexBufferStrides = new[] { vertexSize }; var vertexBufferOffsets = new[] { 0 }; var vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shader.fx", "VS", "vs_4_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shader.fx", "PS", "ps_4_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode); var inputLayout = new InputLayout(device, signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); context.InputAssembler.InputLayout = inputLayout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, vertexBuffers, vertexBufferStrides, vertexBufferOffsets); context.VertexShader.SetConstantBuffer(0, constantBuffer); context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); // 2. Rasterizer, OM stage: viewport, render targets & depth-stencil test. var viewport = new Viewport(0, 0, mainWnd.ClientSize.Width, mainWnd.ClientSize.Height, 0.0f, 1.0f); var backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); var depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = mainWnd.ClientSize.Width, Height = mainWnd.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); var renderView = new RenderTargetView(device, backBuffer); var depthView = new DepthStencilView(device, depthBuffer); context.Rasterizer.SetViewport(viewport); context.OutputMerger.SetTargets(depthView, renderView); // Setup transformations & control. var eye = new Vector3(0, 0, -10); var rotateWorld = 0.0f; var keyMap = new Dictionary <char, bool>(); keyMap['w'] = false; keyMap['s'] = false; keyMap['a'] = false; keyMap['d'] = false; keyMap['q'] = false; keyMap['e'] = false; var mouseBaseX = 0; var mouseBaseY = 0; var mousePosX = 0.0f; var mousePosY = 0.0f; var jump = 0.0f; var jumpVec = 0.0f; mainWnd.MouseMove += (sender, e) => { mousePosX = ((e.X + mainWnd.ClientSize.Width - mouseBaseX) % mainWnd.ClientSize.Width) * 1.0f / mainWnd.ClientSize.Width; mousePosY = ((e.Y + mainWnd.ClientSize.Height - mouseBaseY) % mainWnd.ClientSize.Height) * 1.0f / mainWnd.ClientSize.Height; mainWnd.debugText.Text = "X: " + e.X + "\tY: " + e.Y + "\r\nPX: " + mousePosX + "\tPY: " + mousePosY + "\r\nJump: " + jump + "\tVec: " + jumpVec; }; mainWnd.KeyDown += (sender, args) => { if (args.KeyCode == Keys.W) { keyMap['w'] = true; } else if (args.KeyCode == Keys.S) { keyMap['s'] = true; } else if (args.KeyCode == Keys.A) { keyMap['a'] = true; } else if (args.KeyCode == Keys.D) { keyMap['d'] = true; } else if (args.KeyCode == Keys.Q) { keyMap['q'] = true; } else if (args.KeyCode == Keys.E) { keyMap['e'] = true; } else if (args.KeyCode == Keys.Space) { jumpVec = 10.0f; } }; mainWnd.KeyUp += (sender, args) => { if (args.KeyCode == Keys.W) { keyMap['w'] = false; } else if (args.KeyCode == Keys.S) { keyMap['s'] = false; } else if (args.KeyCode == Keys.A) { keyMap['a'] = false; } else if (args.KeyCode == Keys.D) { keyMap['d'] = false; } else if (args.KeyCode == Keys.Q) { keyMap['q'] = false; } else if (args.KeyCode == Keys.E) { keyMap['e'] = false; } else if (args.KeyCode == Keys.Escape) { mainWnd.Close(); } }; // Render. var vertexCount = vertexBuffer.Description.SizeInBytes / vertexSize; RenderLoop.Run(mainWnd, () => { if (keyMap['w']) { eye.X += 1.5f / 60.0f; } if (keyMap['s']) { eye.X -= 1.5f / 60.0f; } if (keyMap['a']) { eye.Y += 1.5f / 60.0f; } if (keyMap['d']) { eye.Y -= 1.5f / 60.0f; } if (keyMap['q']) { rotateWorld += 0.1f / 60.0f; } if (keyMap['e']) { rotateWorld -= 0.1f / 60.0f; } // Clear views. context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); context.ClearRenderTargetView(renderView, Color.Black); // Update world data. if (jump > 0.0f || (jump == 0.0f && jumpVec != 0.0f)) { jump += jumpVec / 60.0f / 3.0f; jumpVec += -9.8f / 60.0f / 3.0f; } else { jump = jumpVec = 0.0f; } var ray = new Vector3(eye.X, eye.Y + 1.0f, eye.Z - jump) - new Vector3(eye.X, eye.Y, eye.Z - jump); var proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, mainWnd.ClientSize.Width / (float)mainWnd.ClientSize.Height, 0.1f, 100.0f); var view = Matrix.LookAtLH(new Vector3(eye.X, eye.Y, eye.Z - jump), new Vector3(eye.X, eye.Y + 1.0f, eye.Z - jump), new Vector3(0, 0, 1)); var world = Matrix.RotationZ(rotateWorld); var matrix = world * (view * Matrix.RotationY(mousePosX * 2.0f * (float)Math.PI) * Matrix.RotationX(-mousePosY * 2.0f * (float)Math.PI)) * proj; matrix.Transpose(); context.UpdateSubresource(ref matrix, constantBuffer); // Draw. context.Draw(vertexCount, 0); swapChain.Present(0, PresentFlags.None); }); }
private void LoadPipeline(RenderForm form) { int width = form.ClientSize.Width; int height = form.ClientSize.Height; viewport.Width = width; viewport.Height = height; viewport.MaxDepth = 1.0f; scissorRect.Right = width; scissorRect.Bottom = height; #if DEBUG // Enable the D3D12 debug layer. { DebugInterface.Get().EnableDebugLayer(); } #endif device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0); using (var factory = new Factory4()) { // Describe and create the command queue. var queueDesc = new CommandQueueDescription(CommandListType.Direct); commandQueue = device.CreateCommandQueue(queueDesc); // Describe and create the swap chain. var swapChainDesc = new SwapChainDescription() { BufferCount = FrameCount, ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, SwapEffect = SwapEffect.FlipDiscard, OutputHandle = form.Handle, //Flags = SwapChainFlags.None, SampleDescription = new SampleDescription(1, 0), IsWindowed = true }; var tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc); swapChain = tempSwapChain.QueryInterface <SwapChain3>(); tempSwapChain.Dispose(); frameIndex = swapChain.CurrentBackBufferIndex; } // Create descriptor heaps. // Describe and create a render target view (RTV) descriptor heap. var rtvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = FrameCount, Flags = DescriptorHeapFlags.None, Type = DescriptorHeapType.RenderTargetView }; renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc); rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView); // Describe and create a constant buffer view (CBV) descriptor heap. // Flags indicate that this descriptor heap can be bound to the pipeline // and that descriptors contained in it can be referenced by a root table. var cbvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; constantBufferViewHeap = device.CreateDescriptorHeap(cbvHeapDesc); // Create frame resources. var rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart; for (int n = 0; n < FrameCount; n++) { renderTargets[n] = swapChain.GetBackBuffer <Resource>(n); device.CreateRenderTargetView(renderTargets[n], null, rtvHandle); rtvHandle += rtvDescriptorSize; } commandAllocator = device.CreateCommandAllocator(CommandListType.Direct); }
/// <summary> /// Called after the normal create if this resource was created from a swapchain backbuffer. /// </summary> internal void CreateFromSwapChain(SwapChain swapChain, uint backbufferIndex) { CreateFromSwapChainImpl(swapChain, backbufferIndex); }
public void Release( ) { chain.Dispose( ); chain = null; presentParams = null; }
private SwapChain CreateSwapChainForUWP() { bufferCount = 2; var description = new SwapChainDescription1 { // Automatic sizing Width = Description.BackBufferWidth, Height = Description.BackBufferHeight, Format = (SharpDX.DXGI.Format)Description.BackBufferFormat.ToNonSRgb(), Stereo = false, SampleDescription = new SharpDX.DXGI.SampleDescription((int)Description.MultisampleCount, 0), Usage = Usage.BackBuffer | Usage.RenderTargetOutput, // Use two buffers to enable flip effect. BufferCount = bufferCount, Scaling = SharpDX.DXGI.Scaling.Stretch, SwapEffect = SharpDX.DXGI.SwapEffect.FlipSequential, }; SwapChain swapChain = null; switch (Description.DeviceWindowHandle.Context) { case Games.AppContextType.UWPXaml: { var nativePanel = ComObject.As <ISwapChainPanelNative>(Description.DeviceWindowHandle.NativeWindow); // Creates the swap chain for XAML composition swapChain = new SwapChain1(GraphicsAdapterFactory.NativeFactory, GraphicsDevice.NativeDevice, ref description); // Associate the SwapChainPanel with the swap chain nativePanel.SwapChain = swapChain; break; } case Games.AppContextType.UWPCoreWindow: { using (var dxgiDevice = GraphicsDevice.NativeDevice.QueryInterface <SharpDX.DXGI.Device2>()) { // Ensure that DXGI does not queue more than one frame at a time. This both reduces // latency and ensures that the application will only render after each VSync, minimizing // power consumption. dxgiDevice.MaximumFrameLatency = 1; // Next, get the parent factory from the DXGI Device. using (var dxgiAdapter = dxgiDevice.Adapter) using (var dxgiFactory = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>()) // Finally, create the swap chain. using (var coreWindow = new SharpDX.ComObject(Description.DeviceWindowHandle.NativeWindow)) { swapChain = new SharpDX.DXGI.SwapChain1(dxgiFactory , GraphicsDevice.NativeDevice, coreWindow, ref description); } } break; } default: throw new NotSupportedException(string.Format("Window context [{0}] not supported while creating SwapChain", Description.DeviceWindowHandle.Context)); } return(swapChain); }
public void Reset( Device device, PresentParameters param ) { presentParams = param; renderWindow = presentParams.DeviceWindow; chain.Dispose( ); chain = new SwapChain( device, param ); }
void CreateDeviceResources() { uint width = (uint)host.ActualWidth; uint height = (uint)host.ActualHeight; // If we don't have a device, need to create one now and all // accompanying D3D resources. CreateDevice(); Factory dxgiFactory = Factory.Create(); SwapChainDescription swapDesc = new SwapChainDescription { BufferDescription = new ModeDescription { Width = width, Height = height, Format = Format.R8G8B8A8UNorm, RefreshRate = new Rational { Numerator = 60, Denominator = 1 } }, SampleDescription = new SampleDescription { Count = 1, Quality = 0 }, BufferUsage = UsageOptions.RenderTargetOutput, BufferCount = 1, OutputWindowHandle = host.Handle, Windowed = true }; swapChain = dxgiFactory.CreateSwapChain( device, swapDesc); // Create rasterizer state object RasterizerDescription rsDesc = new RasterizerDescription(); rsDesc.AntiAliasedLineEnable = false; rsDesc.CullMode = CullMode.None; rsDesc.DepthBias = 0; rsDesc.DepthBiasClamp = 0; rsDesc.DepthClipEnable = true; rsDesc.FillMode = D3D10.FillMode.Solid; rsDesc.FrontCounterclockwise = false; // Must be FALSE for 10on9 rsDesc.MultisampleEnable = false; rsDesc.ScissorEnable = false; rsDesc.SlopeScaledDepthBias = 0; rasterizerState = device.CreateRasterizerState( rsDesc); device.RS.State = rasterizerState; // If we don't have a D2D render target, need to create all of the resources // required to render to one here. // Ensure that nobody is holding onto one of the old resources device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { null }); InitializeDepthStencil(width, height); // Create views on the RT buffers and set them on the device RenderTargetViewDescription renderDesc = new RenderTargetViewDescription(); renderDesc.Format = Format.R8G8B8A8UNorm; renderDesc.ViewDimension = RenderTargetViewDimension.Texture2D; Texture2DRenderTargetView renderView = renderDesc.Texture2D; renderView.MipSlice = 0; renderDesc.Texture2D = renderView; using (D3DResource spBackBufferResource = swapChain.GetBuffer <D3DResource>(0)) { renderTargetView = device.CreateRenderTargetView( spBackBufferResource, renderDesc); } device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { renderTargetView }, depthStencilView); SetViewport(width, height); // Create a D2D render target which can draw into the surface in the swap chain RenderTargetProperties props = new RenderTargetProperties( RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Premultiplied), 96, 96, RenderTargetUsages.None, FeatureLevel.Default); // Allocate a offscreen D3D surface for D2D to render our 2D content into Texture2DDescription tex2DDescription = new Texture2DDescription { ArraySize = 1, BindingOptions = BindingOptions.RenderTarget | BindingOptions.ShaderResource, CpuAccessOptions = CpuAccessOptions.None, Format = Format.R8G8B8A8UNorm, Height = 4096, Width = 512, MipLevels = 1, MiscellaneousResourceOptions = MiscellaneousResourceOptions.None, SampleDescription = new SampleDescription { Count = 1, Quality = 0 }, Usage = Usage.Default }; offscreenTexture = device.CreateTexture2D(tex2DDescription); using (Surface dxgiSurface = offscreenTexture.GraphicsSurface) { // Create a D2D render target which can draw into our offscreen D3D surface renderTarget = d2DFactory.CreateGraphicsSurfaceRenderTarget( dxgiSurface, props); } PixelFormat alphaOnlyFormat = new PixelFormat(Format.A8UNorm, AlphaMode.Premultiplied); opacityRenderTarget = renderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None, alphaOnlyFormat); // Load pixel shader // Open precompiled vertex shader // This file was compiled using DirectX's SDK Shader compilation tool: // fxc.exe /T fx_4_0 /Fo SciFiText.fxo SciFiText.fx shader = LoadResourceShader(device, "SciFiTextDemo.SciFiText.fxo"); // Obtain the technique technique = shader.GetTechniqueByName("Render"); // Obtain the variables worldMatrixVariable = shader.GetVariableByName("World").AsMatrix; viewMatrixVariable = shader.GetVariableByName("View").AsMatrix; projectionMarixVariable = shader.GetVariableByName("Projection").AsMatrix; diffuseVariable = shader.GetVariableByName("txDiffuse").AsShaderResource; // Create the input layout PassDescription passDesc = new PassDescription(); passDesc = technique.GetPassByIndex(0).Description; vertexLayout = device.CreateInputLayout( inputLayoutDescriptions, passDesc.InputAssemblerInputSignature, passDesc.InputAssemblerInputSignatureSize ); // Set the input layout device.IA.InputLayout = vertexLayout; IntPtr verticesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.VerticesInstance)); Marshal.StructureToPtr(VertexArray.VerticesInstance, verticesDataPtr, true); BufferDescription bd = new BufferDescription(); bd.Usage = Usage.Default; bd.ByteWidth = (uint)Marshal.SizeOf(VertexArray.VerticesInstance); bd.BindingOptions = BindingOptions.VertexBuffer; bd.CpuAccessOptions = CpuAccessOptions.None; bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None; SubresourceData InitData = new SubresourceData { SystemMemory = verticesDataPtr }; vertexBuffer = device.CreateBuffer(bd, InitData); Marshal.FreeHGlobal(verticesDataPtr); // Set vertex buffer uint stride = (uint)Marshal.SizeOf(typeof(SimpleVertex)); uint offset = 0; device.IA.SetVertexBuffers( 0, new D3DBuffer[] { vertexBuffer }, new uint[] { stride }, new uint[] { offset } ); IntPtr indicesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.IndicesInstance)); Marshal.StructureToPtr(VertexArray.IndicesInstance, indicesDataPtr, true); bd.Usage = Usage.Default; bd.ByteWidth = (uint)Marshal.SizeOf(VertexArray.IndicesInstance); bd.BindingOptions = BindingOptions.IndexBuffer; bd.CpuAccessOptions = CpuAccessOptions.None; bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None; InitData.SystemMemory = indicesDataPtr; facesIndexBuffer = device.CreateBuffer( bd, InitData ); Marshal.FreeHGlobal(indicesDataPtr); // Set primitive topology device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList; // Convert the D2D texture into a Shader Resource View textureResourceView = device.CreateShaderResourceView( offscreenTexture); // Initialize the world matrices worldMatrix = Matrix4x4F.Identity; // Initialize the view matrix Vector3F Eye = new Vector3F(0.0f, 0.0f, 13.0f); Vector3F At = new Vector3F(0.0f, -3.5f, 45.0f); Vector3F Up = new Vector3F(0.0f, 1.0f, 0.0f); viewMatrix = Camera.MatrixLookAtLH(Eye, At, Up); // Initialize the projection matrix projectionMatrix = Camera.MatrixPerspectiveFovLH( (float)Math.PI * 0.1f, width / (float)height, 0.1f, 100.0f); // Update Variables that never change viewMatrixVariable.Matrix = viewMatrix; projectionMarixVariable.Matrix = projectionMatrix; GradientStop[] gradientStops = { new GradientStop(0.0f, new ColorF(GetColorValues(System.Windows.Media.Colors.Yellow))), new GradientStop(1.0f, new ColorF(GetColorValues(System.Windows.Media.Colors.Black))) }; GradientStopCollection spGradientStopCollection = renderTarget.CreateGradientStopCollection( gradientStops, Gamma.StandardRgb, ExtendMode.Clamp); // Create a linear gradient brush for text textBrush = renderTarget.CreateLinearGradientBrush( new LinearGradientBrushProperties(new Point2F(0, 0), new Point2F(0, -2048)), spGradientStopCollection ); }