Example #1
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 #2
0
        /// <summary>
        /// Initialization
        /// </summary>
        public virtual void Setup()
        {
            form = new RenderForm(Window.Title);
            form.SetBounds(Window.Left, Window.Top, Window.Width, Window.Height);
            sw = new Stopwatch();

            timing = new GameTime();

            SwapChainDescription desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(Window.Width, Window.Height, new Rational(FrameRate, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };


            Device1.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, out device, out swapChain);

            D2DFactory = new SharpDX.Direct2D1.Factory();

            factory = swapChain.GetParent <SharpDX.DXGI.Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

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

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

            D2DRenderTarget = new RenderTarget(D2DFactory, surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
        }
Example #3
0
        protected virtual void Initialize(Configuration config)
        {
            var desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(config.Width, config.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = DisplayHandle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

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

            SharpDX.DXGI.Factory factory = swapChain.GetParent <SharpDX.DXGI.Factory>();
            factory.MakeWindowAssociation(DisplayHandle, WindowAssociationFlags.IgnoreAll);

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



            Factory2D = new SharpDX.Direct2D1.Factory();
            using (var surface = BackBuffer.QueryInterface <Surface>()) {
                RenderTarget2D = new RenderTarget(Factory2D, surface,
                                                  new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
            }
            RenderTarget2D.AntialiasMode = AntialiasMode.PerPrimitive;

            FactoryDWrite   = new SharpDX.DirectWrite.Factory();
            SceneColorBrush = new SolidColorBrush(RenderTarget2D, SharpDX.Color.White);
        }
Example #4
0
        /// <summary>
        ///
        /// </summary>
        protected void InitializeD3D10(int pWidth, int pHeight)
        {
            // SwapChain description
            var desc = new DXGI.SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new DXGI.ModeDescription(pWidth, pHeight, new DXGI.Rational(60, 1), DXGI.Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = DisplayHandle,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                SwapEffect        = DXGI.SwapEffect.Discard,
                Usage             = DXGI.Usage.RenderTargetOutput
            };

            // Create Device and SwapChain
            SharpDX.Direct3D10.Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, SharpDX.Direct3D10.FeatureLevel.Level_10_0, out mDevice, out mSwapChain);

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

            // New RenderTargetView from the backbuffer
            mBackBuffer     = Texture2D.FromSwapChain <Texture2D>(mSwapChain, 0);
            mBackBufferView = new RenderTargetView(mDevice, mBackBuffer);
        }
Example #5
0
        public void InitRendering()
        {
            try
            {
                lock (_drawLock)
                {
                    m_Ready      = false;
                    ResizeRedraw = true;
                    var desc = new SwapChainDescription
                    {
                        BufferCount     = 2,
                        ModeDescription = new ModeDescription(ClientSize.Width, ClientSize.Height, new Rational(60, 1),
                                                              Format.R8G8B8A8_UNorm),
                        IsWindowed        = true,
                        OutputHandle      = Handle,
                        SampleDescription = new SampleDescription(1, 0),
                        SwapEffect        = SwapEffect.Discard,
                        Usage             = Usage.RenderTargetOutput | Usage.Shared
                    };

                    Device.CreateWithSwapChain(DriverType.Hardware,
                                               DeviceCreationFlags.BgraSupport,
                                               new[] { SharpDX.Direct3D.FeatureLevel.Level_9_3 },
                                               desc,
                                               out device,
                                               out swapChain);

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

                    Factory factory = swapChain.GetParent <Factory>();
                    factory.MakeWindowAssociation(Handle, WindowAssociationFlags.IgnoreAll);

                    Texture2D backBuffer = Resource.FromSwapChain <Texture2D>(swapChain, 0);

                    surface = backBuffer.QueryInterface <Surface>();

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


                    var bitmapProperties = new BitmapProperties(new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Ignore));

                    clientArea = new RawRectangleF
                    {
                        Left   = 0,
                        Top    = 0,
                        Bottom = ClientSize.Height,
                        Right  = ClientSize.Width
                    };

                    factory.Dispose();
                    backBuffer.Dispose();
                    m_Ready = true;
                }
            }
            catch (Exception ee)
            {
            }
        }
Example #6
0
        private D3DSystem()
        {
            device           = new Device(DriverType.Hardware, DeviceCreationFlags.Debug);
            immediateContext = device.ImmediateContext;

            dxgi        = device.QueryInterface <SharpDX.DXGI.Device> ();
            dxgiFactory = dxgi.Adapter.GetParent <SharpDX.DXGI.Factory>();
        }
Example #7
0
 public void TestDXGI()
 {
     // Force to load DXGI assembly
     var factory = new Factory();
     factory.Dispose();
     // Look for DXGI descriptor SharpDX.DXGI.ResultCode.DeviceRemoved
     var descriptor = ResultDescriptor.Find(0x887A0005);
     Assert.AreEqual(descriptor.NativeApiCode, "DXGI_ERROR_DEVICE_REMOVED");
 }
Example #8
0
        public MainWindow() : base("Heat Simulator")
        {
            ClientSize  = new Size(400, 400);
            MouseClick += MainWindow_MouseClick;
            MouseMove  += MainWindow_MouseMove;
            MaximizeBox = false;
            KeyPreview  = true;
            KeyPress   += MainWindow_KeyPress;

            var desc = new SwapChainDescription {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(Width, Height, new Rational(60, 1), Format.B8G8R8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport,
                                       new[] { FeatureLevel.Level_12_0, FeatureLevel.Level_11_0 }, desc, out device, out swapChain);

            factory = swapChain.GetParent <Factory>();
            factory.MakeWindowAssociation(Handle, WindowAssociationFlags.IgnoreAll);
            backBuffer = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            renderView = new RenderTargetView(device, backBuffer);
            surface    = backBuffer.QueryInterface <Surface>();

            factory2d      = new Factory2D();
            renderTarget2d = new RenderTarget(factory2d, surface,
                                              new RenderTargetProperties(new PixelFormat(Format.Unknown,
                                                                                         AlphaMode.Premultiplied)));

            sColorBrush = new SolidColorBrush(renderTarget2d, Color4.White);

            factoryWrite = new FactoryW();
            textFormat   = new TextFormat(factoryWrite, "Ricty", 25)
            {
                TextAlignment      = TextAlignment.Leading,
                ParagraphAlignment = ParagraphAlignment.Near
            };
            renderTarget2d.TextAntialiasMode = TextAntialiasMode.Cleartype;
            textArea = new RectangleF(0, 0, Width / 2f, Height / 2f);

            simulator = new HeatSimulator();
            stopWatch = new Stopwatch();
            cells     = new GridCell[simulator.DivNum, simulator.DivNum];
            for (var i = 0; i < simulator.DivNum; i++)
            {
                for (var j = 0; j < simulator.DivNum; j++)
                {
                    cells[i, j] = new GridCell(factory2d, Width, Height, i, j, simulator.DivNum, simulator.State);
                }
            }
        }
Example #9
0
        public void TestDXGI()
        {
            // Force to load DXGI assembly
            var factory = new Factory();

            factory.Dispose();
            // Look for DXGI descriptor SharpDX.DXGI.ResultCode.DeviceRemoved
            var descriptor = ResultDescriptor.Find(0x887A0005);

            Assert.AreEqual(descriptor.NativeApiCode, "DXGI_ERROR_DEVICE_REMOVED");
        }
Example #10
0
        public Game(string windowName,
                    int windowWidth, int windowHeight,
                    bool isWindowed = true)
        {
            RenderForm                   = new RenderForm(windowName);
            RenderForm.Width             = windowWidth;
            RenderForm.Height            = windowHeight;
            RenderForm.AllowUserResizing = false;

            var desc = new SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription =
                    new ModeDescription(
                        (int)(RenderForm.Width),
                        (int)(RenderForm.Height),
                        new Rational(60, 1),
                        Format.R8G8B8A8_UNorm),
                IsWindowed        = isWindowed,
                OutputHandle      = RenderForm.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(DriverType.Hardware,
                                       DeviceCreationFlags.BgraSupport,
                                       new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 },
                                       desc, out Device, out SwapChain);

            Factory2D = new SharpDX.Direct2D1.Factory();
            Factory factory = SwapChain.GetParent <Factory>();

            factory.MakeWindowAssociation(RenderForm.Handle,
                                          WindowAssociationFlags.IgnoreAll);

            Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0);

            Surface = backBuffer.QueryInterface <Surface>();

            RenderTarget2D = new RenderTarget(Factory2D, Surface, new RenderTargetProperties(
                                                  new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));

            //WEB_SOCKET
            Connect();
            System.Threading.Tasks.Task.Delay(1000);

            _gameRender = new GameRender(RenderForm, Factory2D, RenderTarget2D);

            _directInput = new DirectInput();
            _keyboard    = new Keyboard(_directInput);
            _keyboard.Properties.BufferSize = 128;
            _keyboard.Acquire();
        }
