private void InitializeDeviceResources() { ModeDescription backBufferDesc = new ModeDescription(Width, Height, new Rational(60, 1), Format.R8G8B8A8_UNorm); // Descriptor for the swap chain SwapChainDescription swapChainDesc = new SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = renderForm.Handle, IsWindowed = true }; // Create device and swap chain D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain); d3dDeviceContext = d3dDevice.ImmediateContext; // Create render target view for back buffer using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0)) { renderTargetView = new D3D11.RenderTargetView(d3dDevice, backBuffer); } }
/// <summary> /// Discards this RenderPass (called after rendering all objects of this pass). /// </summary> /// <param name="renderState">The current render state.</param> public override void Discard(RenderState renderState) { D3D11.DeviceContext deviceContext = renderState.Device.DeviceImmediateContextD3D11; deviceContext.OutputMerger.BlendState = m_defaultResources.DefaultBlendState; deviceContext.OutputMerger.DepthStencilState = m_defaultResources.DepthStencilStateDefault; }
/// <summary> /// Applies this RenderPass (called before starting rendering first objects with it). /// </summary> /// <param name="renderState">The current render state.</param> public override void Apply(RenderState renderState) { D3D11.DeviceContext deviceContext = renderState.Device.DeviceImmediateContextD3D11; deviceContext.OutputMerger.BlendState = m_defaultResources.AlphaBlendingBlendState; deviceContext.OutputMerger.DepthStencilState = m_defaultResources.DepthStencilStateDisableZWrites; }
public override void Draw(SharpDX.Direct3D11.DeviceContext context, int index) { foreach (var emitter in _liveEmitter) { emitter.Draw(context, index); } }
//startup settings private void InitializeDeviceResources() { //params,FPS,buffer pixel format ModeDescription backBufferDesc = new ModeDescription(Width, Height, new Rational(30, 1), Format.R8G8B8A8_UNorm); SwapChainDescription swapChainDesc = new SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = renderForm.Handle, IsWindowed = true }; //GPU,Special flag,descriptor for swap chain,holders D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain); //Getting device context d3dDeviceContext = d3dDevice.ImmediateContext; using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0)) { renderTargetView = new D3D11.RenderTargetView(d3dDevice, backBuffer); } }
/// <summary> /// Initializes the specified device. /// </summary> /// <param name="graphicsProfiles">The graphics profiles.</param> /// <param name="deviceCreationFlags">The device creation flags.</param> /// <param name="windowHandle">The window handle.</param> private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle) { if (nativeDevice != null) { // Destroy previous device ReleaseDevice(); } // Profiling is supported through pix markers IsProfilingSupported = true; // Map GraphicsProfile to D3D11 FeatureLevel SharpDX.Direct3D.FeatureLevel[] levels = graphicsProfiles.ToFeatureLevel(); creationFlags = (SharpDX.Direct3D11.DeviceCreationFlags)deviceCreationFlags; // Create Device D3D11 with feature Level based on profile nativeDevice = new SharpDX.Direct3D11.Device(Adapter.NativeAdapter, creationFlags, levels); nativeDeviceContext = nativeDevice.ImmediateContext; if (IsDebugMode) { GraphicsResourceBase.SetDebugName(this, nativeDeviceContext, "ImmediateContext"); } InitializeStages(); // Create the input layout manager if (InputLayoutManager == null) { InputLayoutManager = new InputLayoutManager(this).DisposeBy(this); } }
/// <summary> /// Create all view resources. /// </summary> Tuple <D3D11.Texture2D, D3D11.RenderTargetView, D3D11.Texture2D, D3D11.DepthStencilView, SharpDX.Mathematics.Interop.RawViewportF, Size2, DpiScaling> IRenderLoopHost.OnRenderLoop_CreateViewResources(EngineDevice device) { //Get references to current render device m_device = device.DeviceD3D11_1; m_deviceContext = m_device.ImmediateContext; // Create swapchain and dummy form m_swapChain = GraphicsHelper.CreateSwapChainForFullScreen( m_dummyForm, m_targetOutput, m_targetOutputMode, device, m_renderLoop.ViewConfiguration); // Take width and height out of the render target m_renderTarget = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(m_swapChain, 0); m_renderTargetView = new D3D11.RenderTargetView(m_device, m_renderTarget); //Create the depth buffer m_renderTargetDepth = GraphicsHelper.CreateDepthBufferTexture(device, m_targetOutputMode.PixelWidth, m_targetOutputMode.PixelHeight, m_renderLoop.ViewConfiguration); m_renderTargetDepthView = new D3D11.DepthStencilView(m_device, m_renderTargetDepth); //Define the viewport for rendering SharpDX.Mathematics.Interop.RawViewportF viewPort = GraphicsHelper.CreateDefaultViewport(m_targetOutputMode.PixelWidth, m_targetOutputMode.PixelHeight); //Return all generated objects return(Tuple.Create(m_renderTarget, m_renderTargetView, m_renderTargetDepth, m_renderTargetDepthView, viewPort, new Size2(m_targetOutputMode.PixelWidth, m_targetOutputMode.PixelHeight), DpiScaling.Default)); }
public override void LoadContent(SharpDX.Direct3D11.DeviceContext context) { ImageLoadInformation imageLoadParam = new ImageLoadInformation() { BindFlags = BindFlags.ShaderResource, Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm, MipLevels = 1 }; _compassPanel = new CompassControl() { FrameName = "WindRose", Bounds = new UniRectangle(new UniScalar(1.0f, -160), 10, 150, 75), CompassTexture = ToDispose(new SpriteTexture(_engine.Device, ClientSettings.TexturePack + @"Gui\WindRose.png", Vector2I.Zero, imageLoadParam)), DayCircle = ToDispose(new SpriteTexture(_engine.Device, ClientSettings.TexturePack + @"Gui\DayCircle.png", Vector2I.Zero, imageLoadParam)), MaskArrow = ToDispose(new SpriteTexture(_engine.Device, ClientSettings.TexturePack + @"Gui\MaskArrow.png", Vector2I.Zero, imageLoadParam)), SoulStoneIcon = ToDispose(new SpriteTexture(_engine.Device, ClientSettings.TexturePack + @"Gui\SoulStoneIcon.png", Vector2I.Zero, imageLoadParam)), sampler = RenderStatesRepo.GetSamplerState(DXStates.Samplers.UVClamp_MinMagMipLinear), }; _dateTime = new LabelControl() { Color = Color.Tomato, Text = "", Bounds = new UniRectangle(-50, -5, new UniScalar(1.0f, 0.0f), 20.0f) }; _compassPanel.Children.Add(_dateTime); _compassPanel.LayoutFlags = S33M3CoreComponents.GUI.Nuclex.Controls.ControlLayoutFlags.Skip; _guiScreen.Desktop.Children.Add(_compassPanel); }
public void ApplyPostEffect( D3D11.ShaderResourceView sourceRenderTarget, D3D11.ShaderResourceView sourceDepthStencil, D3D11.RenderTargetView destRenderTarget, PostProcessing.PostEffect effect) { D3D11.DeviceContext deviceContext = deviceResources.DeviceContext; // No rendering directly to DepthStencil deviceContext.OutputMerger.SetRenderTargets(null, destRenderTarget); deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip; deviceContext.InputAssembler.InputLayout = effect.Shader.InputLayout; deviceContext.VertexShader.Set(effect.Shader.VertexShader); deviceContext.PixelShader.Set(effect.Shader.PixelShader); deviceContext.PixelShader.SetShaderResource(0, sourceRenderTarget); deviceContext.PixelShader.SetShaderResource(1, sourceDepthStencil); deviceContext.PixelShader.SetSampler(0, sampler); deviceContext.Draw(4, 0); // Reset deviceContext.OutputMerger.SetRenderTargets( renderTargetHandler.GetDepthStencilView(), renderTargetHandler.GetRenderTargetView() ); }
/// <summary> /// Инициализирует объекты связанные с графическим устройство - Девайс его контекст и Свапчейн /// </summary> private void InitializeDeviceResources() { //Создаем объектное преставление нашего GPU, его контекст и класс который будет менят местами буфферы в которые рисует наша GPU DX11.Device.CreateWithSwapChain( SharpDX.Direct3D.DriverType.Hardware, DX11.DeviceCreationFlags.None | DX11.DeviceCreationFlags.BgraSupport, new[] { SharpDX.Direct3D.FeatureLevel.Level_11_0 }, new SwapChainDescription() { ModeDescription = new ModeDescription( _renderForm.ClientSize.Width, _renderForm.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(4, 0), Usage = Usage.BackBuffer | Usage.RenderTargetOutput, BufferCount = 2, OutputHandle = _renderForm.Handle, IsWindowed = true, SwapEffect = SwapEffect.Discard, Flags = SwapChainFlags.None }, out _dx11Device, out _swapChain); //Игноровать все события видновс _factory = _swapChain.GetParent <Factory>(); _factory.MakeWindowAssociation(_renderForm.Handle, WindowAssociationFlags.IgnoreAll); // Создаем буффер и вьюшку глубины using (var _depthBuffer = new DX11.Texture2D( _dx11Device, new DX11.Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = _renderForm.ClientSize.Width, Height = _renderForm.ClientSize.Height, SampleDescription = _swapChain.Description.SampleDescription, Usage = DX11.ResourceUsage.Default, BindFlags = DX11.BindFlags.DepthStencil, CpuAccessFlags = DX11.CpuAccessFlags.None, OptionFlags = DX11.ResourceOptionFlags.None })) _depthView = new DX11.DepthStencilView(_dx11Device, _depthBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription() { Dimension = (SwapChain.Description.SampleDescription.Count > 1 || SwapChain.Description.SampleDescription.Quality > 0) ? DX11.DepthStencilViewDimension.Texture2DMultisampled : DX11.DepthStencilViewDimension.Texture2D, Flags = DX11.DepthStencilViewFlags.None }); //Создаем буффер и вьюшку для рисования using (DX11.Texture2D backBuffer = _swapChain.GetBackBuffer <DX11.Texture2D>(0)) _renderView = new DX11.RenderTargetView(_dx11Device, backBuffer); //Создаем контекст нашего GPU _dx11DeviceContext = _dx11Device.ImmediateContext; //Устанавливаем размер конечной картинки _dx11DeviceContext.Rasterizer.SetViewport(0, 0, _renderForm.ClientSize.Width, _renderForm.ClientSize.Height); _dx11DeviceContext.OutputMerger.SetTargets(_depthView, _renderView); }
public void Draw(SharpDX.Direct3D11.DeviceContext context, int index) { if (_particules.Count == 0) { return; } //Accumulate particules here for this emitters, and render them ColoredParticule p; _particuleRenderer.Begin(context, true); for (int i = 0; i < _particules.Count; i++) { p = _particules[i]; Vector3 position = p.Position.ValueInterp.AsVector3(); ByteColor color = p.ParticuleColor; //Add a new Particule Matrix result; Matrix scaling = Matrix.Scaling(p.Size.X, p.Size.Y, p.Size.Y); Matrix rotation = Matrix.RotationQuaternion(p.RotationAngles.ValueInterp); //Identity rotation Matrix translation = Matrix.Translation(position); result = scaling * rotation * translation; _particuleRenderer.Processor.Draw(ref color, ref p.ColorReceived, ref result); } _particuleRenderer.End(context); }
private void Render(D3D11.Device device, D3D11.RenderTargetView[] rtvs) { D3D11.DeviceContext deviceContext = device.ImmediateContext; for (int i = 0; i < 6; ++i) { deviceContext.OutputMerger.SetRenderTargets(rtvs[i]); deviceContext.ClearRenderTargetView(rtvs[i], Color.Red); //if (i == 5) // continue; KDX_SKYBOX_ENV_RENDERER_BUFFER buffer = new KDX_SKYBOX_ENV_RENDERER_BUFFER(); buffer.World = Matrix.Transpose(Matrix.Identity); buffer.View = Matrix.Transpose(views[i]); buffer.Proj = Matrix.Transpose(Matrix.PerspectiveFovLH(MathUtil.DegreesToRadians(90), 1, 0.01f, 100.0f)); buffer.MVP = (buffer.Proj * buffer.View * buffer.World); deviceContext.UpdateSubresource(ref buffer, perFaceBuffer); deviceContext.DrawIndexed(cubeMesh.Triangles.Count() * 3, 0, 0); rtvs[i].Dispose(); } }
internal void Dispose() { if (_outputDuplication != null) { _outputDuplication.Dispose(); _outputDuplication = null; } if (_device != null) { _device.Dispose(); _device = null; } if (_deviceContext != null) { _deviceContext.Dispose(); _deviceContext = null; } if (_adapter != null) { _adapter.Dispose(); _adapter = null; } }
private void InitializeDeviceResources() { ModeDescription backBufferDesc = new ModeDescription(Width, Height, new Rational(60, 1), Format.R8G8B8A8_UNorm); // Descriptor for the swap chain SwapChainDescription swapChainDesc = new SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = renderForm.Handle, IsWindowed = true }; // Create device and swap chain D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain); d3dDeviceContext = d3dDevice.ImmediateContext; // Create render target view for back buffer using(D3D11.Texture2D backBuffer = swapChain.GetBackBuffer<D3D11.Texture2D>(0)) { renderTargetView = new D3D11.RenderTargetView(d3dDevice, backBuffer); } // Set back buffer as current render target view d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView); }
/// <summary> /// Applies alpha based sprite rendering. /// </summary> /// <param name="deviceContext">The target device context.</param> protected void ApplyAlphaBasedSpriteRendering(D3D11.DeviceContext deviceContext) { deviceContext.VertexShader.Set(m_vertexShader.VertexShader); deviceContext.OutputMerger.DepthStencilState = m_defaultResources.DepthStencilStateAllwaysPassDepth; deviceContext.OutputMerger.BlendState = m_defaultResources.AlphaBlendingBlendState; }
public static SharpDX.Direct3D11.Texture2D CreateTex2DFromBitmap(SharpDX.Direct3D11.DeviceContext device, BitmapSource bsource) { SharpDX.Direct3D11.Texture2DDescription desc; desc.Width = bsource.Size.Width; desc.Height = bsource.Size.Height; desc.ArraySize = 1; desc.BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource; desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default; desc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None; desc.Format = Format.R8G8B8A8_UNorm; desc.MipLevels = 1; desc.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None; desc.SampleDescription.Count = 1; desc.SampleDescription.Quality = 0; var s = new DataStream(bsource.Size.Height * bsource.Size.Width * 4, true, true); bsource.CopyPixels(bsource.Size.Width * 4, s); var rect = new DataRectangle(s.DataPointer, bsource.Size.Width * 4); var t2D = new SharpDX.Direct3D11.Texture2D(device.Device, desc, rect); return(t2D); }
protected void InitializeDeviceResources() { var backBufferDesc = new ModeDescription(Width, Height, new Rational(60, 1), Format.R8G8B8A8_UNorm); SwapChainDescriptor = new SwapChainDescription() { BufferCount = 1, ModeDescription = backBufferDesc, IsWindowed = true, OutputHandle = RenderForm.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, }; Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, Direct3D11.DeviceCreationFlags.BgraSupport, SwapChainDescriptor, out GameDevice, out SwapChain); DeviceContext = GameDevice.ImmediateContext; Viewport = new Viewport(0, 0, Width, Height, 0.0f, 1.0f); DeviceContext.Rasterizer.SetViewport(Viewport); Factory = SwapChain.GetParent <SharpDX.DXGI.Factory>(); //factory.MakeWindowAssociation(renderForm.Handle, WindowAssociationFlags.IgnoreAll); BackBufer = SwapChain.GetBackBuffer <Direct3D11.Texture2D>(0); RenderTargetView = new RenderTargetView(GameDevice, BackBufer); }
/// <summary> /// Заргуражет писели из картинки /// </summary> /// <param name="device">Устройство с помощью которого будет рисоваться эта картинка</param> /// <param name="filename">Путь к файлу с картинкой</param> /// <returns>Набор пикселей</returns> public static BitmapSource LoadBitmapSource(SharpDX.Direct3D11.DeviceContext device, string filename) { var pFormat = SharpDX.WIC.PixelFormat.Format32bppPRGBA; string ext = System.IO.Path.GetExtension(filename); if (ext.ToLower() == ".dds") { pFormat = SharpDX.WIC.PixelFormat.Format32bppRGBA; } using (var Imgfactory = new ImagingFactory2()) using (var d = new BitmapDecoder( Imgfactory, filename, DecodeOptions.CacheOnDemand )) using (var frame = d.GetFrame(0)) { var fconv = new FormatConverter(Imgfactory); fconv.Initialize( frame, pFormat, BitmapDitherType.None, null, 0.0, BitmapPaletteType.Custom); return(fconv); } }
public override void Draw(SharpDX.Direct3D11.DeviceContext context, int index) { if (_engine.CurrentMSAASampling.Count <= 1) { if (OffSreenRenderTarget == null) { context.CopyResource(_engine.BackBufferTex, _renderTexture); } else { context.CopyResource(OffSreenRenderTarget, _renderTexture); } } else { if (OffSreenRenderTarget == null) { context.ResolveSubresource(_engine.BackBufferTex, 0, _renderTexture, 0, Format.R8G8B8A8_UNorm); } else { context.ResolveSubresource(OffSreenRenderTarget, 0, _renderTexture, 0, Format.R8G8B8A8_UNorm); } } }
/// <summary> /// Triggers internal rendering within the resource (e. g. Render to Texture). /// </summary> /// <param name="renderState">Current render state.</param> public void Render(RenderState renderState) { D3D11.DeviceContext deviceContext = renderState.Device.DeviceImmediateContextD3D11; // Upload the last read video frame to texture buffer on the graphics device if (m_thumbnailFrame != null) { SharpDX.DataBox dataBox = deviceContext.MapSubresource(m_texture, 0, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None); try { unsafe { int *frameBufferPointerNative = (int *)m_thumbnailFrame.Pointer.ToPointer(); int *textureBufferPointerNative = (int *)dataBox.DataPointer.ToPointer(); // Performance optimization using MemCopy // see http://www.rolandk.de/wp/2015/05/wie-schnell-man-speicher-falsch-kopieren-kann/ for (int loopY = 0; loopY < m_videoHeight; loopY++) { IntPtr rowStartTexture = new IntPtr(textureBufferPointerNative + (dataBox.RowPitch / 4) * loopY); IntPtr rowStartSource = new IntPtr(frameBufferPointerNative + (m_videoWidth) * loopY); CommonTools.CopyMemory(rowStartSource, rowStartTexture, (ulong)dataBox.RowPitch); } } } finally { GraphicsHelper.SafeDispose(ref m_thumbnailFrame); deviceContext.UnmapSubresource(m_texture, 0); } } }
public void SetSkyboxSRVT(Skybox skybox) { D3D11.DeviceContext deviceContext = deviceResources.DeviceContext; deviceContext.PixelShader.SetShaderResource(SKYBOX_ENV_SLOT, skybox.Cubemap.Enviroment.SRVT); deviceContext.PixelShader.SetShaderResource(SKYBOX_IRR_SLOT, skybox.Cubemap.Irradiance.SRVT); }
/// <summary> /// Draws the specified context. /// </summary> /// <param name="context">The context.</param> public override void Draw(D3D11.DeviceContext context) { if (Vertices != null && Indices != null) { context.DrawIndexed(Indices.Length, 0, 0); } }
public void Cleanup() { m_DeviceContext.PixelShader.Set(null); m_DeviceContext.VertexShader.Set(null); m_SwapChain.Dispose(); m_SwapChain = null; Device.Dispose(); Device = null; m_DeviceContext.Dispose(); m_DeviceContext = null; //-------- m_ShaderMgr.Dispose(); m_ShaderMgr = null; m_TextureMgr.Dispose(); m_TextureMgr = null; m_TriMeshMgr.Dispose(); m_TriMeshMgr = null; }
/// <summary> /// Sets given content to the constant buffer. /// </summary> /// <param name="deviceContext">The context used for updating the constant buffer.</param> /// <param name="dataToSet">The data to set.</param> internal void SetData(D3D11.DeviceContext deviceContext, T dataToSet) { DataBox dataBox = deviceContext.MapSubresource(base.ConstantBuffer, 0, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None); SharpDX.Utilities.Write(dataBox.DataPointer, ref dataToSet); deviceContext.UnmapSubresource(base.ConstantBuffer, 0); }
public InfoText(SharpDX.Direct3D11.Device device, int width, int height) { _immediateContext = device.ImmediateContext; _rect.Size = new Size2F(width, height); _bitmapSize = width * height * 4; IsEnabled = true; using (var factoryWic = new SharpDX.WIC.ImagingFactory()) { _wicBitmap = new SharpDX.WIC.Bitmap(factoryWic, width, height, _pixelFormat, SharpDX.WIC.BitmapCreateCacheOption.CacheOnLoad); } var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None, SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT); using (var factory2D = new SharpDX.Direct2D1.Factory()) { _wicRenderTarget = new WicRenderTarget(factory2D, _wicBitmap, renderTargetProperties); _wicRenderTarget.TextAntialiasMode = TextAntialiasMode.Default; } using (var factoryDWrite = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared)) { _textFormat = new TextFormat(factoryDWrite, "Tahoma", 20); } Color4 color = new Color4(1, 1, 1, 1); _sceneColorBrush = new SolidColorBrush(_wicRenderTarget, color); _clearColor = color; _clearColor.Alpha = 0; _renderTexture = new Texture2D(device, new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.Write, Format = Format.R8G8B8A8_UNorm, Height = height, Width = width, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Dynamic }); OverlayBufferView = new ShaderResourceView(device, _renderTexture, new ShaderResourceViewDescription() { Format = _renderTexture.Description.Format, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0 } }); }
private void InitializeDeviceResources() { ModeDescription backBufferDesc = new ModeDescription(Size.X, Size.Y, new Rational(60, 1), Format.R8G8B8A8_UNorm); SwapChainDescription swapChainDesc = new SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 2, IsWindowed = true, OutputHandle = Form.Handle }; viewport = new Viewport(0, 0, Size.X, Size.Y); D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.Debug, swapChainDesc, out device, out swapChain); deviceContext = device.ImmediateContext; using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0)) { view = new D3D11.RenderTargetView(device, backBuffer); } deviceContext.OutputMerger.SetRenderTargets(view); deviceContext.Rasterizer.SetViewport(viewport); vertexBuffer = D3D11.Buffer.Create <Vertex>(device, D3D11.BindFlags.VertexBuffer, new Vertex[1]); lastVertexArrayLength = 1; }
protected void InitializeDeviceResources() { ModeDescription backBufferDesc = new ModeDescription(Width, Height, new Rational(60, 1), Format.R8G8B8A8_UNorm); SwapChainDescription swapChainDesc = new SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = renderForm.Handle, IsWindowed = true }; D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain); d3dDeviceContext = d3dDevice.ImmediateContext; viewport = new Viewport(0, 0, Width, Height); d3dDeviceContext.Rasterizer.SetViewport(viewport); using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0)) { renderTargetView = new D3D11.RenderTargetView(d3dDevice, backBuffer); } }
public override void Draw(SharpDX.Direct3D11.DeviceContext context, int index) { if (_activatedEffect == null) { if (_backBufferClouds.OffSreenRenderTarget != null) { _backBufferClouds.OffSreenRenderTarget = null; } return; } if (index == _postEffectStartingDrawId) { //Change RenderTarget to this offline texture //Clear renderTarger _engine.ImmediateContext.ClearRenderTargetView(_renderTargetView, __renderTargetViewDefaultColor); _engine.ImmediateContext.OutputMerger.SetTargets(_engine.DepthStencilTarget, _renderTargetView); _backBufferClouds.OffSreenRenderTarget = _renderTexture; _postEffectStartDrawDone = true; } else if (index == _postEffectEndingDrawId && _postEffectStartDrawDone) { //We have finished to draw into the offline texture, link back the screen backbuffer _engine.SetRenderTargets(context); //Start the Post effect code here RenderStatesRepo.ApplyStates(context, DXStates.Rasters.Default, DXStates.Blenders.Disabled, DXStates.DepthStencils.DepthDisabled); _vBuffer.SetToDevice(context, 0); _iBuffer.SetToDevice(context, 0); _activatedEffect.Render(context); context.DrawIndexed(6, 0, 0); _postEffectStartDrawDone = false; } }
internal void Initialize(DeviceContext context = null) { MyRenderProxy.Assert(m_deviceContext == null, "Initialize is called to already initialized object. Whether initialization has been performed or not, check by the method 'IsInitialized()'"); if (context == null) { context = new DeviceContext(MyRender11.Device); m_isDeferred = true; } else { m_isDeferred = false; } m_deviceContext = context; m_vertexShaderStage.Init(m_deviceContext, m_deviceContext.VertexShader, m_statistics); m_geometryShaderStage.Init(m_deviceContext, m_deviceContext.GeometryShader, m_statistics); m_pixelShaderStage.Init(m_deviceContext, m_deviceContext.PixelShader, m_statistics); m_computeShaderStage.Init(m_deviceContext, m_deviceContext.ComputeShader, m_statistics); m_state.Init(m_deviceContext, m_statistics); if (m_annotations == null) { m_annotations = m_deviceContext.QueryInterface <SharpDX.Direct3D11.UserDefinedAnnotation>(); } m_statistics.Clear(); }
/// <summary> /// Applies the material to the given render state. /// </summary> /// <param name="renderState">Current render state</param> /// <param name="instancingMode">The instancing mode for which to apply the material.</param> /// <param name="previousMaterial">The previously applied material.</param> /// <exception cref="SeeingSharpGraphicsException">Effect + this.Effect + not supported!</exception> internal override void Apply(RenderState renderState, MaterialApplyInstancingMode instancingMode, MaterialResource previousMaterial) { D3D11.DeviceContext deviceContext = renderState.Device.DeviceImmediateContextD3D11; bool isResourceSameType = (previousMaterial != null) && (previousMaterial.ResourceType == base.ResourceType); if (!isResourceSameType) { deviceContext.PixelShader.SetSampler(0, m_defaultResources.GetSamplerState(TextureSamplerQualityLevel.Low)); } // Set texture resource (if set) if (m_textureResource != null) { deviceContext.PixelShader.SetShaderResource(0, m_textureResource.TextureView); } else { deviceContext.PixelShader.SetShaderResource(0, null); } // Set shader resources deviceContext.VertexShader.Set(m_vertexShader.VertexShader); deviceContext.PixelShader.Set(m_pixelShader.PixelShader); }
public InfoText(SharpDX.Direct3D11.Device device, int width, int height) { _immediateContext = device.ImmediateContext; _rect.Size = new Size2F(width, height); _bitmapSize = width * height * 4; IsEnabled = true; using (var factoryWic = new SharpDX.WIC.ImagingFactory()) { _wicBitmap = new SharpDX.WIC.Bitmap(factoryWic, width, height, _pixelFormat, SharpDX.WIC.BitmapCreateCacheOption.CacheOnLoad); } var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None, SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT); using (var factory2D = new SharpDX.Direct2D1.Factory()) { _wicRenderTarget = new WicRenderTarget(factory2D, _wicBitmap, renderTargetProperties); _wicRenderTarget.TextAntialiasMode = TextAntialiasMode.Default; } using (var factoryDWrite = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared)) { _textFormat = new TextFormat(factoryDWrite, "Tahoma", 20); } Color4 color = new Color4(1, 1, 1, 1); _sceneColorBrush = new SolidColorBrush(_wicRenderTarget, color); _clearColor = color; _clearColor.Alpha = 0; _renderTexture = new Texture2D(device, new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.Write, Format = Format.R8G8B8A8_UNorm, Height = height, Width = width, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Dynamic }); OverlayBufferRes = new ShaderResourceView(device, _renderTexture, new ShaderResourceViewDescription() { Format = _renderTexture.Description.Format, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0 } }); }
/// <summary> /// Applies all parameters. /// </summary> /// <param name="renderState">The render state on which to apply.</param> internal void Apply(RenderState renderState) { D3D11.DeviceContext deviceContext = renderState.Device.DeviceImmediateContextD3D11; // Apply constant buffer on shaders deviceContext.VertexShader.SetConstantBuffer(2, m_cbPerObject.ConstantBuffer); deviceContext.PixelShader.SetConstantBuffer(2, m_cbPerObject.ConstantBuffer); }
public Texture2DRenderTargetFactory() { //_syncRoot = new object(); _d3d11Device = new D3D11.Device(D3D.DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport | D3D11.DeviceCreationFlags.SingleThreaded #if DEBUG | D3D11.DeviceCreationFlags.Debug #endif ); _d3d11Context = _d3d11Device.ImmediateContext; }
public RenderContext(IDeviceManager deviceManager, Control control) { if (deviceManager == null) { throw new ArgumentNullException("deviceManager", "Device Manager cannot be null"); } if (control == null) { throw new ArgumentNullException("control", "Control cannot be null"); } this.deviceManager = deviceManager; this.deviceContext = deviceManager.DeviceContext; this.control = control; createSwapChain(); }
/// <summary> /// Initializes a new instance of the <see cref="GraphicsDevice" /> class using the default GraphicsAdapter /// and the Level10 <see cref="GraphicsProfile" />. /// </summary> /// <param name="device">The device.</param> private GraphicsDevice(GraphicsDevice device) { RootDevice = device; Adapter = device.Adapter; creationFlags = device.creationFlags; Features = device.Features; sharedDataPerDevice = device.sharedDataPerDevice; InputLayoutManager = device.InputLayoutManager; nativeDevice = device.NativeDevice; nativeDeviceContext = new SharpDX.Direct3D11.DeviceContext(NativeDevice).DisposeBy(this); nativeDeviceProfiler = SharpDX.ComObject.QueryInterfaceOrNull<UserDefinedAnnotation>(nativeDeviceContext.NativePointer); isDeferred = true; IsDebugMode = device.IsDebugMode; if (IsDebugMode) { GraphicsResourceBase.SetDebugName(device, nativeDeviceContext, "DeferredContext"); } NeedWorkAroundForUpdateSubResource = !Features.HasDriverCommandLists; primitiveQuad = new PrimitiveQuad(this).DisposeBy(this); InitializeStages(); }
/// <summary> /// Create resources that depend on the Direct3D device. /// </summary> /// <param name="deviceManager">The <see cref="DeviceManager"/> associated with this instance.</param> private void CreateDeviceResources(Tesseract gameEngine) { // Release any pre-existing resources RemoveAndDispose(ref PerFrameBuffer); RemoveAndDispose(ref PerMaterialBuffer); RemoveAndDispose(ref PerObjectBuffer); // Get & store references to the Direct3D device & device context Device3D = gameEngine.DeviceManager.Device3D; Context3D = gameEngine.DeviceManager.Context3D; // Release any pre-existing swap chain if (SwapChain != null) { RemoveAndDispose(ref SwapChain); } // Create constant buffers for shader resources CreateConstantBuffers(Device3D, Context3D); // Set depth-stencil & rasterizer states Context3D.OutputMerger.DepthStencilState = ToDispose(new DepthStencilState(Device3D, new DepthStencilStateDescription() { IsDepthEnabled = true, DepthComparison = Comparison.Less, DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.All, IsStencilEnabled = false, StencilReadMask = 0xff, StencilWriteMask = 0xff, FrontFace = new DepthStencilOperationDescription() { Comparison = Comparison.Always, PassOperation = StencilOperation.Keep, FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment }, BackFace = new DepthStencilOperationDescription() { Comparison = Comparison.Always, PassOperation = StencilOperation.Keep, FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement } })); Context3D.Rasterizer.State = ToDispose( new RasterizerState(Device3D, new RasterizerStateDescription() { FillMode = SettingsManager.ShowWireframe ? SharpDX.Direct3D11.FillMode.Wireframe : SharpDX.Direct3D11.FillMode.Solid, CullMode = CullMode.Back, IsFrontCounterClockwise = SettingsManager.VertexWindingCCW, })); }
// Initialize hardware-dependent resources. private void CreateDeviceResources() { // Unlike the original C++ sample, we don't have smart pointers so we need to // dispose Direct3D objects explicitly Utilities.Dispose(ref d3dDevice); Utilities.Dispose(ref vertexShader); Utilities.Dispose(ref inputLayout); Utilities.Dispose(ref pixelShader); Utilities.Dispose(ref constantBuffer); Utilities.Dispose(ref vertexBuffer); Utilities.Dispose(ref indexBuffer); // This flag adds support for surfaces with a different color channel ordering // than the API default. It is required for compatibility with Direct2D. var creationFlags = DeviceCreationFlags.BgraSupport; #if DEBUG // If the project is in a debug build, enable debugging via SDK Layers. creationFlags |= DeviceCreationFlags.Debug; #endif // This array defines the set of DirectX hardware feature levels this app will support. // Note the ordering should be preserved. // Don't forget to declare your application's minimum required feature level in its // description. All applications are assumed to support 9.1 unless otherwise stated. FeatureLevel[] featureLevels = { FeatureLevel.Level_11_1, FeatureLevel.Level_11_0, FeatureLevel.Level_10_1, FeatureLevel.Level_10_0, FeatureLevel.Level_9_3, FeatureLevel.Level_9_2, FeatureLevel.Level_9_1, }; // Create the Direct3D 11 API device object. d3dDevice = new Device(DriverType.Hardware, creationFlags, featureLevels); d3dContext = d3dDevice.ImmediateContext; // Get the Direct3D 11.1 API device. using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device>()) { // Query for ISurfaceImageSourceNative interface. using (var sisNative = ComObject.QueryInterface<ISurfaceImageSourceNative>(this)) { sisNative.Device = dxgiDevice; } } // Load the vertex shader. var vsBytecode = ReadData("Scenario2Component\\SimpleVertexShader.cso"); vertexShader = new VertexShader(d3dDevice, vsBytecode); // Create input layout for vertex shader. var vertexDesc = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, Format.R32G32B32_Float, 12, 0, InputClassification.PerVertexData, 0), }; inputLayout = new InputLayout(d3dDevice, vsBytecode, vertexDesc); // Load the pixel shader. var psBytecode = ReadData("Scenario2Component\\SimplePixelShader.cso"); pixelShader = new PixelShader(d3dDevice, psBytecode); // Create the constant buffer. var constantBufferDesc = new BufferDescription() { SizeInBytes = Utilities.SizeOf<ModelViewProjectionConstantBuffer>(), BindFlags = BindFlags.ConstantBuffer }; constantBuffer = new Buffer(d3dDevice, constantBufferDesc); // Describe the vertices of the cube. var cubeVertices = new[] { new VertexPositionColor(new Vector3(-0.5f, -0.5f, -0.5f), new Vector3(0.0f, 0.0f, 0.0f)), new VertexPositionColor(new Vector3(-0.5f, -0.5f, 0.5f), new Vector3(0.0f, 0.0f, 1.0f)), new VertexPositionColor(new Vector3(-0.5f, 0.5f, -0.5f), new Vector3(0.0f, 1.0f, 0.0f)), new VertexPositionColor(new Vector3(-0.5f, 0.5f, 0.5f), new Vector3(0.0f, 1.0f, 1.0f)), new VertexPositionColor(new Vector3(0.5f, -0.5f, -0.5f), new Vector3(1.0f, 0.0f, 0.0f)), new VertexPositionColor(new Vector3(0.5f, -0.5f, 0.5f), new Vector3(1.0f, 0.0f, 1.0f)), new VertexPositionColor(new Vector3(0.5f, 0.5f, -0.5f), new Vector3(1.0f, 1.0f, 0.0f)), new VertexPositionColor(new Vector3(0.5f, 0.5f, 0.5f), new Vector3(1.0f, 1.0f, 1.0f)), }; var vertexBufferDesc = new BufferDescription() { SizeInBytes = Utilities.SizeOf<VertexPositionColor>() * cubeVertices.Length, BindFlags = BindFlags.VertexBuffer }; vertexBuffer = Buffer.Create(d3dDevice, cubeVertices, vertexBufferDesc); // Describe the cube indices. var cubeIndices = new ushort[] { 0, 2, 1, // -x 1, 2, 3, 4, 5, 6, // +x 5, 7, 6, 0, 1, 5, // -y 0, 5, 4, 2, 6, 7, // +y 2, 7, 3, 0, 4, 6, // -z 0, 6, 2, 1, 3, 7, // +z 1, 7, 5, }; indexCount = cubeIndices.Length; // Create the index buffer. var indexBufferDesc = new BufferDescription() { SizeInBytes = sizeof(ushort) * cubeIndices.Length, BindFlags = BindFlags.IndexBuffer }; indexBuffer = Buffer.Create(d3dDevice, cubeIndices, indexBufferDesc); // Calculate the aspect ratio and field of view. float aspectRatio = (float)width / (float)height; float fovAngleY = 70.0f * MathUtil.Pi / 180.0f; if (aspectRatio < 1.0f) { fovAngleY /= aspectRatio; } // Set right-handed perspective projection based on aspect ratio and field of view. constantBufferData.projection = Matrix.Transpose( Matrix.PerspectiveFovRH( fovAngleY, aspectRatio, 0.01f, 100.0f ) ); // Start animating at frame 0. frameCount = 0; }
public DeviceManager(Device device) { d3dDevice = device; d3dContext = device.ImmediateContext; }
/// <summary> /// Initializes the specified device. /// </summary> /// <param name="graphicsProfiles">The graphics profiles.</param> /// <param name="deviceCreationFlags">The device creation flags.</param> /// <param name="windowHandle">The window handle.</param> private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle) { if (nativeDevice != null) { // Destroy previous device ReleaseDevice(); } // Profiling is supported through pix markers IsProfilingSupported = true; // Map GraphicsProfile to D3D11 FeatureLevel SharpDX.Direct3D.FeatureLevel[] levels = graphicsProfiles.ToFeatureLevel(); creationFlags = (SharpDX.Direct3D11.DeviceCreationFlags)deviceCreationFlags; // Create Device D3D11 with feature Level based on profile nativeDevice = new SharpDX.Direct3D11.Device(Adapter.NativeAdapter, creationFlags, levels); nativeDeviceContext = nativeDevice.ImmediateContext; if (IsDebugMode) { GraphicsResourceBase.SetDebugName(this, nativeDeviceContext, "ImmediateContext"); } InitializeStages(); // Create the input layout manager if (InputLayoutManager == null) InputLayoutManager = new InputLayoutManager(this).DisposeBy(this); }
unsafe void InitializeInner(AntiAliasingMode antiAliasingMode) { worldMatrix = Matrix.Identity; textMatrix = Matrix.Identity; device = new D3D11.Device(DriverType.Hardware, D3D11.DeviceCreationFlags.None, new[] { FeatureLevel.Level_11_1, FeatureLevel.Level_11_0, FeatureLevel.Level_10_1, FeatureLevel.Level_10_0 }); tkDevice = TK.GraphicsDevice.New(device); deviceContext = device.ImmediateContext; deviceContext.Rasterizer.State = device.CreateRasterizerState(); //TODO: replace with precompiled bytecode const string shaderFile = @"..\..\..\GameUtils\Graphics\shaders.fx"; ShaderBytecode vertexShaderBytecode = ShaderBytecode.CompileFromFile(shaderFile, "VS", "vs_4_0", ShaderFlags.Debug); ShaderBytecode pixelShaderBytecode = ShaderBytecode.CompileFromFile(shaderFile, "PS", "ps_4_0", ShaderFlags.Debug); InitializeShaders(vertexShaderBytecode, pixelShaderBytecode); indexBuffers = new D3D11.Buffer[BufferCount]; vertexBuffers = new D3D11.Buffer[BufferCount]; for (int i = 0, indexBufferSize = IndexBufferStartSize, vertexBufferSize = VertexBufferStartSize; i < BufferCount; i++, indexBufferSize <<= BufferSizeStep, vertexBufferSize <<= BufferSizeStep) { indexBuffers[i] = device.CreateDynamicBuffer(sizeof(int) * indexBufferSize, D3D11.BindFlags.IndexBuffer); vertexBuffers[i] = device.CreateDynamicBuffer(sizeof(Vertex) * vertexBufferSize, D3D11.BindFlags.VertexBuffer); } currentBufferIndex = 0; indexBuffer = indexBuffers[0]; vertexBuffer = vertexBuffers[0]; //indexBuffer = device.CreateDynamicBuffer(sizeof(int) * IndexBufferSize, D3D11.BindFlags.IndexBuffer); //vertexBuffer = device.CreateDynamicBuffer(sizeof(Vertex) * VertexBufferSize, D3D11.BindFlags.VertexBuffer); matrixBuffer = device.CreateConstantBuffer(sizeof(MatrixBuffer)); brushBuffer = device.CreateConstantBuffer(sizeof(Brush.BrushBuffer)); deviceContext.InputAssembler.SetIndexBuffer(indexBuffer, DXGI.Format.R32_UInt, 0); deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer, sizeof(Vertex), 0)); deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; blendState = device.CreateBlendState(); deviceContext.OutputMerger.SetBlendState(blendState); currentWrapMode = WrapMode.Clamp; currentInterpolationMode = InterpolationMode.Linear; samplerState = device.CreateSamplerState(WrapMode.Clamp, InterpolationMode.Linear); deviceContext.PixelShader.SetSampler(0, samplerState); sampleDescription = device.GetMultisamplingLevel(antiAliasingMode); defaultDepthStencilState = device.CreateDepthStencilState(D3D11.Comparison.Always, D3D11.StencilOperation.Keep, D3D11.StencilOperation.Keep); clipDepthStencilState = device.CreateDepthStencilState(D3D11.Comparison.Never, D3D11.StencilOperation.Replace, D3D11.StencilOperation.Keep); clippingDepthStencilState = device.CreateDepthStencilState(D3D11.Comparison.Equal, D3D11.StencilOperation.Keep, D3D11.StencilOperation.Keep); deviceContext.OutputMerger.SetDepthStencilState(defaultDepthStencilState); }