Example #1
0
        //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);
            }
        }
Example #2
0
        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);
            }
        }
        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;
        }
Example #4
0
        /// <summary>
        /// Find the display mode that most closely matches the requested display mode.
        /// </summary>
        /// <param name="targetProfiles">The target profile, as available formats are different depending on the feature level..</param>
        /// <param name="mode">The mode.</param>
        /// <returns>Returns the closes display mode.</returns>
        /// <unmanaged>HRESULT IDXGIOutput::FindClosestMatchingMode([In] const DXGI_MODE_DESC* pModeToMatch,[Out] DXGI_MODE_DESC* pClosestMatch,[In, Optional] IUnknown* pConcernedDevice)</unmanaged>
        /// <remarks>Direct3D devices require UNORM formats. This method finds the closest matching available display mode to the mode specified in pModeToMatch. Similarly ranked fields (i.e. all specified, or all unspecified, etc) are resolved in the following order.  ScanlineOrdering Scaling Format Resolution RefreshRate  When determining the closest value for a particular field, previously matched fields are used to filter the display mode list choices, and  other fields are ignored. For example, when matching Resolution, the display mode list will have already been filtered by a certain ScanlineOrdering,  Scaling, and Format, while RefreshRate is ignored. This ordering doesn't define the absolute ordering for every usage scenario of FindClosestMatchingMode, because  the application can choose some values initially, effectively changing the order that fields are chosen. Fields of the display mode are matched one at a time, generally in a specified order. If a field is unspecified, FindClosestMatchingMode gravitates toward the values for the desktop related to this output.  If this output is not part of the desktop, then the default desktop output is used to find values. If an application uses a fully unspecified  display mode, FindClosestMatchingMode will typically return a display mode that matches the desktop settings for this output.   Unspecified fields are lower priority than specified fields and will be resolved later than specified fields.</remarks>
        public DisplayMode FindClosestMatchingDisplayMode(FeatureLevel[] targetProfiles, DisplayMode mode)
        {
            ModeDescription closestDescription;

            SharpDX.Direct3D11.Device deviceTemp = null;
            try
            {
                deviceTemp = new SharpDX.Direct3D11.Device(adapter, DeviceCreationFlags.None, targetProfiles);
            }
            catch (Exception ex) {}

            var descriprtion = new ModeDescription()
            {
                Width            = mode.Width,
                Height           = mode.Height,
                RefreshRate      = mode.RefreshRate,
                Format           = mode.Format,
                Scaling          = DisplayModeScaling.Unspecified,
                ScanlineOrdering = DisplayModeScanlineOrder.Unspecified
            };

            using (var device = deviceTemp)
                output.GetClosestMatchingMode(device, descriprtion, out closestDescription);

            return(DisplayMode.FromDescription(closestDescription));
        }
Example #5
0
        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);
        }
Example #6
0
        private void CreateSwapChain(bool IsAlpha = false)
        {
            ModeDescription mode;

            if (IsAlpha)
            {
                mode = new ModeDescription(
                    _RenderForm.ClientSize.Width,
                    _RenderForm.ClientSize.Height,
                    new Rational(5, 1),
                    Format.A8_UNorm);
            }
            else
            {
                mode = new ModeDescription(
                    _RenderForm.ClientSize.Width,
                    _RenderForm.ClientSize.Height,
                    new Rational(5, 1),
                    Format.B8G8R8A8_UNorm);
            }

            _SwapDesc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = mode,
                IsWindowed        = true,
                OutputHandle      = _RenderForm.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };
        }
        public static ModeDescription GetAdapterDisplayMode(int adapterOrdinal, int outputOrdinal)
        {
            OutputInfo10 outputInfo = Enumeration10.GetOutputInfo(adapterOrdinal, outputOrdinal);

            ModeDescription mode = new ModeDescription();

            mode.RefreshRate      = new Rational(0, 0);
            mode.Format           = Format.R8G8B8A8_UNorm;
            mode.Scaling          = DisplayModeScaling.Unspecified;
            mode.ScanlineOrdering = DisplayModeScanlineOrdering.Unspecified;
            mode.Width            = 640;
            mode.Height           = 480;

            if (outputInfo != null)
            {
                Rectangle rectangle = outputInfo.OutputDescription.DesktopBounds;
                mode.Width  = rectangle.Width;
                mode.Height = rectangle.Height;
            }

            if (mode.Format == Format.B8G8R8A8_UNorm)
            {
                mode.Format = Format.R8G8B8A8_UNorm;
            }

            return(mode);
        }
Example #8
0
        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);
        }
Example #9
0
        internal Depth(Device Device, ModeDescription Resolution, SampleDescription AA)
        {
            this.Resolution = Resolution;

            DepthStencilTexture = new Texture2D(Device, new Texture2DDescription
            {
                Width             = Resolution.Width,
                Height            = Resolution.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.R32_Typeless,
                SampleDescription = AA,
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });

            DepthStencilView = new DepthStencilView(Device, DepthStencilTexture, new DepthStencilViewDescription
            {
                Format    = Format.D32_Float,
                Dimension = (AA.Count > 1 ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D),
                Texture2D = new DepthStencilViewDescription.Texture2DResource
                {
                    MipSlice = 0
                }
            });
        }
