private Texture2D CaptureTexture(DeviceContext deviceContext, Texture2D source, out Texture2DDescription desc) { Device d3dDevice = deviceContext.Device; // debug: i got it! //D3D11.Texture2D texture = source.QueryInterface<D3D11.Texture2D>(); Texture2D staging = null; desc = source.Description; if (desc.SampleDescription.Count > 1) { desc.SampleDescription.Count = 1; desc.SampleDescription.Quality = 0; Texture2D temp = new Texture2D(d3dDevice, desc); DXGI.Format fmt = EnsureNotTypeless(desc.Format); FormatSupport support = d3dDevice.CheckFormatSupport(fmt); if ((support & FormatSupport.MultisampleResolve) == 0) { return(null); } for (int item = 0; item < desc.ArraySize; ++item) { for (int level = 0; level < desc.MipLevels; ++level) { int index = Resource.CalculateSubResourceIndex(level, item, desc.MipLevels); deviceContext.ResolveSubresource(temp, index, source, index, fmt); } } desc.BindFlags = 0; desc.OptionFlags &= ResourceOptionFlags.TextureCube; desc.CpuAccessFlags = CpuAccessFlags.Read; desc.Usage = ResourceUsage.Staging; staging = new Texture2D(d3dDevice, desc); deviceContext.CopyResource(temp, staging); } else if (desc.Usage == ResourceUsage.Staging && desc.CpuAccessFlags == CpuAccessFlags.Read) { staging = source; } else { desc.BindFlags = 0; desc.OptionFlags &= ResourceOptionFlags.TextureCube; desc.CpuAccessFlags = CpuAccessFlags.Read; desc.Usage = ResourceUsage.Staging; staging = new Texture2D(d3dDevice, desc); deviceContext.CopyResource(source, staging); } return(staging); }
public float ReadFloat(Buffer stagingBuffer, Buffer dataBuffer) { float[] buf = new float[1]; ctx.CopyResource(dataBuffer, stagingBuffer); var db = ctx.MapSubresource(stagingBuffer, 0, SharpDX.Direct3D11.MapMode.Read, MapFlags.None); Marshal.Copy(db.DataPointer, buf, 0, 1); ctx.UnmapSubresource(stagingBuffer, 0); return(buf[0]); }
/// <summary cref="DirectXBuffer.OnMap(DeviceContext)"/> protected override unsafe IntPtr OnMap(DeviceContext context) { Debug.Assert(box.IsEmpty); // Copy the texture into the staging texture if (ViewFlags != DirectXViewFlags.WriteDiscard) { context.CopyResource(Texture, stagingTexture); } var mapMode = CPUDirectXAccelerator.ConvertToMapMode(ViewFlags); box = context.MapSubresource(stagingTexture, 0, mapMode, MapFlags.None); // Reserve enough space var lengthInBytes = box.SlicePitch; EnsureSpace(lengthInBytes); if (ViewFlags != DirectXViewFlags.WriteDiscard) { // Copy the contents of the staging texture into the CPU-memory buffer System.Buffer.MemoryCopy( box.DataPointer.ToPointer(), cpuMemory.NativePtr.ToPointer(), lengthInBytes, lengthInBytes); } return(cpuMemory.NativePtr); }
public SpriteTexture CloneToSpriteTexture(DeviceContext context) { Texture2D clonedTexture = new Texture2D(context.Device, _textureDesc); context.CopyResource(RenderTargetTexture, clonedTexture); return(new SpriteTexture(context.Device, clonedTexture, Vector2I.Zero)); }
public Texture2D CloneTexture(DeviceContext context, ResourceUsage defaultResourceUsage) { // Setup the render target texture description. Texture2DDescription clonetextureDesc = new Texture2DDescription() { Width = _textureWidth, Height = _textureHeight, MipLevels = 1, ArraySize = 1, Format = _textureFormat, Usage = defaultResourceUsage, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription() { Count = 1, Quality = 0 } }; if (defaultResourceUsage == ResourceUsage.Staging) { clonetextureDesc.BindFlags = BindFlags.None; clonetextureDesc.CpuAccessFlags = CpuAccessFlags.Read | CpuAccessFlags.Write; } else { clonetextureDesc.BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource; clonetextureDesc.CpuAccessFlags = CpuAccessFlags.None; } Texture2D clonedTexture = new Texture2D(context.Device, clonetextureDesc); context.CopyResource(RenderTargetTexture, clonedTexture); return(clonedTexture); }
public void End() { _d3dContext.CopyResource(_buffer, _resultBuffer); _d3dContext.Flush(); _d3dContext.ComputeShader.SetUnorderedAccessView(0, null); _d3dContext.ComputeShader.Set(null); }
/// <summary> /// Captures the texture. /// </summary> /// <param name="context">The context.</param> /// <param name="source">The source.</param> /// <param name="stagingTexture">The staging texture.</param> /// <returns></returns> public static bool CaptureTexture(DeviceContext context, Texture2D source, out Texture2D stagingTexture) { stagingTexture = null; if (source == null) { return(false); } var desc = source.Description; if (source.Description.SampleDescription.Count > 1) { desc.SampleDescription.Count = 1; desc.SampleDescription.Quality = 0; using (var texture = new Texture2D(context.Device, desc)) { for (var i = 0; i < desc.ArraySize; ++i) { for (var level = 0; level < desc.MipLevels; ++level) { int mipSize; var index = texture.CalculateSubResourceIndex(level, i, out mipSize); context.ResolveSubresource(source, index, texture, index, desc.Format); } } desc.BindFlags = BindFlags.None; desc.Usage = ResourceUsage.Staging; desc.CpuAccessFlags = CpuAccessFlags.Read; desc.OptionFlags &= ResourceOptionFlags.TextureCube; stagingTexture = new Texture2D(context.Device, desc); context.CopyResource(texture, stagingTexture); } } else if (desc.Usage == ResourceUsage.Staging && desc.CpuAccessFlags == CpuAccessFlags.Read) { stagingTexture = source; } else { desc.BindFlags = BindFlags.None; desc.OptionFlags &= ResourceOptionFlags.TextureCube; desc.CpuAccessFlags = CpuAccessFlags.Read; desc.Usage = ResourceUsage.Staging; stagingTexture = new Texture2D(context.Device, desc); context.CopyResource(source, stagingTexture); } return(true); }
private FramePlaneDesc Map(DirectXResource input, DirectXDownloaderPlaneData plane, DeviceContext ctx) { ctx.CopyResource(plane.GpuTexture.Texture2D, plane.CpuTexture.Texture2D); var db = ctx.MapSubresource(plane.CpuTexture.Texture2D, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None); return(new FramePlaneDesc { Data = db.DataPointer, Stride = db.RowPitch, StrideCount = _height / plane.Format.HeightFactor }); }
public void Copy(DeviceContext ctx, DX11StructuredBuffer destination) { if (this.Size == destination.Size) { ctx.CopyResource(this.Buffer, destination.Buffer); } else { throw new Exception("Invalid Matching sizes"); } }
public void Copy(DeviceContext ctx, DX11StructuredBuffer <T> destination) { if (this.Size == destination.Size) { ctx.CopyResource(this.Buffer, destination.Buffer); } else { throw new Exception("Invalid Matching sizes"); } }
/// <summary> /// Converts rendered image to bitmap byte array /// </summary> /// <param name="backBuffer"></param> /// <returns></returns> private byte[] CalculateBitmapBytes(Texture2D backBuffer) { byte[] data = null; // We want to copy the texture from the back buffer Texture2DDescription desc = backBuffer.Description; desc.CpuAccessFlags = CpuAccessFlags.Read; desc.Usage = ResourceUsage.Staging; desc.OptionFlags = ResourceOptionFlags.None; desc.BindFlags = BindFlags.None; using (var texture = new Texture2D(_device, desc)) { _context.CopyResource(backBuffer, texture); using (var surface = texture.QueryInterface <Surface>()) { texture.Dispose(); DataStream dataStream; var map = surface.Map(SharpDX.DXGI.MapFlags.Read, out dataStream); int lines = (int)(dataStream.Length / map.Pitch); data = new byte[surface.Description.Width * surface.Description.Height * 4]; int dataCounter = 0; // Width of the surface - 4 bytes per pixel. Red, Green, Blue, Alpha(transparency) one byte each int actualWidth = surface.Description.Width * 4; for (int y = 0; y < lines; y++) { for (int x = 0; x < map.Pitch; x++) { if (x < actualWidth) { data[dataCounter++] = dataStream.Read <byte>(); } else { dataStream.Read <byte>(); } } } dataStream.Dispose(); surface.Unmap(); } } return(data); }
public T[] ReadContents(DeviceContext context) { context.CopyResource(buffer, stagingBuffer); DataBox dataBox = context.MapSubresource(stagingBuffer, 0, MapMode.Read, MapFlags.None, out DataStream dataStream); try { T[] elements = dataStream.ReadRange <T>(elementCount); return(elements); } finally { context.UnmapSubresource(stagingBuffer, 0); dataStream.Dispose(); } }
public void Render() { if (hmd == null) { return; } OculusWrap.OVR.Vector3f[] hmdToEyeViewOffsets = { eye_texes[0].HmdToEyeViewOffset, eye_texes[1].HmdToEyeViewOffset }; OculusWrap.OVR.FrameTiming frameTiming = hmd.GetFrameTiming(0); OculusWrap.OVR.TrackingState trackingState = hmd.GetTrackingState(frameTiming.DisplayMidpointSeconds); OculusWrap.OVR.Posef[] exe_poses = new OculusWrap.OVR.Posef[2]; // Calculate the position and orientation of each eye. oculus.CalcEyePoses(trackingState.HeadPose.ThePose, hmdToEyeViewOffsets, ref exe_poses); UVSCR_variable.Set(UVSCR()); for (int eye_idx = 0; eye_idx < 2; eye_idx++) { OculusWrap.OVR.EyeType eye = (OculusWrap.OVR.EyeType)eye_idx; EyeTexture eye_tex = eye_texes[eye_idx]; layer_eye_fov.RenderPose[eye_idx] = exe_poses[eye_idx]; // Retrieve the index of the active texture and select the next texture as being active next. int tex_idx = eye_tex.SwapTextureSet.CurrentIndex++; ctx.OutputMerger.SetRenderTargets(eye_tex.DepthStencilView, eye_tex.RenderTargetViews[tex_idx]); ctx.ClearDepthStencilView(eye_tex.DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0); ctx.ClearRenderTargetView(eye_tex.RenderTargetViews[tex_idx], ScreenColor); ctx.Rasterizer.SetViewport(eye_tex.Viewport); UpdateTransform(exe_poses[eye_idx], eye_tex.FieldOfView); DrawFigure(); } hmd.SubmitFrame(0, layers); ctx.CopyResource(mtex, buf0); swap_chain.Present(0, PresentFlags.None); }
///<summary>Works even on immutable buffers</summary> public byte[] ReadBuffer(Buffer buffer, int size) { using (Buffer tempBuffer = new Buffer(Device, new BufferDescription(size, ResourceUsage.Staging, BindFlags.None, CpuAccessFlags.Read, ResourceOptionFlags.None, 0))) { Context.CopyResource(buffer, tempBuffer); DataBox mappedBuffer = Context.MapSubresource(tempBuffer, 0, MapMode.Read, MapFlags.None); try { byte[] result = new byte[size]; Marshal.Copy(mappedBuffer.DataPointer, result, 0, size); return(result); } finally { Context.UnmapSubresource(tempBuffer, 0); } } }
/// <summary cref="DirectXBuffer.OnUnmap(DeviceContext)"/> protected override unsafe void OnUnmap(DeviceContext context) { if (ViewFlags != DirectXViewFlags.ReadOnly) { // We have to copy the contents of the CPU-memory buffer into the DX buffer Debug.Assert(!box.IsEmpty); System.Buffer.MemoryCopy( cpuMemory.NativePtr.ToPointer(), box.DataPointer.ToPointer(), cpuMemory.LengthInBytes, cpuMemory.LengthInBytes); } context.UnmapSubresource(stagingBuffer, 0); box = default; if (ViewFlags != DirectXViewFlags.ReadOnly) { context.CopyResource(stagingBuffer, Buffer); } }
public void MapObjectId() { DataStream dataStream; deviceContext.CopyResource(objectIdBuffer, objectIdStagingBuffer); DataBox dataBox = deviceContext.MapSubresource(objectIdStagingBuffer, 0, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out dataStream); for (int j = 0; j < objectIdDesc.Height; ++j) { // rows bytes are padded at the end up RowPitch number of bytes, in the texture data array, so move to the start of each row to read its data dataStream.Position = dataBox.RowPitch * j; for (int i = 0; i < objectIdDesc.Width; ++i) { PixelUserData[i, j] = dataStream.Read <uint>(); } } deviceContext.UnmapSubresource(objectIdStagingBuffer, 0); }
/// <summary cref="DirectXBuffer.OnMap(DeviceContext)"/> protected override unsafe IntPtr OnMap(DeviceContext context) { Debug.Assert(box.IsEmpty); var mapMode = CPUDirectXAccelerator.ConvertToMapMode(ViewFlags); // Copy the buffer to the staging buffer if (ViewFlags != DirectXViewFlags.WriteDiscard) { context.CopyResource(Buffer, stagingBuffer); } box = context.MapSubresource(stagingBuffer, 0, mapMode, MapFlags.None); // We have to copy the contents of the DX buffer into the CPU-memory buffer if (ViewFlags != DirectXViewFlags.WriteDiscard) { System.Buffer.MemoryCopy( box.DataPointer.ToPointer(), cpuMemory.NativePtr.ToPointer(), cpuMemory.LengthInBytes, cpuMemory.LengthInBytes); } return(cpuMemory.NativePtr); }
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); } }
public DataBox LockBuffer(DeviceContext context) { context.CopyResource(m_BufferObject, m_StagingBufferObject); return context.MapSubresource(m_StagingBufferObject, MapMode.Read, SlimDX.Direct3D11.MapFlags.None); }
public void SaveToFile(DeviceContext context, string path) { context.CopyResource(texRenderTargetTexture, extRenderTargetTexture); SharpDX.Direct3D11.Resource.ToFile(context, extRenderTargetTexture, ImageFileFormat.Jpg, path); }
public DataBox LockBuffer(DeviceContext context) { context.CopyResource(m_BufferObject, m_StagingBufferObject); return(context.MapSubresource(m_StagingBufferObject, MapMode.Read, SlimDX.Direct3D11.MapFlags.None)); }
/// <summary> /// 建立一個臨時的 Texture 以便擷取資源 /// </summary> /// <param name="source">來源texture</param> /// <param name="staging">複本texture</param> /// <returns></returns> private static Result CreateStagingTexture(DeviceContext deviceContext, Resource source, out Texture2DDescription desc, out Texture2D staging) { desc = new Texture2DDescription(); staging = null; if (deviceContext == null && source == null) { return(Result.InvalidArg); } ResourceDimension resourceDimension = source.Dimension; if (resourceDimension != ResourceDimension.Texture2D) { return(Result.InvalidArg); } if (!(source.QueryInterface <Texture2D>() is Texture2D src)) { return(Result.Fail); } desc = src.Description; var d3dDevice = deviceContext.Device; if (desc.SampleDescription.Count > 1) { desc.SampleDescription.Count = 1; desc.SampleDescription.Quality = 0; Texture2D temp; try { temp = new Texture2D(d3dDevice, desc); } catch (SharpDXException e) { return(e.ResultCode); } DXGI.Format fmt = desc.Format.EnsureNotTypeless(); FormatSupport support = FormatSupport.None; try { support = d3dDevice.CheckFormatSupport(fmt); } catch (SharpDXException e) { return(e.ResultCode); } if ((support & FormatSupport.MultisampleResolve) == 0) { return(Result.Fail); } for (int item = 0; item < desc.ArraySize; ++item) { for (int level = 0; level < desc.MipLevels; ++level) { int index = Resource.CalculateSubResourceIndex(level, item, desc.MipLevels); deviceContext.ResolveSubresource(temp, index, source, index, fmt); } } desc.BindFlags = BindFlags.None; desc.OptionFlags &= ResourceOptionFlags.TextureCube; desc.CpuAccessFlags = CpuAccessFlags.Read; desc.Usage = ResourceUsage.Staging; try { staging = new Texture2D(d3dDevice, desc); deviceContext.CopyResource(temp, staging); } catch (SharpDXException e) { return(e.ResultCode); } } else if (desc.Usage == ResourceUsage.Staging && desc.CpuAccessFlags == CpuAccessFlags.Read) { staging = source.QueryInterface <Texture2D>(); } else { desc.BindFlags = BindFlags.None; desc.OptionFlags &= ResourceOptionFlags.TextureCube; desc.CpuAccessFlags = CpuAccessFlags.Read; desc.Usage = ResourceUsage.Staging; try { staging = new Texture2D(d3dDevice, desc); if (staging != null) { deviceContext.CopyResource(source, staging); } else { return(Result.Fail); } } catch (SharpDXException e) { return(e.ResultCode); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); return(Result.Fail); } } return(Result.Ok); }
public static void Save(this Texture2D texture, DeviceContext context, Device device, string path, bool withMips) { var textureCopy = new Texture2D(device, new Texture2DDescription { Width = texture.Description.Width, Height = texture.Description.Height, MipLevels = texture.Description.MipLevels, ArraySize = texture.Description.ArraySize, Format = texture.Description.Format, Usage = ResourceUsage.Staging, SampleDescription = new SampleDescription(1, 0), BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, OptionFlags = ResourceOptionFlags.None }); context.CopyResource(texture, textureCopy); if (texture.Description.ArraySize == 1) { if (textureCopy.Description.Format == Format.R16G16_Float) { DataBox dataBox = context.MapSubresource( textureCopy, 0, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out DataStream dataStream); AssetsMeta.Texture2DAsset asset2D = new AssetsMeta.Texture2DAsset(); asset2D.Name = path; asset2D.Data.Width = textureCopy.Description.Width; asset2D.Data.Height = textureCopy.Description.Height; asset2D.Data.ColorSpace = ColorSpaceEnum.Linear; asset2D.Data.ChannelsCount = ChannelsCountEnum.Two; asset2D.Data.BytesPerChannel = BytesPerChannelEnum.Two; asset2D.Data.buffer = ReadFully(dataStream); AssetsManagerInstance.GetManager().FSWorker.CreateAssetFile(asset2D, true); context.UnmapSubresource(textureCopy, 0); textureCopy.Dispose(); return; } InternalSaveTexture($"{path}.png", 0, 0, Factory, textureCopy, context); textureCopy.Dispose(); return; } AssetsMeta.TextureCubeAsset asset = new AssetsMeta.TextureCubeAsset(); asset.Name = path; asset.Data.Width = textureCopy.Description.Width; asset.Data.Height = textureCopy.Description.Height; asset.Data.ColorSpace = ColorSpaceEnum.Linear; asset.Data.ChannelsCount = 4; asset.Data.BytesPerChannel = 2; asset.Data.MipLevels = withMips ? textureCopy.Description.MipLevels : 1; asset.Data.buffer = new byte[6][][]; for (int i = 0; i < 6; i++) { asset.Data.buffer[i] = new byte[asset.Data.MipLevels][]; for (int mip = 0; mip < asset.Data.MipLevels; mip++) { DataBox dataBox = context.MapSubresource( textureCopy, mip, i, MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out DataStream dataStream); byte[] allMipBytes = ReadFully(dataStream); dataStream.Dispose(); int mipSize = (int)(asset.Data.Width * Math.Pow(0.5, mip)); int pitch = mipSize * asset.Data.ChannelsCount * asset.Data.BytesPerChannel; int n = mipSize * pitch; asset.Data.buffer[i][mip] = new byte[n]; for (int j = 0; j < mipSize; j++) { for (int k = 0; k < pitch; k++) { asset.Data.buffer[i][mip][j * pitch + k] = allMipBytes[j * dataBox.RowPitch + k]; } } context.UnmapSubresource(textureCopy, textureCopy.CalculateSubResourceIndex(mip, i, out int m)); // Dont work cause wrong dataBox.RowPitch on mip levels issue. // asset.Data.buffer[i][mip] = ReadFully(dataStream); } } AssetsManagerInstance.GetManager().FSWorker.CreateAssetFile(asset, true); // DEBUG RO PNG /*if (textureCopy.Description.MipLevels != 5) { * textureCopy.Dispose(); * return; * } * * for (int mip = 0; mip < textureCopy.Description.MipLevels; mip++) { * for (int i = 0; i < texture.Description.ArraySize; i++) { * InternalSaveTexture($"{path}_{CubePostfixes[i]}_mip{mip}.png", i, mip, Factory, textureCopy, context); * } * }*/ textureCopy.Dispose(); }
/// <summary> /// バックバッファをBMP形式でファイルに保存します。 /// </summary> /// <param name="file">ファイル名</param> public void SaveToBitmap(string file) { var intermediateDesc = buf0.Description; intermediateDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0); var desc = buf0.Description; desc.BindFlags = SharpDX.Direct3D11.BindFlags.None; desc.Usage = SharpDX.Direct3D11.ResourceUsage.Staging; desc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read; desc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0); using (Texture2D intermediate = new SharpDX.Direct3D11.Texture2D(device, intermediateDesc)) { ctx.ResolveSubresource(buf0, 0, intermediate, 0, buf0.Description.Format); using (Texture2D buf1 = new SharpDX.Direct3D11.Texture2D(device, desc)) { ctx.CopyResource(intermediate, buf1); DataStream stream; ctx.MapSubresource(buf1, 0, MapMode.Read, MapFlags.None, out stream); IntPtr src = stream.DataPointer; using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(desc.Width, desc.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb)) { // Lock the bitmap's bits. System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height); System.Drawing.Imaging.BitmapData bitmapData = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, bitmap.PixelFormat); // Get the address of the first line. IntPtr ptr = bitmapData.Scan0; #if false Utilities.CopyMemory(ptr, src, bitmapData.Stride * bitmapData.Height); #endif // drop Alpha ch. for (int y = 0; y < bitmapData.Height; y++) { for (int x = 0; x < bitmapData.Width; x++) { Utilities.CopyMemory(ptr, src, 3); ptr = IntPtr.Add(ptr, 3); src = IntPtr.Add(src, 4); } } // Unlock the bits. bitmap.UnlockBits(bitmapData); bitmap.Save(file); } ctx.UnmapSubresource(buf1, 0); } } }
private Result CaptureTextureFix(DeviceContext deviceContext, Texture2D source, out Texture2DDescription desc, out Texture2D staging) { desc = new Texture2DDescription(); staging = null; if (deviceContext == null || source == null) { return(Result.InvalidArg); } var resType = source.Dimension; if (resType != ResourceDimension.Texture2D) { //string message = SharpDX.Diagnostics.ErrorManager.GetErrorMessage(0); //return Result.GetResultFromWin32Error(ERROR_NOT_SUPPORTED) } desc = source.Description; var d3dDevice = deviceContext.Device; //Texture2D staging = null; if (desc.SampleDescription.Count > 1) { desc.SampleDescription.Count = 1; desc.SampleDescription.Quality = 0; Texture2D temp; try { temp = new Texture2D(d3dDevice, desc); } catch (SharpDXException e) { return(e.ResultCode); } var fmt = EnsureNotTypeless(desc.Format); FormatSupport support; try { support = d3dDevice.CheckFormatSupport(fmt); } catch (SharpDXException e) { return(e.ResultCode); } if ((support & FormatSupport.MultisampleResolve) == 0) { return(Result.Fail); } for (var item = 0; item < desc.ArraySize; ++item) { for (var level = 0; level < desc.MipLevels; ++level) { var index = Resource.CalculateSubResourceIndex(level, item, desc.MipLevels); deviceContext.ResolveSubresource(temp, index, source, index, fmt); } } desc.BindFlags = 0; desc.OptionFlags &= ResourceOptionFlags.TextureCube; desc.CpuAccessFlags = CpuAccessFlags.Read; desc.Usage = ResourceUsage.Staging; try { staging = new Texture2D(d3dDevice, desc); deviceContext.CopyResource(temp, staging); } catch (SharpDXException e) { return(e.ResultCode); } } else if (desc.Usage == ResourceUsage.Staging && desc.CpuAccessFlags == CpuAccessFlags.Read) { staging = source; } else { desc.BindFlags = 0; desc.OptionFlags &= ResourceOptionFlags.TextureCube; desc.CpuAccessFlags = CpuAccessFlags.Read; desc.Usage = ResourceUsage.Staging; try { staging = new Texture2D(d3dDevice, desc); deviceContext.CopyResource(source, staging); } catch (SharpDXException e) { return(e.ResultCode); } } return(Result.Ok); }
public void CopyToStagingBuffer(DeviceContext context, Buffer sourceBuffer) { context.CopyResource(sourceBuffer, buffer); }
private static void ProjectCubeMap(ref DeviceContext context, ref Texture cubeMap, int order, out float[] resultR, out float[] resultG, out float[] resultB) { var desc = cubeMap.NativeTexture.Description; Texture2D texture; if (!desc.CpuAccessFlags.HasFlag(CpuAccessFlags.Read)) { var stagingDesc = desc; stagingDesc.BindFlags = BindFlags.None; stagingDesc.CpuAccessFlags = CpuAccessFlags.Read; stagingDesc.Usage = ResourceUsage.Staging; texture = new Texture2D(context.Device, stagingDesc); context.CopyResource(cubeMap.NativeTexture, texture); } else { texture = cubeMap.NativeTexture; } float fSize = desc.Width; float fPicSize = 1.0f / fSize; float fB = -1.0f + 1.0f / fSize; float fS = (desc.Width > 1) ? (2.0f * (1.0f - 1.0f / fSize) / (fSize - 1.0f)) : 0f; float fWt = 0.0f; resultR = new float[order * order]; resultG = new float[order * order]; resultB = new float[order * order]; var shBuff = new float[_maxOrder * _maxOrder]; var shBuffB = new float[_maxOrder * _maxOrder]; for (int face = 0; face < 6; face++) { var dindex = Resource.CalculateSubResourceIndex(0, face, desc.MipLevels); DataStream mapped; var box = context.MapSubresource(texture, dindex, MapMode.Read, 0, out mapped); var pSrc = mapped.DataPointer; for (var y = 0; y < desc.Height; ++y) { float fV = y * fS + fB; for (var x = 0; x < desc.Width; ++x) { float fU = x * fS + fB; float ix, iy, iz; switch (face) { case 0: // Positive X iz = 1.0f - (2.0f * x + 1.0f) * fPicSize; iy = 1.0f - (2.0f * y + 1.0f) * fPicSize; ix = 1.0f; break; case 1: // Negative X iz = -1.0f + (2.0f * x + 1.0f) * fPicSize; iy = 1.0f - (2.0f * y + 1.0f) * fPicSize; ix = -1; break; case 2: // Positive Y iz = -1.0f + (2.0f * y + 1.0f) * fPicSize; iy = 1.0f; ix = -1.0f + (2.0f * x + 1.0f) * fPicSize; break; case 3: // Negative Y iz = 1.0f - (2.0f * y + 1.0f) * fPicSize; iy = -1.0f; ix = -1.0f + (2.0f * x + 1.0f) * fPicSize; break; case 4: // Positive Z iz = 1.0f; iy = 1.0f - (2.0f * y + 1.0f) * fPicSize; ix = -1.0f + (2.0f * x + 1.0f) * fPicSize; break; case 5: // Negative Z iz = -1.0f; iy = 1.0f - (2.0f * y + 1.0f) * fPicSize; ix = 1.0f - (2.0f * x + 1.0f) * fPicSize; break; default: throw new AccessViolationException(nameof(order)); } var dir = new Vector3(ix, iy, iz).unit; float fDiffSolid = 4.0f / ((1.0f + fU * fU + fV * fV) * Mathf.Sqrt(1.0f + fU * fU + fV * fV)); fWt += fDiffSolid; EvalDirection(ref shBuff, order, ref dir); var colour = Marshal.PtrToStructure <Color4>(pSrc); pSrc += 4; SHAdd(ref resultR, order, ref resultR, SHScale(ref shBuffB, order, ref shBuff, colour.Red * fDiffSolid)); SHAdd(ref resultG, order, ref resultG, SHScale(ref shBuffB, order, ref shBuff, colour.Green * fDiffSolid)); SHAdd(ref resultB, order, ref resultB, SHScale(ref shBuffB, order, ref shBuff, colour.Blue * fDiffSolid)); } } context.UnmapSubresource(texture, dindex); } }