public void Dispose() { Debug.WriteLine("DeviceContextHolder.Dispose()"); DisposeHelper.Dispose(ref _states); Debug.WriteLine("_states disposed"); DisposeHelper.Dispose(ref _quadBuffers); Debug.WriteLine("_quadBuffers disposed"); _effects.DisposeEverything(); Debug.WriteLine("_effects disposed"); _helpers.DisposeEverything(); Debug.WriteLine("_helpers disposed"); _randomTextures.DisposeEverything(); Debug.WriteLine("_randomTextures disposed"); DisposeHelper.Dispose(ref _flatNmView); Debug.WriteLine("_flatNm disposed"); _something.Values.OfType <IDisposable>().DisposeEverything(); _something.Clear(); Debug.WriteLine("_something disposed"); DeviceContext.ClearState(); DeviceContext.Flush(); // we don’t need to dispose deviceContext — it’s the same as device Device.Dispose(); Debug.WriteLine("Device disposed"); }
/// <summary> /// Dispose of the window and other things once the app is closing to prevent memory leaks. /// </summary> public static void Dispose() { RenderTarget.Dispose(); SwapChain.Dispose(); Device.Dispose(); Form.Dispose(); }
private void disposeResources() { renderTargetView.Dispose(); BackBuffer.Dispose(); device.Dispose(); swapChain.Dispose(); }
protected override void DisposeOverride() { DiagnosticsWriter.WriteInformation("Disconnecting from device"); var resources = mResources?.ToArray() ?? new HardwareResource[0]; if (resources.Length > 0) { DiagnosticsWriter.WriteWarning("The is being disconnected from but there are still {0} associated resource(s) allocated. The resources will be disposed to avoid memory leaks", resources.Length); foreach (var resource in resources) { resource?.Dispose(); } } mResources?.Clear(); mResources = null; System.Diagnostics.Debug.Assert(!mDevice.Disposed); mDevice?.Dispose(); mFactory?.Dispose(); mDevice = null; mFactory = null; DiagnosticsWriter.WriteInformation("Disconnection completed."); }
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { ReleaseResources(); swapChain.Dispose(); device11.Dispose(); device11 = null; }
/// <summary> /// Releases various D3D COM resources. /// </summary> /// <param name="deviceAndSwapChain"> /// true to release the device and swapchain objects; otherwise false. /// </param> void ReleaseCOMObjects(bool deviceAndSwapChain) { if (renderTargetView != null) { renderTargetView.Dispose(); renderTargetView = null; } if (depthStencilView != null) { depthStencilView.Dispose(); depthStencilView = null; } if (depthStencilBuffer != null) { depthStencilBuffer.Dispose(); depthStencilBuffer = null; } if (deviceAndSwapChain) { if (swapChain != null) { swapChain.Dispose(); swapChain = null; } if (device != null) { if (Context.Rasterizer.State != null) { Context.Rasterizer.State.Dispose(); } device.Dispose(); device = null; } } }
static void Main(string[] args) { // Setup var form = SlimDXHelper.InitD3D(out _device, out _swapChain, out _renderView); var temp = form.ClientRectangle; _finalRender = new FSQ(_device, _renderView, "SimpleFSQ.fx"); /*_simulation = * new HybridFluidSim( * _finalRender, * _device);*/ _simulation = new SemiGridSPHSimulation(_device, _finalRender.UAV); //_simulation = new MovingGridFluid.MovingGridFluid(_device, _finalRender.UAV); // Main loop MessagePump.Run(form, SimMain); // Tear down _finalRender.Dispose(); _swapChain.Dispose(); _renderView.Dispose(); _simulation.Dispose(); _device.Dispose(); }
private void DisposeDevice() { UnloadContent(); RenderTarget.Dispose(); GraphicsDevice.ImmediateContext.Rasterizer.State.Dispose(); GraphicsDevice.Dispose(); SwapChain.Dispose(); }
public void Dispose() { foreach (ShaderResourceView srv in textureDictionary.Values) { srv.Dispose(); } device.Dispose(); }
public static void Terminate(ref Factory dxgiFactory, ref SlimDX.Direct3D11.Device d3d11Device) { d3d11Device.Dispose(); d3d11Device = null; dxgiFactory.Dispose(); dxgiFactory = null; }
public void ShutDown() { depthStencil.Dispose(); depthStencilTexture.Dispose(); renderTarget.Dispose(); backBufferTexture.Dispose(); swapChain.Dispose(); device.Dispose(); }
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { layout.Dispose(); effect.Dispose(); renderTargetView.Dispose(); backBuffer.Dispose(); swapChain.Dispose(); device11.Dispose(); device11 = null; }
public void Dispose() { foreach (var rt in m_RenderTargets) { rt.Dispose(); } UnloadCommonContent(); m_Device.Dispose(); }
private void DisposeDevice() { UnloadContent(); factor?.Dispose(); device.ImmediateContext.OutputMerger.BlendState?.Dispose(); device.ImmediateContext?.Dispose(); depthStencil?.Dispose(); renderTarget?.Dispose(); device?.Dispose(); swapChain?.Dispose(); }
internal void Dispose() { profileVertexBuffer.Dispose(); depthView.Dispose(); renderView.Dispose(); depthBuffer.Dispose(); backBuffer.Dispose(); device.Dispose(); swapChain.SetFullScreenState(false, null); swapChain.Dispose(); }
/// <summary> /// 掃除 /// </summary> void DisposeContent() { _renderTarget.Dispose(); _swapChain.Dispose(); _depthStencil.Dispose(); _device.Dispose(); onDraw = null; _instance = null; _dxKeyboardInput?.Dispose(); _keyboard?.Dispose(); }
public void Destroy() { vertices.Close(); vertexBuffer.Dispose(); layout.Dispose(); inputSignature.Dispose(); vertexShader.Dispose(); pixelShader.Dispose(); renderTarget.Dispose(); swapChain.Dispose(); device.Dispose(); }
protected void Createdevice() { if (_device != null) { _device.Dispose(); } var description = new SwapChainDescription { BufferCount = 2, Usage = Usage.RenderTargetOutput, OutputHandle = OutputhandlePtr, IsWindowed = true, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(1, 0), Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard }; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, description, out _device, out _swapchain); }
public void Dispose() { foreach (var scene in m_scenes) { scene.Dispose(); } foreach (var s in samplerStates_) { s.Value.Dispose(); } m_rasterizerState.Dispose(); renderView_.Dispose(); backBuffer_.Dispose(); device_.Dispose(); swapChain_.Dispose(); m_depthBuffer.Dispose(); m_depthView.Dispose(); }
public static void CleanUp() { device.Dispose(); inputLayoutTextured.Dispose(); inputLayoutColor.Dispose(); renderTarget.Dispose(); swapChain.Dispose(); depthStencilView.Dispose(); backCullState.Dispose(); transBlendState.Dispose(); depthStencilBuffer.Dispose(); fx.Dispose(); if (ActiveModel != null) { ActiveModel.Dispose(); } grid.Dispose(); }
static void Main(string[] args) { // Setup var form = SlimDXHelper.InitD3D(out device, out swapChain, out renderView); finalRender = new FSQ(device, renderView, "SimpleFSQ.fx"); globeShader = new GlobeShader(device, finalRender.UAV); // Main loop MessagePump.Run(form, SimMain); // Tear down finalRender.Dispose(); globeShader.Dispose(); swapChain.Dispose(); renderView.Dispose(); device.Dispose(); }
protected override void Dispose(bool disposing) { base.Dispose(disposing); // clean up all resources // anything we missed will show up in the debug output vertices.Close(); constantBuffer.Dispose(); vertexBuffer.Dispose(); layout.Dispose(); inputSignature.Dispose(); vertexShader.Dispose(); pixelShader.Dispose(); rasteriserState.Dispose(); depthStencilState.Dispose(); depthStencilView.Dispose(); renderTarget.Dispose(); swapChain.Dispose(); device.Dispose(); }
public void Dispose() { if (Device != null) { Device.Dispose(); } if (SwapChain != null) { SwapChain.Dispose(); } if (RenderTargetView != null) { RenderTargetView.Dispose(); } if (DepthStencilView != null) { DepthStencilView.Dispose(); } }
public virtual void Dispose() { if (!Context.Disposed && Context.Rasterizer.State != null && !Context.Rasterizer.State.Disposed) { Context.Rasterizer.State.Dispose(); } if (Device != null && !Device.Disposed) { Device.Dispose(); } if (Device10 != null && !Device10.Disposed) { Device10.Dispose(); } if (CurrentAdapter != null && !CurrentAdapter.Disposed) { CurrentAdapter.Dispose(); } if (Factory != null && !Factory.Disposed) { Factory.Dispose(); } }
private void DoRenderLoop(object pmMain = null) { RasterizerStateDescription rsd = new RasterizerStateDescription(); rsd.CullMode = CullMode.None; rsd.FillMode = FillMode.Solid; mainD11.ImmediateContext.Rasterizer.State = RasterizerState.FromDescription(mainD11, rsd); SamplerDescription sd = new SamplerDescription(); sd.Filter = Filter.MinLinearMagPointMipLinear; sd.AddressU = TextureAddressMode.Wrap; sd.AddressV = TextureAddressMode.Wrap; sd.AddressW = TextureAddressMode.Wrap; sd.BorderColor = new Color4(Color.White); SamplerState ssMain = SamplerState.FromDescription(mainD11, sd); Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(mainSC, 0); var renderView = new RenderTargetView(mainD11, backBuffer); BlendStateDescription bsd = new BlendStateDescription(); bsd.RenderTargets[0] = new RenderTargetBlendDescription(); bsd.RenderTargets[0].BlendEnable = true; bsd.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; bsd.RenderTargets[0].BlendOperation = BlendOperation.Add; bsd.RenderTargets[0].SourceBlend = BlendOption.SourceColor; bsd.RenderTargets[0].DestinationBlend = BlendOption.DestinationAlpha; bsd.RenderTargets[0].SourceBlendAlpha = BlendOption.One; bsd.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add; bsd.RenderTargets[0].DestinationBlendAlpha = BlendOption.One; mainD11.ImmediateContext.OutputMerger.BlendState = BlendState.FromDescription(mainD11, bsd); Dictionary <int, MmapUnit> mmapIndexDictionaryFloor = null; Dictionary <int, MmapUnit> mmapIndexDictionarySurface = null; ShaderResourceView resourceViewFloor = GenerateMmapSRV(mainD11, 0, 512, out mmapIndexDictionaryFloor); ShaderResourceView resourceViewSurface = GenerateMmapSRV(mainD11, 512, 1024, out mmapIndexDictionarySurface); MapRange mmapRangeFloor = GenerateMmapRange(mainD11, 1, 0, 80, 0, 210, mmapIndexDictionaryFloor, screenPixelRateX, screenPixelRateY); MapRange mmapRangeSurface = GenerateMmapRange(mainD11, 2, 0, 80, 0, 210, mmapIndexDictionarySurface, screenPixelRateX, screenPixelRateY); var colorBytecodeV = ShaderBytecode.CompileFromFile("Color.hlsl", "VS", "vs_5_0", ShaderFlags.None, EffectFlags.None); VertexShader vsColor = new VertexShader(mainD11, colorBytecodeV); var colorBytecodeP = ShaderBytecode.CompileFromFile("Color.hlsl", "PS", "ps_5_0", ShaderFlags.None, EffectFlags.None); PixelShader psColor = new PixelShader(mainD11, colorBytecodeP); var signatureColor = ShaderSignature.GetInputSignature(colorBytecodeV); var layoutColor = new InputLayout(mainD11, signatureColor, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); var textureBytecodeV = ShaderBytecode.CompileFromFile("Texture.hlsl", "VS", "vs_5_0", ShaderFlags.None, EffectFlags.None); VertexShader vsTexture = new VertexShader(mainD11, textureBytecodeV); var textureBytecodeP = ShaderBytecode.CompileFromFile("Texture.hlsl", "PS", "ps_5_0", ShaderFlags.None, EffectFlags.None); PixelShader psTexture = new PixelShader(mainD11, textureBytecodeP); var signatureTexture = ShaderSignature.GetInputSignature(textureBytecodeV); var layoutTexture = new InputLayout(mainD11, signatureTexture, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32B32A32_Float, 16, 0) }); mainD11.ImmediateContext.OutputMerger.SetTargets(renderView); mainD11.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, this.Width, this.Height, 0.0f, 1.0f)); mainD11.ImmediateContext.PixelShader.SetSampler(ssMain, 0); mainD11.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; mainD11.ImmediateContext.InputAssembler.InputLayout = layoutTexture; mainD11.ImmediateContext.VertexShader.Set(vsTexture); mainD11.ImmediateContext.PixelShader.Set(psTexture); Matrix projection = Matrix.OrthoLH(2f, 2f, 0, 2f); Matrix view = Matrix.LookAtLH(new Vector3(0, 0, -1f), Vector3.Zero, Vector3.UnitY); Matrix world = Matrix.Translation(Vector3.Zero); Matrix WVP = world * view * projection; Buffer11 constantBufferCB = new Buffer11(mainD11, new BufferDescription { Usage = ResourceUsage.Default, SizeInBytes = Marshal.SizeOf(WVP), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0, }); mainD11.ImmediateContext.VertexShader.SetConstantBuffer(constantBufferCB, 0); while (running) { mainD11.ImmediateContext.ClearRenderTargetView(renderView, Color.Black); world = Matrix.Translation(new Vector3(moveX, moveY, 0)); WVP = world * view * projection; DataStream dsCamera = new DataStream(Marshal.SizeOf(WVP), true, true); dsCamera.Write(WVP); dsCamera.Position = 0; mainD11.ImmediateContext.UpdateSubresource(new DataBox(0, 0, dsCamera), constantBufferCB, 0); mainD11.ImmediateContext.PixelShader.SetShaderResource(resourceViewFloor, 0); mainD11.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(mmapRangeFloor.mapVertexBuffer, 32, 0)); mainD11.ImmediateContext.Draw(mmapRangeFloor.vector4Count, 0); mainD11.ImmediateContext.PixelShader.SetShaderResource(resourceViewSurface, 0); if (mmapRangeSurface != null) { mainD11.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(mmapRangeSurface.mapVertexBuffer, 32, 0)); mainD11.ImmediateContext.Draw(mmapRangeSurface.vector4Count, 0); } mainSC.Present(0, PresentFlags.None); Thread.Sleep(10); } colorBytecodeP.Dispose(); colorBytecodeV.Dispose(); textureBytecodeP.Dispose(); textureBytecodeV.Dispose(); mmapRangeFloor.mapVertexBuffer.Dispose(); if (mmapRangeSurface != null) { mmapRangeSurface.mapVertexBuffer.Dispose(); } layoutColor.Dispose(); layoutTexture.Dispose(); constantBufferCB.Dispose(); renderView.Dispose(); backBuffer.Dispose(); mainD11.Dispose(); mainSC.Dispose(); }
public void Dispose() { isInitialized = false; if (CursorMesh != null) { CursorMesh.Dispose(); CursorMesh = null; } if (AxesMesh != null) { AxesMesh.Dispose(); AxesMesh = null; } if (BlendedVertexLayout != null) { BlendedVertexLayout.Dispose(); BlendedVertexLayout = null; } if (normalMapEffect != null) { normalMapEffect.Dispose(); normalMapEffect = null; } if (LineLayout != null) { LineLayout.Dispose(); LineLayout = null; } if (PositionColorEffect != null) { PositionColorEffect.Dispose(); PositionColorEffect = null; } if ((renderControl != null) && !renderControl.IsDisposed) { UnregisterControlEvents(); renderControl = null; } if (depthStencilView != null) { depthStencilView.Dispose(); depthStencilView = null; } if (depthStencilBuffer != null) { depthStencilBuffer.Dispose(); depthStencilBuffer = null; } if (renderTarget != null) { renderTarget.Dispose(); renderTarget = null; } if (transparentBS != null) { transparentBS.Dispose(); transparentBS = null; } if (swapChain != null) { swapChain.Dispose(); swapChain = null; } /* if (TextFont != null) * { * TextFont.Dispose(); * TextFont = null; * }*/ if (Device != null) { Device.Dispose(); Device = null; } }
protected override void Dispose(bool disposing) { if (!IsDisposed) { /* * The following text is from MSDN (http://msdn.microsoft.com/en-us/library/fs2xkftw%28VS.80%29.aspx) * * Dispose(bool disposing) executes in two distinct scenarios: * If disposing equals true, the method has been called directly or indirectly by a user's code and managed and unmanaged resources can be disposed. * If disposing equals false, the method has been called by the runtime from inside the finalizer and only unmanaged resources can be disposed. * When an object is executing its finalization code, it should not reference other objects, because finalizers do not execute in any particular order. * If an executing finalizer references another object that has already been finalized, the executing finalizer will fail. */ if (disposing) { if (_vertexShader != null) { _vertexShader.Dispose(); } foreach (var pixelShader in _pixelShaders.Values) { pixelShader.Dispose(); } _pixelShaders.Clear(); if (_boxVertexBuffer != null) { _boxVertexBuffer.Dispose(); } if (_swapChain != null) { _swapChain.Dispose(); } if (_renderTargetView != null) { _renderTargetView.Dispose(); } if (_inputLayout != null) { _inputLayout.Dispose(); } if (_matricesBuffer != null) { _matricesBuffer.Dispose(); } if (_matricesBufferDataStream != null) { _matricesBufferDataStream.Dispose(); } if (_depthStencilTexture != null) { _depthStencilTexture.Dispose(); } if (_depthStencilView != null) { _depthStencilView.Dispose(); } if (_device != null) { _device.Dispose(); } if (_deviceContext != null) { _deviceContext.Dispose(); } } } base.Dispose(disposing); }
static void Main(string[] args) { const int elementCount = 16; const int bufferSizeInBytes = elementCount * sizeof(float); D3D.Device device = new D3D.Device(D3D.DriverType.Hardware, D3D.DeviceCreationFlags.Debug); // The input to the computation will be a constant buffer containing // integers (in floating point representation) from 1 to numberOfElements, // inclusive. The compute shader itself will double these values and write // them to the output buffer. D3D.BufferDescription inputBufferDescription = new D3D.BufferDescription { BindFlags = D3D.BindFlags.ConstantBuffer, CpuAccessFlags = D3D.CpuAccessFlags.Write, OptionFlags = D3D.ResourceOptionFlags.None, SizeInBytes = bufferSizeInBytes, StructureByteStride = sizeof(float), Usage = D3D.ResourceUsage.Dynamic, }; D3D.Buffer inputBuffer = new D3D.Buffer(device, inputBufferDescription); DataBox input = device.ImmediateContext.MapSubresource(inputBuffer, 0, bufferSizeInBytes, D3D.MapMode.WriteDiscard, D3D.MapFlags.None); for (int value = 1; value <= elementCount; ++value) input.Data.Write((float)value); device.ImmediateContext.UnmapSubresource(inputBuffer, 0); // A staging buffer is used to copy data between the CPU and GPU; the output // buffer (which gets the computation results) cannot be mapped directly. D3D.BufferDescription stagingBufferDescription = new D3D.BufferDescription { BindFlags = D3D.BindFlags.None, CpuAccessFlags = D3D.CpuAccessFlags.Read, OptionFlags = D3D.ResourceOptionFlags.StructuredBuffer, SizeInBytes = bufferSizeInBytes, StructureByteStride = sizeof(float), Usage = D3D.ResourceUsage.Staging, }; D3D.Buffer stagingBuffer = new D3D.Buffer(device, stagingBufferDescription); // The output buffer itself, and the view required to bind it to the pipeline. D3D.BufferDescription outputBufferDescription = new D3D.BufferDescription { BindFlags = D3D.BindFlags.UnorderedAccess | D3D.BindFlags.ShaderResource, OptionFlags = D3D.ResourceOptionFlags.StructuredBuffer, SizeInBytes = bufferSizeInBytes, StructureByteStride = sizeof(float), Usage = D3D.ResourceUsage.Default, }; D3D.Buffer outputBuffer = new D3D.Buffer(device, outputBufferDescription); D3D.UnorderedAccessViewDescription outputViewDescription = new D3D.UnorderedAccessViewDescription { ElementCount = elementCount, Format = DXGI.Format.Unknown, Dimension = D3D.UnorderedAccessViewDimension.Buffer }; D3D.UnorderedAccessView outputView = new D3D.UnorderedAccessView(device, outputBuffer, outputViewDescription); // Compile the shader. ShaderBytecode computeShaderCode = ShaderBytecode.CompileFromFile("BasicComputeShader.hlsl", "main", "cs_4_0", ShaderFlags.None, EffectFlags.None); D3D.ComputeShader computeShader = new D3D.ComputeShader(device, computeShaderCode); device.ImmediateContext.ComputeShader.Set(computeShader); device.ImmediateContext.ComputeShader.SetUnorderedAccessView(outputView, 0); device.ImmediateContext.ComputeShader.SetConstantBuffer(inputBuffer, 0); // Compute shaders execute on multiple threads at the same time. Those execution // threads are grouped; Dispatch() indicates how many groups in the X, Y and Z // dimension will be utilized. The shader itself specified how many threads per // group (also in X, Y and Z dimensions) to use via the [numthreads] attribute. // In this sample, one thread group will be used with 16 threads, each thread // will process one element of the input data. device.ImmediateContext.Dispatch(1, 1, 1); device.ImmediateContext.CopyResource(outputBuffer, stagingBuffer); DataBox output = device.ImmediateContext.MapSubresource(stagingBuffer, 0, sizeof(float) * elementCount, D3D.MapMode.Read, D3D.MapFlags.None); Console.Write("Results:"); for (int index = 0; index < elementCount; ++index) Console.Write(" {0}", output.Data.Read<float>()); device.ImmediateContext.UnmapSubresource(outputBuffer, 0); Console.WriteLine(); computeShader.Dispose(); outputView.Dispose(); outputBuffer.Dispose(); stagingBuffer.Dispose(); inputBuffer.Dispose(); device.Dispose(); }
/// <summary> /// Supprime les ressources non managées. /// </summary> public void Dispose() { m_device.Dispose(); m_swapChain.Dispose(); }
static void Main(string[] args) { const int elementCount = 16; const int bufferSizeInBytes = elementCount * sizeof(float); D3D.Device device = new D3D.Device(D3D.DriverType.Hardware, D3D.DeviceCreationFlags.Debug); // The input to the computation will be a constant buffer containing // integers (in floating point representation) from 1 to numberOfElements, // inclusive. The compute shader itself will double these values and write // them to the output buffer. D3D.BufferDescription inputBufferDescription = new D3D.BufferDescription { BindFlags = D3D.BindFlags.ConstantBuffer, CpuAccessFlags = D3D.CpuAccessFlags.Write, OptionFlags = D3D.ResourceOptionFlags.None, SizeInBytes = bufferSizeInBytes, StructureByteStride = sizeof(float), Usage = D3D.ResourceUsage.Dynamic, }; D3D.Buffer inputBuffer = new D3D.Buffer(device, inputBufferDescription); DataBox input = device.ImmediateContext.MapSubresource(inputBuffer, D3D.MapMode.WriteDiscard, D3D.MapFlags.None); for (int value = 1; value <= elementCount; ++value) { input.Data.Write((float)value); } device.ImmediateContext.UnmapSubresource(inputBuffer, 0); // A staging buffer is used to copy data between the CPU and GPU; the output // buffer (which gets the computation results) cannot be mapped directly. D3D.BufferDescription stagingBufferDescription = new D3D.BufferDescription { BindFlags = D3D.BindFlags.None, CpuAccessFlags = D3D.CpuAccessFlags.Read, OptionFlags = D3D.ResourceOptionFlags.StructuredBuffer, SizeInBytes = bufferSizeInBytes, StructureByteStride = sizeof(float), Usage = D3D.ResourceUsage.Staging, }; D3D.Buffer stagingBuffer = new D3D.Buffer(device, stagingBufferDescription); // The output buffer itself, and the view required to bind it to the pipeline. D3D.BufferDescription outputBufferDescription = new D3D.BufferDescription { BindFlags = D3D.BindFlags.UnorderedAccess | D3D.BindFlags.ShaderResource, OptionFlags = D3D.ResourceOptionFlags.StructuredBuffer, SizeInBytes = bufferSizeInBytes, StructureByteStride = sizeof(float), Usage = D3D.ResourceUsage.Default, }; D3D.Buffer outputBuffer = new D3D.Buffer(device, outputBufferDescription); D3D.UnorderedAccessViewDescription outputViewDescription = new D3D.UnorderedAccessViewDescription { ElementCount = elementCount, Format = DXGI.Format.Unknown, Dimension = D3D.UnorderedAccessViewDimension.Buffer }; D3D.UnorderedAccessView outputView = new D3D.UnorderedAccessView(device, outputBuffer, outputViewDescription); // Compile the shader. ShaderBytecode computeShaderCode = ShaderBytecode.CompileFromFile("BasicComputeShader.hlsl", "main", "cs_4_0", ShaderFlags.None, EffectFlags.None); D3D.ComputeShader computeShader = new D3D.ComputeShader(device, computeShaderCode); device.ImmediateContext.ComputeShader.Set(computeShader); device.ImmediateContext.ComputeShader.SetUnorderedAccessView(outputView, 0); device.ImmediateContext.ComputeShader.SetConstantBuffer(inputBuffer, 0); // Compute shaders execute on multiple threads at the same time. Those execution // threads are grouped; Dispatch() indicates how many groups in the X, Y and Z // dimension will be utilized. The shader itself specified how many threads per // group (also in X, Y and Z dimensions) to use via the [numthreads] attribute. // In this sample, one thread group will be used with 16 threads, each thread // will process one element of the input data. device.ImmediateContext.Dispatch(1, 1, 1); device.ImmediateContext.CopyResource(outputBuffer, stagingBuffer); DataBox output = device.ImmediateContext.MapSubresource(stagingBuffer, D3D.MapMode.Read, D3D.MapFlags.None); Console.Write("Results:"); for (int index = 0; index < elementCount; ++index) { Console.Write(" {0}", output.Data.Read <float>()); } device.ImmediateContext.UnmapSubresource(outputBuffer, 0); Console.WriteLine(); computeShader.Dispose(); outputView.Dispose(); outputBuffer.Dispose(); stagingBuffer.Dispose(); inputBuffer.Dispose(); device.Dispose(); }
public Renderer(MainForm form, Control target) { t = new Stopwatch(); mainForm = form; targetControl = target; form.Renderer = this; description = new SwapChainDescription() { BufferCount = 2, Usage = Usage.RenderTargetOutput, OutputHandle = target.Handle, IsWindowed = true, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(1, 0), Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard }; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, description, out device, out swapChain); // create a view of our render target, which is the backbuffer of the swap chain we just created using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0)) renderTarget = new RenderTargetView(device, resource); // setting a viewport is required if you want to actually see anything context = device.ImmediateContext; viewport = new Viewport(0.0f, 0.0f, target.ClientSize.Width, target.ClientSize.Height); context.OutputMerger.SetTargets(renderTarget); context.Rasterizer.SetViewports(viewport); CreateShaders(File.ReadAllText("vteffect.fx")); // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms using (var factory = swapChain.GetParent <Factory>()) factory.SetWindowAssociation(target.Handle, WindowAssociationFlags.IgnoreAltEnter); // handle alt+enter ourselves form.KeyDown += (o, e) => { //if (e.Alt && e.KeyCode == Keys.Enter) //swapChain.IsFullScreen = !swapChain.IsFullScreen; }; // handle form size changes form.Resize += (o, e) => { renderTarget.Dispose(); viewport = new Viewport(0.0f, 0.0f, target.ClientSize.Width, target.ClientSize.Height); swapChain.ResizeBuffers(2, 0, 0, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch); using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0)) renderTarget = new RenderTargetView(device, resource); context.OutputMerger.SetTargets(renderTarget); context.Rasterizer.SetViewports(viewport); SetTexture(currentEntry); }; MessagePump.Run(form, Render); // clean up all resources // anything we missed will show up in the debug output vertices.Close(); vertexBuffer.Dispose(); layout.Dispose(); inputSignature.Dispose(); vertexShader.Dispose(); pixelShader.Dispose(); renderTarget.Dispose(); swapChain.Dispose(); device.Dispose(); UpdateRenderer = true; }