Example #10
0
        public void NativeLoad(IDXViewPipe videoPipe, VideoFormat videoFormat)
        {
            this.timer.Enabled = false;
            ModeDescription      backBufferDesc = new ModeDescription(videoFormat.width, videoFormat.height, new Rational(videoFormat.fps, 1), Format.R8G8B8A8_UNorm);
            SwapChainDescription swapChainDesc  = new SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = this.Handle,
                IsWindowed        = true
            };

            SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc,
                                                          out deviceDx11, out swapChain);
            deviceCtx        = deviceDx11.ImmediateContext;
            backBuffer       = swapChain.GetBackBuffer <Texture2D>(0);
            renderTargetView = new RenderTargetView(deviceDx11, backBuffer);
            deviceCtx.OutputMerger.SetRenderTargets(renderTargetView);
            viewPipe = videoPipe;
            SetBlendInput();
            this.timer.Interval = 1000 / videoFormat.fps;
            this.timer.Enabled  = true;
            //Action action = () => { RenderLoop.Run(this, Draw); };
            //this.BeginInvoke(action);
        }
Example #11
0
        private void CreateSwapChainForDesktop()
        {
            ModeDescription BackBufferDesc = new ModeDescription()
            {
                Width       = Description.BackBufferWidth,
                Height      = Description.BackBufferHeight,
                Format      = Format.R8G8B8A8_UNorm,
                RefreshRate = new Rational()
                {
                    Numerator   = 60,
                    Denominator = 1
                },
                ScanlineOrdering = ModeScanlineOrder.Unspecified,
                Scaling          = ModeScaling.Unspecified,
            };

            SampleDescription sampleDescription = new SampleDescription()
            {
                Count   = 1,
                Quality = 0
            };

            SwapChainFlags Flags = Description.Settings.Fullscreen ? SwapChainFlags.None : SwapChainFlags.AllowModeSwitch;



            SwapChainDescription swapChainDesc = new SwapChainDescription()      // Initialize the swap chain description.
            {
                BufferCount       = bufferCount,                                 // Set to a single back buffer.
                BufferDescription = BackBufferDesc,                              // Set the width and height of the back buffer.
                Usage             = Usage.Backbuffer | Usage.RenderTargetOutput, // Set the usage of the back buffer.
                OutputWindow      = Description.DeviceHandle,                    // Set the handle for the window to render to.
                SampleDescription = sampleDescription,                           // Turn multisampling off.
                IsWindowed        = true,                                        // Set to full screen or windowed mode.
                Flags             = Flags,                                       // Don't set the advanced flags.
                SwapEffect        = SwapEffect.FlipDiscard,                      // Discard the back buffer content after presenting.
            };



            IDXGIFactory4 Factory = GraphicsDevice.NativeAdapter.NativeFactory;

            IDXGISwapChain swapChain = Factory.CreateSwapChain(GraphicsDevice.NativeDirectCommandQueue.Queue, swapChainDesc);

            if (Description.Settings.Fullscreen)
            {
                // Before fullscreen switch
                swapChain.ResizeTarget(BackBufferDesc);

                // Switch to full screen
                swapChain.SetFullscreenState(true, default);

                // This is really important to call ResizeBuffers AFTER switching to IsFullScreen
                swapChain.ResizeBuffers(3, Description.BackBufferWidth, Description.BackBufferHeight, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch);
            }



            NativeSwapChain = swapChain.QueryInterface <IDXGISwapChain3>();
        }
        public SwapChainDescription CreateSwapChain(int PBufferCount, Usage PUsage, IntPtr PFormHandle, bool PIsWindowed, int PModeDescriptionWidth, int PModeDescriptionHeight, Rational PModeDescriptionRefreshRate, Format PModeDescriptionFormat, int PSampleDescriptionCount, int PSampleDescriptionQuality, SwapChainFlags PSwapChainFlags, SwapEffect PSwapEffect)
        {
            this._BufferCount                = PBufferCount;
            this._Usage                      = PUsage;
            this._FormHandle                 = PFormHandle;
            this._IsWindowed                 = PIsWindowed;
            this._ModeDescriptionWidth       = PModeDescriptionWidth;
            this._ModeDescriptionHeight      = PModeDescriptionHeight;
            this._ModeDescriptionRefreshRate = PModeDescriptionRefreshRate;
            this._ModeDescriptionFormat      = PModeDescriptionFormat;
            this._SampleDescriptionCount     = PSampleDescriptionCount;
            this._SampleDescriptionQuality   = PSampleDescriptionQuality;
            this._SwapChainFlags             = PSwapChainFlags;
            this._SwapEffect                 = PSwapEffect;
            _SampleDescription               = new SampleDescription(_SampleDescriptionCount, _SampleDescriptionQuality);
            _ModeDescription                 = new ModeDescription(_ModeDescriptionWidth, _ModeDescriptionHeight, _ModeDescriptionRefreshRate, _ModeDescriptionFormat);
            _SwapChainDesc                   = new SwapChainDescription()
            {
                BufferCount       = _BufferCount,
                Usage             = _Usage,
                OutputHandle      = _FormHandle,
                IsWindowed        = _IsWindowed,
                ModeDescription   = _ModeDescription,
                SampleDescription = _SampleDescription,
                Flags             = _SwapChainFlags,
                SwapEffect        = _SwapEffect
            };

            return(_SwapChainDesc);
        }
Example #13
0
        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);
            }
        }
Example #14
0
 internal EngineOutputModeInfo(EngineOutputInfo hostOutput, ModeDescription modeDescription)
 {
     this.HostOutput             = hostOutput;
     this.PixelWidth             = modeDescription.Width;
     this.PixelHeight            = modeDescription.Height;
     this.RefreshRateNumerator   = modeDescription.RefreshRate.Numerator;
     this.RefreshRateDenominator = modeDescription.RefreshRate.Denominator;
 }