Example #11
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="dg"></param>
 /// <returns></returns>
 public static IEnumerable<Adapter> GetAdapters(DisposeGroup dg)
 {
     // NOTE: SharpDX 1.3 requires explicit Dispose() of everything
     // hence the DisposeGroup, to enforce it
     using (var f = new Factory())
     {
         int n = AdapterCount;
         for (int i = 0; i < n; i++)
             yield return dg.Add(f.GetAdapter(i));
     }
 }
Example #12
0
        public RForm(string text) : base(text)
        {
            this.ClientSize = new System.Drawing.Size(screenWidth, screenHeight);

            desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(this.ClientSize.Width, this.ClientSize.Height, new Rational(144, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = this.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }, desc, out device, out swapChain);
            d2dFactory = new SharpDX.Direct2D1.Factory();
            factory    = swapChain.GetParent <Factory>();
            factory.MakeWindowAssociation(this.Handle, WindowAssociationFlags.IgnoreAll);
            backBuffer                     = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            renderView                     = new RenderTargetView(device, backBuffer);
            surface                        = backBuffer.QueryInterface <Surface>();
            d2dRenderTarget                = new RenderTarget(d2dFactory, surface, new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
            solidColorBrush                = new SolidColorBrush(d2dRenderTarget, Color.White);
            solidColorBrush.Color          = Color.White;
            directInput                    = new DirectInput();
            keyboard                       = new Keyboard(directInput);
            keyboard.Properties.BufferSize = 128;
            keyboard.Acquire();
            userInputProcessor = new UserInputProcessor();
            scoreTextFormat    = new SharpDX.DirectWrite.TextFormat(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Isolated), "Gill Sans", FontWeight.UltraBold, FontStyle.Normal, 36);
            scoreTextArea      = new SharpDX.Mathematics.Interop.RawRectangleF(10, 10, 400, 400);
            livesTextArea      = new SharpDX.Mathematics.Interop.RawRectangleF(10, 46, 400, 400);
            gameOverTextFormat = new SharpDX.DirectWrite.TextFormat(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Isolated), "Gill Sans", FontWeight.UltraBold, FontStyle.Normal, 108);
            gameOverTextArea   = new SharpDX.Mathematics.Interop.RawRectangleF(0, 0, screenWidth, screenHeight);
            gameOverTextFormat.ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Center;
            gameOverTextFormat.TextAlignment      = SharpDX.DirectWrite.TextAlignment.Center;;
            rand = new Random();


            ship      = new Ship(screenWidth / 2, screenHeight / 2);
            bullets   = new List <Bullet>();
            asteroids = new List <Asteroid>();

            int count = rand.Next(10, 15);

            for (int i = 0; i < count; i++)
            {
                asteroids.Add(new Asteroid(rand.Next(-25, screenWidth + 25), rand.Next(-25, screenWidth + 25), rand.Next(1, 4) * 10, rand, d2dFactory));
            }

            gameInputTimer = new Stopwatch();
            gameInputTimer.Start();
        }
Example #13
0
        /// <summary>
        /// Disposes all loaded view resources.
        /// </summary>
        void IRenderLoopHost.OnRenderLoop_DisposeViewResources(EngineDevice device)
        {
            m_factory             = null;
            m_renderDevice        = null;
            m_renderDeviceContext = null;

            m_renderTargetDepth = GraphicsHelper.DisposeObject(m_renderTargetDepth);
            m_depthBuffer       = GraphicsHelper.DisposeObject(m_depthBuffer);
            m_renderTarget      = GraphicsHelper.DisposeObject(m_renderTarget);
            m_backBuffer        = GraphicsHelper.DisposeObject(m_backBuffer);
            m_swapChain         = GraphicsHelper.DisposeObject(m_swapChain);
        }
Example #14
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);
        }
        private void InitializeDevices()
        {
            try
            {
                SwapChainDescription                   = new DXGI.SwapChainDescription();
                SwapChainDescription.BufferCount       = 2;
                SwapChainDescription.SampleDescription = new DXGI.SampleDescription(1, 0);
                SwapChainDescription.SwapEffect        = DXGI.SwapEffect.Discard;
                SwapChainDescription.Usage             = DXGI.Usage.BackBuffer | DXGI.Usage.RenderTargetOutput;
                SwapChainDescription.IsWindowed        = true;
                SwapChainDescription.ModeDescription   = new DXGI.ModeDescription(GameWindow.Current.WindowParameters.Width, GameWindow.Current.WindowParameters.Height, new DXGI.Rational(60, 1), DXGI.Format.B8G8R8A8_UNorm);
                SwapChainDescription.OutputHandle      = GameWindowHandle;

                D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport, featureLevels, SwapChainDescription, out D3DDefaultDevice, out SwapChain);

                DXGI.Factory factory = SwapChain.GetParent <DXGI.Factory>();
                factory.MakeWindowAssociation(GameWindowHandle, DXGI.WindowAssociationFlags.IgnoreAll);

                D3DDevice = D3DDefaultDevice.QueryInterface <D3D11.Device1>();

                Backbuffer       = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(SwapChain, 0);
                RenderTargetView = new D3D11.RenderTargetView(D3DDevice, Backbuffer);
                D3DDevice.ImmediateContext.Rasterizer.SetViewport(0, 0, GameWindow.Current.WindowParameters.Width, GameWindow.Current.WindowParameters.Height);
                D3DDevice.ImmediateContext.OutputMerger.SetTargets(RenderTargetView);

                DXGIDevice = D3DDevice.QueryInterface <DXGI.Device>();

                D2DFactory       = new D2D1.Factory1(D2D1.FactoryType.MultiThreaded);
                D2DDevice        = new D2D1.Device(D2DFactory, DXGIDevice);
                D2DDeviceContext = new D2D1.DeviceContext(D2DDevice, D2D1.DeviceContextOptions.None);

                RenderTargetSurface        = Backbuffer.QueryInterface <DXGI.Surface>();
                RenderTarget               = new D2D1.RenderTarget(D2DFactory, RenderTargetSurface, new D2D1.RenderTargetProperties(new D2D1.PixelFormat(DXGI.Format.Unknown, D2D1.AlphaMode.Premultiplied)));
                RenderTarget.AntialiasMode = D2D1.AntialiasMode.PerPrimitive;

                // Initialize debug drawings brushes
                DrawingBoundsBrush  = new D2D1.SolidColorBrush(RenderTarget, new SharpDX.Color(1f, 1f, 0f));
                CollisionBoxesBrush = new D2D1.SolidColorBrush(RenderTarget, new SharpDX.Color(1f, 0f, 0f));

                RenderFrame = new RenderFrame(RenderTarget);

                Clock = Stopwatch.StartNew();
            }
            catch (Exception ex)
            {
                throw new DeviceInitializationException("Unable to initialize DirectX device!", ex);
            }
        }
