public RenderContainer(SwapChainDescription swapChainDescription, RenderControl control) { try { _swapChainDescription = swapChainDescription; using (Factory1 factory = new Factory1()) using (Adapter adapter = factory.GetAdapter(0)) { Device11 = new Dx11ChainedDevice(adapter, _swapChainDescription); Device10 = new Dx10Device(adapter); } GraphicsDevice = new GenericGraphicsDevice(Device11.Device); SpriteBatch = new SpriteBatch(GraphicsDevice); Reset(control.Width, control.Height); control.Resize += OnRenderControlResize; } catch { Dispose(); throw; } }
protected override void Initialize(DemoConfiguration demoConfiguration) { // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(demoConfiguration.Width, demoConfiguration.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = DisplayHandle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new [] { FeatureLevel.Level_10_0 }, desc, out _device, out _swapChain); // Ignore all windows events Factory factory = _swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(DisplayHandle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer _backBuffer = Texture2D.FromSwapChain<Texture2D>(_swapChain, 0); _backBufferView = new RenderTargetView(_device, _backBuffer); }
public override void Initialize() { Device tmpDevice; SwapChain sc; using (var rf = new RenderForm()) { var desc = new SwapChainDescription { BufferCount = 1, Flags = SwapChainFlags.None, IsWindowed = true, ModeDescription = new ModeDescription(100, 100, new Rational(60, 1), SlimDX.DXGI.Format.R8G8B8A8_UNorm), OutputHandle = rf.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; var res = Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out tmpDevice, out sc); if (res.IsSuccess) { using (tmpDevice) { using (sc) { PresentPointer = Pulse.Magic.GetObjectVtableFunction(sc.ComPointer, VMT_PRESENT); ResetTargetPointer = Pulse.Magic.GetObjectVtableFunction(sc.ComPointer, VMT_RESIZETARGET); } } } } _presentDelegate = Pulse.Magic.RegisterDelegate<Direct3D11Present>(PresentPointer); _presentHook = Pulse.Magic.Detours.CreateAndApply(_presentDelegate, new Direct3D11Present(Callback), "D11Present"); }
public D3DManager(Form renderForm) { if (renderForm == null) throw new ArgumentNullException("renderForm"); var swapChainDescription = new SwapChainDescription { BufferCount = 1, IsWindowed = true, ModeDescription = new ModeDescription(renderForm.ClientSize.Width, renderForm.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), OutputHandle = renderForm.Handle, SampleDescription = new SampleDescription(4, 4), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDescription, out Device, out SwapChain); SwapChain.GetParent<Factory>().SetWindowAssociation(renderForm.Handle, WindowAssociationFlags.IgnoreAll); CreateRenderTargets(renderForm.ClientSize.Width, renderForm.ClientSize.Height); Device.ImmediateContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView); Device.ImmediateContext.Rasterizer.State = RasterizerState.FromDescription(Device, new RasterizerStateDescription { CullMode = CullMode.Back, FillMode = FillMode.Solid, IsMultisampleEnabled = true }); }
public D3D11RenderingPane( Factory dxgiFactory, SlimDX.Direct3D11.Device d3D11Device, DeviceContext d3D11DeviceContext, D3D11HwndDescription d3D11HwndDescription ) { mDxgiFactory = dxgiFactory; mD3D11Device = d3D11Device; mD3D11DeviceContext = d3D11DeviceContext; var swapChainDescription = new SwapChainDescription { BufferCount = 1, ModeDescription = new ModeDescription( d3D11HwndDescription.Width, d3D11HwndDescription.Height, new Rational( 60, 1 ), Format.R8G8B8A8_UNorm ), IsWindowed = true, OutputHandle = d3D11HwndDescription.Handle, SampleDescription = new SampleDescription( 1, 0 ), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; mSwapChain = new SwapChain( mDxgiFactory, mD3D11Device, swapChainDescription ); mDxgiFactory.SetWindowAssociation( d3D11HwndDescription.Handle, WindowAssociationFlags.IgnoreAll ); CreateD3D11Resources( d3D11HwndDescription.Width, d3D11HwndDescription.Height ); PauseRendering = false; }
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); }
protected override void CreateImpl() { var swapChainDesc = new SwapChainDescription() { BufferCount = (int)Desc.BufferCount, ModeDescription = new ModeDescription((int) Desc.Width, (int)Desc.Height, new Rational(0,0), Memory.Enums.ToDXGIFormat[(int)Desc.Format]), Usage = Usage.RenderTargetOutput, SwapEffect = SwapEffect.FlipDiscard, OutputHandle = Desc.WindowHandle, SampleDescription = new SampleDescription { Count = (int) Desc.SampleCount, Quality = (int) Desc.SampleQuality }, IsWindowed = !Desc.Fullscreen }; using (var factory = new Factory4()) { var tempSwapChain = new SharpDX.DXGI.SwapChain(factory, ((CommandQueue)Desc.AssociatedGraphicsQueue).CommandQueueD3D12, swapChainDesc); SwapChainDXGI = tempSwapChain.QueryInterface<SwapChain3>(); tempSwapChain.Dispose(); CurrentBackBufferIndex = (uint)SwapChainDXGI.CurrentBackBufferIndex; } SwapChainDXGI.DebugName = Label; Log.Info("Created SwapChain"); }
public DX11SwapChain(DX11RenderContext context, IntPtr handle, Format format, SampleDescription sampledesc) { this.context = context; this.handle = handle; SwapChainDescription sd = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), format), IsWindowed = true, OutputHandle = handle, SampleDescription = sampledesc, SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput | Usage.ShaderInput, Flags = SwapChainFlags.None }; if (sd.SampleDescription.Count == 1 && context.IsFeatureLevel11) { sd.Usage |= Usage.UnorderedAccess; this.allowuav = true; } this.swapchain = new SwapChain(context.Device.Factory, context.Device, sd); this.Resource = Texture2D.FromSwapChain<Texture2D>(this.swapchain, 0); this.context.Factory.SetWindowAssociation(handle, WindowAssociationFlags.IgnoreAltEnter); this.RTV = new RenderTargetView(context.Device, this.Resource); this.SRV = new ShaderResourceView(context.Device, this.Resource); if (this.allowuav) { this.UAV = new UnorderedAccessView(context.Device, this.Resource); } this.desc = this.Resource.Description; }
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); } }
public Renderer(int Width, int Height, IntPtr? OutputHandle) { if (Width < 1) Width = 1; if (Height < 1) Height = 1; bufferWidth = Width; bufferHeight = Height; deviceUsers++; if (device == null) device = new Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport, FeatureLevel.Level_11_0); if (OutputHandle.HasValue) { SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(BufferWidth, BufferHeight, new Rational(120, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = OutputHandle.Value, SampleDescription = BufferSampleDescription, SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, Flags = SwapChainFlags.AllowModeSwitch, }; swapChain = new SwapChain(device.Factory, Device, swapChainDesc); using (var factory = swapChain.GetParent<Factory>()) factory.SetWindowAssociation(OutputHandle.Value, WindowAssociationFlags.IgnoreAltEnter); } LightingSystem = new ForwardLighting(this); SetupRenderTargets(); LightingSystem.Initialize(); }
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); }
public override void Initialize() { using (var fac = new Factory()) { using (var tmpDevice = new Device(fac.GetAdapter(0), DriverType.Hardware, DeviceCreationFlags.None)) { using (var rf = new RenderForm()) { var desc = new SwapChainDescription { BufferCount = 1, Flags = SwapChainFlags.None, IsWindowed = true, ModeDescription = new ModeDescription(100, 100, new Rational(60, 1), Format.R8G8B8A8_UNorm), OutputHandle = rf.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; using (var sc = new SwapChain(fac, tmpDevice, desc)) { PresentPointer = Pulse.Magic.GetObjectVtableFunction(sc.ComPointer, VMT_PRESENT); ResetTargetPointer = Pulse.Magic.GetObjectVtableFunction(sc.ComPointer, VMT_RESIZETARGET); } } } } _presentDelegate = Pulse.Magic.RegisterDelegate<Direct3D10Present>(PresentPointer); _presentHook = Pulse.Magic.Detours.CreateAndApply(_presentDelegate, new Direct3D10Present(Callback), "D10Present"); }
private void LoadPipeline(IntPtr handleToWindow) { // create swap chain descriptor var swapChainDescription = new SwapChainDescription() { BufferCount = SwapBufferCount, ModeDescription = new ModeDescription(Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, OutputHandle = handleToWindow, SwapEffect = SwapEffect.FlipDiscard, SampleDescription = new SampleDescription(1, 0), IsWindowed = true }; // create the device try { device = CreateDeviceWithSwapChain(DriverType.Hardware, FeatureLevel.Level_11_0, swapChainDescription, out swapChain, out commandQueue); } catch (SharpDXException) { device = CreateDeviceWithSwapChain(DriverType.Warp, FeatureLevel.Level_11_0, swapChainDescription, out swapChain, out commandQueue); } // create command queue and allocator objects commandListAllocator = device.CreateCommandAllocator(CommandListType.Direct); }
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); }
/// <summary> /// Initializes a new instance of the <see cref="RenderControl" /> class. /// </summary> public RenderControl() { SwapChainDescription swapCHainDesc = new SwapChainDescription { BufferCount = 2, Usage = Usage.RenderTargetOutput, OutputHandle = Handle, IsWindowed = true, ModeDescription = new ModeDescription( Width, Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(1, 0), Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard }; Device.CreateWithSwapChain( DriverType.Hardware, DeviceCreationFlags.BgraSupport, swapCHainDesc, out _device, out _swapChain); Debug.Assert(_swapChain != null, "_swapChain != null"); // ReSharper disable once AssignNullToNotNullAttribute _backBuffer = Surface.FromSwapChain(_swapChain, 0); Debug.Assert(_backBuffer != null, "_backBuffer != null"); Size2F dpi = DirectXResourceManager.FactoryD2D.DesktopDpi; RenderTarget renderTarget = new RenderTarget( DirectXResourceManager.FactoryD2D, _backBuffer, new RenderTargetProperties { DpiX = dpi.Width, DpiY = dpi.Height, MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT, PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Ignore), Type = RenderTargetType.Default, Usage = RenderTargetUsage.None }); _renderTargetContainer = RenderTargetContainer.CreateContainer(renderTarget, out _renderTargetRef); using (FactoryDXGI factory = _swapChain.GetParent<FactoryDXGI>()) { Debug.Assert(factory != null, "factory != null"); factory.MakeWindowAssociation(Handle, WindowAssociationFlags.IgnoreAltEnter); } _renderThread = new Thread(RenderLoop) { Name = "Render Thread", IsBackground = true }; }
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); }
public DX11GraphicsDevice(Form form) { this.Form = form; var scDesc = new SwapChainDescription { BufferCount = 2, Flags = SwapChainFlags.AllowModeSwitch, IsWindowed = true, ModeDescription = new ModeDescription( form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), format), OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Sequential, Usage = Usage.RenderTargetOutput }; var levels = new[] { FeatureLevel.Level_9_2, FeatureLevel.Level_9_1 }; Device.CreateWithSwapChain( DriverType.Hardware, DeviceCreationFlags.None, levels, scDesc, out device, out swapChain); ResetDevice(); form.ResizeEnd += ResizeEnd; }
public DX11Renderer(IntPtr windowHandle, Size2 size, Device dev = null) { RenderSize = size; _windowHandle = windowHandle; if(dev != null) { _dxDevice = dev; } else { var swapchainDesc = new SwapChainDescription() { BufferCount = 2, ModeDescription = new ModeDescription(size.Width, size.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = windowHandle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapchainDesc, out _dxDevice, out _swapChain); // Ignore all windows events // var factory = _swapChain.GetParent<Factory>(); // factory.MakeWindowAssociation(windowHandle, WindowAssociationFlags.None); Reset(size.Width, size.Height); } }
public Direct3D11Base(Form form, SwapChainDescription swapDesc, Adapter adapter = null, DriverType type = DriverType.Hardware, DeviceCreationFlags flags = DeviceCreationFlags.None, FeatureLevel[] levels = null) { IsDisposed = false; try { _isInitializing = true; _form = form; _isComposited = DwmApi.IsCompositionEnabled; if (_isComposited) { DwmApi.EnableMMCSS(true); DwmPresentParameters present = new DwmPresentParameters() { IsQueued = true, BufferCount = 2, RefreshesPerFrame = 1, }; DwmApi.SetPresentParameters(form.Handle, ref present); } if (swapDesc.OutputHandle != IntPtr.Zero) { throw new ArgumentException("Output handle must not be set."); } if (swapDesc.Usage != Usage.RenderTargetOutput) { throw new ArgumentException("Usage must be RenderTargetOutput."); } swapDesc.OutputHandle = _form.Handle; bool setFullscreen = !swapDesc.IsWindowed; swapDesc.IsWindowed = true; Device.CreateWithSwapChain(adapter, type, DeviceCreationFlags.None, levels, swapDesc, out _device, out _swapChain); _swapChain.ResizeTarget(swapDesc.ModeDescription); _factory = _swapChain.GetParent<Factory>(); _factory.SetWindowAssociation(_form.Handle, WindowAssociationFlags.IgnoreAll); _form.SizeChanged += SizeChanged_Handler; _form.ResizeBegin += ResizeBegin_Handler; _form.Resize += Resize_Handler; _form.ResizeEnd += ResizeEnd_Handler; _form.KeyDown += KeyDown_Handler; if (setFullscreen) { ChangeMode(true); } _isInitializing = false; } catch { Dispose(); throw; } }
/// <summary> /// /// </summary> /// <param name="parameters"></param> public GenericDisplay( Game game, GraphicsDevice device, GraphicsParameters parameters ) : base( game, device, parameters ) { try { window = CreateTouchForm(parameters, null); } catch (System.EntryPointNotFoundException e) { Log.Warning("Looks like your system does't support touch gestures. You need Windows 8.1 or newer for this."); window = CreateForm(parameters, null); } try { NvApi.Initialize(); NvApi.Stereo_Disable(); } catch (NVException nvex) { Log.Debug(nvex.Message); } var deviceFlags = DeviceCreationFlags.BgraSupport; //deviceFlags |= DeviceCreationFlags.SingleThreaded; deviceFlags |= parameters.UseDebugDevice ? DeviceCreationFlags.Debug : DeviceCreationFlags.None; var driverType = DriverType.Hardware; var featureLevel = HardwareProfileChecker.GetFeatureLevel( parameters.GraphicsProfile ); swapChainDesc = new SwapChainDescription () { BufferCount = 1, // UE4 use this. ModeDescription = new ModeDescription( parameters.Width, parameters.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm ), IsWindowed = true, OutputHandle = window.Handle, SampleDescription = new SampleDescription(parameters.MsaaLevel, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, Flags = SwapChainFlags.None, }; D3D.Device.CreateWithSwapChain( driverType, deviceFlags, new[]{ featureLevel }, swapChainDesc, out d3dDevice, out swapChain ); //Log.Message(" compute shaders : {0}", d3dDevice.CheckFeatureSupport(Feature.ComputeShaders) ); //Log.Message(" shader doubles : {0}", d3dDevice.CheckFeatureSupport(Feature.ShaderDoubles) ); //Log.Message(" threading : {0}", d3dDevice.CheckFeatureSupport(Feature.Threading) ); bool driverConcurrentCreates; bool driverCommandLists; d3dDevice.CheckThreadingSupport( out driverConcurrentCreates, out driverCommandLists ); //d3dDevice.GetCounterCapabilities(); Log.Message(" Concurrent Creates : {0}", driverConcurrentCreates ); Log.Message(" Command Lists : {0}", driverCommandLists ); var factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation( window.Handle, WindowAssociationFlags.IgnoreAll ); clientWidth = window.ClientSize.Width; clientHeight = window.ClientSize.Height; }
static void Main() { var form = new RenderForm("KinectLight"); form.Size = new System.Drawing.Size(1920,1200); 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 }; SharpDX.Direct3D10.Device1 device; SwapChain swapChain; SharpDX.Direct3D10.Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, SharpDX.Direct3D10.FeatureLevel.Level_10_1, out device, out swapChain); var d2dFactory = new SharpDX.Direct2D1.Factory(); var surface = Surface.FromSwapChain(swapChain, 0); RenderTarget dc = new RenderTarget(d2dFactory, surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied))); MainGame.Instance.Height = form.ClientSize.Height; MainGame.Instance.Width = form.ClientSize.Width; GameTime gameTime = new GameTime(); var config = new HttpSelfHostConfiguration("http://localhost:8080"); config.Routes.MapHttpRoute( "API Default", "api/{controller}/{action}/{name}", new { id = RouteParameter.Optional }); HttpSelfHostServer server = new HttpSelfHostServer(config); server.OpenAsync().Wait(); RenderLoop.Run(form, () => { gameTime.StartFrame(); MainGame.Instance.Update(gameTime); dc.BeginDraw(); dc.Clear(Colors.White); MainGame.Instance.Render(dc); var res = dc.EndDraw(); swapChain.Present(1, PresentFlags.None); //Thread.Sleep(1); }); server.Dispose(); MainGame.Instance.Dispose(); dc.Dispose(); surface.Dispose(); d2dFactory.Dispose(); device.Dispose(); swapChain.Dispose(); }
public void Create3dObjects() { //Create RenderWindow RenderWindowInstance = new ModelRenderWindow(); FormInstance = RenderWindowInstance.CreateWindow(1080,1240,FormStartPosition.CenterScreen); //Create SwapChain SwapChainCreator = new ModelSwapChainDesc(); SwapChainD = SwapChainCreator.CreateSwapChain(2, Usage.RenderTargetOutput, FormInstance.Handle, true, 0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm, 1,0,SwapChainFlags.AllowModeSwitch, SwapEffect.Discard); //Create Device Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, SwapChainD, out GraphicsDevice, out NewSwapChain); //Create Back buffer BackBuffer = Surface.FromSwapChain(NewSwapChain, 0); //Create Factory FactoryD2D FactoryInstance = new FactoryD2D(); //Create RenderTarget RenderTargetInstance = new ModelRenderTarget(); RenderTarget = RenderTargetInstance.CreateRenderTarget(SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT, new PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Ignore), RenderTargetType.Default, RenderTargetUsage.None, BackBuffer, FactoryInstance); RenderLoop.Run(FormInstance, () => { RenderTarget.BeginDraw(); RenderTarget.Transform = Matrix3x2.Identity; RenderTarget.Clear(Color.White); using (var brush = new SolidColorBrush(RenderTarget, Color.Red)) { //for (int x = 0; x < RenderTarget.Size.Width; x += 10) // RenderTarget.DrawLine(new Vector2(x, 0), new Vector2(x, RenderTarget.Size.Height), brush, 0.5f); //for (int y = 0; y < RenderTarget.Size.Height; y += 10) // RenderTarget.DrawLine(new Vector2(0, y), new Vector2(RenderTarget.Size.Width, y), brush, 0.5f); RenderTarget.DrawLine(new Vector2(300, 10), new Vector2(300, 300), brush,1.5f); // RenderTarget.FillRectangle(new RectangleF(RenderTarget.Size.Width / 2 - 50, RenderTarget.Size.Height / 2 - 50, 100, 100), brush); } // RenderTarget.DrawRectangle( // new RectangleF(RenderTarget.Size.Width / 2 - 100, RenderTarget.Size.Height / 2 - 100, 200, 200), // new SolidColorBrush(RenderTarget, Color.CornflowerBlue)); RenderTarget.EndDraw(); NewSwapChain.Present(0, PresentFlags.None); }); RenderTarget.Dispose(); NewSwapChain.Dispose(); GraphicsDevice.Dispose(); }
protected override void InitializeInternal() { var clientSize = D3DApp11.I.ControlWindow.ClientSize; _swapChainDescription = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(clientSize.Width, clientSize.Height, new Rational(60, 1), Format.B8G8R8A8_UNorm), IsWindowed = true, OutputHandle = D3DApp11.I.ControlWindow.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; }
static void Main() { RenderForm window = new RenderForm("Some title"); SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(window.ClientSize.Width, window.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = window.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; //debug Configuration.EnableObjectTracking = true; D3D11Device device; SwapChain swapChain; D3D11Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); DeviceContext context = device.ImmediateContext; Factory factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(window.Handle, WindowAssociationFlags.IgnoreAll); Stopwatch clock = new Stopwatch(); clock.Start(); bool resized = true; window.UserResized += (sender, args) => resized = true; window.KeyUp += (sender, args) => { if (args.KeyCode == Keys.F5) swapChain.SetFullscreenState(true, null); else if (args.KeyCode == Keys.F4) swapChain.SetFullscreenState(false, null); else if (args.KeyCode == Keys.Enter) window.Close(); }; RenderLoop.Run(window, () => { swapChain.Present(0, PresentFlags.None); }); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); factory.Dispose(); }
public void InitContext() { var modeDesc = new ModeDescription { Format = Format.R8G8B8A8_UNorm, Height = mWindow.ClientSize.Height, Width = mWindow.ClientSize.Width, RefreshRate = new Rational(60, 1), Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrder.Unspecified }; mSwapChainDesc = new SwapChainDescription() { BufferCount = 1, Flags = SwapChainFlags.None, IsWindowed = true, OutputHandle = mWindow.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; mOutput.GetClosestMatchingMode(null, modeDesc, out modeDesc); modeDesc.Width = mWindow.ClientSize.Width; modeDesc.Height = mWindow.ClientSize.Height; mSwapChainDesc.ModeDescription = modeDesc; #if DEBUG Device = new Device(Adapter, DeviceCreationFlags.Debug); #else Device = new Device(Adapter); #endif BuildMultisample(); mSwapChain = new SwapChain(mFactory, Device, mSwapChainDesc); Context = Device.ImmediateContext; InitRenderTarget(); InitDepthBuffer(); Context.OutputMerger.SetRenderTargets(mDepthBuffer, mRenderTarget); Context.Rasterizer.SetViewport(new Viewport(0, 0, mWindow.ClientSize.Width, mWindow.ClientSize.Height)); Texture.InitDefaultTexture(this); mWindow.Resize += OnResize; }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (DesignMode) return; // create swap chain, rendertarget var swapChainDesc = new SwapChainDescription() { BufferCount = 1, Usage = Usage.RenderTargetOutput, OutputHandle = videoPanel1.Handle, IsWindowed = true, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard, SampleDescription = new SampleDescription(1, 0), }; swapChain = new SwapChain(factory, device, swapChainDesc); // render target renderTarget = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); renderTargetView = new RenderTargetView(device, renderTarget); // depth buffer var depthBufferDesc = new Texture2DDescription() { Width = videoPanel1.Width, Height = videoPanel1.Height, MipLevels = 1, ArraySize = 1, Format = Format.D32_Float, // necessary? SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None }; depthStencil = new Texture2D(device, depthBufferDesc); depthStencilView = new DepthStencilView(device, depthStencil); // viewport viewport = new Viewport(0, 0, videoPanel1.Width, videoPanel1.Height, 0f, 1f); }
public DeviceContext11(IntPtr handle, DeviceSettings settings) { Contract.Requires(handle != IntPtr.Zero); Contract.Requires(settings != null); Settings = settings; LogEvent.Engine.Log(settings.ToString()); eventHandlerList = new EventHandlerList(); SwapChainDescription swapChainDesc = new SwapChainDescription { BufferCount = 1, IsWindowed = Settings.IsWindowed, ModeDescription = new ModeDescription{ Width = Settings.ScreenWidth, Height = Settings.ScreenHeight, RefreshRate= new Rational(0, 1), Format = Settings.Format, Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrdering.Unspecified, }, //new Rational(120, 1), Settings.Format), OutputHandle = handle, SampleDescription = Settings.SampleDescription, Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, }; FeatureLevel[] featureLevels = new FeatureLevel[] { FeatureLevel.Level_11_0, FeatureLevel.Level_10_1, FeatureLevel.Level_10_0 }; LogEvent.Engine.Log(Resources.INFO_OE_DeviceCreating); Device.CreateWithSwapChain(DriverType.Hardware, Settings.CreationFlags, featureLevels, swapChainDesc, out device, out swapChain); factory = swapChain.GetParent<Factory>(); factory.SetWindowAssociation(handle, WindowAssociationFlags.IgnoreAltEnter | WindowAssociationFlags.IgnoreAll); immediate = device.ImmediateContext; CreateTargets(); LogEvent.Engine.Log(Resources.INFO_OE_DeviceCreated); }
/// <summary> /// /// </summary> /// <param name="parameters"></param> public StereoInterlacedDisplay( Game game, GraphicsDevice device, GraphicsParameters parameters ) : base( game, device, parameters ) { try { NvApi.Initialize(); NvApi.Stereo_Disable(); } catch (NVException nvex) { Log.Debug(nvex.Message); } window = CreateForm( parameters, null ); var deviceFlags = DeviceCreationFlags.None; deviceFlags |= parameters.UseDebugDevice ? DeviceCreationFlags.Debug : DeviceCreationFlags.None; var driverType = DriverType.Hardware; var featureLevel = HardwareProfileChecker.GetFeatureLevel( parameters.GraphicsProfile ); swapChainDesc = new SwapChainDescription () { BufferCount = 1, ModeDescription = new ModeDescription( parameters.Width, parameters.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm ), IsWindowed = true, OutputHandle = window.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, Flags = SwapChainFlags.None, }; D3D.Device.CreateWithSwapChain( driverType, deviceFlags, new[]{ featureLevel }, swapChainDesc, out d3dDevice, out swapChain ); var factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation( window.Handle, WindowAssociationFlags.IgnoreAll ); clientWidth = window.ClientSize.Width; clientHeight = window.ClientSize.Height; }
public static SwapChain3 CreateSwapchain(RenderForm form, CommandQueue queue,Config config) { using (var Factory = new Factory4()) { var swapChainDesc = new SwapChainDescription() { BufferCount = config.FrameCount, ModeDescription = new ModeDescription(config.Width, config.Height, new Rational(config.RefreshRate, 1), config.Format), Usage = Usage.RenderTargetOutput, SwapEffect = SwapEffect.FlipDiscard, OutputHandle = form.Handle, SampleDescription = new SampleDescription(config.SampleCount, config.SampleQuality), IsWindowed = true }; var tempSwapChain = new SwapChain(Factory, queue, swapChainDesc); var SwapChain = tempSwapChain.QueryInterface<SwapChain3>(); tempSwapChain.Dispose(); return SwapChain; } }
public static SwapChainDescription ConvertToSwapChainDescription(Graphics3DConfiguration configuration) { SwapChainDescription description = new SwapChainDescription(); description.BufferCount = 1; //TODO description.IsWindowed = !configuration.ScreenConfiguration.FullScreen; description.OutputHandle = configuration.Target; description.SwapEffect = SlimDX.DXGI.SwapEffect.Discard; description.Usage = SlimDX.DXGI.Usage.RenderTargetOutput; description.ModeDescription = new ModeDescription( configuration.ScreenConfiguration.Width, configuration.ScreenConfiguration.Height, new Rational(60, 1), //TODO Hz ConvertToFormat(configuration.ScreenConfiguration.ColorMode)); description.SampleDescription = new SampleDescription( 1, //TODO 0); description.Flags = SwapChainFlags.AllowModeSwitch; return description; }
private static void Main() { var form = new RenderForm("SharpDX - MiniTri Direct3D 11 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); var context = device.ImmediateContext; // Ignore all windows events var factory = swapChain.GetParent <Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer var backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None); var pixelShader = new PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout( device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }); // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0)); context.VertexShader.Set(vertexShader); context.Rasterizer.SetViewport(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.PixelShader.Set(pixelShader); context.OutputMerger.SetTargets(renderView); // Main loop RenderLoop.Run(form, () => { context.ClearRenderTargetView(renderView, Color.Black); context.Draw(3, 0); swapChain.Present(0, PresentFlags.None); }); // Release all resources vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vertices.Dispose(); layout.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); factory.Dispose(); }
public bool Initialize(SystemConfiguration configuration, IntPtr windowHandle) { try { // Store the vsync setting. VerticalSyncEnabled = SystemConfiguration.VerticalSyncEnabled; // Create a DirectX graphics interface factory. var factory = new Factory(); // Use the factory to create an adapter for the primary graphics interface (video card). var adapter = factory.GetAdapter(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; // Release the adapter output. monitor.Dispose(); // Release the adapter. adapter.Dispose(); // Release the factory. factory.Dispose(); // 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 = !SystemConfiguration.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. Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; // 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); // Initialize and set up the description of the stencil state. var depthStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, // Stencil operation if pixel front-facing. FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, // Stencil operation if pixel is back-facing. BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; // Create the depth stencil state. DepthStencilState = new DepthStencilState(Device, depthStencilDesc); // Set the depth stencil state. DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1); // 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); // 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); // 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); // Setup and create the projection matrix. ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), (float)(configuration.Width / configuration.Height), SystemConfiguration.ScreenNear, SystemConfiguration.ScreenDepth); // Initialize the world matrix to the identity matrix. WorldMatrix = Matrix.Identity; // Create an orthographic projection matrix for 2D rendering. OrthoMatrix = Matrix.OrthoLH(configuration.Width, configuration.Height, SystemConfiguration.ScreenNear, SystemConfiguration.ScreenDepth); return(true); } catch (Exception) { return(false); } }
private static void InitialDirectX() { rand = new Random(); player = new Player(20, 20, 25, 0); items = new List <Item>(); // for(int i = 0; i< rand.Next(2,4); i++) int k = rand.Next(1, 2); int j = rand.Next(0, 1); for (int i = 0; i < 5; i++) { Item item = new Item(RandomGenerate.GetCoord((k * i + j) % 9).X, RandomGenerate.GetCoord((k * i + j) % 9).Y); items.Add(item); } exit = new Exit(RandomGenerate.GetCoord(rand.Next(9, 12)).X, RandomGenerate.GetCoord(rand.Next(9, 12)).Y); polygons = new List <Polygon>(); uniqueAngles = new List <float>(); uniqueAnglesNotOnFOV = new List <float>(); intersects = new List <ParamPoint>(); backViewSide = new List <PointF>(); mouseRay = new Ray { Begin = new PointF(player.X, player.Y), Mouse = new PointF(Cursor.Position.X, Cursor.Position.Y) }; raysFOG = new List <Ray>(); raysBACK = new List <Ray>(); // creat form; renderForm = new RenderForm(title); // set windows size renderForm.Size = new System.Drawing.Size(892, 498); renderForm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; // creat swapchain var swapChainDesc = new SwapChainDescription() { BufferCount = 4, Flags = SwapChainFlags.AllowModeSwitch, IsWindowed = true, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), OutputHandle = renderForm.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; D3D.FeatureLevel[] featureLevel = { D3D.FeatureLevel.Level_9_3, D3D.FeatureLevel.Level_10_1, D3D.FeatureLevel.Level_11_1 }; Device.CreateWithSwapChain(D3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport, featureLevel, swapChainDesc, out device, out swapChain); Surface backbuffer = Surface.FromSwapChain(swapChain, 0); factory2d = new Factory2D(FactoryType.MultiThreaded); var dpi = factory2d.DesktopDpi; renderTarget = new RenderTarget(factory2d, backbuffer, new RenderTargetProperties() { DpiX = dpi.Width, DpiY = dpi.Height, MinLevel = FeatureLevel.Level_9, PixelFormat = new PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore), Type = RenderTargetType.Default, Usage = RenderTargetUsage.None }); // auto resize windows system renderForm.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; renderTarget.AntialiasMode = AntialiasMode.Aliased; renderTarget.TextAntialiasMode = TextAntialiasMode.Aliased; using (SharpDX.DirectWrite.Factory textFactory = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared)) { textFormat = new Text( textFactory, "MS Sans Serif", SharpDX.DirectWrite.FontWeight.SemiBold, SharpDX.DirectWrite.FontStyle.Normal, SharpDX.DirectWrite.FontStretch.Medium, 16.0f); } renderForm.Click += RenderForm_Click; renderForm.KeyUp += RenderForm_KeyUp; renderForm.KeyDown += RenderForm_KeyDown; renderForm.Load += RenderForm_Load; renderForm.MouseMove += RenderForm_MouseMove; }
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); }
public void InitializeD3D11(IntPtr wndHandle, int width, int height) { CloseD3D11(); _dxgiFactory = new Factory1(); _dxiAdapter = _dxgiFactory.Adapters[0]; _d3d11Device = new Device(_dxiAdapter, DeviceCreationFlags.BgraSupport, FeatureLevel.Level_11_0); _dxgiDevice = _d3d11Device.QueryInterface <DXGIDevice>(); _dxgiDevice.MaximumFrameLatency = 1; // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("VSShader.fx", "main", "vs_4_0", ShaderFlags.None, EffectFlags.None); _vertexShader = new VertexShader(_d3d11Device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("PSShader.fx", "main", "ps_4_0", ShaderFlags.None, EffectFlags.None); _pixelShader = new PixelShader(_d3d11Device, pixelShaderByteCode); InputElement[] inputElements = new InputElement[3]; inputElements[0] = new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0); inputElements[1] = new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0); inputElements[2] = new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 20, 0, InputClassification.PerVertexData, 0); _inputLayout = new InputLayout(_d3d11Device, vertexShaderByteCode, inputElements); BufferDescription vertexShaderDesc = new BufferDescription(Matrix.SizeInBytes * 2, BindFlags.ConstantBuffer, ResourceUsage.Default); _vertexShaderConstans = new Buffer(_d3d11Device, vertexShaderDesc); SamplerStateDescription samplerStateDescription = new SamplerStateDescription(); samplerStateDescription.Filter = Filter.MinMagMipLinear; samplerStateDescription.AddressU = TextureAddressMode.Clamp; samplerStateDescription.AddressV = TextureAddressMode.Clamp; samplerStateDescription.AddressW = TextureAddressMode.Clamp; samplerStateDescription.MipLodBias = 0.0f; samplerStateDescription.MaximumAnisotropy = 1; samplerStateDescription.ComparisonFunction = Comparison.Always; samplerStateDescription.MinimumLod = 0.0f; samplerStateDescription.MaximumLod = float.MaxValue; _samplerState = new SamplerState(_d3d11Device, samplerStateDescription); RasterizerStateDescription rasterizerStateDescription = new RasterizerStateDescription(); rasterizerStateDescription.IsAntialiasedLineEnabled = false; rasterizerStateDescription.CullMode = CullMode.None; rasterizerStateDescription.DepthBias = 0; rasterizerStateDescription.DepthBiasClamp = 0.0f; rasterizerStateDescription.IsDepthClipEnabled = true; rasterizerStateDescription.FillMode = FillMode.Solid; rasterizerStateDescription.IsFrontCounterClockwise = false; rasterizerStateDescription.IsMultisampleEnabled = false; rasterizerStateDescription.IsScissorEnabled = false; rasterizerStateDescription.SlopeScaledDepthBias = 0.0f; _rasterizerState = new RasterizerState(_d3d11Device, rasterizerStateDescription); _d3d11Device.ImmediateContext.InputAssembler.InputLayout = _inputLayout; _d3d11Device.ImmediateContext.VertexShader.SetShader(_vertexShader, null, 0); _d3d11Device.ImmediateContext.VertexShader.SetConstantBuffers(0, 1, _vertexShaderConstans); SwapChainDescription swapChainDescription = new SwapChainDescription(); swapChainDescription.ModeDescription.Width = width; swapChainDescription.ModeDescription.Height = height; swapChainDescription.ModeDescription.Format = Format.B8G8R8A8_UNorm; swapChainDescription.ModeDescription.RefreshRate.Numerator = 1; //pretty ugly //its better to autodetect screen refresh rate swapChainDescription.ModeDescription.RefreshRate.Denominator = 60; swapChainDescription.SampleDescription.Count = 1; swapChainDescription.SampleDescription.Quality = 0; swapChainDescription.Usage = Usage.RenderTargetOutput; swapChainDescription.BufferCount = 2; swapChainDescription.ModeDescription.Scaling = DisplayModeScaling.Unspecified; swapChainDescription.SwapEffect = SwapEffect.FlipSequential; swapChainDescription.Flags = 0; swapChainDescription.IsWindowed = true; swapChainDescription.OutputHandle = wndHandle; _swapChain = new SwapChain(_dxgiFactory, _d3d11Device, swapChainDescription); _dxgiFactory.MakeWindowAssociation(wndHandle, WindowAssociationFlags.IgnoreAll); Texture2D backBuffer = _swapChain.GetBackBuffer <Texture2D>(0); _mainRenderTargerView = new RenderTargetView(_d3d11Device, backBuffer); backBuffer.Dispose(); backBuffer = null; Matrix projection = Matrix.Identity; Matrix view = new Matrix(); /* Update the view matrix */ view[0, 0] = 2.0f / (float)width; view[0, 1] = 0.0f; view[0, 2] = 0.0f; view[0, 3] = 0.0f; view[1, 0] = 0.0f; view[1, 1] = -2.0f / (float)height; view[1, 2] = 0.0f; view[1, 3] = 0.0f; view[2, 0] = 0.0f; view[2, 1] = 0.0f; view[2, 2] = 1.0f; view[2, 3] = 0.0f; view[3, 0] = -1.0f; view[3, 1] = 1.0f; view[3, 2] = 0.0f; view[3, 3] = 1.0f; VertexShaderConstants vertexShaderConstansData = new VertexShaderConstants(); vertexShaderConstansData.projectionAndView = Matrix.Multiply(view, projection); vertexShaderConstansData.model = Matrix.Identity; _vertexShaderConstansData = Marshal.AllocHGlobal(Marshal.SizeOf(vertexShaderConstansData)); Marshal.StructureToPtr(vertexShaderConstansData, _vertexShaderConstansData, false); _d3d11Device.ImmediateContext.UpdateSubresource(ref vertexShaderConstansData, _vertexShaderConstans); ViewPort viewPort = new ViewPort(); viewPort.X = 0; viewPort.Y = 0; viewPort.Width = width; viewPort.Height = height; viewPort.MinDepth = 0.0f; viewPort.MaxDepth = 1.0f; _d3d11Device.ImmediateContext.Rasterizer.SetViewport(viewPort); float minu, maxu, minv, maxv; minu = 0.0f; maxu = 1.0f; minv = 0.0f; maxv = 1.0f; // Instantiate Vertex buiffer from vertex data var vertices = Buffer.Create(_d3d11Device, BindFlags.VertexBuffer, new[] { //ul 0.0f, 0.0f, 0.0f, minu, minv, 1.0f, 1.0f, 1.0f, 1.0f, //dl 0.0f, (float)height, 0.0f, minu, maxv, 1.0f, 1.0f, 1.0f, 1.0f, //ur (float)width, 0.0f, 0.0f, maxu, minv, 1.0f, 1.0f, 1.0f, 1.0f, //dr (float)width, (float)height, 0.0f, maxu, maxv, 1.0f, 1.0f, 1.0f, 1.0f }); _d3d11Device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 36, 0)); _d3d11Device.ImmediateContext.Rasterizer.State = _rasterizerState; _d3d11Device.ImmediateContext.PixelShader.SetShader(_pixelShader, null, 0); _d3d11Device.ImmediateContext.PixelShader.SetSamplers(0, 1, _samplerState); _d3d11Device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip; }