Example #15
0
        internal Renderer(LoopWindow Window)
        {
            var Levels = new[]
            {
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_10_1,
                FeatureLevel.Level_10_0,
                FeatureLevel.Level_9_3,
                FeatureLevel.Level_9_2,
                FeatureLevel.Level_9_1,
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport | (Program.DebugMode ? DeviceCreationFlags.Debug : DeviceCreationFlags.None), Levels, new SwapChainDescription
            {
                BufferCount     = 1,
                Flags           = SwapChainFlags.AllowModeSwitch,
                IsWindowed      = true,
                ModeDescription = new ModeDescription
                {
                    Format = FormatRGB
                },
                OutputHandle      = Window.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            }, out Device, out SwapChain);


            var Bounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;

            using (var Factory = SwapChain.GetParent <Factory>())
            {
                foreach (var Output in Factory.Adapters.First().Outputs)
                {
                    foreach (var PossibleResolution in Output.GetDisplayModeList(FormatRGB, 0))
                    {
                        if (PossibleResolution.Width == Bounds.Width && PossibleResolution.Height == Bounds.Height)
                        {
                            Resolution = PossibleResolution;
                        }
                    }
                }
            }

            Window.Borderless(Resolution.Width, Resolution.Height);
            ResizeBuffers();

            Depth.InitStencilRasterState(Device);
            LoadWithAA(1);

            Device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            if (Program.DebugMode)
            {
                Debug = new DeviceDebug(Device);
            }
        }
Example #16
0
        /// <summary>
        ///     Hooked to allow resizing a texture/surface that is reused. Currently not in use as we create the texture for each
        ///     request
        ///     to support different sizes each time (as we use DirectX to copy only the region we are after rather than the entire
        ///     backbuffer)
        /// </summary>
        /// <param name="swapChainPtr"></param>
        /// <param name="newTargetParameters"></param>
        /// <returns></returns>
        private int ResizeTargetHook(IntPtr swapChainPtr, ref ModeDescription newTargetParameters)
        {
            var swapChain = (SwapChain)swapChainPtr;

            // This version creates a new texture for each request so there is nothing to resize.
            // IF the size of the texture is known each time, we could create it once, and then possibly need to resize it here

            swapChain.ResizeTarget(ref newTargetParameters);
            return(Result.Ok.Code);
        }
Example #17
0
 /// <summary>
 /// Function to convert a ModeDescription to a ModeDescription1.
 /// </summary>
 /// <param name="mode">ModeDescription to convert.</param>
 /// <returns>The new mode description.</returns>
 public static ModeDescription1 ToModeDesc1(this ModeDescription mode) => new ModeDescription1
 {
     Format           = mode.Format,
     Height           = mode.Height,
     Scaling          = mode.Scaling,
     Width            = mode.Width,
     ScanlineOrdering = mode.ScanlineOrdering,
     RefreshRate      = mode.RefreshRate,
     Stereo           = false
 };
Example #18
0
        /// <summary>
        /// Initializes the graphics.
        /// </summary>
        public void Initialize()
        {
            var descMode = new ModeDescription
            {
                Width       = _graphicsDevice.BackBuffer.Width,
                Height      = _graphicsDevice.BackBuffer.Height,
                Format      = Format.R8G8B8A8_UNorm,
                RefreshRate = new Rational(60, 1),
                Scaling     = DisplayModeScaling.Stretched
            };

            var descSwap = new SwapChainDescription
            {
                BufferCount       = 1,
                ModeDescription   = descMode,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = _graphicsDevice.RenderTarget.Handle,
                SampleDescription = new SampleDescription(1, 0),
                IsWindowed        = true,
                SwapEffect        = SwapEffect.Discard,
                Flags             = SwapChainFlags.None,
            };


            Result creationResult = Device1.CreateWithSwapChain(null, DriverType.Hardware,
                                                                DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0, descSwap,
                                                                out _direct3D10Device, out _swapChain);

            if (creationResult.IsFailure)
            {
                throw new GraphicsException("DirectX10 is not supported on the current platform.");
            }

            SlimDX.DXGI.Surface backBuffer = SlimDX.DXGI.Surface.FromSwapChain(_swapChain, 0);
            var d2DFactory = new SlimDX.Direct2D.Factory(SlimDX.Direct2D.FactoryType.Multithreaded);

            RenderTarget renderTarget = RenderTarget.FromDXGI(d2DFactory, backBuffer, new RenderTargetProperties
            {
                HorizontalDpi       = 96,
                VerticalDpi         = 96,
                MinimumFeatureLevel = SlimDX.Direct2D.FeatureLevel.Default,
                PixelFormat         = new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied),
                Type  = RenderTargetType.Hardware,
                Usage = RenderTargetUsage.None
            });

            renderTarget.AntialiasMode = SmoothingMode == SmoothingMode.AntiAlias
                ? AntialiasMode.Aliased
                : AntialiasMode.PerPrimitive;
            renderTarget.TextAntialiasMode = TextAntialiasMode.ClearType;

            _renderTarget = renderTarget;
            DirectXHelper.RenderTarget    = _renderTarget;
            DirectXHelper.Direct2DFactory = d2DFactory;
        }