Example #16
0
        /// <summary>
        /// Create all view resources.
        /// </summary>
        Tuple <D3D11.Texture2D, D3D11.RenderTargetView, D3D11.Texture2D, D3D11.DepthStencilView, SharpDX.Mathematics.Interop.RawViewportF, Size2, DpiScaling> IRenderLoopHost.OnRenderLoop_CreateViewResources(EngineDevice device)
        {
            int width  = this.Width;
            int height = this.Height;

            if (width <= Constants.MIN_VIEW_WIDTH)
            {
                width = Constants.MIN_VIEW_WIDTH;
            }
            if (height <= Constants.MIN_VIEW_HEIGHT)
            {
                height = Constants.MIN_VIEW_HEIGHT;
            }

            //Get all factories
            m_factory = device.FactoryDxgi;

            //Get all devices
            m_renderDevice        = device.DeviceD3D11_1;
            m_renderDeviceContext = m_renderDevice.ImmediateContext;

            //Create the swap chain and the render target
            m_swapChain    = GraphicsHelper.CreateSwapChainForWinForms(this, device, m_renderLoop.ViewConfiguration);
            m_backBuffer   = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(m_swapChain, 0);
            m_renderTarget = new D3D11.RenderTargetView(m_renderDevice, m_backBuffer);

            //Create the depth buffer
            m_depthBuffer       = GraphicsHelper.CreateDepthBufferTexture(device, width, height, m_renderLoop.ViewConfiguration);
            m_renderTargetDepth = new D3D11.DepthStencilView(m_renderDevice, m_depthBuffer);

            //Define the viewport for rendering
            SharpDX.Mathematics.Interop.RawViewportF viewPort = GraphicsHelper.CreateDefaultViewport(width, height);

            // Query for current dpi value
            DpiScaling dpiScaling = DpiScaling.Default;

            using (Graphics graphics = this.CreateGraphics())
            {
                dpiScaling.DpiX = graphics.DpiX;
                dpiScaling.DpiY = graphics.DpiY;
            }

            //Return all generated objects
            return(Tuple.Create(m_backBuffer, m_renderTarget, m_depthBuffer, m_renderTargetDepth, viewPort, new Size2(width, height), dpiScaling));
        }
Example #17
0
        private Device()
        {
            DeviceCreationFlags flags = DeviceCreationFlags.DisableGpuTimeout;

#if DEBUG
            flags |= DeviceCreationFlags.Debug;
#endif
            // create 11.1 if possible (disable gpu timeout) but 11.0 is also fine
            Handle = new SharpDX.Direct3D11.Device(DriverType.Hardware, flags, new FeatureLevel[] { FeatureLevel.Level_11_1, FeatureLevel.Level_11_0 });

            // obtain the factory that created the device
            var obj     = Handle.QueryInterface <SharpDX.DXGI.Device>();
            var adapter = obj.Adapter;
            FactoryHandle = adapter.GetParent <SharpDX.DXGI.Factory>();
            context       = Handle.ImmediateContext;

            SetDefaults();
        }
Example #18
0
        private GraphicCore()
        {
            form                 = new RenderForm("");
            form.Width           = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width;
            form.Height          = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height;
            form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
            form.ControlBox      = false;
            form.MaximizeBox     = false;
            var desc = new SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription =
                    new ModeDescription(form.Width, form.Height, new Rational(frame_rate, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Camera.width  = form.Width;
            Camera.height = form.Height;

            Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc,
                                        SharpDX.Direct3D10.FeatureLevel.Level_10_0, out device, out swapChain);

            factory2d   = new SharpDX.Direct2D1.Factory();
            factoryText = new SharpDX.DirectWrite.Factory();

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

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

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

            this.render2d = new RenderTarget(factory2d, surface,
                                             new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));

            brush      = new SolidColorBrush(this.render2d, Color.White);
            _isRunning = true;
        }
Example #19
0
        private void createSwapChain()
        {
            lock (deviceManager.DeviceLock)
            {
                var factory = new DXGI.Factory();

                var description = new DXGI.SwapChainDescription()
                {
                    BufferCount     = 1,
                    ModeDescription =
                        new DXGI.ModeDescription(
                            control.ClientSize.Width,
                            control.ClientSize.Height,
                            new DXGI.Rational(60, 1),
                            DXGI.Format.R8G8B8A8_UNorm),
                    IsWindowed        = true,
                    SampleDescription = new DXGI.SampleDescription(1, 0),
                    SwapEffect        = DXGI.SwapEffect.Discard,
                    Usage             = DXGI.Usage.RenderTargetOutput,
                    OutputHandle      = control.Handle
                };

                swapChain = new DXGI.SwapChain(factory, deviceContext.Device, description);

                backbuffer     = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(swapChain, 0);
                backbufferView = new D3D11.RenderTargetView(deviceContext.Device, backbuffer);
            }

            var d2dFactory = deviceManager.Direct2dFactory;
            var surface    = backbuffer.QueryInterface <DXGI.Surface>();

            renderTarget = new D2D.RenderTarget(
                d2dFactory,
                surface,
                new D2D.RenderTargetProperties(
                    new D2D.PixelFormat(
                        DXGI.Format.Unknown,
                        D2D.AlphaMode.Premultiplied)));

            renderTarget.AntialiasMode = D2D.AntialiasMode.Aliased;

            createViewport();
        }
Example #20
0
        public static void Initialize(string name, int width, int height, Color bgColor)
        {
            form            = new RenderForm(name);
            form.ClientSize = new System.Drawing.Size(width, height);
            screenFrame     = new Frame();
            screenFrame.setTransform(1, 0, 0, 1, 0, 0);
            screenFrame.addHitbox(new Hitbox(0, 0, width, height));
            TCM_Graphics.bgColor = bgColor;

            //overall begin drawing
            transformStack = new Stack <RawMatrix3x2>();
            var swapDescription = new SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height,
                                                      new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport,
                                       new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 },
                                       swapDescription, out dev, out sc);

            d2dFactory = new SharpDX.Direct2D1.Factory();

            fact = sc.GetParent <Factory>();
            fact.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            backBuffer = Texture2D.FromSwapChain <Texture2D>(sc, 0);
            rtv        = new RenderTargetView(dev, backBuffer);
            Surface surf = backBuffer.QueryInterface <Surface>();


            rt = new RenderTarget(d2dFactory, surf,
                                  new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));

            brush = new SolidColorBrush(rt, bgColor);
        }
Example #21
0
    public RenderTarget CreateRenderTarget(RenderForm form)
    {
        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(2, 0),
            SwapEffect        = SwapEffect.Discard,
            Usage             = Usage.RenderTargetOutput
        };


        Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }, desc, out device, out swapChain);

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

        int width  = form.ClientSize.Width;
        int height = form.ClientSize.Height;

        var rectangleGeometry = new RoundedRectangleGeometry(d2dFactory, new RoundedRectangle()
        {
            RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, width - 128 * 2, height - 128 * 2)
        });

        factory = swapChain.GetParent <Factory>();
        factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

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

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

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

        return(d2dRenderTarget);
    }
