public void Draw(DeviceContextHolder holder, ShaderResourceView view, RenderTargetView target, TargetResourceTexture temporaryEdges, TargetResourceTexture temporaryBlending) { holder.PrepareQuad(_effect.LayoutPT); holder.DeviceContext.OutputMerger.BlendState = null; // edges holder.DeviceContext.OutputMerger.SetTargets(temporaryEdges.TargetView); holder.DeviceContext.ClearRenderTargetView(temporaryEdges.TargetView, new Color4(0f, 0f, 0f, 0f)); _effect.FxScreenSizeSpec.Set(new Vector4(1f / holder.Width, 1f / holder.Height, holder.Width, holder.Height)); _effect.FxInputMap.SetResource(view); _effect.TechSmaa.DrawAllPasses(holder.DeviceContext, 6); // blending holder.DeviceContext.OutputMerger.SetTargets(temporaryBlending.TargetView); holder.DeviceContext.ClearRenderTargetView(temporaryBlending.TargetView, new Color4(0f, 0f, 0f, 0f)); _effect.FxEdgesMap.SetResource(temporaryEdges.View); _effect.FxAreaTexMap.SetResource(_areasTexMap); _effect.FxSearchTexMap.SetResource(_searchTexMap); _effect.TechSmaaB.DrawAllPasses(holder.DeviceContext, 6); // final part holder.DeviceContext.OutputMerger.SetTargets(target); _effect.FxBlendMap.SetResource(temporaryBlending.View); _effect.TechSmaaN.DrawAllPasses(holder.DeviceContext, 6); }
public override void Resize(DeviceContextHolder holder, int width, int height) { if (width == Width && height == Height) return; base.Resize(holder, width, height); TargetView = new RenderTargetView(holder.Device, Texture); View = new ShaderResourceView(holder.Device, Texture); }
/// <summary> /// Create Direct3D device and swap chain /// </summary> public void InitDevice() { device = D3DDevice.CreateDeviceAndSwapChain(host.Handle, out swapChain); // Create a render target view using (Texture2D pBuffer = swapChain.GetBuffer<Texture2D>(0)) { renderTargetView = device.CreateRenderTargetView(pBuffer); } device.OM.SetRenderTargets(new RenderTargetView[] { renderTargetView }, null); // Setup the viewport Viewport vp = new Viewport() { Width = (uint)host.ActualWidth, Height = (uint)host.ActualHeight, MinDepth = 0.0f, MaxDepth = 1.0f, TopLeftX = 0, TopLeftY = 0 }; device.RS.SetViewports(new Viewport[] { vp }); }
public void InitializeD3D() { var description = new SwapChainDescription() { BufferCount = 2, Usage = Usage.RenderTargetOutput, OutputHandle = form.Handle, IsWindowed = true, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(1, 0), Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard }; //Create swap chain Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out this.device, out swapChain); // create a view of our render target, which is the backbuffer of the swap chain we just created // setting a viewport is required if you want to actually see anything var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0); renderTarget = new RenderTargetView(device, resource); var context = device.ImmediateContext; var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height); context.OutputMerger.SetTargets(renderTarget); context.Rasterizer.SetViewports(viewport); }
public void LoadResources() { if (m_Disposed == true) { Buffer = new Texture2D(GameEnvironment.Device, new Texture2DDescription() { Format = m_Format, Width = m_Width, Height = m_Height, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }); View = new RenderTargetView(GameEnvironment.Device, Buffer); ResourceView = new ShaderResourceView(GameEnvironment.Device, Buffer); Viewport = new Viewport(0, 0, Buffer.Description.Width, Buffer.Description.Height); m_Disposed = false; } }
//void Update() //{ // stereoCamera.Update(); // SceneTree.Update(); // isDirty = false; //} public override void Execute() { //Game.RenderEvent.Wait(); //if (isDirty) // Update(); //stereoCamera.Update(); //SceneTree.Update(); lTexture = new Texture2D(Game.Context.Device, RenderTextureDesc); rTexture = new Texture2D(Game.Context.Device, RenderTextureDesc); rTargetViewLeft = new SlimDX.Direct3D11.RenderTargetView(Game.Context.Device, lTexture); rTargetViewRight = new SlimDX.Direct3D11.RenderTargetView(Game.Context.Device, rTexture); stereoCamera.EnableLeftStereoProjection(); RenderSceneImage(lTexture, rTargetViewLeft); stereoCamera.EnableRightStereoProjection(); RenderSceneImage(rTexture, rTargetViewRight); Texture2D newTexture = Stereo.Make3D(lTexture, rTexture); FreeResources(); Texture = newTexture; }
private void InitalizeGraphics() { if (Window.RenderCanvasHandle == IntPtr.Zero) throw new InvalidOperationException("Window handle cannot be zero"); SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = 1, Flags = SwapChainFlags.None, IsWindowed = true, OutputHandle = Window.RenderCanvasHandle, SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, ModeDescription = new ModeDescription() { Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm, //Format = SlimDX.DXGI.Format.B8G8R8A8_UNorm, Width = Window.ClientSize.Width, Height = Window.ClientSize.Height, RefreshRate = new Rational(60, 1), Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrdering.Unspecified }, SampleDescription = new SampleDescription(1, 0) }; var giFactory = new SlimDX.DXGI.Factory(); var adapter = giFactory.GetAdapter(0); Device device; SwapChain swapChain; Device.CreateWithSwapChain(adapter, DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); _swapChain = swapChain; GraphicsDevice = device; // create a view of our render target, which is the backbuffer of the swap chain we just created using (var resource = SlimDX.Direct3D10.Resource.FromSwapChain<Texture2D>(swapChain, 0)) { _backBuffer = new RenderTargetView(device, resource); } // setting a viewport is required if you want to actually see anything var viewport = new Viewport(0, 0, Window.ClientSize.Width, Window.ClientSize.Height); device.OutputMerger.SetTargets(_backBuffer); device.Rasterizer.SetViewports(viewport); CreateDepthStencil(); LoadVisualizationEffect(); // Allocate a large buffer to write the PhysX visualization vertices into // There's more optimized ways of doing this, but for this sample a large buffer will do _userPrimitivesBuffer = new SlimDX.Direct3D10.Buffer(GraphicsDevice, VertexPositionColor.SizeInBytes * 50000, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None); var elements = new[] { new InputElement("Position", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("Color", 0, Format.R32G32B32A32_Float, 16, 0) }; _inputLayout = new InputLayout(GraphicsDevice, _visualizationEffect.RenderScenePass0.Description.Signature, elements); }
protected D3DApp(IntPtr hInstance) { AppInst = hInstance; MainWindowCaption = "D3D11 Application"; DriverType = DriverType.Hardware; ClientWidth = 800; ClientHeight = 600; Enable4XMsaa = false; Window = null; AppPaused = false; Minimized = false; Maximized = false; Resizing = false; Msaa4XQuality = 0; Device = null; ImmediateContext = null; SwapChain = null; DepthStencilBuffer = null; RenderTargetView = null; DepthStencilView = null; Viewport = new Viewport(); Timer = new GameTimer(); GD3DApp = this; }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); SwapChainDescription desc=new SwapChainDescription() { BufferCount = 2, Flags = SwapChainFlags.AllowModeSwitch, IsWindowed = true, ModeDescription = new ModeDescription() { Format = Format.R8G8B8A8_UNorm, Height = Height, Width = Width, RefreshRate = new Rational(1,60), Scaling = DisplayModeScaling.Centered, ScanlineOrdering = DisplayModeScanlineOrdering.Progressive }, OutputHandle = Handle, SampleDescription = new SampleDescription(1,0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, new FeatureLevel[1] {FeatureLevel.Level_11_0}, desc, out device, out swapChain); using (Texture2D tex=Texture2D.FromSwapChain<Texture2D>(swapChain,0)) { renderTarget=new RenderTargetView(device,tex); } }
protected override void OnResourceLoad() { using (Texture2D texture = Texture2D.FromSwapChain<Texture2D>(Context10.SwapChain, 0)) { renderTargetView = new RenderTargetView(Context10.Device, texture); } effect = Effect.FromFile(Context10.Device, "SimpleTriangle10.fx", "fx_4_0"); technique = effect.GetTechniqueByIndex(0); pass = technique.GetPassByIndex(0); ShaderSignature signature = pass.Description.Signature; inputLayout = new InputLayout(Context10.Device, signature, new[] { new InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, SlimDX.DXGI.Format.R32G32B32A32_Float, 16, 0) }); vertexBuffer = new Buffer( Context10.Device, 3 * 32, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None ); DataStream stream = vertexBuffer.Map(MapMode.WriteDiscard, MapFlags.None); stream.WriteRange(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) }); vertexBuffer.Unmap(); }
public DX11RenderTexture3D(DX11RenderContext context, int w, int h, int d, Format format) : base(context) { Texture3DDescription desc = new Texture3DDescription() { BindFlags = BindFlags.UnorderedAccess | BindFlags.ShaderResource | BindFlags.RenderTarget, CpuAccessFlags = CpuAccessFlags.None, Depth = d, Format = format, Height = h, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, Usage = ResourceUsage.Default, Width = w }; RenderTargetViewDescription rtvd = new RenderTargetViewDescription(); rtvd.Format = format; rtvd.Dimension = RenderTargetViewDimension.Texture3D; rtvd.MipSlice = 0; rtvd.FirstDepthSlice = 0; rtvd.DepthSliceCount = d; this.Resource = new Texture3D(context.Device, desc); this.SRV = new ShaderResourceView(context.Device, this.Resource); this.UAV = new UnorderedAccessView(context.Device, this.Resource); this.RTV = new RenderTargetView(context.Device, this.Resource, rtvd); this.Width = desc.Width; this.Height = desc.Height; this.Format = desc.Format; this.Depth = desc.Depth; }
/// <summary> /// Constructor /// Creates the texture we will render to based on the supplied width and height /// </summary> /// <param name="device">The device we will create the texture with</param> /// <param name="texWidth"></param> /// <param name="texHeight"></param> public RenderTexture(Device device, int texWidth, int texHeight) { Texture2DDescription textureDescription = new Texture2DDescription() { Width = texWidth, Height = texHeight, MipLevels = 1, ArraySize = 1, Format = SlimDX.DXGI.Format.R32G32B32A32_Float, SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0), BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, Usage = ResourceUsage.Default, }; Texture = new Texture2D(device, textureDescription); RenderTargetViewDescription renderTargetViewDescription = new RenderTargetViewDescription() { Format = textureDescription.Format, Dimension = RenderTargetViewDimension.Texture2D, MipSlice = 0, }; renderTargetView = new RenderTargetView(device, Texture, renderTargetViewDescription); ShaderResourceViewDescription shaderResourceViewDescription = new ShaderResourceViewDescription() { Format = textureDescription.Format, Dimension = ShaderResourceViewDimension.Texture2D, MostDetailedMip = 0, MipLevels = 1 }; shaderResourceView = new ShaderResourceView(device, Texture, shaderResourceViewDescription); }
/// <summary> /// Create Direct3D device and swap chain /// </summary> protected void InitDevice() { device = D3DDevice.CreateDeviceAndSwapChain(directControl.Handle, out swapChain); // Create a render target view using (Texture2D pBuffer = swapChain.GetBuffer<Texture2D>(0)) { renderTargetView = device.CreateRenderTargetView(pBuffer); } device.OM.SetRenderTargets(new RenderTargetView[] { renderTargetView }); // Setup the viewport Viewport vp = new Viewport() { Width = (uint)directControl.ClientSize.Width, Height = (uint)directControl.ClientSize.Height, MinDepth = 0.0f, MaxDepth = 1.0f, TopLeftX = 0, TopLeftY = 0 }; device.RS.SetViewports(new Viewport[] { vp }); }
public static void CreateDeviceSwapChainAndRenderTarget(Form form, out Device device, out SwapChain swapChain, out RenderTargetView renderTarget) { try { // the debug mode requires the sdk to be installed otherwise an exception is thrown device = new Device(DeviceCreationFlags.Debug); } catch (Direct3D10Exception) { device = new Device(DeviceCreationFlags.None); } var swapChainDescription = new SwapChainDescription(); var modeDescription = new ModeDescription(); var sampleDescription = new SampleDescription(); modeDescription.Format = Format.R8G8B8A8_UNorm; modeDescription.RefreshRate = new Rational(60, 1); modeDescription.Scaling = DisplayModeScaling.Unspecified; modeDescription.ScanlineOrdering = DisplayModeScanlineOrdering.Unspecified; modeDescription.Width = WIDTH; modeDescription.Height = HEIGHT; sampleDescription.Count = 1; sampleDescription.Quality = 0; swapChainDescription.ModeDescription = modeDescription; swapChainDescription.SampleDescription = sampleDescription; swapChainDescription.BufferCount = 1; swapChainDescription.Flags = SwapChainFlags.None; swapChainDescription.IsWindowed = true; swapChainDescription.OutputHandle = form.Handle; swapChainDescription.SwapEffect = SwapEffect.Discard; swapChainDescription.Usage = Usage.RenderTargetOutput; using (var factory = new Factory()) { swapChain = new SwapChain(factory, device, swapChainDescription); } using (var resource = swapChain.GetBuffer<Texture2D>(0)) { renderTarget = new RenderTargetView(device, resource); } var viewport = new Viewport { X = 0, Y = 0, Width = WIDTH, Height = HEIGHT, MinZ = 0.0f, MaxZ = 1.0f }; device.Rasterizer.SetViewports(viewport); device.OutputMerger.SetTargets(renderTarget); }
public void Draw(DeviceContextHolder holder, ShaderResourceView view, RenderTargetView target) { holder.DeviceContext.OutputMerger.SetTargets(target); holder.QuadBuffers.Prepare(holder.DeviceContext, _effect.LayoutPT); _effect.FxScreenSize.Set(new Vector4(holder.Width, holder.Height, 1f / holder.Width, 1f / holder.Height)); _effect.FxInputMap.SetResource(view); _effect.TechFxaa.DrawAllPasses(holder.DeviceContext, 6); }
public override void Dispose() { base.Dispose(); if (TargetView != null) { TargetView.Dispose(); TargetView = null; } }
public RenderTargetTexture(Device device, int width, int height, Format format = Format.B8G8R8A8_UNorm, ResourceOptionFlags optionFlags = ResourceOptionFlags.None) : base(new Texture2D(device, CreateTextureDescription(width, height, format, optionFlags))) { InternalRenderTargetView = new RenderTargetView(device, InternalTexture2D); }
public DX11RenderTarget2D(DX11RenderContext context, Texture2D tex) { this.context = context; this.Resource = tex; this.SRV = new ShaderResourceView(context.Device, tex); this.RTV = new RenderTargetView(context.Device, tex); }
public View(Viewer viewer, Viewport viewport, RenderTargetView target) { if (viewer == null) throw new ArgumentNullException("viewer"); if (target == null) throw new ArgumentNullException("target"); Viewer = viewer; Viewport = viewport; Target = target; }
public void Render( DeviceContext deviceContext, Viewport viewport, RenderTargetView renderTargetView, DepthStencilView depthStencilView ) { deviceContext.ClearRenderTargetView( renderTargetView, Constants.CLEAR_COLOR ); deviceContext.ClearDepthStencilView( depthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0x00 ); //mTinyTextContext.Print( viewport, "Frame Time: " + FrameTimeString, 10, 10 ); //mTinyTextContext.Render(); mStopwatch.Reset(); mStopwatch.Start(); }
private void CreateRenderTargetView() { var renderTargetViewDesc = new RenderTargetViewDescription(); renderTargetViewDesc.ArraySize = layerCount; renderTargetViewDesc.Dimension = RenderTargetViewDimension.Texture2DArray; renderTargetViewDesc.FirstArraySlice = 0; renderTargetViewDesc.Format = format; renderTargetViewDesc.MipSlice = 0; renderTargetViewAsArray = new RenderTargetView(device, texture, renderTargetViewDesc); }
void InitDevice() { // create Direct 3D device device = D3DDevice.CreateDeviceAndSwapChain(renderHost.Handle); swapChain = device.SwapChain; // Create a render target view using (Texture2D pBuffer = swapChain.GetBuffer<Texture2D>(0)) { renderTargetView = device.CreateRenderTargetView(pBuffer); } // Create depth stencil texture Texture2DDescription descDepth = new Texture2DDescription() { Width = (uint)renderHost.ActualWidth, Height = (uint)renderHost.ActualHeight, MipLevels = 1, ArraySize = 1, Format = Format.D32Float, SampleDescription = new SampleDescription() { Count = 1, Quality = 0 }, BindingOptions = BindingOptions.DepthStencil, }; depthStencil = device.CreateTexture2D(descDepth); // Create the depth stencil view DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription() { Format = descDepth.Format, ViewDimension = DepthStencilViewDimension.Texture2D }; depthStencilView = device.CreateDepthStencilView(depthStencil, depthStencilViewDesc); // bind the views to the device device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { renderTargetView }, depthStencilView); // Setup the viewport Viewport vp = new Viewport() { Width = (uint)renderHost.ActualWidth, Height = (uint)renderHost.ActualHeight, MinDepth = 0.0f, MaxDepth = 1.0f, TopLeftX = 0, TopLeftY = 0 }; device.RS.Viewports = new Viewport[] { vp }; }
public void Apply() { if (stack.Count > 0) { stack.Peek().Apply(context.CurrentDeviceContext); } else { RenderTargetView[] zero = new RenderTargetView[] { null,null,null,null,null,null,null,null }; context.CurrentDeviceContext.OutputMerger.SetTargets(null, zero); } }
private void CreateRenderTargetViews() { var renderTargetViewDesc = new RenderTargetViewDescription(); renderTargetViewDesc.Format = texture.Description.Format; renderTargetViewDesc.Dimension = RenderTargetViewDimension.Texture2DArray; renderTargetViewDesc.ArraySize = 1; renderTargetViewDesc.MipSlice = 0; for (int i = 0; i < deferredShadingConfiguration.LayerCount; ++i) { renderTargetViewDesc.FirstArraySlice = i; var renderTargetView = new RenderTargetView(device, texture, renderTargetViewDesc); renderTargetViews.Add(renderTargetView); } }
// Functions public TextureObject() { m_Width = m_Height = 1; m_Mips = 1; m_Depth = 1; m_ArraySize = 1; m_IsCube = false; m_TexFormat = Format.Unknown; m_TextureObject2D = null; m_TextureObject3D = null; m_RenderTargetView = null; m_ShaderResourceView = null; m_DepthStencilView = null; m_UnorderedAccessView = null; m_ArrayRenderTargetViews = null; m_ArrayShaderResourceViews = null; m_ArrayDepthStencilViews = null; m_ArrayUnorderedAccessViews = null; }
public RenderToTextureCommand(int width, int height, SceneManager sceneTree) : base(CommandType.Action) { SceneTree = sceneTree; RenderTextureDesc = new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R8G8B8A8_UNorm, Width = width, Height = height, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; texture = new Texture2D(Game.Context.Device, RenderTextureDesc); Texture2DDescription depthBufferDesc = new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, Format = Format.D32_Float, Width = width, Height = height, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; using (Texture2D depthBuffer = new Texture2D(Game.Context.Device, depthBufferDesc)) { DepthStencilView = new DepthStencilView(Game.Context.Device, depthBuffer); } RenderTargetView = new RenderTargetView(Game.Context.Device, texture); }
public void Initialize() { var description = new SwapChainDescription { BufferCount = 1, Usage = Usage.RenderTargetOutput, OutputHandle = _form.Handle, IsWindowed = true, ModeDescription = new ModeDescription { Width = 0, Height = 0, Format = Format.R8G8B8A8_UNorm, RefreshRate = new Rational(60, 1), Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrdering.Unspecified }, SampleDescription = new SampleDescription { Count = 1, Quality = 0 }, Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard }; // Create device SlimDX.Direct3D10_1.Device1.CreateWithSwapChain(null, DriverType.Hardware, DeviceCreationFlags.None, description, out _device, out _swapChain); using (var resource = Resource.FromSwapChain<Texture2D>(_swapChain, 0)) { _renderTargetView = new RenderTargetView(_device, resource); } _viewport = new Viewport(0, 0, _form.ClientSize.Width, _form.ClientSize.Height, 0.0f, 1.0f); _device.Rasterizer.SetViewports(_viewport); _device.OutputMerger.SetTargets(_renderTargetView); }
private void MainForm_Load(object sender, System.EventArgs e) { // Creating device (we accept dx10 cards or greater) FeatureLevel[] levels = { FeatureLevel.Level_11_0, FeatureLevel.Level_10_1, FeatureLevel.Level_10_0 }; // Defining our swap chain SwapChainDescription desc = new SwapChainDescription(); desc.BufferCount = 1; desc.Usage = Usage.BackBuffer | Usage.RenderTargetOutput; desc.ModeDescription = new ModeDescription(0, 0, new Rational(0, 0), Format.R8G8B8A8_UNorm); desc.SampleDescription = new SampleDescription(1, 0); desc.OutputHandle = Handle; desc.IsWindowed = true; desc.SwapEffect = SwapEffect.Discard; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, levels, desc, out device11, out swapChain); // Getting back buffer backBuffer = Resource.FromSwapChain<Texture2D>(swapChain, 0); // Defining render view renderTargetView = new RenderTargetView(device11, backBuffer); device11.ImmediateContext.OutputMerger.SetTargets(renderTargetView); device11.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, ClientSize.Width, ClientSize.Height, 0.0f, 1.0f)); // Preparing shaders PrepareShaders(); // Creating geometry CreateGeometry(); // Setting constants AffectConstants(); }
public override void Resize(DeviceContextHolder holder, int width, int height) { base.Resize(holder, width, height); StencilView = new DepthStencilView(holder.Device, Texture, new DepthStencilViewDescription { Flags = DepthStencilViewFlags.None, Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, MipSlice = 0 }); TargetView = new RenderTargetView(holder.Device, Texture, new RenderTargetViewDescription { MipSlice = 0, Dimension = RenderTargetViewDimension.Texture2D, Format = Format.D24_UNorm_S8_UInt }); View = new ShaderResourceView(holder.Device, Texture, new ShaderResourceViewDescription { Format = Format.R24_UNorm_X8_Typeless, Dimension = ShaderResourceViewDimension.Texture2D, MipLevels = 1, MostDetailedMip = 0 }); }
public void Shutdown() { // Before shutting down set to windowed mode or when you release the swap chain it will throw an exception. if (SwapChain != null) { SwapChain.SetFullscreenState(false, null); } if (AlphaEnableBlendingState != null) { AlphaEnableBlendingState.Dispose(); AlphaEnableBlendingState = null; } if (AlphaDisableBlendingState != null) { AlphaDisableBlendingState.Dispose(); AlphaDisableBlendingState = null; } if (DepthDisabledStencilState != null) { DepthDisabledStencilState.Dispose(); DepthDisabledStencilState = null; } if (RasterState != null) { RasterState.Dispose(); RasterState = null; } if (DepthStencilView != null) { DepthStencilView.Dispose(); DepthStencilView = null; } if (DepthStencilState != null) { DepthStencilState.Dispose(); DepthStencilState = null; } if (DepthStencilBuffer != null) { DepthStencilBuffer.Dispose(); DepthStencilBuffer = null; } if (RenderTargetView != null) { RenderTargetView.Dispose(); RenderTargetView = null; } if (Device != null) { Device.Dispose(); Device = null; } if (SwapChain != null) { SwapChain.Dispose(); SwapChain = null; } }
public void Draw(DeviceContextHolder holder, ShaderResourceView view, RenderTargetView target) { Draw(holder, view, target, false); }
private void Initialize() { factory2d = new Factory2D(SharpDX.Direct2D1.FactoryType.MultiThreaded, DebugLevel.Information); HookControl = Control.FromHandle(HookHandle); HookControl.Resize += HookResized; var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(0, 0, new Rational(0, 0), Format.B8G8R8A8_UNorm), // BGRA | Required for Direct2D/DirectWrite (<Win8) IsWindowed = true, OutputHandle = HookHandle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; /* [Enable Debug Layer] * * https://docs.microsoft.com/en-us/windows/win32/direct3d11/using-the-debug-layer-to-test-apps * To use this flag, you must have D3D11*SDKLayers.dll installed; otherwise, device creation fails. To get D3D11_1SDKLayers.dll, install the SDK for Windows 8. */ // Enable on-demand to avoid "Failed to create device issue" //#if DEBUG // Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport, desc, out device, out swapChain); //#else Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, out device, out swapChain); //#endif var factory = swapChain.GetParent <FactoryDX>(); factory.MakeWindowAssociation(HookHandle, WindowAssociationFlags.IgnoreAll); backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); rtv = new RenderTargetView(device, backBuffer); context = device.ImmediateContext; factoryWrite = new FactoryDW(); surface = backBuffer.QueryInterface <Surface>(); rtv2d = new RenderTarget(factory2d, surface, new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied))); brush2d = new SolidColorBrush(rtv2d, Color.White); var VertexShaderByteCode = ShaderBytecode.Compile(Properties.Resources.VertexShader, "main", "vs_5_0", ShaderFlags.Debug); vertexLayout = new InputLayout(device, VertexShaderByteCode, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), }); vertexShader = new VertexShader(device, VertexShaderByteCode); var PixelShaderByteCode = ShaderBytecode.Compile(Properties.Resources.PixelShader, "main", "ps_5_0", ShaderFlags.Debug); pixelShader = new PixelShader(device, PixelShaderByteCode); var PixelShaderByteCodeYUV = ShaderBytecode.Compile(Properties.Resources.PixelShader_YUV, "main", "ps_5_0", ShaderFlags.Debug); pixelShaderYUV = new PixelShader(device, PixelShaderByteCodeYUV); vertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer, new[] { -1.0f, -1.0f, 0, 0.0f, 1.0f, -1.0f, 1.0f, 0, 0.0f, 0.0f, 1.0f, -1.0f, 0, 1.0f, 1.0f, 1.0f, -1.0f, 0, 1.0f, 1.0f, -1.0f, 1.0f, 0, 0.0f, 0.0f, 1.0f, 1.0f, 0, 1.0f, 0.0f }); SamplerState textureSampler = new SamplerState(device, new SamplerStateDescription() { AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, ComparisonFunction = Comparison.Never, Filter = Filter.MinMagMipLinear, MaximumAnisotropy = 1, MaximumLod = float.MaxValue, MinimumLod = 0, MipLodBias = 0.0f }); context.InputAssembler.InputLayout = vertexLayout; context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, Utilities.SizeOf <float>() * 5, 0)); context.VertexShader.Set(vertexShader); context.PixelShader.SetSampler(0, textureSampler); textureRGB = new Texture2D(device, new Texture2DDescription() { Usage = ResourceUsage.Default, Format = Format.R8G8B8A8_UNorm, Width = HookControl.Width, Height = HookControl.Height, BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), ArraySize = 1, MipLevels = 1 }); srvDescYUV = new ShaderResourceViewDescription(); srvDescYUV.Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D; srvDescYUV.Format = Format.R8_UNorm; srvDescYUV.Texture2D.MostDetailedMip = 0; srvDescYUV.Texture2D.MipLevels = 1; videoDevice1 = device.QueryInterface <VideoDevice1>(); videoContext1 = device.ImmediateContext.QueryInterface <VideoContext1>(); vpcd = new VideoProcessorContentDescription() { Usage = VideoUsage.PlaybackNormal, InputFrameFormat = VideoFrameFormat.Progressive, InputFrameRate = new Rational(1, 1), OutputFrameRate = new Rational(1, 1), InputWidth = 1, OutputWidth = 1, InputHeight = 1, OutputHeight = 1 }; videoDevice1.CreateVideoProcessorEnumerator(ref vpcd, out vpe); videoDevice1.CreateVideoProcessor(vpe, 0, out videoProcessor); vpivd = new VideoProcessorInputViewDescription() { FourCC = 0, Dimension = VpivDimension.Texture2D, Texture2D = new Texture2DVpiv() { MipSlice = 0, ArraySlice = 0 } }; vpovd = new VideoProcessorOutputViewDescription() { Dimension = VpovDimension.Texture2D }; vpsa = new VideoProcessorStream[1]; SetViewport(); //foreach (var osdsurf in osd) //osdsurf.Value.Init(); }
public DepthAndColorShader(Device device) { shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorFloatVS.cso")); depthAndColorVS = new VertexShader(device, shaderByteCode); depthAndColorGS = new GeometryShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorGS.cso"))); depthAndColorPS = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorPS.cso"))); // depth stencil state var depthStencilStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.LessEqual, IsStencilEnabled = false, }; depthStencilState = new DepthStencilState(device, depthStencilStateDesc); // rasterizer state var rasterizerStateDesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsDepthClipEnabled = true, IsFrontCounterClockwise = true, IsMultisampleEnabled = true, }; rasterizerState = new RasterizerState(device, rasterizerStateDesc); // color sampler state var colorSamplerStateDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Border, AddressV = TextureAddressMode.Border, AddressW = TextureAddressMode.Border, //BorderColor = new SharpDX.Color4(0.5f, 0.5f, 0.5f, 1.0f), BorderColor = new SharpDX.Color4(0, 0, 0, 1.0f), }; colorSamplerState = new SamplerState(device, colorSamplerStateDesc); //// Kinect depth image //var depthImageTextureDesc = new Texture2DDescription() //{ // Width = depthImageWidth, // Height = depthImageHeight, // MipLevels = 1, // ArraySize = 1, // Format = SharpDX.DXGI.Format.R16_UInt, // R32_Float // SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), // Usage = ResourceUsage.Dynamic, // BindFlags = BindFlags.ShaderResource, // CpuAccessFlags = CpuAccessFlags.Write, //}; //depthImageTexture = new Texture2D(device, depthImageTextureDesc); //depthImageTextureRV = new ShaderResourceView(device, depthImageTexture); // filtered depth image var filteredDepthImageTextureDesc = new Texture2DDescription() { Width = depthImageWidth * 3, Height = depthImageHeight * 3, MipLevels = 1, ArraySize = 1, Format = SharpDX.DXGI.Format.R32G32_Float, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, }; filteredDepthImageTexture = new Texture2D(device, filteredDepthImageTextureDesc); filteredRenderTargetView = new RenderTargetView(device, filteredDepthImageTexture); filteredDepthImageSRV = new ShaderResourceView(device, filteredDepthImageTexture); filteredDepthImageTexture2 = new Texture2D(device, filteredDepthImageTextureDesc); filteredRenderTargetView2 = new RenderTargetView(device, filteredDepthImageTexture2); filteredDepthImageSRV2 = new ShaderResourceView(device, filteredDepthImageTexture2); //// Kinect color image //var colorImageStagingTextureDesc = new Texture2DDescription() //{ // Width = colorImageWidth, // Height = colorImageHeight, // MipLevels = 1, // ArraySize = 1, // Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, // //Format = SharpDX.DXGI.Format.YUY2 // SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), // Usage = ResourceUsage.Dynamic, // BindFlags = BindFlags.ShaderResource, // CpuAccessFlags = CpuAccessFlags.Write //}; //colorImageStagingTexture = new Texture2D(device, colorImageStagingTextureDesc); //var colorImageTextureDesc = new Texture2DDescription() //{ // Width = colorImageWidth, // Height = colorImageHeight, // MipLevels = 0, // ArraySize = 1, // Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, // SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), // Usage = ResourceUsage.Default, // BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget, // CpuAccessFlags = CpuAccessFlags.None, // OptionFlags = ResourceOptionFlags.GenerateMipMaps //}; //colorImageTexture = new Texture2D(device, colorImageTextureDesc); //colorImageTextureRV = new ShaderResourceView(device, colorImageTexture); // constant buffer var constantBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, SizeInBytes = ConstantBuffer.size, CpuAccessFlags = CpuAccessFlags.Write, StructureByteStride = 0, OptionFlags = 0, }; constantBuffer = new SharpDX.Direct3D11.Buffer(device, constantBufferDesc); bilateralFilter = new BilateralFilter(device, depthImageWidth, depthImageHeight); vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[] { new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0), }); }
public void SetRenderTarget(RenderTargetView rtv) { deviceContext.OutputMerger.SetRenderTargets(null, rtv); }
private void CreateCharTable(byte bytePrefix) { var TableDesc = new CharTableDescription(); //Get appropriate texture size int sizeX = (int)(Font.FontSize * 12); sizeX = (int)Math.Pow(2, Math.Ceiling(Math.Log(sizeX, 2))); //Try how many lines are needed: var tl = new TextLayout[256]; int line = 0, xPos = 0, yPos = 0; for (int i = 0; i < 256; ++i) { tl[i] = new TextLayout(ModelEx.FontManager.Instance.WriteFactory, Convert.ToChar(i + (bytePrefix << 8)).ToString(), Font); int charWidth = 2 + (int)Math.Ceiling(tl[i].Metrics.LayoutWidth + tl[i].OverhangMetrics.Left + tl[i].OverhangMetrics.Right); int charHeight = 2 + (int)Math.Ceiling(tl[i].Metrics.LayoutHeight + tl[i].OverhangMetrics.Top + tl[i].OverhangMetrics.Bottom); line = Math.Max(line, charHeight); if (xPos + charWidth >= sizeX) { xPos = 0; yPos += line; line = 0; } xPos += charWidth; } int sizeY = (int)(line + yPos); sizeY = (int)Math.Pow(2, Math.Ceiling(Math.Log(sizeY, 2))); //Create Texture var TexDesc = new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R8G8B8A8_UNorm, Height = sizeY, Width = sizeX, MipLevels = 1, OptionFlags = ResourceOptionFlags.Shared, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; var texture = new Texture2D(ModelEx.FontManager.Instance.D3DDevice10, TexDesc); var rtv = new RenderTargetView(ModelEx.FontManager.Instance.D3DDevice10, texture); ModelEx.FontManager.Instance.D3DDevice10.ClearRenderTargetView(rtv, new SlimDX.Color4(0, 1, 1, 1)); //D3DDevice10.ClearRenderTargetView(rtv, new SlimDX.Color4(1, 0, 0, 0)); Surface surface = texture.AsSurface(); var target = RenderTarget.FromDXGI(ModelEx.FontManager.Instance.D2DFactory, surface, rtp); var color = new SolidColorBrush(target, new SlimDX.Color4(1, 1, 1, 1)); target.BeginDraw(); line = 0; xPos = 0; yPos = 0; //for (int i = 0; i < 256; ++i) for (int i = 0; i < 256; ++i) { //1 additional pixel on each side int charWidth = 2 + (int)Math.Ceiling(tl[i].Metrics.LayoutWidth + tl[i].OverhangMetrics.Left + tl[i].OverhangMetrics.Right); int charHeight = 2 + (int)Math.Ceiling(tl[i].Metrics.LayoutHeight + tl[i].OverhangMetrics.Top + tl[i].OverhangMetrics.Bottom); line = Math.Max(line, charHeight); if (xPos + charWidth >= sizeX) { xPos = 0; yPos += line; line = 0; } var charDesc = new CharDescription(); charDesc.CharSize = new Vector2(tl[i].Metrics.WidthIncludingTrailingWhitespace, tl[i].Metrics.Height); charDesc.OverhangLeft = tl[i].OverhangMetrics.Left + 1; charDesc.OverhangTop = tl[i].OverhangMetrics.Top + 1; //Make XPos + CD.Overhang.Left an integer number in order to draw at integer positions charDesc.OverhangLeft += (float)Math.Ceiling(xPos + charDesc.OverhangLeft) - (xPos + charDesc.OverhangLeft); //Make YPos + CD.Overhang.Top an integer number in order to draw at integer positions charDesc.OverhangTop += (float)Math.Ceiling(yPos + charDesc.OverhangTop) - (yPos + charDesc.OverhangTop); charDesc.OverhangRight = charWidth - charDesc.CharSize.X - charDesc.OverhangLeft; charDesc.OverhangBottom = charHeight - charDesc.CharSize.Y - charDesc.OverhangTop; charDesc.TexCoordsStart = new Vector2(((float)xPos / sizeX), ((float)yPos / sizeY)); charDesc.TexCoordsSize = new Vector2((float)charWidth / sizeX, (float)charHeight / sizeY); charDesc.TableDescription = TableDesc; TableDesc.Chars[i] = charDesc; target.DrawTextLayout(new PointF(xPos + charDesc.OverhangLeft, yPos + charDesc.OverhangTop), tl[i], color); xPos += charWidth; tl[i].Dispose(); } target.EndDraw(); color.Dispose(); //This is a workaround for Windows 8.1 machines. //If these lines would not be present, the shared resource would be empty. //TODO: find a nicer solution using (var ms = new MemoryStream()) Texture2D.ToStream(texture, ImageFileFormat.Bmp, ms); System.Threading.Monitor.Enter(D3DDevice11); var dxgiResource = new SlimDX.DXGI.Resource(texture); SlimDX.Direct3D11.Texture2D Texture11; if (PixCompatible) { Texture11 = new SlimDX.Direct3D11.Texture2D(D3DDevice11, new SlimDX.Direct3D11.Texture2DDescription() { ArraySize = 1, BindFlags = SlimDX.Direct3D11.BindFlags.ShaderResource | SlimDX.Direct3D11.BindFlags.RenderTarget, CpuAccessFlags = SlimDX.Direct3D11.CpuAccessFlags.None, Format = Format.R8G8B8A8_UNorm, Height = sizeY, Width = sizeX, MipLevels = 1, OptionFlags = SlimDX.Direct3D11.ResourceOptionFlags.Shared, SampleDescription = new SampleDescription(1, 0), Usage = SlimDX.Direct3D11.ResourceUsage.Default }); } else { Texture11 = D3DDevice11.OpenSharedResource <SlimDX.Direct3D11.Texture2D>(dxgiResource.SharedHandle); } var srv = new SlimDX.Direct3D11.ShaderResourceView(D3DDevice11, Texture11); TableDesc.Texture = Texture11; TableDesc.SRV = srv; rtv.Dispose(); System.Threading.Monitor.Exit(D3DDevice11); System.Diagnostics.Debug.WriteLine("Created Char Table " + bytePrefix + " in " + sizeX + " x " + sizeY); //System.Threading.Monitor.Enter(D3DDevice11); //SlimDX.Direct3D11.Texture2D.SaveTextureToFile(Sprite.Device.ImmediateContext, Texture11, SlimDX.Direct3D11.ImageFileFormat.Png, Font.FontFamilyName + "Table" + BytePrefix + ".png"); //System.Threading.Monitor.Exit(D3DDevice11); CharTables.Add(bytePrefix, TableDesc); dxgiResource.Dispose(); target.Dispose(); surface.Dispose(); texture.Dispose(); }
private void SetupBuffers() { // Dispose all previous allocated resources Utilities.Dispose(ref backBuffer); Utilities.Dispose(ref renderView); Utilities.Dispose(ref depthBuffer); Utilities.Dispose(ref depthView); Utilities.Dispose(ref resolutionBuffer); // Resize the backbuffer swapChain.ResizeBuffers(swapChainDescription.BufferCount, (int)RenderContext.ViewportSize.X, (int)RenderContext.ViewportSize.Y, 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 = (int)RenderContext.ViewportSize.X, Height = (int)RenderContext.ViewportSize.Y, 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.State = new RasterizerState(device, new RasterizerStateDescription() { CullMode = CullMode.None, DepthBias = 0, DepthBiasClamp = 0, FillMode = FillMode.Solid, IsAntialiasedLineEnabled = false, IsDepthClipEnabled = true, IsFrontCounterClockwise = false, IsMultisampleEnabled = true, IsScissorEnabled = false, SlopeScaledDepthBias = 0 }); context.Rasterizer.SetViewport(new Viewport(0, 0, (int)RenderContext.ViewportSize.X, (int)RenderContext.ViewportSize.Y, 0.0f, 1.0f)); context.OutputMerger.SetTargets(depthView, renderView); context.OutputMerger.SetDepthStencilState(new DepthStencilState(device, new DepthStencilStateDescription() { IsDepthEnabled = false, }), 0); Vector4 iResolution = new Vector4(RenderContext.ViewportSize, 0, 0); resolutionBuffer = Buffer.Create(device, BindFlags.ConstantBuffer, ref iResolution); resolutionBuffer.DebugName = "ResolutionBuffer"; }
public void ClearRenderTargetView(RenderTargetView renderTargetViewRef, Color4 colorRGBA) { deviceContext.ClearRenderTargetView(renderTargetViewRef, colorRGBA); }
void DxResize() { if (_renderTarget != null) { _renderTarget.Dispose(); _renderTargetTexture.Dispose(); _depthState.Dispose(); _depthStencilView.Dispose(); _depthStencilTexture.Dispose(); } _renderTargetTexture = new Texture2D(CurrentDevice, new Texture2DDescription { Width = _width, Height = _height, MipLevels = 1, ArraySize = 1, Format = Format.R8G8B8A8_UNorm, SampleDescription = _sampleDesc, Usage = ResourceUsage.Default, BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); _renderTarget = new RenderTargetView(CurrentDevice, _renderTargetTexture); _renderTargetResource = new ShaderResourceView(CurrentDevice, _renderTargetTexture); _depthStencilTexture = new Texture2D(CurrentDevice, new Texture2DDescription { Width = _width, Height = _height, MipLevels = 1, ArraySize = 1, Format = Format.R24G8_Typeless, SampleDescription = _sampleDesc, Usage = ResourceUsage.Default, BindFlags = BindFlags.ShaderResource | BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }) { DebugName = "DepthStencilBuffer" }; _depthStencilView = new DepthStencilView(CurrentDevice, _depthStencilTexture, new DepthStencilViewDescription { Flags = DepthStencilViewFlags.None, Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2DMultisampled, MipSlice = 0 }); _depthState = DepthStencilState.FromDescription(CurrentDevice, new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, }); _viewport = new Viewport(0, 0, _width, _height, 0.0f, 1.0f); _context.Rasterizer.SetViewports(_viewport); _camera.SetLens(AspectRatio); }
/// <summary> /// Creates the texture and necessary structures for 256 chars whose unicode number starts with the given byte. /// The table containing ASCII has a prefix of 0 (0x00/00 - 0x00/FF). /// </summary> /// <param name="BytePrefix">The byte prefix of characters.</param> private void CreateCharTable(byte BytePrefix) { var TableDesc = new CharTableDescription(); //Get appropriate texture size int SizeX = (int)(Font.FontSize * 12); SizeX = (int)Math.Pow(2, Math.Ceiling(Math.Log(SizeX, 2))); //Try how many lines are needed: var TL = new TextLayout[256]; float Line = 0, XPos = 0, YPos = 0; for (int i = 0; i < 256; ++i) { TL[i] = new TextLayout(WriteFactory, Convert.ToChar(i + (BytePrefix << 8)).ToString(), Font); float CharWidth = 2 + (float)Math.Ceiling(TL[i].Metrics.LayoutWidth + Math.Max(0, TL[i].OverhangMetrics.Left) + Math.Max(0, TL[i].OverhangMetrics.Right)); float CharHeight = 2 + (float)Math.Ceiling(TL[i].Metrics.LayoutHeight + Math.Max(0, TL[i].OverhangMetrics.Top) + Math.Max(0, TL[i].OverhangMetrics.Bottom)); Line = Math.Max(Line, CharHeight); if (XPos + CharWidth >= SizeX) { XPos = 0; YPos += Line; Line = 0; } XPos += CharWidth; } int SizeY = (int)(Line + YPos); SizeY = (int)Math.Pow(2, Math.Ceiling(Math.Log(SizeY, 2))); //Create Texture var TexDesc = new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget, CpuAccessFlags = CpuAccessFlags.None, Format = Format.B8G8R8A8_UNorm, Height = SizeY, Width = SizeX, MipLevels = 1, OptionFlags = ResourceOptionFlags.KeyedMutex, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; var Texture = new Texture2D(D3DDevice10, TexDesc); var rtv = new RenderTargetView(D3DDevice10, Texture); D3DDevice10.ClearRenderTargetView(rtv, new global::SlimDX.Color4(0, 1, 1, 1)); //D3DDevice10.ClearRenderTargetView(rtv, new SlimDX.Color4(1, 0, 0, 0)); Surface Surface = Texture.AsSurface(); Surface1 s1; var Target = RenderTarget.FromDXGI(D2DFactory, Surface, rtp); var Color = new SolidColorBrush(Target, new global::SlimDX.Color4(1, 1, 1, 1)); Target.BeginDraw(); Line = 0; XPos = 0; YPos = 0; for (int i = 0; i < 256; ++i) { float CharWidth = 2 + (float)Math.Ceiling(TL[i].Metrics.LayoutWidth + Math.Max(0, TL[i].OverhangMetrics.Left) + Math.Max(0, TL[i].OverhangMetrics.Right)); float CharHeight = 2 + (float)Math.Ceiling(TL[i].Metrics.LayoutHeight + Math.Max(0, TL[i].OverhangMetrics.Top) + Math.Max(0, TL[i].OverhangMetrics.Bottom)); Line = Math.Max(Line, CharHeight); if (XPos + CharWidth >= SizeX) { XPos = 0; YPos += Line; Line = 0; } var CD = new CharDescription(); CD.CharSize = new Vector2(TL[i].Metrics.WidthIncludingTrailingWhitespace, TL[i].Metrics.Height); CD.OverhangLeft = TL[i].OverhangMetrics.Left; CD.OverhangTop = TL[i].OverhangMetrics.Top; CD.OverhangRight = TL[i].Metrics.LayoutWidth + TL[i].OverhangMetrics.Right - TL[i].Metrics.WidthIncludingTrailingWhitespace; CD.OverhangBottom = TL[i].Metrics.LayoutHeight + TL[i].OverhangMetrics.Bottom - TL[i].Metrics.Height; //Safety space around chars that are not unvisible if (CD.CharSize.X + CD.OverhangLeft + CD.OverhangRight > 0 && CD.CharSize.Y + CD.OverhangTop + CD.OverhangBottom > 0) { CD.OverhangBottom += 1; CD.OverhangTop += 1; CD.OverhangRight += 1; CD.OverhangLeft += 1; } //Correct overhangs, so size in pixels will be integer numbers //this avoids incorrect filtering results CD.OverhangRight += (float)Math.Ceiling(CD.OverhangLeft + CD.CharSize.X + CD.OverhangRight) - (CD.OverhangLeft + CD.CharSize.X + CD.OverhangRight); CD.OverhangBottom += (float)Math.Ceiling(CD.OverhangTop + CD.CharSize.Y + CD.OverhangBottom) - (CD.OverhangTop + CD.CharSize.Y + CD.OverhangBottom); CD.TexCoordsStart = new Vector2((XPos / SizeX), (YPos / SizeY)); CD.TexCoordsSize = new Vector2((CD.OverhangLeft + CD.CharSize.X + CD.OverhangRight) / SizeX, (CD.OverhangTop + CD.CharSize.Y + CD.OverhangBottom) / SizeY); CD.TableDescription = TableDesc; TableDesc.Chars[i] = CD; Target.DrawTextLayout(new PointF(XPos + CD.OverhangLeft, YPos + CD.OverhangTop), TL[i], Color); XPos += CharWidth; TL[i].Dispose(); } Target.EndDraw(); Color.Dispose(); System.Threading.Monitor.Enter(D3DDevice11); var DXGIResource = new global::SlimDX.DXGI.Resource(Texture); global::SlimDX.Direct3D11.Texture2D Texture11; if (PixCompatible) { Texture11 = new global::SlimDX.Direct3D11.Texture2D(D3DDevice11, new global::SlimDX.Direct3D11.Texture2DDescription() { ArraySize = 1, BindFlags = global::SlimDX.Direct3D11.BindFlags.ShaderResource | global::SlimDX.Direct3D11.BindFlags.RenderTarget, CpuAccessFlags = global::SlimDX.Direct3D11.CpuAccessFlags.None, Format = Format.R8G8B8A8_UNorm, Height = SizeY, Width = SizeX, MipLevels = 1, OptionFlags = global::SlimDX.Direct3D11.ResourceOptionFlags.Shared, SampleDescription = new SampleDescription(1, 0), Usage = global::SlimDX.Direct3D11.ResourceUsage.Default }); } else { Texture11 = D3DDevice11.OpenSharedResource <global::SlimDX.Direct3D11.Texture2D>(DXGIResource.SharedHandle); } var SRV = new global::SlimDX.Direct3D11.ShaderResourceView(D3DDevice11, Texture11); TableDesc.Texture = Texture11; TableDesc.SRV = SRV; rtv.Dispose(); System.Threading.Monitor.Exit(D3DDevice11); System.Diagnostics.Debug.WriteLine("Created Char Table " + BytePrefix + " in " + SizeX + " x " + SizeY); //System.Threading.Monitor.Enter(D3DDevice11); //SlimDX.Direct3D11.Texture2D.SaveTextureToFile(Sprite.Device.ImmediateContext, Texture11, SlimDX.Direct3D11.ImageFileFormat.Png, Font.FontFamilyName + "Table" + BytePrefix + ".png"); //System.Threading.Monitor.Exit(D3DDevice11); CharTables.Add(BytePrefix, TableDesc); DXGIResource.Dispose(); Target.Dispose(); Surface.Dispose(); Texture.Dispose(); }
void DrawPreviousFrameTo(RenderTargetView target) { DrawSomethingFromTo(_renderTargetResource, target, _effectScreen.TechCopy); }
public void DrawSomethingFromTo(ShaderResourceView res, RenderTargetView target, EffectTechnique tech, RasterizerState rast = null) { DrawSomethingFromTo(res, target, _effectScreen.LayoutPT, _effectScreen.FxInputImage, tech, rast); }
public DeferredRenderer(DX11Game game) { this.game = game; var device = game.Device; context = device.ImmediateContext; screenWidth = game.Form.Form.ClientSize.Width; screenHeight = game.Form.Form.ClientSize.Height; int width = screenWidth; int height = screenHeight; gBuffer = new GBuffer(game.Device, width, height); texturePool = new TexturePool(game); meshesRenderer = new DeferredMeshesRenderer(game, gBuffer, TexturePool); directionalLightRenderer = new DirectionalLightRenderer(game, GBuffer); spotLightRenderer = new SpotLightRenderer(game, GBuffer); pointLightRenderer = new PointLightRenderer(game, GBuffer); combineFinalRenderer = new CombineFinalRenderer(game, GBuffer); var desc = new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.R16G16B16A16_Float, Width = screenWidth, Height = screenHeight, ArraySize = 1, SampleDescription = new SampleDescription(1, 0), MipLevels = 1 }; hdrImage = new Texture2D(device, desc); hdrImageRtv = new RenderTargetView(device, hdrImage); hdrImageRV = new ShaderResourceView(device, hdrImage); calculater = new AverageLuminanceCalculater(game, hdrImageRV); toneMap = new ToneMapRenderer(game); var tempDesc = new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, Format = Format.R32_Float, Height = 1, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Staging, Width = 1 }; tempTex = new Texture2D(device, tempDesc); ssao = new HorizonSSAORenderer(game, screenWidth, screenHeight); Vector3 radius = new Vector3(500, 1000, 500); frustumCuller = new FrustumCuller(new BoundingBox(-radius, radius), 1); gbufferView = frustumCuller.CreateView(); meshesRenderer.Culler = frustumCuller; Texture2D skyColorTexture;// = Texture2D.FromFile(game.Device, TWDir.GameData.CreateSubdirectory("Core") + "\\skyColor.bmp"); var strm = new DataStream(16 * 4, true, true); var multiplier = 2; strm.Write(new Half4(new Half(135f / 255f * multiplier), new Half(206f / 255f * multiplier), new Half(235 / 255f * multiplier), new Half(1))); strm.Position = 0; var dataRectangle = new DataRectangle(16 * 4, strm); skyColorTexture = new Texture2D(game.Device, new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R16G16B16A16_Float, Height = 1, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, Width = 1 }, dataRectangle); skyColorRV = new ShaderResourceView(game.Device, skyColorTexture); postProcessRT1 = CreateBackbufferLikeRT(); postProcessRT2 = CreateBackbufferLikeRT(); fogRenderer = new FogEffect(game); backgroundDepthStencilState = DepthStencilState.FromDescription(game.Device, new DepthStencilStateDescription() { IsDepthEnabled = true, DepthComparison = Comparison.LessEqual, DepthWriteMask = DepthWriteMask.Zero, }); lineManager = new LineManager3D(game.Device); updateRasterizerState(); }
public D3D11Framebuffer(Device device, ref FramebufferDescription description) : base(description.DepthTarget, description.ColorTargets) { if (description.DepthTarget != null) { D3D11Texture d3dDepthTarget = Util.AssertSubtype <Texture, D3D11Texture>(description.DepthTarget.Value.Target); DepthStencilViewDescription dsvDesc = new DepthStencilViewDescription() { Format = D3D11Formats.GetDepthFormat(d3dDepthTarget.Format), }; if (d3dDepthTarget.ArrayLayers == 1) { if (d3dDepthTarget.SampleCount == TextureSampleCount.Count1) { dsvDesc.Dimension = DepthStencilViewDimension.Texture2D; dsvDesc.Texture2D.MipSlice = (int)description.DepthTarget.Value.MipLevel; } else { dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled; } } else { if (d3dDepthTarget.SampleCount == TextureSampleCount.Count1) { dsvDesc.Dimension = DepthStencilViewDimension.Texture2DArray; dsvDesc.Texture2DArray.FirstArraySlice = (int)description.DepthTarget.Value.ArrayLayer; dsvDesc.Texture2DArray.ArraySize = 1; dsvDesc.Texture2DArray.MipSlice = (int)description.DepthTarget.Value.MipLevel; } else { dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampledArray; dsvDesc.Texture2DMSArray.FirstArraySlice = (int)description.DepthTarget.Value.ArrayLayer; dsvDesc.Texture2DMSArray.ArraySize = 1; } } DepthStencilView = new DepthStencilView(device, d3dDepthTarget.DeviceTexture, dsvDesc); } if (description.ColorTargets != null && description.ColorTargets.Length > 0) { RenderTargetViews = new RenderTargetView[description.ColorTargets.Length]; for (int i = 0; i < RenderTargetViews.Length; i++) { D3D11Texture d3dColorTarget = Util.AssertSubtype <Texture, D3D11Texture>(description.ColorTargets[i].Target); RenderTargetViewDescription rtvDesc = new RenderTargetViewDescription { Format = D3D11Formats.ToDxgiFormat(d3dColorTarget.Format, false), }; if (d3dColorTarget.ArrayLayers > 1 || (d3dColorTarget.Usage & TextureUsage.Cubemap) != 0) { if (d3dColorTarget.SampleCount == TextureSampleCount.Count1) { rtvDesc.Dimension = RenderTargetViewDimension.Texture2DArray; rtvDesc.Texture2DArray = new RenderTargetViewDescription.Texture2DArrayResource { ArraySize = 1, FirstArraySlice = (int)description.ColorTargets[i].ArrayLayer, MipSlice = (int)description.ColorTargets[i].MipLevel }; } else { rtvDesc.Dimension = RenderTargetViewDimension.Texture2DMultisampledArray; rtvDesc.Texture2DMSArray = new RenderTargetViewDescription.Texture2DMultisampledArrayResource { ArraySize = 1, FirstArraySlice = (int)description.ColorTargets[i].ArrayLayer }; } } else { if (d3dColorTarget.SampleCount == TextureSampleCount.Count1) { rtvDesc.Dimension = RenderTargetViewDimension.Texture2D; rtvDesc.Texture2D.MipSlice = (int)description.ColorTargets[i].MipLevel; } else { rtvDesc.Dimension = RenderTargetViewDimension.Texture2DMultisampled; } } RenderTargetViews[i] = new RenderTargetView(device, d3dColorTarget.DeviceTexture, rtvDesc); } } else { RenderTargetViews = Array.Empty <RenderTargetView>(); } }
/// <summary> /// Initializes a new instance of the <see cref="RenderTargetCube"/> class. /// </summary> /// <param name="graphicsDevice">The graphics device.</param> /// <param name="size">The width and height of a texture cube face in pixels.</param> /// <param name="mipMap"><see langword="true"/> to generate a full mipmap chain; otherwise <see langword="false"/>.</param> /// <param name="preferredFormat">The preferred format of the surface.</param> /// <param name="preferredDepthFormat">The preferred format of the depth-stencil buffer.</param> /// <param name="preferredMultiSampleCount">The preferred number of multisample locations.</param> /// <param name="usage">The usage mode of the render target.</param> public RenderTargetCube(GraphicsDevice graphicsDevice, int size, bool mipMap, SurfaceFormat preferredFormat, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage) : base(graphicsDevice, size, mipMap, preferredFormat, true) { DepthStencilFormat = preferredDepthFormat; MultiSampleCount = preferredMultiSampleCount; RenderTargetUsage = usage; #if DIRECTX // Create one render target view per cube map face. _renderTargetViews = new RenderTargetView[6]; for (int i = 0; i < _renderTargetViews.Length; i++) { var renderTargetViewDescription = new RenderTargetViewDescription { Dimension = RenderTargetViewDimension.Texture2DArray, Format = SharpDXHelper.ToFormat(preferredFormat), Texture2DArray = { ArraySize = 1, FirstArraySlice = i, MipSlice = 0 } }; _renderTargetViews[i] = new RenderTargetView(graphicsDevice._d3dDevice, _texture, renderTargetViewDescription); } // If we don't need a depth buffer then we're done. if (preferredDepthFormat == DepthFormat.None) { return; } var sampleDescription = new SampleDescription(1, 0); if (preferredMultiSampleCount > 1) { sampleDescription.Count = preferredMultiSampleCount; sampleDescription.Quality = (int)StandardMultisampleQualityLevels.StandardMultisamplePattern; } var depthStencilDescription = new Texture2DDescription { Format = SharpDXHelper.ToFormat(preferredDepthFormat), ArraySize = 1, MipLevels = 1, Width = size, Height = size, SampleDescription = sampleDescription, BindFlags = BindFlags.DepthStencil, }; using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(graphicsDevice._d3dDevice, depthStencilDescription)) { var depthStencilViewDescription = new DepthStencilViewDescription { Dimension = DepthStencilViewDimension.Texture2D, Format = SharpDXHelper.ToFormat(preferredDepthFormat), }; _depthStencilView = new DepthStencilView(graphicsDevice._d3dDevice, depthBuffer, depthStencilViewDescription); } #else throw new NotImplementedException(); #endif }
// viewport, render target internal unsafe static void Draw(RenderTargetView rtv, MyViewport viewport) { if (StackTop().m_internalBatch.Texture != null && StackTop().m_internalBatch.Count > 0) { StackTop().m_internalBatch.Commit(); } StackTop().m_internalBatch = new MySpritesBatch(); RC.DeviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip; RC.SetIL(m_inputLayout); //RC.SetupScreenViewport(); RC.DeviceContext.Rasterizer.SetViewport(viewport.OffsetX, viewport.OffsetY, viewport.Width, viewport.Height); RC.SetVS(m_vs); RC.SetCB(MyCommon.FRAME_SLOT, MyCommon.FrameConstants); RC.SetCB(MyCommon.PROJECTION_SLOT, MyCommon.GetObjectCB(64)); RC.SetPS(m_ps); RC.DeviceContext.PixelShader.SetSamplers(0, SamplerStates.StandardSamplers); //RC.BindDepthRT(null, DepthStencilAccess.DepthReadOnly, MyRender11.Backbuffer); // to reset state RC.BindDepthRT(null, DepthStencilAccess.DepthReadOnly, null); RC.DeviceContext.OutputMerger.SetRenderTargets(rtv); RC.SetBS(MyRender11.BlendGui); CheckBufferSize(StackTop().m_instances.Count); RC.SetVB(0, m_VB.Buffer, m_VB.Stride); var mapping = MyMapping.MapDiscard(m_VB.Buffer); for (int i = 0; i < StackTop().m_instances.Count; i++) { var helper = StackTop().m_instances[i]; mapping.WriteAndPosition(ref helper); } mapping.Unmap(); mapping = MyMapping.MapDiscard(MyCommon.GetObjectCB(64)); var viewportSize = new Vector2(viewport.Width, viewport.Height); mapping.WriteAndPosition(ref viewportSize); mapping.Unmap(); foreach (var batch in StackTop().m_batches) { if (batch.ScissorRectangle.HasValue) { RC.SetRS(MyRender11.m_scissorTestRasterizerState); var scissor = batch.ScissorRectangle.Value; RC.DeviceContext.Rasterizer.SetScissorRectangle((int)scissor.X, (int)scissor.Y, (int)(scissor.X + scissor.Width), (int)(scissor.Y + scissor.Height)); } else { RC.SetRS(MyRender11.m_nocullRasterizerState); } RC.BindRawSRV(0, batch.Texture); RC.DeviceContext.DrawInstanced(4, batch.Count, 0, batch.Start); } RC.SetBS(null); RC.SetRS(null); StackTop().m_instances.Clear(); StackTop().m_batches.Clear(); }
private void CreateAndBindTargets() { this.D3DSurface.SetRenderTargetDX10(null); Disposer.RemoveAndDispose(ref this.RenderTargetView); Disposer.RemoveAndDispose(ref this.RenderTarget1View); Disposer.RemoveAndDispose(ref this.RenderTarget2View); Disposer.RemoveAndDispose(ref this.OutputRenderTargetView); Disposer.RemoveAndDispose(ref this.DepthStencilView); Disposer.RemoveAndDispose(ref this.BlendingState); Disposer.RemoveAndDispose(ref this.OutputRenderTarget); Disposer.RemoveAndDispose(ref this.RenderTarget); Disposer.RemoveAndDispose(ref this.RenderTarget1); Disposer.RemoveAndDispose(ref this.RenderTarget2); Disposer.RemoveAndDispose(ref this.ShaderTargetView); Disposer.RemoveAndDispose(ref this.ShaderTarget1View); Disposer.RemoveAndDispose(ref this.ShaderTarget2View); Disposer.RemoveAndDispose(ref this.DepthStencil); width = Math.Max((int)base.ActualWidth, 100); height = Math.Max((int)base.ActualHeight, 100); SampleDescription quality = new SampleDescription(1, 0); Texture2DDescription colordesc = new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = (int)width, Height = (int)height, MipLevels = 1, SampleDescription = quality, Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.Shared, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1 }; Texture2DDescription depthdesc = new Texture2DDescription { BindFlags = BindFlags.DepthStencil, Format = Format.D32_Float_S8X24_UInt, Width = (int)width, Height = (int)height, MipLevels = 1, SampleDescription = quality, Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.None, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1 }; this.RenderTarget = new Texture2D(this.Device, colordesc); this.OutputRenderTarget = new Texture2D(this.Device, colordesc); this.DepthStencil = new Texture2D(this.Device, depthdesc); RenderTarget1 = new Texture2D(this.Device, new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, Format = Format.B8G8R8A8_UNorm, Width = (int)width / 2, Height = (int)height / 2, MipLevels = 1, OptionFlags = ResourceOptionFlags.Shared, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }); RenderTarget2 = new Texture2D(this.Device, new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, Format = Format.B8G8R8A8_UNorm, Width = (int)width / 2, Height = (int)height / 2, MipLevels = 1, OptionFlags = ResourceOptionFlags.Shared, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }); BlendStateDescription stateDesc = new BlendStateDescription { SourceBlend = BlendOption.One, DestinationBlend = BlendOption.One, BlendOperation = BlendOperation.Add, SourceAlphaBlend = BlendOption.One, DestinationAlphaBlend = BlendOption.One, AlphaBlendOperation = BlendOperation.Add }; stateDesc.IsBlendEnabled[0] = true; stateDesc.RenderTargetWriteMask[0] = ColorWriteMaskFlags.All; stateDesc.IsAlphaToCoverageEnabled = false; BlendingState = new BlendState(Device, ref stateDesc); this.DepthStencilView = new DepthStencilView(this.Device, this.DepthStencil); this.RenderTargetView = new RenderTargetView(this.Device, this.RenderTarget); this.RenderTarget1View = new RenderTargetView(this.Device, this.RenderTarget1); this.RenderTarget2View = new RenderTargetView(this.Device, this.RenderTarget2); this.OutputRenderTargetView = new RenderTargetView(this.Device, this.OutputRenderTarget); this.ShaderTargetView = new ShaderResourceView(this.Device, this.RenderTarget); this.ShaderTarget1View = new ShaderResourceView(this.Device, this.RenderTarget1); this.ShaderTarget2View = new ShaderResourceView(this.Device, this.RenderTarget2); try { this.D3DSurface.SetRenderTargetDX10(this.OutputRenderTarget); } catch { } }
public void SetRenderTarget(DepthStencilView dsv, RenderTargetView renderTarget) { deviceContext.OutputMerger.SetRenderTargets(dsv, renderTarget); }
/// <summary> /// /// </summary> /// <param name="desc"></param> public void Initialize(BufferDesc desc) { var device = GraphicsCore.D3D11Device; // 情報取得 width_ = desc.width; height_ = desc.height; format_ = desc.format; mips_ = desc.mips; if (mips_ == 0) { mips_ = 1; } BindFlags bindFlags = BindFlags.ShaderResource; if (desc.IsRenderTarget) { bindFlags |= BindFlags.RenderTarget; } if (desc.IsDepthStencil) { bindFlags |= BindFlags.DepthStencil; } if (desc.IsUnorderedAccess) { bindFlags |= BindFlags.UnorderedAccess; } CpuAccessFlags acc_flag = CpuAccessFlags.None; ResourceUsage res_usage = ResourceUsage.Default; bool isCube = (desc.optionFlags & ResourceOptionFlags.TextureCube) != 0; int array_size = (!isCube) ? 1 : 6; // 初期化データ DataRectangle[] dataRect = null; if (desc.initData != null) { dataRect = new DataRectangle[desc.initData.Length * desc.initData[0].Length]; int index = 0; for (int i = 0; i < desc.initData[0].Length; i++) { for (int m = 0; m < desc.initData.Length; m++) { dataRect[index++] = new DataRectangle((width_ >> m) * 4, new DataStream(desc.initData[m][i], true, true)); } } } // テクスチャオブジェクト Texture2DDescription textureDescription = new Texture2DDescription { ArraySize = array_size, BindFlags = bindFlags, CpuAccessFlags = acc_flag, Format = desc.format, Height = desc.height, Width = desc.width, MipLevels = mips_, //OptionFlags = (mips_ > 1 && needsGpuWrite) ? ResourceOptionFlags.GenerateMipMaps : ResourceOptionFlags.None, OptionFlags = desc.optionFlags, SampleDescription = new SampleDescription(1, 0), Usage = res_usage }; var texture2d = new Texture2D(device, textureDescription, dataRect); buffer_ = texture2d; // 初期データ解放 if (dataRect != null) { foreach (var d in dataRect) { d.Data.Close(); } } Format srvFormat = desc.format; // Special case for depth if (desc.IsDepthStencil) { srvFormat = (desc.format == Format.R32_Typeless) ? Format.R32_Float : Format.R24_UNorm_X8_Typeless; } ShaderResourceViewDescription srvViewDesc = new ShaderResourceViewDescription { ArraySize = 0, Format = srvFormat, Dimension = (isCube) ? ShaderResourceViewDimension.TextureCube : ShaderResourceViewDimension.Texture2D, Flags = 0, FirstArraySlice = 0, MostDetailedMip = 0, MipLevels = mips_ }; shaderResourceView_ = new ShaderResourceView(device, texture2d, srvViewDesc); // レンダーターゲットビュー if (desc.IsRenderTarget) { if (!isCube) { // 通常 RenderTargetViewDescription rtViewDesc = new RenderTargetViewDescription { Dimension = RenderTargetViewDimension.Texture2D, Format = desc.format, MipSlice = 0, }; renderTargetView_ = new RenderTargetView(device, texture2d, rtViewDesc); } else { // キューブマップ RenderTargetViewDescription rtViewDesc = new RenderTargetViewDescription { Dimension = RenderTargetViewDimension.Texture2DArray, Format = desc.format, MipSlice = 0, ArraySize = 1, }; arrayRenderTargetView_ = new RenderTargetView[array_size * mips_]; for (int m = 0; m < mips_; m++) { for (int i = 0; i < array_size; i++) { rtViewDesc.MipSlice = m; rtViewDesc.FirstArraySlice = i; arrayRenderTargetView_[m * 6 + i] = new RenderTargetView(device, texture2d, rtViewDesc); } } } } // デプスステンシルビュー if (desc.IsDepthStencil) { DepthStencilViewDescription dsViewDesc = new DepthStencilViewDescription { ArraySize = 0, Format = (desc.format == Format.R32_Typeless) ? Format.D32_Float : Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, MipSlice = 0, Flags = 0, FirstArraySlice = 0 }; depthStencilView_ = new DepthStencilView(device, texture2d, dsViewDesc); } // UAV if (desc.IsUnorderedAccess) { UnorderedAccessViewDescription uavDesc = new UnorderedAccessViewDescription { ArraySize = 0, DepthSliceCount = 1, Dimension = UnorderedAccessViewDimension.Texture2D, ElementCount = 1, FirstArraySlice = 0, FirstDepthSlice = 0, FirstElement = 0, Flags = UnorderedAccessViewBufferFlags.None, Format = desc.format, MipSlice = 0 }; unorderedAccessView_ = new UnorderedAccessView(device, texture2d, uavDesc); } }
public bool Initialize(DSystemConfiguration configuration, IntPtr windowHandle) { try { #region Environment Configuration // Store the vsync setting. VerticalSyncEnabled = DSystemConfiguration.VerticalSyncEnabled; // Create a DirectX graphics interface factory. var factory = new Factory1(); // Use the factory to create an adapter for the primary graphics interface (video card). var adapter = factory.GetAdapter1(0); // Get the primary adapter output (monitor). var monitor = adapter.GetOutput(0); // Get modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor). var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); // Now go through all the display modes and find the one that matches the screen width and height. // When a match is found store the the refresh rate for that monitor, if vertical sync is enabled. // Otherwise we use maximum refresh rate. var rational = new Rational(0, 1); if (VerticalSyncEnabled) { foreach (var mode in modes) { if (mode.Width == configuration.Width && mode.Height == configuration.Height) { rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator); break; } } } // Get the adapter (video card) description. var adapterDescription = adapter.Description; // Store the dedicated video card memory in megabytes. VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; // Convert the name of the video card to a character array and store it. VideoCardDescription = adapterDescription.Description.Trim('\0'); // Release the adapter output. monitor.Dispose(); // Release the adapter. adapter.Dispose(); // Release the factory. factory.Dispose(); #endregion #region Initialize swap chain and d3d device // Initialize the swap chain description. var swapChainDesc = new SwapChainDescription() { // Set to a single back buffer. BufferCount = 1, // Set the width and height of the back buffer. ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm), // Set the usage of the back buffer. Usage = Usage.RenderTargetOutput, // Set the handle for the window to render to. OutputHandle = windowHandle, // Turn multisampling off. SampleDescription = new SampleDescription(1, 0), // Set to full screen or windowed mode. IsWindowed = !DSystemConfiguration.FullScreen, // Don't set the advanced flags. Flags = SwapChainFlags.None, // Discard the back buffer content after presenting. SwapEffect = SwapEffect.Discard }; // Create the swap chain, Direct3D device, and Direct3D device context. SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; #endregion #region Initialize buffers // Get the pointer to the back buffer. var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0); // Create the render target view with the back buffer pointer. RenderTargetView = new RenderTargetView(device, backBuffer); // Release pointer to the back buffer as we no longer need it. backBuffer.Dispose(); // Initialize and set up the description of the depth buffer. var depthBufferDesc = new Texture2DDescription() { Width = configuration.Width, Height = configuration.Height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; // Create the texture for the depth buffer using the filled out description. DepthStencilBuffer = new Texture2D(device, depthBufferDesc); #endregion #region Initialize Depth Enabled Stencil #endregion #region Initialize Output Merger // Initialize and set up the depth stencil view. var depthStencilViewDesc = new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; // Create the depth stencil view. DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc); // Bind the render target view and depth stencil buffer to the output render pipeline. DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView); #endregion #region Initialize Raster State // Setup the raster description which will determine how and what polygon will be drawn. var rasterDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; // Create the rasterizer state from the description we just filled out. RasterState = new RasterizerState(Device, rasterDesc); #endregion #region Initialize Rasterizer // Now set the rasterizer state. DeviceContext.Rasterizer.State = RasterState; // Setup and create the viewport for rendering. DeviceContext.Rasterizer.SetViewport(0, 0, configuration.Width, configuration.Height, 0, 1); #endregion #region Initialize matrices // Setup and create the projection matrix. ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)configuration.Width / (float)configuration.Height), DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth); // Initialize the world matrix to the identity matrix. WorldMatrix = Matrix.Identity; #endregion #region Initialize Depth Disabled Stencil #endregion #region Initialize Blend States #endregion return(true); } catch (Exception) { return(false); } }
private static void Main() { Noesis.Log.SetLogCallback((level, channel, message) => { if (channel == "") { // [TRACE] [DEBUG] [INFO] [WARNING] [ERROR] string[] prefixes = new string[] { "T", "D", "I", "W", "E" }; string prefix = (int)level < prefixes.Length ? prefixes[(int)level] : " "; Console.WriteLine("[NOESIS/" + prefix + "] " + message); } }); // Noesis initialization. This must be the first step before using any NoesisGUI functionality Noesis.GUI.Init("LICENSE_NAME", "LICENSE_KEY"); // Setup theme NoesisApp.Application.SetThemeProviders(); Noesis.GUI.LoadApplicationResources("Theme/NoesisTheme.DarkBlue.xaml"); // For simplicity purposes we are not using resource providers in this sample. ParseXaml() is // enough if there is no extra XAML dependencies Noesis.Grid xaml = (Noesis.Grid)Noesis.GUI.ParseXaml(@" <Grid xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""> <Grid.Background> <LinearGradientBrush StartPoint=""0,0"" EndPoint=""0,1""> <GradientStop Offset=""0"" Color=""#FF123F61""/> <GradientStop Offset=""0.6"" Color=""#FF0E4B79""/> <GradientStop Offset=""0.7"" Color=""#FF106097""/> </LinearGradientBrush> </Grid.Background> <Viewbox> <StackPanel Margin=""50""> <Button Content=""Hello World!"" Margin=""0,30,0,0""/> <Rectangle Height=""5"" Margin=""-10,20,-10,0""> <Rectangle.Fill> <RadialGradientBrush> <GradientStop Offset=""0"" Color=""#40000000""/> <GradientStop Offset=""1"" Color=""#00000000""/> </RadialGradientBrush> </Rectangle.Fill> </Rectangle> </StackPanel> </Viewbox> </Grid>"); // View creation to render and interact with the user interface // We transfer the ownership to a global pointer instead of a Ptr<> because there is no way // in GLUT to do shutdown and we don't want the Ptr<> to be released at global time Noesis.View view = Noesis.GUI.CreateView(xaml); view.SetFlags(Noesis.RenderFlags.PPAA | Noesis.RenderFlags.LCD); // Creation of the system window RenderForm form = new RenderForm("NoesisGUI - IntegrationSharpDX D3D11") { Width = 1000, Height = 600, Icon = new System.Drawing.Icon("Noesis.ico") }; view.SetSize(form.ClientSize.Width, form.ClientSize.Height); // SwapChain description SwapChainDescription 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); DeviceContext context = device.ImmediateContext; Factory factory = swapChain.GetParent <Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); factory.Dispose(); // Renderer initialization with a Direct3D11 device view.Renderer.Init(new Noesis.RenderDeviceD3D11(context.NativePointer)); // New RenderTargetView from the backbuffer Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); RenderTargetView renderView = new RenderTargetView(device, backBuffer); backBuffer.Dispose(); // Register window events form.SizeChanged += (s, e) => { context.OutputMerger.SetRenderTargets(null, (RenderTargetView)null); renderView.Dispose(); swapChain.ResizeBuffers(0, 0, 0, Format.Unknown, SwapChainFlags.None); backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); renderView = new RenderTargetView(device, backBuffer); backBuffer.Dispose(); view.SetSize(form.ClientSize.Width, form.ClientSize.Height); }; form.MouseMove += (s, e) => { view.MouseMove(e.X, e.Y); }; form.MouseDown += (s, e) => { if (e.Button == MouseButtons.Left) { view.MouseButtonDown(e.X, e.Y, Noesis.MouseButton.Left); } }; form.MouseUp += (s, e) => { if (e.Button == MouseButtons.Left) { view.MouseButtonUp(e.X, e.Y, Noesis.MouseButton.Left); } }; // Main loop DateTime start = DateTime.Now; RenderLoop.Run(form, () => { // Update view (layout, animations, ...) view.Update((DateTime.Now - start).TotalSeconds); // Offscreen rendering phase populates textures needed by the on-screen rendering view.Renderer.UpdateRenderTree(); view.Renderer.RenderOffscreen(); // If you are going to render here with your own engine you need to restore the GPU state // because noesis changes it. In this case only framebuffer and viewport need to be restored context.Rasterizer.SetViewport(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.OutputMerger.SetTargets(renderView); context.ClearRenderTargetView(renderView, Color.Black); // Rendering is done in the active framebuffer view.Renderer.Render(); // Present and swap buffers swapChain.Present(0, PresentFlags.None); }); // Release all resources renderView.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); }
public void Setup(OperatorPart outputOpPart, double startTime = 0, double endTime = 184, double frameRate = 30, double width = 1920, double height = 1080, string fileExtension = "png", bool skipExistingFiles = false, string directory = "output", string filenameFormat = "[T]", SharpDX.DXGI.Format imageFormat = Format.R8G8B8A8_UNorm) { try { Dispose(); _outputOpPart = outputOpPart; _directory = directory; _fileNameFormat = filenameFormat; _startTime = startTime; _endTime = endTime; _frameRate = frameRate; _width = (int)width; _height = (int)height; _samples = 2; _fileExtension = fileExtension.ToLower(); _skipExistingFiles = skipExistingFiles; _defaultContext = new OperatorPartContext(0.0f); _defaultContext.Variables.Add("Screensize.Width", _width); _defaultContext.Variables.Add("Screensize.Height", _height); _defaultContext.Variables.Add("AspectRatio", (float)_width / _height); _defaultContext.Variables.Add("Samples", _samples); _defaultContext.Variables.Add("FullScreen", 0.0f); _defaultContext.Variables.Add("LoopMode", 0.0f); _defaultContext.ImageBufferFormat = imageFormat; _frameTime = 1.0 / _frameRate; Directory.CreateDirectory(_directory); _renderer = new DefaultRenderer(); _texture = ShaderResourceView.FromFile(D3DDevice.Device, "./assets-common/image/white.png"); _renderTargetResource = null; ResourceManager.ValidateRenderTargetResource(ref _renderTargetResource, _outputOpPart, D3DDevice.Device, _width, _height, imageFormat); _renderTargetView = new RenderTargetView(D3DDevice.Device, _renderTargetResource.Texture); _renderDepthResource = null; ResourceManager.ValidateDepthStencilResource(ref _renderDepthResource, _outputOpPart, D3DDevice.Device, _width, _height); var depthViewDesc = new DepthStencilViewDescription(); depthViewDesc.Format = Format.D32_Float; depthViewDesc.Dimension = DepthStencilViewDimension.Texture2D; _renderTargetDepthView = new DepthStencilView(D3DDevice.Device, _renderDepthResource.Texture, depthViewDesc); _gpuSyncer = new BlockingGpuSyncer(D3DDevice.Device); D3DDevice.Device.ImmediateContext.OutputMerger.SetTargets(_renderTargetDepthView, _renderTargetView); _viewport = new ViewportF(0, 0, _width, _height, 0.0f, 1.0f); D3DDevice.Device.ImmediateContext.Rasterizer.SetViewport(_viewport); var timeAccessorCollector = new OperatorPart.CollectOpPartFunctionsOfType <OperatorPartTraits.ITimeAccessor>(); _outputOpPart.TraverseWithFunction(timeAccessorCollector, null); _timeAccessorOpPartFunctions = new List <OperatorPart.Function>(); foreach (var opPartFunction in timeAccessorCollector.CollectedOpPartFunctions) { _timeAccessorOpPartFunctions.Add(opPartFunction as OperatorPart.Function); } _currentTime = _startTime; } catch (Exception e) { Logger.Error("Failed to setup image-sequence {0}", e.Message); } }
public bool Initialize(int screenWidth, int screenHeight, bool vSync, IntPtr hwnd, bool fullScreen, float screenDepth, float screenNear) { try { vSyncEnabled = vSync; Rational refreshRate = new Rational(0, 0); var factory = new Factory1(); var adapter = factory.Adapters[0]; var adapterOutput = adapter.Outputs[0]; var modes = adapterOutput.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); for (int i = 0; i < modes.Length; i++) { if (modes[i].Width == screenWidth) { if (modes[i].Height == screenHeight) { refreshRate = modes[i].RefreshRate; } } } VideoCardMemory = adapter.Description.DedicatedVideoMemory / 1024 / 1024; VideoCardDescription = adapter.Description.Description; adapterOutput.Dispose(); adapter.Dispose(); factory.Dispose(); var swapChainDescription = new SwapChainDescription { BufferCount = 1, ModeDescription = { Width = screenWidth, Height = screenHeight, Format = Format.R8G8B8A8_UNorm, RefreshRate = vSyncEnabled ? refreshRate : new Rational(0, 0), ScanlineOrdering = DisplayModeScanlineOrder.Unspecified, Scaling = DisplayModeScaling.Unspecified }, Usage = Usage.RenderTargetOutput, OutputHandle = hwnd, SampleDescription = { Count = 1, Quality = 0 }, IsWindowed = !fullScreen, SwapEffect = SwapEffect.Discard, Flags = SwapChainFlags.None }; var featureLevel = FeatureLevel.Level_11_0; Device device; Device.CreateWithSwapChain( DriverType.Hardware, DeviceCreationFlags.Debug, new[] { featureLevel }, swapChainDescription, out device, out swapChain ); Device = device; DeviceContext = device.ImmediateContext; using (var backBuffer = swapChain.GetBackBuffer <Texture2D>(0)) { renderTargetView = new RenderTargetView(device, backBuffer); } var depthBufferDescription = new Texture2DDescription { Width = screenWidth, Height = screenHeight, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; depthStencilBuffer = new Texture2D(device, depthBufferDescription); var depthStencilStateDescription = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; depthStencilState = new DepthStencilState(device, depthStencilStateDescription); var depthStencilViewDescription = new DepthStencilViewDescription { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = { MipSlice = 0 } }; depthStencilView = new DepthStencilView(device, depthStencilBuffer, depthStencilViewDescription); DeviceContext.OutputMerger.SetRenderTargets(depthStencilView, renderTargetView); var rasterizerStateDescription = new RasterizerStateDescription { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }; rasterizerState = new RasterizerState(device, rasterizerStateDescription); DeviceContext.Rasterizer.State = rasterizerState; var viewport = new Viewport { Width = screenWidth, Height = screenHeight, MinDepth = 0.0f, MaxDepth = 1.0f, X = 0, Y = 0 }; DeviceContext.Rasterizer.SetViewport(viewport); var fieldOfView = MathUtil.Pi / 4.0f; var screenAspect = (float)screenWidth / screenHeight; Projection = Matrix.PerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth); World = Matrix.Identity; Orthogonal = Matrix.OrthoLH(screenWidth, screenHeight, screenNear, screenDepth); } catch { return(false); } return(true); }
/// <summary> /// Updates resources associated with a holographic camera's swap chain. /// The app does not access the swap chain directly, but it does create /// resource views for the back buffer. /// </summary> public void CreateResourcesForBackBuffer( DeviceResources deviceResources, HolographicCameraRenderingParameters cameraParameters ) { var device = deviceResources.D3DDevice; // Get the WinRT object representing the holographic camera's back buffer. IDirect3DSurface surface = cameraParameters.Direct3D11BackBuffer; // Get a DXGI interface for the holographic camera's back buffer. // Holographic cameras do not provide the DXGI swap chain, which is owned // by the system. The Direct3D back buffer resource is provided using WinRT // interop APIs. InteropStatics.IDirect3DDxgiInterfaceAccess surfaceDxgiInterfaceAccess = surface as InteropStatics.IDirect3DDxgiInterfaceAccess; IntPtr pResource = surfaceDxgiInterfaceAccess.GetInterface(InteropStatics.ID3D11Resource); SharpDX.Direct3D11.Resource resource = SharpDX.Direct3D11.Resource.FromPointer <SharpDX.Direct3D11.Resource>(pResource); Marshal.Release(pResource); // Get a Direct3D interface for the holographic camera's back buffer. Texture2D cameraBackBuffer = resource.QueryInterface <Texture2D>(); // Determine if the back buffer has changed. If so, ensure that the render target view // is for the current back buffer. if ((null == d3dBackBuffer) || (d3dBackBuffer.NativePointer != cameraBackBuffer.NativePointer)) { // This can change every frame as the system moves to the next buffer in the // swap chain. This mode of operation will occur when certain rendering modes // are activated. d3dBackBuffer = cameraBackBuffer; // Create a render target view of the back buffer. // Creating this resource is inexpensive, and is better than keeping track of // the back buffers in order to pre-allocate render target views for each one. d3dRenderTargetView = ToDispose(new RenderTargetView(device, BackBufferTexture2D)); // Get the DXGI format for the back buffer. // This information can be accessed by the app using CameraResources::GetBackBufferDXGIFormat(). Texture2DDescription backBufferDesc = BackBufferTexture2D.Description; dxgiFormat = backBufferDesc.Format; // Check for render target size changes. Size currentSize = holographicCamera.RenderTargetSize; if (d3dRenderTargetSize != currentSize) { // Set render target size. d3dRenderTargetSize = HolographicCamera.RenderTargetSize; // A new depth stencil view is also needed. RemoveAndDispose(ref d3dDepthStencilView); } } // Refresh depth stencil resources, if needed. if (null == DepthStencilView) { // Create a depth stencil view for use with 3D rendering if needed. var depthStencilDesc = new Texture2DDescription { Format = SharpDX.DXGI.Format.D16_UNorm, Width = (int)RenderTargetSize.Width, Height = (int)RenderTargetSize.Height, ArraySize = IsRenderingStereoscopic ? 2 : 1, // Create two textures when rendering in stereo. MipLevels = 1, // Use a single mipmap level. BindFlags = BindFlags.DepthStencil, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0) }; using (var depthStencil = new Texture2D(device, depthStencilDesc)) { var depthStencilViewDesc = new DepthStencilViewDescription(); depthStencilViewDesc.Dimension = IsRenderingStereoscopic ? DepthStencilViewDimension.Texture2DArray : DepthStencilViewDimension.Texture2D; depthStencilViewDesc.Texture2DArray.ArraySize = IsRenderingStereoscopic ? 2 : 0; d3dDepthStencilView = ToDispose(new DepthStencilView(device, depthStencil, depthStencilViewDesc)); } } // Create the constant buffer, if needed. if (null == viewProjectionConstantBuffer) { // Create a constant buffer to store view and projection matrices for the camera. ViewProjectionConstantBuffer viewProjectionConstantBufferData = new ViewProjectionConstantBuffer(); viewProjectionConstantBuffer = ToDispose(SharpDX.Direct3D11.Buffer.Create( device, BindFlags.ConstantBuffer, ref viewProjectionConstantBufferData)); } }
public void Render(DeviceContext deviceContext, ShaderResourceView depthImageTextureRV, ShaderResourceView colorImageTextureRV, SharpDX.Direct3D11.Buffer vertexBuffer, RenderTargetView renderTargetView, DepthStencilView depthStencilView, Viewport viewport) { //bilateralFilter.Render(deviceContext, depthImageTextureRV, filteredRenderTargetView2); //bilateralFilter.Render(deviceContext, filteredDepthImageSRV2, filteredRenderTargetView); //bilateralFilter.Render(deviceContext, filteredDepthImageSRV, filteredRenderTargetView2); //bilateralFilter.Render(deviceContext, filteredDepthImageSRV2, filteredRenderTargetView); deviceContext.InputAssembler.InputLayout = vertexInputLayout; deviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; deviceContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, VertexPosition.SizeInBytes, 0)); // bytes per vertex deviceContext.Rasterizer.State = rasterizerState; deviceContext.Rasterizer.SetViewport(viewport); deviceContext.VertexShader.Set(depthAndColorVS); deviceContext.VertexShader.SetShaderResource(0, depthImageTextureRV); //deviceContext.VertexShader.SetShaderResource(0, depthAndMaskRV); //deviceContext.VertexShader.SetShaderResource(0, filteredDepthImageSRV); deviceContext.VertexShader.SetConstantBuffer(0, constantBuffer); deviceContext.GeometryShader.Set(depthAndColorGS); deviceContext.PixelShader.Set(depthAndColorPS); deviceContext.PixelShader.SetShaderResource(0, colorImageTextureRV); deviceContext.PixelShader.SetSampler(0, colorSamplerState); deviceContext.OutputMerger.SetTargets(depthStencilView, renderTargetView); deviceContext.OutputMerger.DepthStencilState = depthStencilState; deviceContext.Draw((depthImageWidth - 1) * (depthImageHeight - 1) * 6, 0); }
void RenderPart(RenderTargetView Target) { }
public void Draw(DeviceContextHolder holder, ShaderResourceView source, Vector2 sourceSize, RenderTargetView destination, Vector2 destinationSize, bool useFoundTech) { holder.DeviceContext.Rasterizer.SetViewports(new Viewport(0f, 0f, destinationSize.X, destinationSize.Y)); holder.DeviceContext.OutputMerger.SetTargets(destination); holder.PrepareQuad(_effect.LayoutPT); _effect.FxInputMap.SetResource(source); _effect.FxScreenSize.Set(new Vector4(destinationSize.X, destinationSize.Y, 1f / destinationSize.X, 1f / destinationSize.Y)); _effect.FxMultipler.Set(new Vector2(destinationSize.X / sourceSize.X, destinationSize.Y / sourceSize.Y)); (useFoundTech ? _effect.TechFound : _effect.TechAverage).DrawAllPasses(holder.DeviceContext, 6); }
void CreateBuffers() { DisposeBuffers(); // New RenderTargetView from the backbuffer using (var bb = Texture2D.FromSwapChain <Texture2D>(_swapChain, 0)) { renderView = new RenderTargetView(_device, bb); } Texture2DDescription gBufferDesc = new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R8G8B8A8_UNorm, Width = _width, Height = _height, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; gBufferLight = new Texture2D(_device, gBufferDesc); gBufferLightView = new RenderTargetView(_device, gBufferLight); gBufferNormal = new Texture2D(_device, gBufferDesc); gBufferNormalView = new RenderTargetView(_device, gBufferNormal); gBufferDiffuse = new Texture2D(_device, gBufferDesc); gBufferDiffuseView = new RenderTargetView(_device, gBufferDiffuse); gBufferViews = new RenderTargetView[] { gBufferLightView, gBufferNormalView, gBufferDiffuseView }; ShaderResourceViewDescription gBufferResourceDesc = new ShaderResourceViewDescription() { Format = Format.R8G8B8A8_UNorm, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0 } }; lightBufferRes = new ShaderResourceView(_device, gBufferLight, gBufferResourceDesc); normalBufferRes = new ShaderResourceView(_device, gBufferNormal, gBufferResourceDesc); diffuseBufferRes = new ShaderResourceView(_device, gBufferDiffuse, gBufferResourceDesc); Texture2DDescription depthDesc = new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R32_Typeless, Width = _width, Height = _height, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; DepthStencilViewDescription depthViewDesc = new DepthStencilViewDescription() { Dimension = DepthStencilViewDimension.Texture2D, Format = Format.D32_Float, }; ShaderResourceViewDescription resourceDesc = new ShaderResourceViewDescription() { Format = Format.R32_Float, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0 } }; depthTexture = new Texture2D(_device, depthDesc); depthView = new DepthStencilView(_device, depthTexture, depthViewDesc); depthRes = new ShaderResourceView(_device, depthTexture, resourceDesc); lightDepthTexture = new Texture2D(_device, depthDesc); lightDepthView = new DepthStencilView(_device, lightDepthTexture, depthViewDesc); lightDepthRes = new ShaderResourceView(_device, lightDepthTexture, resourceDesc); lightBufferVar = effect2.GetVariableByName("lightBuffer").AsShaderResource(); normalBufferVar = effect2.GetVariableByName("normalBuffer").AsShaderResource(); diffuseBufferVar = effect2.GetVariableByName("diffuseBuffer").AsShaderResource(); depthMapVar = effect2.GetVariableByName("depthMap").AsShaderResource(); lightDepthMapVar = effect2.GetVariableByName("lightDepthMap").AsShaderResource(); inverseProjectionVar = effect2.GetVariableByName("InverseProjection").AsMatrix(); inverseViewVar = effect2.GetVariableByName("InverseView").AsMatrix(); lightInverseViewProjectionVar = effect2.GetVariableByName("LightInverseViewProjection").AsMatrix(); lightPositionVar = effect2.GetVariableByName("LightPosition").AsVector(); eyePositionVar = effect2.GetVariableByName("EyePosition").AsVector(); tanHalfFOVXVar = effect2.GetVariableByName("TanHalfFOVX").AsScalar(); tanHalfFOVYVar = effect2.GetVariableByName("TanHalfFOVY").AsScalar(); projectionAVar = effect2.GetVariableByName("ProjectionA").AsScalar(); projectionBVar = effect2.GetVariableByName("ProjectionB").AsScalar(); overlayViewProjectionVar = effect2.GetVariableByName("OverlayViewProjection").AsMatrix(); _immediateContext.Rasterizer.SetViewport(new ViewportF(0, 0, _width, _height)); }
void CreateBuffers() { DisposeBuffers(); // New RenderTargetView from the backbuffer using (var bb = Texture2D.FromSwapChain <Texture2D>(_swapChain, 0)) { renderView = new RenderTargetView(Device, bb); } var gBufferDesc = new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R8G8B8A8_UNorm, Width = _width, Height = _height, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; gBufferLight = new Texture2D(Device, gBufferDesc); gBufferLightView = new RenderTargetView(Device, gBufferLight); gBufferNormal = new Texture2D(Device, gBufferDesc); gBufferNormalView = new RenderTargetView(Device, gBufferNormal); gBufferDiffuse = new Texture2D(Device, gBufferDesc); gBufferDiffuseView = new RenderTargetView(Device, gBufferDiffuse); gBufferPostProcess = new Texture2D(Device, gBufferDesc); gBufferPostProcessView = new RenderTargetView(Device, gBufferPostProcess); if (depthOfFieldEnabled) { gBufferPostProcessBlur1 = new Texture2D(Device, gBufferDesc); gBufferPostProcessViewBlur1 = new RenderTargetView(Device, gBufferPostProcessBlur1); gBufferPostProcessBlur2 = new Texture2D(Device, gBufferDesc); gBufferPostProcessViewBlur2 = new RenderTargetView(Device, gBufferPostProcessBlur2); } gBufferViews = new[] { gBufferNormalView, gBufferDiffuseView }; var gBufferResourceDesc = new ShaderResourceViewDescription { Format = Format.R8G8B8A8_UNorm, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0 } }; lightBufferRes = new ShaderResourceView(Device, gBufferLight, gBufferResourceDesc); normalBufferRes = new ShaderResourceView(Device, gBufferNormal, gBufferResourceDesc); diffuseBufferRes = new ShaderResourceView(Device, gBufferDiffuse, gBufferResourceDesc); postProcessBufferRes = new ShaderResourceView(Device, gBufferPostProcess, gBufferResourceDesc); if (depthOfFieldEnabled) { postProcessBufferBlur1Res = new ShaderResourceView(Device, gBufferPostProcessBlur1, gBufferResourceDesc); postProcessBufferBlur2Res = new ShaderResourceView(Device, gBufferPostProcessBlur2, gBufferResourceDesc); } var depthDesc = new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R32_Typeless, Height = _height, Width = _width, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; var depthViewDesc = new DepthStencilViewDescription { Dimension = DepthStencilViewDimension.Texture2D, Format = Format.D32_Float, }; var resourceDesc = new ShaderResourceViewDescription { Format = Format.R32_Float, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0 } }; depthTexture = new Texture2D(Device, depthDesc); depthView = new DepthStencilView(Device, depthTexture, depthViewDesc); depthBufferRes = new ShaderResourceView(Device, depthTexture, resourceDesc); lightDepthTexture = new Texture2D(Device, depthDesc); lightDepthView = new DepthStencilView(Device, lightDepthTexture, depthViewDesc); lightDepthRes = new ShaderResourceView(Device, lightDepthTexture, resourceDesc); _immediateContext.Rasterizer.SetViewport(0, 0, _width, _height); }
static void Main() { var form = new RenderForm("SlimDX - MiniTri Direct3D 10 Sample"); 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 }; Device device; SwapChain swapChain; Device.CreateWithSwapChain(null, DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain); //Stops Alt+enter from causing fullscreen skrewiness. device.Factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); var effect = Effect.FromFile(device, "MiniTri.fx", "fx_4_0"); var technique = effect.GetTechniqueByIndex(0); var pass = technique.GetPassByIndex(0); var layout = new InputLayout(device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); var stream = new DataStream(3 * 32, true, true); stream.WriteRange(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) }); stream.Position = 0; var vertices = new SlimDX.Direct3D10.Buffer(device, stream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = 3 * 32, Usage = ResourceUsage.Default }); stream.Dispose(); device.OutputMerger.SetTargets(renderView); device.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); MessagePump.Run(form, () => { device.ClearRenderTargetView(renderView, Color.Black); device.InputAssembler.SetInputLayout(layout); device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList); device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0)); for (int i = 0; i < technique.Description.PassCount; ++i) { pass.Apply(); device.Draw(3, 0); } swapChain.Present(0, PresentFlags.None); }); vertices.Dispose(); layout.Dispose(); effect.Dispose(); renderView.Dispose(); backBuffer.Dispose(); device.Dispose(); swapChain.Dispose(); //foreach (var item in ObjectTable.Objects) // item.Dispose(); }
// Puvlix Methods public bool Initialize(SharpDX.Direct3D11.Device device, DSystemConfiguration configuration) { try { // Initialize and set up the render target description. Texture2DDescription textureDesc = new Texture2DDescription() { // Shadow Map Texture size as a 1024x1024 Square Width = 1024, Height = 1024, MipLevels = 1, ArraySize = 1, Format = Format.R32G32B32A32_Float, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; // Create the render target texture. RenderTargetTexture = new Texture2D(device, textureDesc); // Setup the description of the render target view. RenderTargetViewDescription renderTargetViewDesc = new RenderTargetViewDescription() { Format = textureDesc.Format, Dimension = RenderTargetViewDimension.Texture2D, }; renderTargetViewDesc.Texture2D.MipSlice = 0; // Create the render target view. RenderTargetView = new RenderTargetView(device, RenderTargetTexture, renderTargetViewDesc); // Setup the description of the shader resource view. ShaderResourceViewDescription shaderResourceViewDesc = new ShaderResourceViewDescription() { Format = textureDesc.Format, Dimension = ShaderResourceViewDimension.Texture2D, }; shaderResourceViewDesc.Texture2D.MipLevels = 1; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; // Create the render target view. ShaderResourceView = new ShaderResourceView(device, RenderTargetTexture, shaderResourceViewDesc); // Initialize and Set up the description of the depth buffer. Texture2DDescription depthStencilDesc = new Texture2DDescription() { Width = 1024, Height = 1024, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; // Create the texture for the depth buffer using the filled out description. DepthStencilBuffer = new Texture2D(device, depthStencilDesc); // Initailze the depth stencil view description. DepthStencilViewDescription deothStencilViewDesc = new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D }; deothStencilViewDesc.Texture2D.MipSlice = 0; // Create the depth stencil view. DepthStencilView = new DepthStencilView(device, DepthStencilBuffer, deothStencilViewDesc); // Setup the viewport for rendering. ViewPort = new ViewportF() { Width = 1024.0f, Height = 1024.0f, MinDepth = 0.0f, MaxDepth = 1.0f, X = 0.0f, Y = 0.0f }; return(true); } catch { return(false); } }