Example #19
0
        /// <summary>
        /// Hooked to allow resizing a texture/surface that is reused. Currently not in use as we create the texture for each request
        /// to support different sizes each time (as we use DirectX to copy only the region we are after rather than the entire backbuffer)
        /// </summary>
        /// <param name="swapChainPtr"></param>
        /// <param name="newTargetParameters"></param>
        /// <returns></returns>
        int ResizeTargetHook(IntPtr swapChainPtr, ref ModeDescription newTargetParameters)
        {
            // Dispose of overlay engine (so it will be recreated with correct renderTarget view size)
            if (_overlayEngine != null)
            {
                _overlayEngine.Dispose();
                _overlayEngine = null;
            }

            return(DXGISwapChain_ResizeTargetHook.Original(swapChainPtr, ref newTargetParameters));
        }
        /// <summary>
        /// Hooked to allow resizing a texture/surface that is reused. Currently not in use as we create the texture for each request
        /// to support different sizes each time (as we use DirectX to copy only the region we are after rather than the entire backbuffer)
        /// </summary>
        /// <param name="swapChainPtr"></param>
        /// <param name="newTargetParameters"></param>
        /// <returns></returns>
        int ResizeTargetHook(IntPtr swapChainPtr, ref ModeDescription newTargetParameters)
        {
            SwapChain swapChain = (global::SharpDX.DXGI.SwapChain)swapChainPtr;
            //using (SharpDX.DXGI.SwapChain swapChain = SharpDX.DXGI.SwapChain.FromPointer(swapChainPtr))
            {
                // This version creates a new texture for each request so there is nothing to resize.
                // IF the size of the texture is known each time, we could create it once, and then possibly need to resize it here

                swapChain.ResizeTarget(ref newTargetParameters);
                return(global::SharpDX.Result.Ok.Code);
            }
        }
Example #21
0
        private ModeDescription DescribeBuffer(int width, int height)
        {
            ModeDescription desc = new ModeDescription()
            {
                Width       = width,
                Height      = height,
                RefreshRate = new Rational(Constants.RefreshRate, 1),
                Format      = Format.R8G8B8A8_UNorm
            };

            return(desc);
        }
Example #22
0
 /// <summary>
 /// Hooked to allow resizing a texture/surface that is reused. Currently not in use as we create the texture for each request
 /// to support different sizes each time (as we use DirectX to copy only the region we are after rather than the entire backbuffer)
 /// </summary>
 /// <param name="swapChainPtr"></param>
 /// <param name="newTargetParameters"></param>
 /// <returns></returns>
 int ResizeTargetHook(IntPtr swapChainPtr, ref ModeDescription newTargetParameters)
 {
     // Dispose of overlay engine (so it will be recreated with correct renderTarget view size)
     if (OverlayEngine != null)
     {
         DebugMessage("ResieTargetHook isn't null");
         OverlayEngine.Dispose();
         OverlayEngine = null;
     }
     DebugMessage("ResieTargetHook else");
     return(DXGISwapChain_ResizeTargetHook.Original(swapChainPtr, ref newTargetParameters));
 }
Example #23
0
        public static ModeDescription GetClosestDisplayMode(Output o, Device device, SlimDX.Rational rational)
        {
            var pt = new System.Drawing.Point(o.Description.DesktopBounds.Left + 1, o.Description.DesktopBounds.Top + 1);

            Screen scr = Screen.FromPoint(pt);

            ModeDescription md = new ModeDescription(scr.Bounds.Width, scr.Bounds.Height, rational, Format.R8G8B8A8_UNorm);
            ModeDescription closest;

            o.GetClosestMatchingMode(device, md, out closest);
            return(closest);
        }
Example #24
0
        public GraphicsDevice(IAppWindow window)
        {
            resourseHash = new ResourseRegistrHash();

            this.handle = window.Handle;

            Compilator = new D3DShaderCompilator();

            var width  = (int)window.Width;
            var height = (int)window.Height;

            var backBufferDesc = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm);

            // Descriptor for the swap chain
            var swapChainDesc = new SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 2,
                OutputHandle      = handle,
                IsWindowed        = true
            };

            var factory = new Factory1();
            var adapter = AdapterFactory.GetBestAdapter(factory);

            VideoCardDescription = adapter.Description.Description.Trim('\0');


            /*
             *
             *  DeviceCreationFlags.Debug - not supported by default, need to install the optional feature Graphics Tools
             *
             */

            // Create device and swap chain
            SharpDX.Direct3D11.Device.CreateWithSwapChain(adapter, DeviceCreationFlags.None, swapChainDesc, out var d3dDevice, out var sch);

            swapChain = sch.QueryInterface <SwapChain4>();
            D3DDevice = d3dDevice.QueryInterface <Device5>();

            ImmediateContext = d3dDevice.ImmediateContext;

            CreateBuffers(width, height);

            //TODO: Динамический оверлей. Direct3D 11.2 https://habr.com/company/microsoft/blog/199380/
            //swapChain.SetSourceSize
            //DContext = new DeviceContext(D3DDevice);

            TexturedLoader = new TextureLoader(D3DDevice);
        }
Example #25
0
        public void Initialise(RenderForm renderForm, bool windowed)
        {
            ModeDescription modeDescription = DescribeBuffer(renderForm.ClientSize.Width, renderForm.ClientSize.Height);

            swapChainDescription = DescribeSwapChain(modeDescription, renderForm, windowed);
            CreateDevice(swapChainDescription);
            // Ignore all windows events
            Factory factory = _swapChain.GetParent <Factory>();

            factory.MakeWindowAssociation(renderForm.Handle, WindowAssociationFlags.IgnoreAll);
            AssignDeviceContext();
            CreateRenderTargetView();
        }
Example #26
0
    public ModeDescription[] GetDisplayModeList(Format format, DisplayModeEnumerationFlags flags)
    {
        int count = 0;

        GetDisplayModeList(format, (int)flags, ref count, null);
        var result = new ModeDescription[count];

        if (count > 0)
        {
            GetDisplayModeList(format, (int)flags, ref count, result);
        }
        return(result);
    }