Example #22
0
        /// <summary>
        /// deviceを作成します。
        /// </summary>
        /// <param name="control">レンダリング先となるcontrol</param>
        /// <param name="ocu_config">設定</param>
        /// <returns>deviceの作成に成功したか</returns>
        public bool InitializeApplication(Control control, OcuConfig ocu_config)
        {
            this.ocu_config = ocu_config;
            oculus = new OculusWrap.Wrap();

            // Initialize the Oculus runtime.
            bool success = oculus.Initialize();
            if (!success)
            {
            MessageBox.Show("Failed to initialize the Oculus runtime library.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
            }

            // Use the head mounted display, if it's available, otherwise use the debug HMD.
            int numberOfHeadMountedDisplays = oculus.Hmd_Detect();
            if (numberOfHeadMountedDisplays > 0)
            hmd = oculus.Hmd_Create(0);
            else
            hmd = oculus.Hmd_CreateDebug(OculusWrap.OVR.HmdType.DK2);

            if (hmd == null)
            {
            MessageBox.Show("Oculus Rift not detected.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
            }

            if (hmd.ProductName == string.Empty)
            MessageBox.Show("The HMD is not enabled.", "There's a tear in the Rift", MessageBoxButtons.OK, MessageBoxIcon.Error);

            // Specify which head tracking capabilities to enable.
            hmd.SetEnabledCaps(OculusWrap.OVR.HmdCaps.LowPersistence | OculusWrap.OVR.HmdCaps.DynamicPrediction);

            // Start the sensor which informs of the Rift's pose and motion
            hmd.ConfigureTracking(OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Orientation | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_MagYawCorrection | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Position, OculusWrap.OVR.TrackingCaps.None);

            // Create DirectX drawing device.
            device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.None);

            ctx = device.ImmediateContext;

            Stopwatch sw = new Stopwatch();
            sw.Start();

            string effect_file = Path.Combine(Application.StartupPath, @"toonshader.fx.bin");
            if (! File.Exists(effect_file))
            {
            Console.WriteLine("File not found: " + effect_file);
            return false;
            }
            try
            {
            var shader_bytecode = ShaderBytecode.FromFile(effect_file);
            effect = new Effect(device, shader_bytecode);
            }
            catch (SharpDX.CompilationException e)
            {
            Console.WriteLine(e.Message + ": " + effect_file);
            return false;
            }

            sw.Stop();
            Console.WriteLine("toonshader.fx.bin read time: " + sw.Elapsed);

            string techmap_file = Path.Combine(Application.StartupPath, @"techmap.txt");
            if (!File.Exists(techmap_file))
            {
            Console.WriteLine("File not found: " + techmap_file);
            return false;
            }
            techmap.Load(techmap_file);

            control.MouseDown += new MouseEventHandler(form_OnMouseDown);

            // Define the properties of the swap chain.
            SwapChainDescription swapChainDescription = DefineSwapChainDescription(control);

            // Create DirectX Graphics Interface factory, used to create the swap chain.
            dxgi_factory = new SharpDX.DXGI.Factory();
            // Create the swap chain.
            swap_chain = new SwapChain(dxgi_factory, device, swapChainDescription);

            // Retrieve the back buffer of the swap chain.
            buf0 = swap_chain.GetBackBuffer<Texture2D>(0);
            buf0_view = new RenderTargetView(device, buf0);

            // Create a depth buffer, using the same width and height as the back buffer.
            Texture2DDescription depthBufferDescription = DefineDepthBufferDescription(control);

            // Create the depth buffer.
            ztex = new Texture2D(device, depthBufferDescription);
            ztex_view = new DepthStencilView(device, ztex);

            ctx.OutputMerger.SetRenderTargets(ztex_view, buf0_view);

            viewport = new Viewport(0, 0, hmd.Resolution.Width, hmd.Resolution.Height, 0.0f, 1.0f);
            ctx.Rasterizer.SetViewport(viewport);

            // Retrieve the DXGI device, in order to set the maximum frame latency.
            using (SharpDX.DXGI.Device1 dxgiDevice = device.QueryInterface<SharpDX.DXGI.Device1>())
            {
            dxgiDevice.MaximumFrameLatency = 1;
            }

            layers = new OculusWrap.Layers();
            layer_eye_fov = layers.AddLayerEyeFov();

            CreateEyeTextures();

            CreateMirrorTexture(control);

            World_variable = effect.GetVariableBySemantic("World").AsMatrix();
            WorldView_variable = effect.GetVariableBySemantic("WorldView").AsMatrix();
            WorldViewProjection_variable = effect.GetVariableBySemantic("WorldViewProjection").AsMatrix();
            /* for HUD */
            Projection_variable = effect.GetVariableBySemantic("Projection").AsMatrix();

            LocalBoneMats_variable = effect.GetVariableByName("LocalBoneMats").AsMatrix();
            LightDirForced_variable = effect.GetVariableByName("LightDirForced").AsVector();
            UVSCR_variable = effect.GetVariableByName("UVSCR").AsVector();

            cb_variable = effect.GetConstantBufferByName("cb");

            ShadeTex_texture_variable = effect.GetVariableByName("ShadeTex_texture").AsShaderResource();
            ColorTex_texture_variable = effect.GetVariableByName("ColorTex_texture").AsShaderResource();

            //figures.Camera = camera;
            figures.TSOFileOpen += delegate(TSOFile tso)
            {
            tso.Open(device, effect);
            techmap.AssignTechniqueIndices(tso);
            };

            // Define an input layout to be passed to the vertex shader.
            var technique = effect.GetTechniqueByIndex(0);
            il = new InputLayout(device, technique.GetPassByIndex(0).Description.Signature, TSOSubMesh.ie);

            // Setup the immediate context to use the shaders and model we defined.
            ctx.InputAssembler.InputLayout = il;

            DefineBlendState();
            DefineDepthStencilState();
            DefineRasterizerState();

            main_camera = new Camera()
            {
            Position = ocu_config.Position,
            Rotation = Quaternion.Identity,
            };

            directInput = new DirectInput();
            keyboard = new Keyboard(directInput);
            keyboard.Acquire();

            keyboardState = keyboard.GetCurrentState();

            return true;
        }
Example #23
0
        static void D2d()
        {
            var plugfire = new Plugfire();

            InitializeXAudio2();
            //var fileStream = new NativeFileStream(@"D:\plug17.mp3", NativeFileMode.Open, NativeFileAccess.Read);
            var embeddedStream = Assembly.GetEntryAssembly().GetManifestResourceStream(typeof(Program), "music.mp3");
            var audioPlayer    = new AudioPlayer(xaudio2, embeddedStream);

            audioPlayer.Play();

            var form = new RenderForm("SharpDX - MiniCube Direct3D11 Sample");

            form.Width  = Plugfire.WIDTH * 4;
            form.Height = Plugfire.HEIGHT * 4;
            Device    device;
            SwapChain swapChain;
            var       d2dFactory = new SharpDX.Direct2D1.Factory();

            var desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = false,
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }, desc, out device, out swapChain);

            // Ignore all windows events
            Factory factory = swapChain.GetParent <Factory>();

            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            form.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.Escape)
                {
                    form.Close();
                }
            };

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            Texture2D        backBuffer = null;
            Bitmap           bitmap     = null;
            RenderTarget     render     = null;
            RenderTargetView renderView = null;

            backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            //var textBuffer = new Texture2D(device, new Texture2DDescription {Height = 100, Width = 100, Format = Format.R8G8B8A8_UNorm});
            renderView = new RenderTargetView(device, backBuffer);
            //var textView = new RenderTargetView(device, textBuffer);
            Surface surface = backBuffer.QueryInterface <Surface>();

            //Surface textSurface = textBuffer.QueryInterface<Surface>();
            render = new RenderTarget(d2dFactory, surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
            //var textRender = new RenderTarget(d2dFactory, textSurface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
            bitmap = new Bitmap(render, new Size2(Plugfire.WIDTH, Plugfire.HEIGHT), new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Ignore)));

            SharpDX.DirectWrite.Factory FactoryDWrite = new SharpDX.DirectWrite.Factory();

            var whiteTextBrush     = new SolidColorBrush(render, new RawColor4(1, 1, 1, 1));
            var debugTextFormat    = new TextFormat(FactoryDWrite, "Arial", 10);
            var titleTextBrush     = new SolidColorBrush(render, new RawColor4(1, 1, 0.3f, 1));
            var foamTextFormat     = new TextFormat(FactoryDWrite, "Arial", FontWeight.Bold, FontStyle.Normal, 100);
            var presentsTextFormat = new TextFormat(FactoryDWrite, "Arial", FontWeight.Bold, FontStyle.Normal, 60);
            var titleTextFormat    = new TextFormat(FactoryDWrite, "Arial", FontWeight.Bold, FontStyle.Normal, 80);

            // Main loop
            RenderLoop.Run(form, () =>
            {
                plugfire.Frame(stopwatch.ElapsedMilliseconds, audioPlayer.Position.TotalMilliseconds);
                bitmap.CopyFromMemory(plugfire.GetRgbImage(), Plugfire.WIDTH * 4);

                render.BeginDraw();
                //render.Clear(Color.Wheat);
                //solidColorBrush.Color = new Color4(1, 1, 1, (float)Math.Abs(Math.Cos(stopwatch.ElapsedMilliseconds * .001)));
                //d2dRenderTarget.FillGeometry(rectangleGeometry, solidColorBrush, null);
                render.DrawBitmap(bitmap, new RawRectangleF(0, 0, render.Size.Width, render.Size.Height), 1.0f, BitmapInterpolationMode.Linear);
                //render.DrawText(audioPlayer.Position.ToString(), debugTextFormat, new RawRectangleF(10,10,100,100), whiteTextBrush);

                //if (plugfire.Mode == 0)
                //{
                //    var fade = (float)Math.Min((stopwatch.Elapsed.TotalMilliseconds - 500) / 2000, 1);
                //    titleTextBrush.Color = new RawColor4(fade, fade, fade * 0.3f, 1);
                //    render.DrawText("FOAM", foamTextFormat, new RawRectangleF(500, 100, 2000, 2000), titleTextBrush);
                //    render.DrawText("presents", presentsTextFormat, new RawRectangleF(520, 200, 2000, 2000), titleTextBrush);
                //    render.DrawText("Plugfire Regurgitated", titleTextFormat, new RawRectangleF(250, 400, 2000, 2000), titleTextBrush);
                //}

                render.EndDraw();

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

            // Release all resources
            renderView.Dispose();
            backBuffer.Dispose();
            device.ImmediateContext.ClearState();
            device.ImmediateContext.Flush();
            device.Dispose();
            device.Dispose();
            swapChain.Dispose();
            factory.Dispose();
        }
Example #24
0
        private void createSwapChain()
        {
            lock (deviceManager.DeviceLock)
            {
                var factory = new DXGI.Factory();

                var description = new DXGI.SwapChainDescription()
                {
                    BufferCount = 1,
                    ModeDescription =
                        new DXGI.ModeDescription(
                            control.ClientSize.Width,
                            control.ClientSize.Height,
                            new DXGI.Rational(60, 1),
                            DXGI.Format.R8G8B8A8_UNorm),
                    IsWindowed = true,
                    SampleDescription = new DXGI.SampleDescription(1, 0),
                    SwapEffect = DXGI.SwapEffect.Discard,
                    Usage = DXGI.Usage.RenderTargetOutput,
                    OutputHandle = control.Handle
                };

                swapChain = new DXGI.SwapChain(factory, deviceContext.Device, description);

                backbuffer = D3D11.Texture2D.FromSwapChain<D3D11.Texture2D>(swapChain, 0);
                backbufferView = new D3D11.RenderTargetView(deviceContext.Device, backbuffer);
            }

            var d2dFactory = deviceManager.Direct2dFactory;
            var surface = backbuffer.QueryInterface<DXGI.Surface>();
            renderTarget = new D2D.RenderTarget(
                d2dFactory,
                surface,
                new D2D.RenderTargetProperties(
                    new D2D.PixelFormat(
                        DXGI.Format.Unknown,
                        D2D.AlphaMode.Premultiplied)));

            renderTarget.AntialiasMode = D2D.AntialiasMode.Aliased;

            createViewport();
        }
Example #25
0
        /// <summary>
        /// A Game powered by SharpDX
        /// </summary>
        /// <param name="Width">The width of the window</param>
        /// <param name="Height">The height of the window</param>
        static public void Initialize(SharpDX_Engine.Utitities.Size Size)
        {
            GC.Collect();

            form = new RenderForm();
            form.StartPosition   = FormStartPosition.CenterScreen;
            form.ClientSize      = new System.Drawing.Size((int)Size.width, (int)Size.height);
            form.MaximizeBox     = false;
            form.FormBorderStyle = FormBorderStyle.FixedSingle;
            form.FormClosed     += form_FormClosed;

            // SwapChain description
            SwapChainDescription desc = new SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription =
                    new ModeDescription(form.ClientSize.Width, form.ClientSize.Height,
                                        new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            // Create Device and SwapChain
            Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, FeatureLevel.Level_10_0, out device, out swapChain);

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

            // Ignore all windows events
            Factory factory = swapChain.GetParent <Factory>();

            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            Texture2D        backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            RenderTargetView renderView = new RenderTargetView(device, backBuffer);

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

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

            form.SizeChanged += form_SizeChanged;
            form.GotFocus    += form_GotFocus;
            form.LostFocus   += form_LostFocus;
            form.Move        += form_Move;
            WindowPosition    = new Coordinate(
                form.Location.X + SystemInformation.FixedFrameBorderSize.Width + SystemInformation.DragSize.Width,
                form.Location.Y + SystemInformation.FixedFrameBorderSize.Height + SystemInformation.CaptionHeight + SystemInformation.DragSize.Height
                );
            TextureManager = new TextureManager(d2dRenderTarget);
            //x swapChain.IsFullScreen = true;
            Game.Size = Size;
            Renderer  = new Renderer(d2dRenderTarget);
            Input     = new InputManager();
            Sound     = new Sound.Sound();

            Stopwatch = new Stopwatch();
            Stopwatch.Start();

            Scene = new DummyScene();

            UpdateThread = new Thread(UpdateScene);
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            LDM.Clear();

            ModeDescription[] DML = null;
            using (SharpDX.DXGI.Factory myFactory = new SharpDX.DXGI.Factory())
            {

                int MyAdapterCount = myFactory.GetAdapterCount();
                try
                {
                    using (SharpDX.DXGI.Adapter MyAdapter = myFactory.GetAdapter(MyAdapterCount - 1))
                    {
                        using (Output OP = MyAdapter.Outputs[0])
                            DML = OP.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);
                    }

                }
                catch (System.Exception ex)
                {
                    using (SharpDX.DXGI.Adapter MyAdapter = myFactory.GetAdapter(MyAdapterCount - 0))
                    {
                        using (Output OP = MyAdapter.Outputs[0])
                            DML = OP.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);
                    }
                }
            }

            foreach (ModeDescription dm in DML)
            {
                bool cor = true;
                foreach (DisplayMode dmd in LDM)
                {
                    if (dmd.Width == dm.Width && dmd.Height == dm.Height)
                    {
                        cor = false;
                    }
                }

                if (cor && dm.Width >= 1024 && dm.Height >= 768)
                    LDM.Add(new DisplayMode(dm.Width, dm.Height));
            }

            config.Width = LDM[comboBox1.SelectedIndex].Width;
            config.Height = LDM[comboBox1.SelectedIndex].Height;
            SetData();
        }
