public void Dispose() { backbufferTexture.Dispose(); backbufferRTV.Dispose(); sceneTexture.Dispose(); sceneRTV.Dispose(); sceneSRV.Dispose(); depthDSV.Dispose(); depthSRV.Dispose(); depthStencilState.Dispose(); rasterizerState.Dispose(); constantBuffer.Dispose(); mainVertexShader.Dispose(); mainPixelShader.Dispose(); trianglePositionVertexBuffer.Dispose(); triangleIndexBuffer.Dispose(); inputLayout.Dispose(); postEffect.Dispose(); }
//private void RenderFS() //{ // DeviceContext.InputAssembler.SetVertexBuffers(0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); // DeviceContext.InputAssembler.SetIndexBuffer(null, (Format)0, 0); // DeviceContext.VertexShader.Set(fsVertexShader); // DeviceContext.PixelShader.Set(fishGlowPixelShader); // DeviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; // DeviceContext.Draw(3, 0); //} public void Dispose() { swapChain.SetFullscreenState(false, null); //inputLayout.Dispose(); //inputSignature.Dispose(); WVP.Dispose(); Sun.Dispose(); decorRenderer.Dispose(); fishGlow.Dispose(); fishRenderer.Dispose(); foodRenderer.Dispose(); raysRenderer.Dispose(); RasterizerStates.Dispose(); DepthStencilStates.Dispose(); BlendStates.Dispose(); triangleVertexBuffer.Dispose(); vertexShader.Dispose(); pixelShader.Dispose(); colorTarget.Dispose(); renderTargetView.Dispose(); swapChain.Dispose(); Device.Dispose(); DeviceContext.Dispose(); renderForm.Dispose(); }
public void Dispose() { vertexBuffer.Dispose(); vertexShader.Dispose(); pixelShader.Dispose(); inputLayout.Dispose(); inputSignature.Dispose(); worldViewProjBuffer.Dispose(); samplerState.Dispose(); }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public override void Dispose() { D3D11.PixelShader shader = Interlocked.Exchange(ref _shader, null); if (shader != null) { Graphics.Log.Print($"Destroying {ShaderType} '{Name}' ({ID})", LoggingLevel.Verbose); shader.Dispose(); } base.Dispose(); }
public void Dispose() { _inputLayout.Dispose(); _inputSignature.Dispose(); _triangleVertexBuffer.Dispose(); _vertexShader.Dispose(); _pixelShader.Dispose(); _renderTargetView.Dispose(); _swapChain.Dispose(); _d3DDevice.Dispose(); _d3DDeviceContext.Dispose(); _renderForm.Dispose(); }
public void Dispose() { inputLayout.Dispose(); inputSignature.Dispose(); triangleVertexBuffer.Dispose(); vertexShader.Dispose(); pixelShader.Dispose(); renderTargetView.Dispose(); swapChain.Dispose(); d3dDevice.Dispose(); d3dDeviceContext.Dispose(); renderForm.Dispose(); }
public void Dispose() { samplerState.Dispose(); constantBuffer.Dispose(); vertexShader.Dispose(); pixelShader.Dispose(); trianglePositionVertexBuffer.Dispose(); triangleTexcoordVertexBuffer.Dispose(); inputLayout.Dispose(); }
/// <summary> /// frees all resources of this window /// </summary> public void Dispose() { Form.Dispose(); view.Dispose(); deviceContext.Dispose(); device.Dispose(); swapChain.Dispose(); vertexBuffer.Dispose(); ratioBuffer.Dispose(); vertexShader.Dispose(); pixelShader.Dispose(); inputLayout.Dispose(); inputSignature.Dispose(); }
public void Dispose() { if (!Initialized) { return; } vertexShader.Dispose(); pixelShader.Dispose(); inputLayout.Dispose(); renderTargetView.Dispose(); swapChain.Dispose(); d3dDevice.Dispose(); d3dDeviceContext.Dispose(); Fonts.Dispose(); }
public void Dispose() { rtvSdrTexture?.Dispose(); textureSDRImage?.Dispose(); inputLayout.Dispose(); samplerState.Dispose(); shaderInputSigVsQuad.Dispose(); psToneMapping.Dispose(); vsQuad.Dispose(); wrtD3D11Device.Dispose(); d3dDevice.Dispose(); wicFactory.Dispose(); }
public void Dispose() { inputLayout.Dispose(); inputSignature.Dispose(); screenVertexBuffer.Dispose(); vertexShader.Dispose(); pixelShader.Dispose(); renderTargetView.Dispose(); swapChain.Dispose(); d3dDevice.Dispose(); d3dDeviceContext.Dispose(); renderForm.Dispose(); UnhookWindowsHookEx(_hookID); }
public void Dispose() { _shaderSignature?.Dispose(); _vertexShaderByteCode?.Dispose(); _vertexShader?.Dispose(); _pixelShaderByteCode?.Dispose(); _pixelShader?.Dispose(); _verticesBuffer?.Dispose(); _inputLayout?.Dispose(); _contantBuffer?.Dispose(); _depthBuffer?.Dispose(); _depthView?.Dispose(); _context?.ClearState(); _context?.Flush(); _swapChain?.Dispose(); _renderView?.Dispose(); _backBuffer?.Dispose(); _device?.Dispose(); _context?.Dispose(); _factory?.Dispose(); }
void Dispose(bool disposing) { depthStencilView?.Dispose(); depthStencilBuffer?.Dispose(); surfaceTarget?.Dispose(); surfaceView?.Dispose(); surfaceTexture?.Dispose(); swapChain.Dispose(); defaultDepthStencilState.Dispose(); clipDepthStencilState.Dispose(); clippingDepthStencilState.Dispose(); blendState.Dispose(); samplerState.Dispose(); for (int i = 0; i < BufferCount; i++) { indexBuffers[i].Dispose(); vertexBuffers[i].Dispose(); } matrixBuffer.Dispose(); brushBuffer.Dispose(); vertexShader.Dispose(); pixelShader.Dispose(); tkDevice.Dispose(); device.Dispose(); if (disposing) { indexBuffers = null; vertexBuffers = null; sw = null; } }
public void Dispose() { backbufferTexture.Dispose(); backbufferRTV.Dispose(); depthDSV.Dispose(); depthStencilState.Dispose(); rasterizerState.Dispose(); blendState.Dispose(); constantBuffer.Dispose(); vertexShader.Dispose(); pixelShader.Dispose(); trianglePositionVertexBuffer.Dispose(); triangleColorVertexBuffer.Dispose(); #if RENDER_CUBE triangleIndexBuffer.Dispose(); #endif softwareRasterizer.Dispose(); inputLayout.Dispose(); }
private static void Main() { var form = new RenderForm("SharpDX - MiniCubeTexture Direct3D11 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain); var context = device.ImmediateContext; // Ignore all windows events var factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCubeTexture.fx", "VS", "vs_4_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCubeTexture.fx", "PS", "ps_4_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { // 3D coordinates UV Texture coordinates -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, // Front -1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // BACK 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, // Top -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f,-1.0f, -1.0f, 1.0f, 1.0f, 0.0f, // Bottom 1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f,-1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f,-1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, // Left -1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 0.0f, // Right 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, }); // Create Constant Buffer var contantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); // Create Depth Buffer & View var depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = form.ClientSize.Width, Height = form.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); var depthView = new DepthStencilView(device, depthBuffer); // Load texture and create sampler var texture = Texture2D.FromFile<Texture2D>(device, "GeneticaMortarlessBlocks.jpg"); var textureView = new ShaderResourceView(device, texture); var sampler = new SamplerState(device, new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = Color.Black, ComparisonFunction = Comparison.Never, MaximumAnisotropy = 16, MipLodBias = 0, MinimumLod = 0, MaximumLod = 16, }); // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf<Vector4>() + Utilities.SizeOf<Vector2>(), 0)); context.VertexShader.SetConstantBuffer(0, contantBuffer); context.VertexShader.Set(vertexShader); context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.PixelShader.Set(pixelShader); context.PixelShader.SetSampler(0, sampler); context.PixelShader.SetShaderResource(0, textureView); context.OutputMerger.SetTargets(depthView, renderView); // Prepare matrices var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY); var proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f); var viewProj = Matrix.Multiply(view, proj); // Use clock var clock = new Stopwatch(); clock.Start(); // Main loop RenderLoop.Run(form, () => { var time = clock.ElapsedMilliseconds / 1000.0f; // Clear views context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); context.ClearRenderTargetView(renderView, Color.Black); // Update WorldViewProj Matrix var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj; worldViewProj.Transpose(); context.UpdateSubresource(ref worldViewProj, contantBuffer); // Draw the cube context.Draw(36, 0); // Present! swapChain.Present(0, PresentFlags.None); }); // Release all resources vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vertices.Dispose(); layout.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); factory.Dispose(); }
private static void Main() { var form = new RenderForm("SharpDX - MiniTri Direct3D 11 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription= new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); var context = device.ImmediateContext; // Ignore all windows events var factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None); var pixelShader = new PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout( device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }); // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0)); context.VertexShader.Set(vertexShader); context.Rasterizer.SetViewport(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.PixelShader.Set(pixelShader); context.OutputMerger.SetTargets(renderView); // Main loop RenderLoop.Run(form, () => { context.ClearRenderTargetView(renderView, Color.Black); context.Draw(3, 0); swapChain.Present(0, PresentFlags.None); }); // Release all resources vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vertices.Dispose(); layout.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); factory.Dispose(); }
// [STAThread] private static void Main() { var form = new RenderForm("SharpDX - MiniCube Direct3D11 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Used for debugging dispose object references // Configuration.EnableObjectTracking = true; // Disable throws on shader compilation errors //Configuration.ThrowOnShaderCompileError = false; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); var context = device.ImmediateContext; // Ignore all windows events var factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Front new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // BACK new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Top new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f,-1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Bottom new Vector4( 1.0f,-1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f,-1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f,-1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f,-1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f,-1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), // Left new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), // Right new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), }); // Create Constant Buffer var contantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf<Vector4>() * 2, 0)); context.VertexShader.SetConstantBuffer(0, contantBuffer); context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); // Prepare matrices var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY); Matrix proj = Matrix.Identity; // Use clock var clock = new Stopwatch(); clock.Start(); // Declare texture for rendering bool userResized = true; Texture2D backBuffer = null; RenderTargetView renderView = null; Texture2D depthBuffer = null; DepthStencilView depthView = null; // Setup handler on resize form form.UserResized += (sender, args) => userResized = true; // Setup full screen mode change F5 (Full) F4 (Window) form.KeyUp += (sender, args) => { if (args.KeyCode == Keys.F5) swapChain.SetFullscreenState(true, null); else if (args.KeyCode == Keys.F4) swapChain.SetFullscreenState(false, null); else if (args.KeyCode == Keys.Escape) form.Close(); }; // Main loop RenderLoop.Run(form, () => { // If Form resized if (userResized) { // Dispose all previous allocated resources ComObject.Dispose(ref backBuffer); ComObject.Dispose(ref renderView); ComObject.Dispose(ref depthBuffer); ComObject.Dispose(ref depthView); // Resize the backbuffer swapChain.ResizeBuffers(desc.BufferCount, form.ClientSize.Width, form.ClientSize.Height, Format.Unknown, SwapChainFlags.None); // Get the backbuffer from the swapchain backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); // Renderview on the backbuffer renderView = new RenderTargetView(device, backBuffer); // Create the depth buffer depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = form.ClientSize.Width, Height = form.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); // Create the depth buffer view depthView = new DepthStencilView(device, depthBuffer); // Setup targets and viewport for rendering context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.OutputMerger.SetTargets(depthView, renderView); // Setup new projection matrix with correct aspect ratio proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f); // We are done resizing userResized = false; } var time = clock.ElapsedMilliseconds / 1000.0f; var viewProj = Matrix.Multiply(view, proj); // Clear views context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); context.ClearRenderTargetView(renderView, Color.Black); // Update WorldViewProj Matrix var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj; worldViewProj.Transpose(); context.UpdateSubresource(ref worldViewProj, contantBuffer); // Draw the cube context.Draw(36, 0); // Present! swapChain.Present(0, PresentFlags.None); }); // Release all resources signature.Dispose(); vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vertices.Dispose(); layout.Dispose(); contantBuffer.Dispose(); depthBuffer.Dispose(); depthView.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); factory.Dispose(); }
private void InitializeOculus() { RenderForm form = new RenderForm("OculusWrap SharpDX demo"); Wrap oculus = new Wrap(); Hmd hmd; form.KeyUp += new System.Windows.Forms.KeyEventHandler(this.Window_KeyUp); //form.moused //form.Activate(); //form.Show(); int textureWidth = 0, textureHeight = 0; newTextureArrived = false; //zoom == 2 is not implemented, because the visual quality would be too low. //zoom == 4 will be implemented in the future. if (zoom == 3) { textureWidth = 3328; textureHeight = 1664; } bool success = oculus.Initialize(); if (!success) { System.Windows.Forms.MessageBox.Show("Failed to initialize the Oculus runtime library.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Use the head mounted display, if it's available, otherwise use the debug HMD. int numberOfHeadMountedDisplays = oculus.Hmd_Detect(); if (numberOfHeadMountedDisplays > 0) hmd = oculus.Hmd_Create(0); else hmd = oculus.Hmd_CreateDebug(OculusWrap.OVR.HmdType.DK2); if (hmd == null) { System.Windows.Forms.MessageBox.Show("Oculus Rift not detected.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (hmd.ProductName == string.Empty) System.Windows.Forms.MessageBox.Show("The HMD is not enabled.", "There's a tear in the Rift", MessageBoxButtons.OK, MessageBoxIcon.Error); // Specify which head tracking capabilities to enable. hmd.SetEnabledCaps(OVR.HmdCaps.LowPersistence | OVR.HmdCaps.DynamicPrediction); // Start the sensor which informs of the Rift's pose and motion hmd.ConfigureTracking(OVR.TrackingCaps.ovrTrackingCap_Orientation | OVR.TrackingCaps.ovrTrackingCap_MagYawCorrection | OVR.TrackingCaps.ovrTrackingCap_Position, OVR.TrackingCaps.None); // Create a set of layers to submit. EyeTexture[] eyeTextures = new EyeTexture[2]; OVR.ovrResult result; // 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 factory = new Factory(); DeviceContext 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. SharpDX.DXGI.SwapChain swapChain = new SwapChain(factory, device, swapChainDescription); // Retrieve the back buffer of the swap chain. Texture2D backBuffer = swapChain.GetBackBuffer<Texture2D>(0); RenderTargetView 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. Texture2D depthBuffer = new Texture2D(device, depthBufferDescription); DepthStencilView depthStencilView = new DepthStencilView(device, depthBuffer); DepthStencilState depthStencilState = new DepthStencilState(device, depthStencilStateDescription); Viewport viewport = new Viewport(0, 0, hmd.Resolution.Width, hmd.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; } Layers layers = new Layers(); LayerEyeFov layerEyeFov = layers.AddLayerEyeFov(); for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++) { OVR.EyeType eye = (OVR.EyeType)eyeIndex; EyeTexture eyeTexture = new EyeTexture(); eyeTextures[eyeIndex] = eyeTexture; // Retrieve size and position of the texture for the current eye. eyeTexture.FieldOfView = hmd.DefaultEyeFov[eyeIndex]; eyeTexture.TextureSize = hmd.GetFovTextureSize(eye, hmd.DefaultEyeFov[eyeIndex], 1.0f); eyeTexture.RenderDescription = hmd.GetRenderDesc(eye, hmd.DefaultEyeFov[eyeIndex]); eyeTexture.HmdToEyeViewOffset = eyeTexture.RenderDescription.HmdToEyeViewOffset; eyeTexture.ViewportSize.Position = new OVR.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 native Direct3D texture description. OVR.D3D11.D3D11_TEXTURE2D_DESC swapTextureDescriptionD3D11 = SharpDXHelpers.CreateTexture2DDescription(eyeTexture.Texture2DDescription); // Create a SwapTextureSet, which will contain the textures to render to, for the current eye. result = hmd.CreateSwapTextureSetD3D11(device.NativePointer, ref swapTextureDescriptionD3D11, out eyeTexture.SwapTextureSet); WriteErrorDetails(oculus, result, "Failed to create swap texture set."); // Create room for each DirectX texture in the SwapTextureSet. eyeTexture.Textures = new Texture2D[eyeTexture.SwapTextureSet.TextureCount]; eyeTexture.RenderTargetViews = new RenderTargetView[eyeTexture.SwapTextureSet.TextureCount]; // Create a texture 2D and a render target view, for each unmanaged texture contained in the SwapTextureSet. for (int textureIndex = 0; textureIndex < eyeTexture.SwapTextureSet.TextureCount; textureIndex++) { // Retrieve the current textureData object. OVR.D3D11.D3D11TextureData textureData = eyeTexture.SwapTextureSet.Textures[textureIndex]; // Create a managed Texture2D, based on the unmanaged texture pointer. eyeTexture.Textures[textureIndex] = new Texture2D(textureData.Texture); // 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. layerEyeFov.ColorTexture[eyeIndex] = eyeTexture.SwapTextureSet.SwapTextureSetPtr; layerEyeFov.Viewport[eyeIndex].Position = new OVR.Vector2i(0, 0); layerEyeFov.Viewport[eyeIndex].Size = eyeTexture.TextureSize; layerEyeFov.Fov[eyeIndex] = eyeTexture.FieldOfView; layerEyeFov.Header.Flags = OVR.LayerFlags.TextureOriginAtBottomLeft; } // Define the texture used to display the rendered result on the computer monitor. Texture2DDescription mirrorTextureDescription = new Texture2DDescription(); mirrorTextureDescription.Width = form.Width; mirrorTextureDescription.Height = form.Height; mirrorTextureDescription.ArraySize = 1; mirrorTextureDescription.MipLevels = 1; mirrorTextureDescription.Format = Format.R8G8B8A8_UNorm; mirrorTextureDescription.SampleDescription = new SampleDescription(1, 0); mirrorTextureDescription.Usage = ResourceUsage.Default; mirrorTextureDescription.CpuAccessFlags = CpuAccessFlags.None; mirrorTextureDescription.BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget; SamplerStateDescription samplerStateDescription = new SamplerStateDescription { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = Filter.Anisotropic }; RasterizerStateDescription rasterizerStateDescription = RasterizerStateDescription.Default(); rasterizerStateDescription.IsFrontCounterClockwise = true; // Convert the SharpDX texture description to the native Direct3D texture description. OVR.D3D11.D3D11_TEXTURE2D_DESC mirrorTextureDescriptionD3D11 = SharpDXHelpers.CreateTexture2DDescription(mirrorTextureDescription); OculusWrap.D3D11.MirrorTexture mirrorTexture; // Create the texture used to display the rendered result on the computer monitor. result = hmd.CreateMirrorTextureD3D11(device.NativePointer, ref mirrorTextureDescriptionD3D11, out mirrorTexture); WriteErrorDetails(oculus, result, "Failed to create mirror texture."); Texture2D mirrorTextureD3D11 = new Texture2D(mirrorTexture.Texture.Texture); #region Vertex and pixel shader // Create vertex shader. ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "VertexShaderMain", "vs_4_0"); VertexShader vertexShader = new VertexShader(device, vertexShaderByteCode); // Create pixel shader. ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "PixelShaderMain", "ps_4_0"); PixelShader pixelShader = new PixelShader(device, pixelShaderByteCode); ShaderSignature shaderSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); Texture2D myTexture = new Texture2D(device, new Texture2DDescription() { Format = Format.R8G8B8A8_UNorm, ArraySize = 1, MipLevels = 1, Width = textureWidth, Height = textureHeight, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, }); ShaderResourceView textureView = new ShaderResourceView(device, myTexture); //set sampler for texture SamplerState samplerState = new SamplerState(device, samplerStateDescription); //initialize rasterizer RasterizerState rasterizerState = new RasterizerState(device, rasterizerStateDescription); // Specify that each vertex consists of a single vertex position and color. int[] indices = null; Vertex[] vertices = null; CreateGeometry(out indices, out vertices); InputElement[] inputElements = new InputElement[] { new InputElement("SV_Position", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0), /*new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0),*/ }; // Define an input layout to be passed to the vertex shader. InputLayout inputLayout = new InputLayout(device, shaderSignature, inputElements); // Create a vertex buffer, containing our 3D model. Buffer vertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer, vertices);//m_vertices); // Create a constant buffer, to contain our WorldViewProjection matrix, that will be passed to the vertex shader. Buffer constantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); Buffer indexBuffer = SharpDX.Direct3D11.Buffer.Create(device, BindFlags.IndexBuffer, indices); // 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, Utilities.SizeOf<Vertex>(), 0)); immediateContext.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0); immediateContext.VertexShader.SetConstantBuffer(0, constantBuffer); immediateContext.VertexShader.Set(vertexShader); immediateContext.PixelShader.Set(pixelShader); immediateContext.PixelShader.SetShaderResource(0, textureView); immediateContext.PixelShader.SetSampler(0, samplerState); #endregion DateTime startTime = DateTime.Now; Vector3 position = new Vector3(0, 0, 0); oculusReady = true; #region Render loop RenderLoop.Run(form, () => { OVR.Vector3f[] hmdToEyeViewOffsets = { eyeTextures[0].HmdToEyeViewOffset, eyeTextures[1].HmdToEyeViewOffset }; OVR.FrameTiming frameTiming = hmd.GetFrameTiming(0); OVR.TrackingState trackingState = hmd.GetTrackingState(frameTiming.DisplayMidpointSeconds); OVR.Posef[] eyePoses = new OVR.Posef[2]; // Calculate the position and orientation of each eye. oculus.CalcEyePoses(trackingState.HeadPose.ThePose, hmdToEyeViewOffsets, ref eyePoses); float timeSinceStart = (float)(DateTime.Now - startTime).TotalSeconds; for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++) { OVR.EyeType eye = (OVR.EyeType)eyeIndex; EyeTexture eyeTexture = eyeTextures[eyeIndex]; layerEyeFov.RenderPose[eyeIndex] = eyePoses[eyeIndex]; // Retrieve the index of the active texture and select the next texture as being active next. int textureIndex = eyeTexture.SwapTextureSet.CurrentIndex++; 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); //added a custom rasterizer immediateContext.Rasterizer.State = rasterizerState; // 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(); //use this to get the first rotation to goal Matrix world = Matrix.Scaling(1.0f) /** Matrix.RotationX(timeSinceStart*0.2f) */* Matrix.RotationY(timeSinceStart * 2 / 10f) /** Matrix.RotationZ(timeSinceStart*3/10f)*/; Matrix viewMatrix = Matrix.LookAtRH(viewPosition, viewPosition + lookAt, lookUp); Matrix projectionMatrix = OVR.ovrMatrix4f_Projection(eyeTexture.FieldOfView, 0.1f, 10.0f, OVR.ProjectionModifier.None).ToMatrix(); projectionMatrix.Transpose(); Matrix worldViewProjection = world * viewMatrix * projectionMatrix; worldViewProjection.Transpose(); // Update the transformation matrix. immediateContext.UpdateSubresource(ref worldViewProjection, constantBuffer); // Draw the cube //immediateContext.Draw(vertices.Length/2, 0); immediateContext.DrawIndexed(indices.Length, 0, 0); } hmd.SubmitFrame(0, layers); immediateContext.CopyResource(mirrorTextureD3D11, backBuffer); swapChain.Present(0, PresentFlags.None); if (newTextureArrived == true) { newTextureArrived = false; DataBox map = device.ImmediateContext.MapSubresource(myTexture, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None); //load the BitMapSource with appropriate formating (Format32bppPRGBA) SharpDX.WIC.BitmapSource bitMap = LoadBitmap(new SharpDX.WIC.ImagingFactory(), streamTexture); //string newFile = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\img_merged.jpg"; //SharpDX.WIC.BitmapSource bitMap = LoadBitmapFromFile(new SharpDX.WIC.ImagingFactory(), newFile); int width = bitMap.Size.Width; int height = bitMap.Size.Height; int stride = bitMap.Size.Width * 4; bitMap.CopyPixels(stride, map.DataPointer, height * stride); device.ImmediateContext.UnmapSubresource(myTexture, 0); //bitMap.Dispose(); streamTexture.Seek(0, SeekOrigin.Begin); } }); #endregion // Release all resources inputLayout.Dispose(); constantBuffer.Dispose(); indexBuffer.Dispose(); vertexBuffer.Dispose(); inputLayout.Dispose(); shaderSignature.Dispose(); pixelShader.Dispose(); pixelShaderByteCode.Dispose(); vertexShader.Dispose(); vertexShaderByteCode.Dispose(); mirrorTextureD3D11.Dispose(); layers.Dispose(); eyeTextures[0].Dispose(); eyeTextures[1].Dispose(); immediateContext.ClearState(); immediateContext.Flush(); immediateContext.Dispose(); depthStencilState.Dispose(); depthStencilView.Dispose(); depthBuffer.Dispose(); backBufferRenderTargetView.Dispose(); backBuffer.Dispose(); swapChain.Dispose(); factory.Dispose(); // 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(); hmd.Dispose(); oculus.Dispose(); }
public Program() { var form = new RenderForm("SharpDX - Load Mesh Sample"); form.Width = 1280; form.Height = 720; // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.Width, form.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain); var context = device.ImmediateContext; // Ignore all windows events var factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); //Load model String fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "sponza/sponza.3ds"); ModelLoader modelLoader = new ModelLoader(device); Model model = modelLoader.Load(fileName); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("LoadMesh.fx", "VS", "vs_5_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("LoadMesh.fx", "PS", "ps_5_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); model.SetInputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode)); // Create Depth Buffer & View var depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = form.Width, Height = form.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); var depthView = new DepthStencilView(device, depthBuffer); //create sampler from texture var sampler = new SamplerState(device, new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = Color.Black, ComparisonFunction = Comparison.Never, MaximumAnisotropy = 16, MipLodBias = 0, MinimumLod = 0, MaximumLod = 16, }); // Create Constant Buffers var vertexConstantBuffer = new Buffer(device, Utilities.SizeOf<VertexShaderData>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); var pixelConstantBuffer = new Buffer(device, Utilities.SizeOf<PixelShaderData>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); // Prepare some of the stages. The others are mesh dependent and will be set later context.VertexShader.Set(vertexShader); context.Rasterizer.SetViewport(new Viewport(0, 0, form.Width, form.Height, 0.0f, 1.0f)); context.PixelShader.Set(pixelShader); context.PixelShader.SetSampler(0, sampler); context.OutputMerger.SetTargets(depthView, renderView); context.VertexShader.SetConstantBuffer(0, vertexConstantBuffer); context.PixelShader.SetConstantBuffer(0, pixelConstantBuffer); //allocate data structs for the vertex and pixel constant buffers VertexShaderData vsData = new VertexShaderData(); PixelShaderData psData = new PixelShaderData(); //set light position psData.lightPos = new Vector4(0, 2.5f, 0, 0); //update pixel shader constant buffer. Only need to do this once. context.UpdateSubresource(ref psData, pixelConstantBuffer); // Calc projection matrix var proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.Width / (float)form.Height, 0.1f, 100.0f); // Use clock var clock = new Stopwatch(); clock.Start(); // Main loop RenderLoop.Run(form, () => { var time = clock.ElapsedMilliseconds / 1000.0f; // Prepare matrices Vector3 cameraPosition = new Vector3(0, 3, 5.0f); Vector3 cameraLookAt = new Vector3(0, 2.0f, 0); //rotate camera Vector4 tempPos = Vector3.Transform(cameraPosition, Matrix.RotationY(0.2f * time)); cameraPosition = new Vector3(tempPos.X, tempPos.Y, tempPos.Z); //calculate the view matrix var view = Matrix.LookAtLH(cameraPosition, cameraLookAt, Vector3.UnitY); var viewProj = Matrix.Multiply(view, proj); // Clear views context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); context.ClearRenderTargetView(renderView, Color.Black); // Update transformation matrices vsData.world = Matrix.Translation(0, -model.AABoxCentre.Y / 2, 0); vsData.worldView = vsData.world * view; vsData.worldViewProj = vsData.world * viewProj; //transpose matrices before sending them to the shader vsData.world.Transpose(); vsData.worldView.Transpose(); vsData.worldViewProj.Transpose(); //update vertex shader constant buffer context.UpdateSubresource(ref vsData, vertexConstantBuffer); // Draw the cube model.Render(context); // Present swapChain.Present(0, PresentFlags.None); }); // Release all resources model.Dispose(); vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); factory.Dispose(); }
private static void Main() { // Form: the window in which we will show our application var form = new RenderForm("COMP30019 - Week 8"); // SwapChain description: set up our double buffer var desc = new SwapChainDescription() { // We need one spare buffer here; if we needed more, // we could set a larger value BufferCount = 1, // Various properties of how the OS/Graphics card // will handle the window ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Used for debugging dispose object references Configuration.EnableObjectTracking = true; // Disable throws on shader compilation errors - hopefully // we won't have any of these! :) //Configuration.ThrowOnShaderCompileError = false; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); var context = device.ImmediateContext; // Compile Vertex and Pixel shaders, given in the accompanying // shader file var vertexShaderByteCode = ShaderBytecode.CompileFromFile("week8.fx", "VS", "vs_4_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("week8.fx", "PS", "ps_4_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode); // Layout from VertexShader input signature: this tells the // program how to interpret the shader source code // Note that we need to keep track of the byte offset for each // element (RGBA*32 bits= 4*4 bytes= 16 bytes) var layout = new InputLayout(device, signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0), new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 32, 0) }); // Create a set of variables for our objects // 8 vertices for the cube: Vector4 front_bottom_left = new Vector4(-1.0f, -1.0f, -1.0f, 1.0f); Vector4 front_top_left = new Vector4(-1.0f, 1.0f, -1.0f, 1.0f); Vector4 front_top_right = new Vector4(1.0f, 1.0f, -1.0f, 1.0f); Vector4 front_bottom_right = new Vector4(1.0f, -1.0f, -1.0f, 1.0f); Vector4 back_bottom_left = new Vector4(-1.0f, -1.0f, 1.0f, 1.0f); Vector4 back_bottom_right = new Vector4(1.0f, -1.0f, 1.0f, 1.0f); Vector4 back_top_left = new Vector4(-1.0f, 1.0f, 1.0f, 1.0f); Vector4 back_top_right = new Vector4(1.0f, 1.0f, 1.0f, 1.0f); // Colours: Vector4 red = new Vector4(1.0f, 0.0f, 0.0f, 1.0f); Vector4 green = new Vector4(0.0f, 1.0f, 0.0f, 1.0f); Vector4 blue = new Vector4(0.0f, 0.0f, 1.0f, 1.0f); Vector4 yellow = new Vector4(1.0f, 1.0f, 0.0f, 1.0f); Vector4 magenta = new Vector4(1.0f, 0.0f, 1.0f, 1.0f); Vector4 cyan = new Vector4(0.0f, 1.0f, 1.0f, 1.0f); // Normals: // *** These need to be calculated for each polygon (face) *** Vector4 top_normal = new Vector4(0.0f, 1.0f, 0.0f, 1.0f); Vector4 bottom_normal = new Vector4(0.0f, -1.0f, 0.0f, 1.0f); Vector4 left_normal = new Vector4(-1.0f, 0.0f, 0.0f, 1.0f); Vector4 right_normal = new Vector4(1.0f, 0.0f, 0.0f, 1.0f); Vector4 front_normal = new Vector4(0.0f, 0.0f, -1.0f, 1.0f); Vector4 back_normal = new Vector4(0.0f, 0.0f, 1.0f, 1.0f); //Funky Normals float oort = 1 / (float)Math.Sqrt(3); Vector4 ftr_normal = new Vector4(new Vector3( 1, 1,-1) * oort, 1); Vector4 btr_normal = new Vector4(new Vector3(1, 1, 1) * oort, 1); Vector4 btl_normal = new Vector4(new Vector3(-1, 1, 1) * oort, 1); Vector4 ftl_normal = new Vector4(new Vector3(-1, 1, -1) * oort, 1); Vector4 fbr_normal = new Vector4(new Vector3(1, -1, -1) * oort, 1); Vector4 bbr_normal = new Vector4(new Vector3(1, -1, 1) * oort, 1); Vector4 bbl_normal = new Vector4(new Vector3(-1, -1, 1) * oort, 1); Vector4 fbl_normal = new Vector4(new Vector3(-1, -1, -1) * oort, 1); // Instantiate Vertex buffer from vertex data var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] {/* // Cube vertices: // Front face front_bottom_left, red, fbl_normal, front_top_left, red, ftl_normal, front_top_right, red, ftr_normal, front_bottom_left, red, fbl_normal, front_top_right, red, ftr_normal, front_bottom_right, red, fbr_normal, // Back face back_bottom_left, green, bbl_normal, back_top_right, green, btr_normal, back_top_left, green, btl_normal, back_bottom_left, green, bbl_normal, back_bottom_right, green, bbr_normal, back_top_right, green, btr_normal, // Top face front_top_left, blue, ftl_normal, back_top_left, blue, btl_normal, back_top_right, blue, btr_normal, front_top_left, blue, ftl_normal, back_top_right, blue, btr_normal, front_top_right, blue, ftr_normal, // Bottom face front_bottom_left, yellow, fbl_normal, back_bottom_right, yellow, bbr_normal, back_bottom_left, yellow, bbl_normal, front_bottom_left, yellow, fbl_normal, front_bottom_right, yellow, fbr_normal, back_bottom_right, yellow, bbr_normal, // Left face front_bottom_left, magenta, fbl_normal, back_bottom_left, magenta, bbl_normal, back_top_left, magenta, btl_normal, front_bottom_left, magenta, fbl_normal, back_top_left, magenta, btl_normal, front_top_left, magenta, ftl_normal, // Right face front_bottom_right, cyan, fbr_normal, back_top_right, cyan, btr_normal, back_bottom_right, cyan, bbr_normal, front_bottom_right, cyan, fbr_normal, front_top_right, cyan, ftr_normal, back_top_right, cyan, btr_normal, */ // Cube vertices: // Front face front_bottom_left, red, front_normal, front_top_left, red, front_normal, front_top_right, red, front_normal, front_bottom_left, red, front_normal, front_top_right, red, front_normal, front_bottom_right, red, front_normal, // Back face back_bottom_left, green, back_normal, back_top_right, green, back_normal, back_top_left, green, back_normal, back_bottom_left, green, back_normal, back_bottom_right, green, back_normal, back_top_right, green, back_normal, // Top face front_top_left, blue, top_normal, back_top_left, blue, top_normal, back_top_right, blue, top_normal, front_top_left, blue, top_normal, back_top_right, blue, top_normal, front_top_right, blue, top_normal, // Bottom face front_bottom_left, yellow, bottom_normal, back_bottom_right, yellow, bottom_normal, back_bottom_left, yellow, bottom_normal, front_bottom_left, yellow, bottom_normal, front_bottom_right, yellow, bottom_normal, back_bottom_right, yellow, bottom_normal, // Left face front_bottom_left, magenta, left_normal, back_bottom_left, magenta, left_normal, back_top_left, magenta, left_normal, front_bottom_left, magenta, left_normal, back_top_left, magenta, left_normal, front_top_left, magenta, left_normal, // Right face front_bottom_right, cyan, right_normal, back_top_right, cyan, right_normal, back_bottom_right, cyan, right_normal, front_bottom_right, cyan, right_normal, front_top_right, cyan, right_normal, back_top_right, cyan, right_normal, }); // Create Constant Buffer: this is how we pass the relevant constant variables // (the projection matrix, light sources, etc.) to the shader var constantBuffer = new Buffer(device, Utilities.SizeOf<S_SHADER_GLOBALS>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); // Prepare all the stages: // Give the graphics card the shader structure context.InputAssembler.InputLayout = layout; // State how to interpret the vertices (in this case, as a // list of triangles context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; // Set up the relevant buffer to process the vertices // (primitives, fragments ...) using the shaders context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf<Vector4>() * 3, 0)); context.VertexShader.SetConstantBuffer(0, constantBuffer); context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); // Prepare matrices: // Here we have our "eye" - it has a position, the direction // that we're "looking" towards, and which direction is "up" // Note that LookAtLH wants a 3D vector, but our shader is going to want // a 4D vector (in homogeneous coordinates) Vector3 eyePos3 = new Vector3(200.0f, 100.0f, -5.0f); Vector4 eyePos4 = new Vector4(eyePos3, 1.0f); var view = Matrix.LookAtLH(eyePos3, new Vector3(200, 100, 0), Vector3.UnitY); // We'll just use the identity matrix as our projection matrix // for now - this would give us orthonormal projection, but // we'll recalculate it later Matrix proj = Matrix.Identity; // Use the clock var clock = new Stopwatch(); clock.Start(); // Declare texture for rendering (even though we aren't // using texture here :) ); we also set up our swap chain back buffer bool userResized = true; Texture2D backBuffer = null; RenderTargetView renderView = null; Texture2D depthBuffer = null; DepthStencilView depthView = null; // Set up the light, a grey ambient light and a white positional light // The positional light is currently located above and behind the cube // (because it's + in Y and + in Z) Vector4 lightAmbCol = new Vector4(0.0f, 0.0f, 0.0f, 1.0f); Vector4 lightPntCol = new Vector4(1.0f, 1.0f, 1.0f, 1.0f); Vector4 lightPntPos = new Vector4(200.0f, 100.0f, -10.0f, 1.0f); // Handle events where we resize our window form.UserResized += (sender, args) => userResized = true; // Main loop: render the objects for each frame of our scene RenderLoop.Run(form, () => { // If the window was resized, we need to reorganise // various properties of the window (don't worry about // this right now) if (userResized) { // Dispose all previous allocated resources ComObject.Dispose(ref backBuffer); ComObject.Dispose(ref renderView); ComObject.Dispose(ref depthBuffer); ComObject.Dispose(ref depthView); // Resize the backbuffer swapChain.ResizeBuffers(desc.BufferCount, form.ClientSize.Width, form.ClientSize.Height, Format.Unknown, SwapChainFlags.None); // Get the backbuffer from the swapchain backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); // Renderview on the backbuffer renderView = new RenderTargetView(device, backBuffer); // Create the depth buffer depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = form.ClientSize.Width, Height = form.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); // Create the depth buffer view depthView = new DepthStencilView(device, depthBuffer); // Setup targets and viewport for rendering context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.OutputMerger.SetTargets(depthView, renderView); // Setup new projection matrix with correct aspect ratio proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f); // We are done resizing userResized = false; } // Keep track of how much time has passed var time = clock.ElapsedMilliseconds / 1000.0f; // Combine the eye with the projection matrix so that we // can correctly transform co-ordinates into the frustum var viewProj = Matrix.Multiply(view, proj); // Clear views context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); context.ClearRenderTargetView(renderView, new Color4(0.0f,0.0f,0.0f,1.0f)); // Update WorldViewProj Matrix, to account for the scene // transformations according to the clock var world = Matrix.RotationX(time * 0.2f) * Matrix.RotationY(time * 0.5f) * Matrix.RotationZ(time * 0.7f) * Matrix.Translation(200, 100, 0); //var worldViewProj = Matrix.Identity; //worldViewProj *= viewProj; // Do some tricky matrix algebra so that we handle our // left-handed system properly world.Transpose(); viewProj.Transpose(); // Update our device handler with our struct containing all of the // constant variables for the shader // There are a couple of efficiency concerns here: // 1) We're creating a new variable every iteration through the render loop, and more importantly: // 2) We're updating all of the globals for every iteration through the render loop // Number (2) can mean that we're wasting a lot of effort re-writing variables to the graphics // card that haven't changed between iterations. S_SHADER_GLOBALS shaderGlobals = new S_SHADER_GLOBALS(eyePos4, lightAmbCol, lightPntPos, lightPntCol, world, viewProj); context.UpdateSubresource(ref shaderGlobals, constantBuffer); // Draw the cube context.Draw(36, 0); // Present! (Swap the buffers) swapChain.Present(0, PresentFlags.None); }); // The main loop ends here - this means the window has been // closed, so the program can end // Release all resources signature.Dispose(); vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vertices.Dispose(); layout.Dispose(); constantBuffer.Dispose(); depthBuffer.Dispose(); depthView.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); }