Example #27
0
        Result ResetDevice()
        {
            game.UnloadContent();


            DeviceSettings newSettings = CurrentSettings.Clone();

            if (IsWindowed && Direct3D10.SwapChain.Description.IsWindowed)
            {
                SwapChainDescription scd = newSettings.Direct3D10.SwapChainDescription;
                ModeDescription      md  = scd.ModeDescription;
                md.Width  = game.Window.ClientSize.Width;
                md.Height = game.Window.ClientSize.Height;
            }

            if (Direct3D10.SwapChain.Description.IsWindowed != newSettings.Direct3D10.SwapChainDescription.IsWindowed)
            {
                if (newSettings.Direct3D10.SwapChainDescription.IsWindowed)
                {
                    Direct3D10.SwapChain.SetFullScreenState(false, null);
                }
                else
                {
                    doNotStoreBufferSize = true;
                    Direct3D10.SwapChain.SetFullScreenState(true, null);
                    doNotStoreBufferSize = false;
                    Direct3D10.SwapChain.ResizeTarget(newSettings.Direct3D10.SwapChainDescription.ModeDescription);
                }
            }
            else
            {
                if (newSettings.Direct3D10.SwapChainDescription.ModeDescription.Width == Direct3D10.SwapChain.Description.ModeDescription.Width &&
                    newSettings.Direct3D10.SwapChainDescription.ModeDescription.Height == Direct3D10.SwapChain.Description.ModeDescription.Height &&
                    newSettings.Direct3D10.SwapChainDescription.ModeDescription.Format != Direct3D10.SwapChain.Description.ModeDescription.Format)
                {
                    ResizeDXGIBuffers(0, 0, !newSettings.Direct3D10.SwapChainDescription.IsWindowed);
                }
                else if (newSettings.Direct3D10.SwapChainDescription.ModeDescription.Width != Direct3D10.SwapChain.Description.ModeDescription.Width ||
                         newSettings.Direct3D10.SwapChainDescription.ModeDescription.Height != Direct3D10.SwapChain.Description.ModeDescription.Height)
                {
                    Direct3D10.SwapChain.ResizeTarget(newSettings.Direct3D10.SwapChainDescription.ModeDescription);
                }
            }


            PropogateSettings();
            UpdateDeviceStats();
            game.LoadContent();

            return(Result.Last);
        }
Example #28
0
        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;
        }
Example #29
0
        /// <summary>
        /// Hooked to allow resizing a texture/surface that is reused. Currently not in use as we create the texture for each request
        /// to support different sizes each time (as we use DirectX to copy only the region we are after rather than the entire backbuffer)
        /// </summary>
        /// <param name="swapChainPtr"></param>
        /// <param name="newTargetParameters"></param>
        /// <returns></returns>
        int ResizeTargetHook(IntPtr swapChainPtr, ref ModeDescription newTargetParameters)
        {
            if (swapChainPtr != _swapChainPointer)
            {
                _swapChain = SlimDX.DXGI.SwapChain.FromPointer(swapChainPtr);
            }
            SwapChain swapChain = _swapChain;
            {
                // This version creates a new texture for each request so there is nothing to resize.
                // IF the size of the texture is known each time, we could create it once, and then possibly need to resize it here

                return(swapChain.ResizeTarget(newTargetParameters).Code);
            }
        }
Example #30
0
        private SwapChainDescription CreateSwapChainDescription()
        {
            ModeDescription bufferDescription = CreateModeDescription();

            return(new SwapChainDescription()
            {
                ModeDescription = bufferDescription,
                SampleDescription = new SampleDescription(1, 0),
                Usage = Usage.RenderTargetOutput,
                BufferCount = 1,
                OutputHandle = Control.Handle,
                IsWindowed = true
            });
        }
Example #31
0
        private void InitializeForm()
        {
            ModeDescription modeDescription = new ModeDescription()
            {
                Width       = ClientSize.Width,
                Height      = ClientSize.Height,
                RefreshRate = new Rational(60, 1),
                Format      = Format.R8G8B8A8_UNorm
            };
            SwapChainDescription desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = modeDescription,
                IsWindowed        = true,
                OutputHandle      = Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            // Create Device and SwapChain
            SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport,
                                                          new[] { SharpDX.Direct3D.FeatureLevel.Level_11_1 }, desc, out SharpDX.Direct3D11.Device device, out SwapChain swapChain);

            SharpDX.Direct2D1.Factory d2dFactory = new SharpDX.Direct2D1.Factory();

            // Ignore all windows events
            SharpDX.DXGI.Factory factory = swapChain.GetParent <SharpDX.DXGI.Factory>();
            factory.MakeWindowAssociation(Handle, WindowAssociationFlags.IgnoreAll);

            Texture2D        backBuffer = SharpDX.Direct3D11.Resource.FromSwapChain <Texture2D>(swapChain, 0);
            RenderTargetView renderView = new RenderTargetView(device, backBuffer);

            Surface surface = backBuffer.QueryInterface <Surface>();

            RenderTarget d2dRenderTarget = new RenderTarget(d2dFactory, surface,
                                                            new RenderTargetProperties(new PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)));

            // Release all resources
            renderView.Dispose();
            backBuffer.Dispose();
            device.ImmediateContext.ClearState();
            device.ImmediateContext.Flush();
            device.Dispose();
            factory.Dispose();

            RulerRender thisForm = this;

            Manager = new Manager(ref thisForm, ref d2dRenderTarget, ref swapChain);
        }