Example #27
0
        public void Run()
        {
            form = CreateForm();

            SwapChainDescription desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(1280, 720, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = DisplayHandle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new[] { FeatureLevelDX.Level_10_0 }, desc, out device, out swapChain);
            FactoryDX factory = swapChain.GetParent <FactoryDX>();

            factory.MakeWindowAssociation(DisplayHandle, WindowAssociationFlags.IgnoreAll);
            backBuffer     = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            backBufferView = new RenderTargetView(device, backBuffer);

            Factory2D = new Factory2D();
            using (Surface surface = backBuffer.QueryInterface <Surface>()) {
                RenderTarget2D = new RenderTarget(Factory2D, surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
            }
            RenderTarget2D.AntialiasMode = AntialiasMode.PerPrimitive;
            FactoryDirectWrite           = new FactoryDW();
            SceneColorBrush = new SolidColorBrush(RenderTarget2D, new RawColor4(1, 1, 1, 1));

            Initialize();
            bool isFormClosed   = false;
            bool formIsResizing = false;

            form.MouseClick  += HandleMouseClick;
            form.KeyDown     += HandleKeyDown;
            form.KeyUp       += HandleKeyUp;
            form.FormClosed  += (o, args) => { isFormClosed = true; };
            form.ResizeBegin += (o, args) => { formIsResizing = true; };
            form.ResizeEnd   += (o, args) => {
                formIsResizing = false;
                HandleResize(o, args);
            };
            form.Resize += (o, args) => {
                if (form.WindowState != currentFormWindowState)
                {
                    HandleResize(o, args);
                }
                currentFormWindowState = form.WindowState;
            };

            LoadContent();
            clock.Start();
            BeginRun();
            RenderLoop.Run(form, () => {
                if (isFormClosed)
                {
                    return;
                }
                OnUpdate();
                if (!formIsResizing)
                {
                    Render();
                }
            });

            UnloadContent();
            EndRun();

            Dispose();
        }
        public StartForm()
        {
            this.BackgroundImage = null;
            bool FileFail = false;
            InitializeComponent();
            FileStream fs = null;
            try
            {
                fs = new FileStream("Config.bin", FileMode.Open, FileAccess.Read);
                config = Serializer.Deserialize<Config>(fs);
                fs.Close();
            }
            catch(Exception ex)
            {
                FileFail = true;
                if (fs != null) fs.Close();
                System.Windows.Forms.MessageBox.Show("Error! Небыл найден файл настроек\n" + ex.Message);
            }

            ModeDescription[] DML = null;

            using (SharpDX.DXGI.Factory myFactory = new SharpDX.DXGI.Factory())
            {

                int MyAdapterCount = myFactory.GetAdapterCount();
                try
                {
                    using (SharpDX.DXGI.Adapter MyAdapter = myFactory.GetAdapter(MyAdapterCount - 1))
                    {
                        using (Output OP = MyAdapter.Outputs[0])
                            DML = OP.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);
                    }

                }
                catch (System.Exception ex)
                {
                    using (SharpDX.DXGI.Adapter MyAdapter = myFactory.GetAdapter(MyAdapterCount - 0))
                    {
                        using (Output OP = MyAdapter.Outputs[0])
                            DML = OP.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);
                    }
                }
            }

            int mw = 0, mh = 0;
            foreach (ModeDescription dm in DML)
            {
                bool cor = true;
                foreach (DisplayMode dmd in LDM)
                {
                    if (dmd.Width == dm.Width && dmd.Height == dm.Height)
                    {
                        cor = false;
                    }
                }

                if (cor && dm.Width >= 1024 && dm.Height >= 768)
                    LDM.Add(new DisplayMode(dm.Width, dm.Height));

                if (dm.Width > mw) mw = dm.Width;
                if (dm.Height > mh) mh = dm.Height;
            }

            if (LDM.Count < 1)
            {
                System.Windows.Forms.MessageBox.Show("Error! Минимальное поддерживаемое разрешение экрана 1024х768");
                this.Close();
            }

            if (config.Width > mw || config.Height > mh)
            {
                FileFail = true;
            }

            if (GetResIndex(config.Width, config.Height, LDM) < 0)
                FileFail = true;

            if (FileFail)
            {
                config = new Config();
                SaveC(config, "Config.bin");
            }
            SetData();

            for (int num = 0; num < LDM.Count; num++)
            {
                comboBox1.Items.Add(LDM[num].Width.ToString() + "x" + LDM[num].Height.ToString());
            }

            int Res = GetResIndex(config.Width, config.Height, LDM);

            if (Res > -1)
            {
                comboBox1.SelectedIndex = Res;
            }

            if (config.VSync>0)
            {
                checkBox1.Checked = true;
            }
            else
            {
                checkBox1.Checked = false;
            }

            if (config.InvAlt > 0)
            {
                checkBox3.Checked = true;
            }
            else
            {
                checkBox3.Checked = false;
            }

            comboBox2.Items.Add("High");
            comboBox2.Items.Add("Medium");
            comboBox2.Items.Add("Low");
            comboBox2.Items.Add("Disable");

            if (config.Shadow < 1)
            {
                comboBox2.SelectedIndex = 3;
            }
            else
            {
                comboBox2.SelectedIndex = config.ShadowQuality;
            }

            comboBox3.Items.Add("Disable");
            comboBox3.Items.Add("Low");
            comboBox3.Items.Add("Medium");
            comboBox3.Items.Add("High");

            if (config.MultiSample > -1 && config.MultiSample < 2)
            {
                comboBox3.SelectedIndex = 0;
            }
            if (config.MultiSample > 1 && config.MultiSample < 4)
            {
                comboBox3.SelectedIndex = 1;
            }
            if (config.MultiSample > 3 && config.MultiSample < 8)
            {
                comboBox3.SelectedIndex = 2;
            }
            if (config.MultiSample > 7)
            {
                comboBox3.SelectedIndex = 3;
            }

            comboBox4.Items.Add("Disable");
            comboBox4.Items.Add("4");
            comboBox4.Items.Add("8");
            comboBox4.Items.Add("12");

            if (config.Light > -1 && config.Light < 4)
            {
                comboBox4.SelectedIndex = 0;
            }
            if (config.Light > 3 && config.Light < 7)
            {
                comboBox4.SelectedIndex = 1;
            }
            if (config.Light > 7 && config.Light < 11)
            {
                comboBox4.SelectedIndex = 2;
            }
            if (config.Light > 11)
            {
                comboBox4.SelectedIndex = 3;
            }

            if (config.FullScr > 0)
            {
                checkBox2.Checked = true;
            }
            else
            {
                checkBox2.Checked = false;
            }

            if (config.Refract > 0)
            {
                checkBox4.Checked = true;
            }
            else
            {
                checkBox4.Checked = false;
            }
        }
Example #29
0
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniTri Direct2D - Direct3D 10 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
            Device1   device;
            SwapChain swapChain;

            Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport, desc, FeatureLevel.Level_10_0, out device, out swapChain);

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

            int width  = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            var rectangleGeometry = new RoundedRectangleGeometry(d2dFactory, new RoundedRect()
            {
                RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, width - 128, height - 128)
            });

            // Ignore all windows events
            Factory factory = swapChain.GetParent <Factory>();

            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            var       renderView = new RenderTargetView(device, backBuffer);

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


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

            var solidColorBrush = new SolidColorBrush(d2dRenderTarget, new Color4(1, 1, 1, 1));

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            // Main loop
            RenderLoop.Run(form, () =>
            {
                d2dRenderTarget.BeginDraw();
                d2dRenderTarget.Clear(new Color4(1.0f, 0.0f, 0.0f, 0.0f));
                solidColorBrush.Color = new Color4((float)Math.Abs(Math.Cos(stopwatch.ElapsedMilliseconds * .001)), 1, 1, 1);
                d2dRenderTarget.FillGeometry(rectangleGeometry, solidColorBrush, null);
                d2dRenderTarget.EndDraw();

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

            // Release all resources
            renderView.Release();
            backBuffer.Release();
            device.ClearState();
            device.Flush();
            device.Release();
            device.Release();
            swapChain.Release();
            factory.Release();
        }
Example #30
0
        /// <summary>
        /// Creates Direct3D11 Device, RenderTargetView, DepthStencilView, Viewport
        /// </summary>
        /// <param name="deviceDescription">The device description.</param>
        /// <exception cref="System.Exception"></exception>
        /// <exception cref="System.ComponentModel.InvalidEnumArgumentException">deviceDescription.MultiSampleCount</exception>
        private void Initialize(DeviceDescription deviceDescription)
        {
            FeatureLevel[] levels = new FeatureLevel[] {
                FeatureLevel.Level_10_0,
                FeatureLevel.Level_10_1,
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_11_1,
            };

            d3dDevice = new D3D11.Device(DriverType.Hardware, D3D11.DeviceCreationFlags.Debug, levels);

            DXGI.ModeDescription backBufferDesc = new DXGI.ModeDescription()
            {
                Width            = width,
                Height           = height,
                Format           = BackBufferFormat,
                RefreshRate      = new DXGI.Rational(60, 1),
                Scaling          = DXGI.DisplayModeScaling.Unspecified,
                ScanlineOrdering = DXGI.DisplayModeScanlineOrder.Progressive,
            };

            DXGI.SwapChainDescription swapChainDesc = new DXGI.SwapChainDescription()
            {
                BufferCount     = 1,
                Flags           = DXGI.SwapChainFlags.None,
                IsWindowed      = !deviceDescription.Fullcreen,
                ModeDescription = backBufferDesc,
                OutputHandle    = renderControl.Handle,
                SwapEffect      = deviceDescription.SwapEffect,
                Usage           = DXGI.Usage.RenderTargetOutput,
            };

            switch (deviceDescription.MultiSampleCount)
            {
            case MultiSampleType.MSAA1:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(1, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA2:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(2, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA4:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(4, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA8:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(8, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA16:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(16, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.Unknown:
                var samples = SharpDXDevice.CheckMultiSample();
                if (samples == null)
                {
                    throw new Exception(MethodBase.GetCurrentMethod().Name +
                                        " Because the MultiSampleCount parameter is [Unknown], the device could not determine the parameter automatically");
                }
                swapChainDesc.SampleDescription = samples.Last();
                break;

            default:
                throw new System.ComponentModel.InvalidEnumArgumentException("deviceDescription.MultiSampleCount",
                                                                             (int)deviceDescription.MultiSampleCount, typeof(MultiSampleType));
            }

            DXGI.Device  device  = d3dDevice.QueryInterface <DXGI.Device>();
            DXGI.Adapter adapter = device.GetParent <DXGI.Adapter>();
            DXGI.Factory factory = adapter.GetParent <DXGI.Factory>();

            swapChain = new DXGI.SwapChain(factory, d3dDevice, swapChainDesc);

            d3dContext = d3dDevice.ImmediateContext;

            D3D11.RasterizerStateDescription rasterDesc = new D3D11.RasterizerStateDescription()
            {
                CullMode = D3D11.CullMode.Back,
                FillMode = D3D11.FillMode.Solid,
                IsAntialiasedLineEnabled = true,
                IsMultisampleEnabled     = true,
                IsDepthClipEnabled       = true,
            };

            viewport = new Viewport(0, 0, width, height);

            this.SetRasterizerState(rasterDesc);
            d3dRenderTarget = CreateRenderTarget();
            d3dDepthStencil = CreateDepthStencil();
        }
Example #31
0
        public override void InitDevice()
        {
            Width  = Surface.ClientSize.Width;
            Height = Surface.ClientSize.Height;

            SwapChainDescription SwapDesc = new SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription = new ModeDescription(
                    Width, Height,
                    new Rational(60, 1),
                    Format.R8G8B8A8_UNorm//R8G8B8A8_UNorm
                    ),
                IsWindowed        = true,
                OutputHandle      = Surface.Handle,
                SampleDescription = new SampleDescription(MSamplesCount, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput,
            };

            Device    device;
            SwapChain swapChain;

            DeviceCreationFlags deviceCreationFlags = DeviceCreationFlags.BgraSupport;

            if (IsDebugMode)
            {
                deviceCreationFlags |= DeviceCreationFlags.Debug;
            }

            Device.CreateWithSwapChain(
                DriverType.Hardware,
                deviceCreationFlags,
                //DeviceCreationFlags.None,
                SwapDesc,
                out device,
                out swapChain
                );
            DeviceRef           = device;
            DeviceRef.DebugName = "The Device";
            DeviceRef.ImmediateContext.DebugName = "The Context";

            CheckFeatures();

            SwapChainRef           = swapChain;
            SwapChainRef.DebugName = "The SwapChain";

            // Ignore all windows events
            FactoryDXGI factory = swapChain.GetParent <FactoryDXGI>();

            factory.MakeWindowAssociation(Surface.Handle, WindowAssociationFlags.IgnoreAll);

            ZBufferTextureDescription = new Texture2DDescription {
                Format            = Format.R32_Typeless,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = Width,
                Height            = Height,
                SampleDescription = new SampleDescription(MSamplesCount, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None,
            };

            Factory2D                = new Factory(FactoryType.SingleThreaded, DebugLevel.Information);
            FactoryDWrite            = new SharpDX.DirectWrite.Factory();
            RenderTarget2DProperites = new RenderTargetProperties(new PixelFormat(
                                                                      Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));
        }
        public PumpkinFaceRenderer(IFaceCamera <System.Drawing.PointF> faceCamera)
        {
            renderForm = new RenderForm("Calabasas");
            renderForm.AllowUserResizing = true;

            this.faceCamera = faceCamera;

            renderForm.KeyPress += OnRenderFormKeyPress;

            renderForm.MouseClick += OnRenderFormMouseClick;

            if (this.faceCamera != null)
            {
                this.faceCamera.OnFaceChanged  += OnFaceChanged;
                this.faceCamera.OnTrackingFace += OnTrackingFace;
            }

            // SwapChain description
            swapChainDesc = new SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription = new ModeDescription(Width, Height,
                                                      new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = renderForm.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[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }, swapChainDesc, out device, out swapChain);

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

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

            // New RenderTargetView from the backbuffer
            backBuffer       = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            renderTargetView = new RenderTargetView(device, backBuffer);

            surface = backBuffer.QueryInterface <Surface>();

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

            // Initialize a TextFormat
            TextFormat = new TextFormat(dwFactory, "Calibri", 18);

            d2dRenderTarget.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype;

            // Initialize a Brush.
            SceneColorBrush = new SolidColorBrush(d2dRenderTarget, Color.White);

            // Initialize geometery/drawable primitives.
            facePointGeometry = new RectangleGeometry(d2dFactory, new SharpDX.Mathematics.Interop.RawRectangleF(-PointSize / 2.0F, -PointSize / 2.0F, PointSize / 2.0F, PointSize / 2.0F));
            facePointBrush    = new SolidColorBrush(d2dRenderTarget, new SharpDX.Color(facePointPenColor.R, facePointPenColor.G, facePointPenColor.B));

            drawingStateBlock = new DrawingStateBlock(d2dFactory);

            framesPerSecond = new FramesPerSecond();
        }
 public void SetFactory(SharpDX.DXGI.Factory v)
 {
     Factory = v;
 }
Example #34
0
        private void _initializeGraphics()
        {
            Console.Write("Initializing graphic device... ");

            var desc = new SwapChainDescription() {
                BufferCount = 1,
                ModeDescription = new ModeDescription(
                    _appConfiguration.Width,
                    _appConfiguration.Height,
                    new Rational(60, 1),
                    Format.R8G8B8A8_UNorm),
                IsWindowed = !_appConfiguration.FullScreen,
                OutputHandle = DisplayHandle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

            Device1.CreateWithSwapChain(
                DriverType.Hardware,
            #if DEBUG
             DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug | DeviceCreationFlags.SingleThreaded,
            #else
                DeviceCreationFlags.BgraSupport,
            #endif
             desc,
                out _device,
                out _swapChain);

            if (_device == null)
                throw new SharpDXException("Failed to initialize graphics device.");

            if (_swapChain == null)
                throw new SharpDXException("Failed to initialize swap chain.");

            ToDispose<Device1>(_device);
            ToDispose<SwapChain>(_swapChain);
            Factory2D = ToDispose<Factory2D>(new Factory2D());

            _factoryDXGI = ToDispose<FactoryDXGI>(_swapChain.GetParent<FactoryDXGI>());
            _factoryDXGI.MakeWindowAssociation(DisplayHandle, WindowAssociationFlags.IgnoreAll);

            _backBuffer = ToDispose<Texture2D>(Texture2D.FromSwapChain<Texture2D>(_swapChain, 0));
            _backBufferRenderTargetView = ToDispose<RenderTargetView>(new RenderTargetView(_device, _backBuffer));

            Viewport = new Viewport(0, 0, _appConfiguration.Width, _appConfiguration.Height);
            using (var surface = _backBuffer.QueryInterface<Surface>()) {
                RenderTarget2D = ToDispose<RenderTarget>(
                    new RenderTarget(Factory2D,
                        surface,
                        new RenderTargetProperties(
                            new PixelFormat(
                                Format.Unknown,
                                AlphaMode.Premultiplied))));
            }
            RenderTarget2D.AntialiasMode = AntialiasMode.PerPrimitive;

            _vsync = Config.VSync;

            ScreenSize = new DrawingSizeF(Viewport.Width, Viewport.Height);

            Console.WriteLine("done.");
        }
Example #35
0
        public static void Run(WorldBase world, int wndWidth = 1280, int wndHeight = 720, string windowTitle = "Ants", int targetFamerate = 60)
        {
            var form = new RenderForm(windowTitle)
            {
                ClientSize = new System.Drawing.Size(wndWidth, wndHeight)
            };
            // 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.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport,
                                       new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 },
                                       desc, out var device, out var swapChain);

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

            int width  = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            var rectangleGeometry = new RoundedRectangleGeometry(d2dFactory,
                                                                 new RoundedRectangle()
            {
                RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, width - 128 * 2, height - 128 * 2)
            });

            // Ignore all windows events
            Factory factory = swapChain.GetParent <Factory>();

            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            var       renderView = new RenderTargetView(device, backBuffer);

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


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


            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            // Main loop
            RenderLoop.Run(form, () =>
            {
                d2dRenderTarget.BeginDraw();
                d2dRenderTarget.Clear(Color.Aqua);
                world.RenderLoop(stopwatch, d2dRenderTarget);
                d2dRenderTarget.EndDraw();
                swapChain.Present(0, PresentFlags.None);
            });

            // Release all resources
            renderView.Dispose();
            backBuffer.Dispose();
            device.ImmediateContext.ClearState();
            device.ImmediateContext.Flush();
            device.Dispose();
            device.Dispose();
            swapChain.Dispose();
            factory.Dispose();
        }
Example #36
0
        public bool Initialize(GameForm pForm, bool pFullScreen)
        {
            _form = pForm;
            try
            {
#if DEBUG
                Device defaultDevice = new Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);
                _debug = defaultDevice.QueryInterface <DeviceDebug>();
#else
                Device defaultDevice = new Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport);
#endif
                Device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();

                var dxgiDevice2  = Device.QueryInterface <SharpDX.DXGI.Device2>();
                var dxgiFactory2 = dxgiDevice2.Adapter.GetParent <SharpDX.DXGI.Factory2>();

                // SwapChain description
                var desc = new SwapChainDescription1()
                {
                    Width             = 0,
                    Height            = 0,
                    Format            = Format.B8G8R8A8_UNorm,
                    Stereo            = false,
                    SampleDescription = new SampleDescription(1, 0),
                    BufferCount       = BUFFER_COUNT,
                    Scaling           = Scaling.None,
                    SwapEffect        = SwapEffect.FlipSequential,
                    Usage             = Usage.RenderTargetOutput
                };

                _swapChain       = new SwapChain1(dxgiFactory2, Device, pForm.Handle, ref desc, null);
                _2dDevice        = new SharpDX.Direct2D1.Device(dxgiDevice2);
                Context          = new SharpDX.Direct2D1.DeviceContext(_2dDevice, DeviceContextOptions.EnableMultithreadedOptimizations);
                SecondaryContext = new SharpDX.Direct2D1.DeviceContext(_2dDevice, DeviceContextOptions.None);
#if DEBUG
                Factory2D = new SharpDX.Direct2D1.Factory(FactoryType.SingleThreaded, DebugLevel.Information);
#else
                Factory2D = new SharpDX.Direct2D1.Factory(FactoryType.SingleThreaded);
#endif
                var dpi  = Factory2D.DesktopDpi;
                var prop = new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), dpi.Height, dpi.Width, BitmapOptions.CannotDraw | BitmapOptions.Target);
                _backBuffer    = _swapChain.GetBackBuffer <Surface>(0);
                _renderTarget  = new Bitmap1(Context, _backBuffer, prop);
                Context.Target = _renderTarget;

                // Ignore all windows events
                using (Factory factory = _swapChain.GetParent <Factory>())
                {
                    factory.MakeWindowAssociation(pForm.Handle, WindowAssociationFlags.IgnoreAll);
                }

                FactoryDWrite = new SharpDX.DirectWrite.Factory();

                return(true);
            }
            catch (System.Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error creating render target: " + e.Message);
                return(false);
            }
        }
Example #37
0
        protected void Initialize()
        {
            apple = new Apple()
            {
                x = 3, y = 3
            };
            snake = new Snake()
            {
                x = 10, y = 10, dy = 1
            };

            rng = new Random();

            // SwapChain description
            var desc = new SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription =
                    new ModeDescription(form.ClientSize.Width, form.ClientSize.Height,
                                        new Rational(Constants.FRAMES_PER_SECOND, 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.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }, desc, out device, out swapChain);

            d2dFactory = new SharpDX.Direct2D1.Factory();

            int width  = form.ClientSize.Width;
            int height = form.ClientSize.Height;

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

            // New RenderTargetView from the backbuffer
            backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            renderView = new RenderTargetView(device, backBuffer);

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

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

            var rectangleGeometry = new RoundedRectangleGeometry(d2dFactory, new RoundedRectangle()
            {
                RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, width - 128 * 2, height - 128 * 2)
            });
            var solidColorBrush = new SolidColorBrush(d2dRenderTarget, Color.White);

            var directInput = new DirectInput();

            keyboard = new Keyboard(directInput);
            keyboard.Acquire();

            apple.Initialize(d2dRenderTarget, Color.Red);
            snake.Initialize(d2dRenderTarget, Color.Green);
        }