Example #32
0
        /// <summary>
        /// Initialize everything D3D in here
        ///  Leave pretty empty for now.
        /// </summary>
        protected virtual void InitD3D()
        {
            // Set up rendering mode description (width, height, frame rate, color format)
            var modeDescription = new ModeDescription(0, 0, new SlimDX.Rational(60, 1), Format.R8G8B8A8_UNorm);

            // Set up swap chain description
            var swapChainDesc = new SwapChainDescription
            {
                BufferCount = 2,
                Usage = Usage.RenderTargetOutput,
                OutputHandle = Handle,
                IsWindowed = true,
                ModeDescription = modeDescription,
                SampleDescription = new SampleDescription(1, 0),
                Flags = SwapChainFlags.AllowModeSwitch,
                SwapEffect = SwapEffect.Discard
            };

            // Create our device and swap chain
            SlimDX.Direct3D11.Device.CreateWithSwapChain
            (
                DriverType.Hardware,
                DeviceCreationFlags.None,
                swapChainDesc,
                out Device,
                out SwapChain
            );

            // Obtain our device context (Immediate context)
            ImmediateContext = Device.ImmediateContext;

            // Prevent DXGI handling of alt+enter...
            using (var factory = SwapChain.GetParent<Factory>())
            {
                factory.SetWindowAssociation(Handle, WindowAssociationFlags.IgnoreAltEnter);
            }

            // Instead, handle the command ourselves
            KeyDown += (sender, e) =>
            {
                if (e.Alt && e.KeyCode == Keys.Enter)
                {
                    SwapChain.IsFullScreen = !SwapChain.IsFullScreen;
                }
            };

            // Add resize handling...
            UserResized += (sender, e) =>
            {
                OnResize(e);
            };

            // Set up viewport, render target (back buffer on swap chain), and render target view
            Viewport = new Viewport(0.0f, 0.0f, ClientSize.Width, ClientSize.Height, 0.0f, 1.0f);
            ImmediateContext.Rasterizer.SetViewports(Viewport);
            using (var resource = SlimDX.Direct3D11.Resource.FromSwapChain<Texture2D>(SwapChain, 0))
            {
                RenderTargetView = new RenderTargetView(Device, resource);
            }

            // Create the depth/stencil buffer and view
            // TODO KAM: On resize the window, do you need to resize the depth/stencil view?
            var depthBufferDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.D32_Float,
                Height = ClientSize.Height,
                Width = ClientSize.Width,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };

            DepthStencilBuffer = new Texture2D(Device, depthBufferDesc);

            var depthStencilViewDesc = new DepthStencilViewDescription
            {
                ArraySize = 0,
                Format = Format.D32_Float,
                Dimension = DepthStencilViewDimension.Texture2D,
                MipSlice = 0,
                Flags = 0,
                FirstArraySlice = 0
            };

            DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc);

            ImmediateContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);

            // Set up the depth/stencil state description
            var dsStateDesc = new DepthStencilStateDescription
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };

            DepthStencilState = DepthStencilState.FromDescription(Device, dsStateDesc);

            // Set depth/stencil state for the output merger
            ImmediateContext.OutputMerger.DepthStencilState = DepthStencilState;
        }
Example #33
0
        private static void Main()
        {
            // Device creation
            var form = new RenderForm("Stereo test")
                           {
                               ClientSize = size,
                               //FormBorderStyle = System.Windows.Forms.FormBorderStyle.None,
                               //WindowState = FormWindowState.Maximized
                           };

            form.KeyDown += new KeyEventHandler(form_KeyDown);
               // form.Resize += new EventHandler(form_Resize);

            ModeDescription mDesc = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height,
                                                        new Rational(120000, 1000), Format.R8G8B8A8_UNorm);
            mDesc.ScanlineOrdering = DisplayModeScanlineOrdering.Progressive;
            mDesc.Scaling = DisplayModeScaling.Unspecified;

            var desc = new SwapChainDescription()
                           {
                               BufferCount = 1,
                               ModeDescription = mDesc,
                                   Flags = SwapChainFlags.AllowModeSwitch,
                               IsWindowed = false,
                               OutputHandle = form.Handle,
                               SampleDescription = new SampleDescription(1, 0),
                               SwapEffect = SwapEffect.Discard,
                               Usage = Usage.RenderTargetOutput
                           };

            Device.CreateWithSwapChain(null, DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device,
                                       out swapChain);

            //Stops Alt+enter from causing fullscreen skrewiness.
            factory = swapChain.GetParent<Factory>();
            factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            backBuffer = Resource.FromSwapChain<Texture2D>(swapChain, 0);
            renderView = new RenderTargetView(device, backBuffer);

            ImageLoadInformation info = new ImageLoadInformation()
                                            {
                                                BindFlags = BindFlags.None,
                                                CpuAccessFlags = CpuAccessFlags.Read,
                                                FilterFlags = FilterFlags.None,
                                                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                                                MipFilterFlags = FilterFlags.None,
                                                OptionFlags = ResourceOptionFlags.None,
                                                Usage = ResourceUsage.Staging,
                                                MipLevels = 1
                                            };

            // Make texture 3D
            sourceTexture = Texture2D.FromFile(device, "medusa.jpg", info);
            ImageLoadInformation info2 = new ImageLoadInformation()
                                            {
                                                BindFlags = BindFlags.ShaderResource,
                                                CpuAccessFlags = CpuAccessFlags.None,
                                                FilterFlags = FilterFlags.None,
                                                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                                                MipFilterFlags = FilterFlags.None,
                                                OptionFlags = ResourceOptionFlags.None,
                                                Usage = ResourceUsage.Default,
                                                MipLevels = 1
                                            };
            Texture2D tShader = Texture2D.FromFile(device, "medusa.jpg", info2);
            srv = new ShaderResourceView(device, tShader);
            //ResizeDevice(new Size(1920, 1080), true);
            // Create a quad that fills the whole screen

            BuildQuad();
            // Create world view (ortho) projection matrices
            //QuaternionCam qCam = new QuaternionCam();

            // Load effect from file. It is a basic effect that renders a full screen quad through
            // an ortho projectio=n matrix
            effect = Effect.FromFile(device, "Texture.fx", "fx_4_0", ShaderFlags.Debug, EffectFlags.None);
            EffectTechnique technique = effect.GetTechniqueByIndex(0);
            EffectPass pass = technique.GetPassByIndex(0);
            InputLayout layout = new InputLayout(device, pass.Description.Signature, new[]
                                                                                         {
                                                                                             new InputElement(
                                                                                                 "POSITION", 0,
                                                                                                 Format.
                                                                                                     R32G32B32A32_Float,
                                                                                                 0, 0),
                                                                                             new InputElement(
                                                                                                 "TEXCOORD", 0,
                                                                                                 Format.
                                                                                                     R32G32_Float,
                                                                                                 16, 0)
                                                                                         });
            //effect.GetVariableByName("mWorld").AsMatrix().SetMatrix(
            //    Matrix.Translation(Layout.OrthographicTransform(Vector2.Zero, 99, size)));
            //effect.GetVariableByName("mView").AsMatrix().SetMatrix(qCam.View);
            //effect.GetVariableByName("mProjection").AsMatrix().SetMatrix(qCam.OrthoProjection);
            //effect.GetVariableByName("tDiffuse").AsResource().SetResource(srv);

            // Set RT and Viewports
            device.OutputMerger.SetTargets(renderView);
            device.Rasterizer.SetViewports(new Viewport(0, 0, size.Width, size.Height, 0.0f, 1.0f));

            // Create solid rasterizer state
            RasterizerStateDescription rDesc = new RasterizerStateDescription()
                                                   {
                                                       CullMode = CullMode.None,
                                                       IsDepthClipEnabled = true,
                                                       FillMode = FillMode.Solid,
                                                       IsAntialiasedLineEnabled = false,
                                                       IsFrontCounterclockwise = true,
                                                       //IsMultisampleEnabled = true,
                                                   };
            RasterizerState rState = RasterizerState.FromDescription(device, rDesc);
            device.Rasterizer.State = rState;

            Texture2DDescription rtDesc = new Texture2DDescription
                                              {
                                                  ArraySize = 1,
                                                  Width = size.Width,
                                                  Height = size.Height,
                                                  BindFlags = BindFlags.RenderTarget,
                                                  CpuAccessFlags = CpuAccessFlags.None,
                                                  Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                                                  OptionFlags = ResourceOptionFlags.None,
                                                  Usage = ResourceUsage.Default,
                                                  MipLevels = 1,
                                                  SampleDescription = new SampleDescription(1, 0)
                                              };
            rtTex = new Texture2D(device, rtDesc);

            rv = new RenderTargetView(device, rtTex);

            stereoizedTexture = Make3D(sourceTexture);
            //ResizeDevice(new Size(1920, 1080), true);
            Console.WriteLine(form.ClientSize);
            // Main Loop
            MessagePump.Run(form, () =>
            {
            device.ClearRenderTargetView(renderView, Color.Cyan);

            //device.InputAssembler.SetInputLayout(layout);
            //device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList);
            //device.OutputMerger.SetTargets(rv);
            //device.InputAssembler.SetVertexBuffers(0,
            //                                new VertexBufferBinding(vertices, 24, 0));
            //device.InputAssembler.SetIndexBuffer(indices, Format.R16_UInt, 0);
            //for (int i = 0; i < technique.Description.PassCount; ++i)
            //{
            //    // Render the full screen quad
            //    pass.Apply();
            //    device.DrawIndexed(6, 0, 0);
            //}
            ResourceRegion stereoSrcBox = new ResourceRegion { Front = 0, Back = 1, Top = 0, Bottom = size.Height, Left = 0, Right = size.Width };
            device.CopySubresourceRegion(stereoizedTexture, 0, stereoSrcBox, backBuffer, 0, 0, 0, 0);
            //device.CopyResource(rv.Resource, backBuffer);

            swapChain.Present(0, PresentFlags.None);
            });

            // Dispose resources
            vertices.Dispose();
            layout.Dispose();
            effect.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();

            rState.Dispose();
            stereoizedTexture.Dispose();
            sourceTexture.Dispose();
            indices.Dispose();
            srv.Dispose();
        }
Example #34
0
        private SwapChain CreateSwapChain(Factory factory)
        {
            var modeDescription = new ModeDescription(mWidth, mHeight, new Rational(60, 1), Format.R8G8B8A8_UNorm);
            var swapChainDescription = new SwapChainDescription
            {
                BufferCount = 2,
                IsWindowed = true,
                Flags = SwapChainFlags.None,
                ModeDescription = modeDescription,
                OutputHandle = mForm.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

            return new SwapChain(factory, Device, swapChainDescription);
        }
Example #35
0
        /// <summary>
        /// Hooked to allow resizing a texture/surface that is reused. Currently not in use as we create the texture for each request
        /// to support different sizes each time (as we use DirectX to copy only the region we are after rather than the entire backbuffer)
        /// </summary>
        /// <param name="swapChainPtr"></param>
        /// <param name="newTargetParameters"></param>
        /// <returns></returns>
        int ResizeTargetHook(IntPtr swapChainPtr, ref ModeDescription newTargetParameters)
        {
            if (swapChainPtr != _swapChainPointer)
            {
                _swapChain = SlimDX.DXGI.SwapChain.FromPointer(swapChainPtr);
            }
            SwapChain swapChain = _swapChain;
            {
                // This version creates a new texture for each request so there is nothing to resize.
                // IF the size of the texture is known each time, we could create it once, and then possibly need to resize it here

                return swapChain.ResizeTarget(newTargetParameters).Code;
            }
        }
Example #36
0
        /// <summary>
        /// Initializes the graphics.
        /// </summary>
        public void Initialize()
        {
            var descMode = new ModeDescription
            {
                Width = _graphicsDevice.BackBuffer.Width,
                Height = _graphicsDevice.BackBuffer.Height,
                Format = Format.R8G8B8A8_UNorm,
                RefreshRate = new Rational(60, 1),
                Scaling = DisplayModeScaling.Stretched
            };

            var descSwap = new SwapChainDescription
            {
                BufferCount = 1,
                ModeDescription = descMode,
                Usage = Usage.RenderTargetOutput,
                OutputHandle = _graphicsDevice.RenderTarget.Handle,
                SampleDescription = new SampleDescription(1, 0),
                IsWindowed = true,
                SwapEffect = SwapEffect.Discard,
                Flags = SwapChainFlags.None,
            };

            Result creationResult = Device1.CreateWithSwapChain(null, DriverType.Hardware,
                DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0, descSwap,
                out _direct3D10Device, out _swapChain);

            if (creationResult.IsFailure)
            {
                throw new GraphicsException("DirectX10 is not supported on the current platform.");
            }

            SlimDX.DXGI.Surface backBuffer = SlimDX.DXGI.Surface.FromSwapChain(_swapChain, 0);
            var d2DFactory = new SlimDX.Direct2D.Factory(SlimDX.Direct2D.FactoryType.Multithreaded);

            RenderTarget renderTarget = RenderTarget.FromDXGI(d2DFactory, backBuffer, new RenderTargetProperties
            {
                HorizontalDpi = 96,
                VerticalDpi = 96,
                MinimumFeatureLevel = SlimDX.Direct2D.FeatureLevel.Default,
                PixelFormat = new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied),
                Type = RenderTargetType.Hardware,
                Usage = RenderTargetUsage.None
            });
            renderTarget.AntialiasMode = SmoothingMode == SmoothingMode.AntiAlias
                ? AntialiasMode.Aliased
                : AntialiasMode.PerPrimitive;
            renderTarget.TextAntialiasMode = TextAntialiasMode.ClearType;

            _renderTarget = renderTarget;
            DirectXHelper.RenderTarget = _renderTarget;
            DirectXHelper.Direct2DFactory = d2DFactory;
        }
Example #37
0
        public void ChangeMode(bool setFullscreen, ModeDescription mode)
        {
            AssertUndisposed();

            Output output;
            _swapChain.GetFullScreenState(out _isFullscreen, out output);

            if (setFullscreen && !_isFullscreen)
            {
                _swapChain.ResizeTarget(mode);
                _swapChain.SetFullScreenState(true, null);
            }
            else if (!setFullscreen && _isFullscreen)
            {
                _swapChain.SetFullScreenState(false, null);
                _swapChain.ResizeTarget(mode);
            }
            else
            {
                _swapChain.ResizeTarget(mode);
            }

            _swapChain.GetFullScreenState(out _isFullscreen, out output);
        }
Example #38
0
        public TeapotScene(TeapotRenderer teapotRenderer)
        {
            // Create a description of the display mode
            ModeDescription modeDescription = new ModeDescription()
            {
                Format = Format.R8G8B8A8_UNorm,
                RefreshRate = new Rational(60, 1),
                
                Width = 512,
                Height = 512
            };

            // Create a description of the multisampler
            SampleDescription sampleDescription = new SampleDescription()
            {
                Count = 1,
                Quality = 0
            };

            // Create a description of the swap chain
            SwapChainDescription swapChainDescription = new SwapChainDescription()
            {
                ModeDescription = modeDescription,
                SampleDescription = sampleDescription,

                BufferCount = 1,
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput,

                IsWindowed = false
            };

            // Create a hardware accelarated rendering device
            renderingDevice = new Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

            // Create the shared texture
            Texture2DDescription colordesc = new Texture2DDescription();
            colordesc.BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource;
            colordesc.Format = Format.B8G8R8A8_UNorm;
            colordesc.Width = 512;
            colordesc.Height = 512;
            colordesc.MipLevels = 1;
            colordesc.SampleDescription = new SampleDescription(1, 0);
            colordesc.Usage = ResourceUsage.Default;
            colordesc.OptionFlags = ResourceOptionFlags.Shared;
            colordesc.CpuAccessFlags = CpuAccessFlags.None;
            colordesc.ArraySize = 1;

            SharedTexture = new Texture2D(renderingDevice, colordesc);

            // Create the render target view
            renderTargetView = new RenderTargetView(renderingDevice, SharedTexture);

            // Creat the depth/stencil buffer
            DepthStencilStateDescription depthStencilStateDescription = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,
            };

            depthStencilState = DepthStencilState.FromDescription(renderingDevice, depthStencilStateDescription);

            Texture2DDescription depthStencilTextureDescription = new Texture2DDescription()
            {
                Width = 512,
                Height = 512,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D32_Float,
                SampleDescription = sampleDescription,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };

            DepthStencilViewDescription depthStencilViewDescription = new DepthStencilViewDescription()
            {
                Format = depthStencilTextureDescription.Format,
                Dimension = depthStencilTextureDescription.SampleDescription.Count > 1 ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D,
                MipSlice = 0
            };

            using (Texture2D depthStencilTexture = new Texture2D(renderingDevice, depthStencilTextureDescription))
            {
                depthStencilView = new DepthStencilView(renderingDevice, depthStencilTexture, depthStencilViewDescription);
            }

            // Setup the default output targets
            renderingDevice.ImmediateContext.OutputMerger.SetTargets(depthStencilView, renderTargetView);

            // Setup the viewport
            Viewport viewPort = new Viewport()
            {
                X = 0,
                Y = 0,
                Width = 512,
                Height = 512,
                MinZ = 0,
                MaxZ = 1
            };

            renderingDevice.ImmediateContext.Rasterizer.SetViewports(viewPort);

            // Create the teappot
            teapotObject = new TeapotObject(teapotRenderer, renderingDevice);

            // Create the camera
            camera = new ThirdPersonCamera(teapotObject);
            
        }