/// <summary>
        /// Function to create the resources for the preview window.
        /// </summary>
        private void CreateResources()
        {
            _swapChain = GraphicsContext.LeaseSwapPresenter(PanelDisplay);
            _renderer  = GraphicsContext.Renderer2D;
            _titleFont = GraphicsContext.FontFactory.GetFont(new GorgonFontInfo(Font.FontFamily.Name, 10.0f, FontHeightMode.Points, $"PreviewTitleFont")
            {
                OutlineSize   = 2,
                OutlineColor1 = GorgonColor.Black,
                OutlineColor2 = GorgonColor.Black,
                FontStyle     = Graphics.Fonts.FontStyle.Bold
            });

            _titleText = new GorgonTextSprite(_titleFont)
            {
                DrawMode   = TextDrawMode.OutlinedGlyphs,
                Alignment  = Gorgon.UI.Alignment.Center,
                LayoutArea = new DX.Size2F(_swapChain.Width, _swapChain.Height)
            };

            using (var stream = new MemoryStream(Resources.no_thumbnail_256x256))
            {
                _defaultTexture = GorgonTexture2DView.FromStream(GraphicsContext.Graphics, stream, new GorgonCodecDds(), options: new GorgonTexture2DLoadOptions
                {
                    Name    = "DefaultPreviewTexture",
                    Binding = TextureBinding.ShaderResource,
                    Usage   = ResourceUsage.Immutable
                });
            }
        }
Exemple #2
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        /// <returns>The main window for the application.</returns>
        private static FormMain Initialize()
        {
            GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation);

            FormMain window = GorgonExample.Initialize(new DX.Size2(Settings.Default.Resolution.Width, Settings.Default.Resolution.Height), "Fonts");

            try
            {
                IReadOnlyList <IGorgonVideoAdapterInfo> videoDevices = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log);

                if (videoDevices.Count == 0)
                {
                    throw new GorgonException(GorgonResult.CannotCreate,
                                              "Gorgon requires at least a Direct3D 11.4 capable video device.\nThere is no suitable device installed on the system.");
                }

                // Find the best video device.
                _graphics = new GorgonGraphics(videoDevices.OrderByDescending(item => item.FeatureSet).First());

                _screen = new GorgonSwapChain(_graphics,
                                              window,
                                              new GorgonSwapChainInfo("Gorgon2D Effects Example Swap Chain")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                // Tell the graphics API that we want to render to the "screen" swap chain.
                _graphics.SetRenderTarget(_screen.RenderTargetView);

                // Initialize the renderer so that we are able to draw stuff.
                _renderer = new Gorgon2D(_graphics);

                // Load our logo.
                GorgonExample.LoadResources(_graphics);

                // We need to create a font factory so we can create/load (and cache) fonts.
                _fontFactory = new GorgonFontFactory(_graphics);

                // Create our fonts.
                GenerateGorgonFonts(LoadTrueTypeFonts(window), window);

                // Build our text sprite.
                _text = new GorgonTextSprite(_fontFactory.DefaultFont, Resources.Lorem_Ipsum)
                {
                    LineSpace = 0
                };

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Exemple #3
0
        /// <summary>
        /// Function called to initialize the application.
        /// </summary>
        private void Initialize()
        {
            GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation);

            // Resize and center the screen.
            var screen = Screen.FromHandle(Handle);

            ClientSize = Settings.Default.Resolution;
            Location   = new Point(screen.Bounds.Left + (screen.WorkingArea.Width / 2) - (ClientSize.Width / 2),
                                   screen.Bounds.Top + (screen.WorkingArea.Height / 2) - (ClientSize.Height / 2));

            // Initialize our graphics.
            IReadOnlyList <IGorgonVideoAdapterInfo> videoAdapters = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log);

            if (videoAdapters.Count == 0)
            {
                throw new GorgonException(GorgonResult.CannotCreate,
                                          "Gorgon requires at least a Direct3D 11.4 capable video device.\nThere is no suitable device installed on the system.");
            }

            // Find the best video device.
            _graphics = new GorgonGraphics(videoAdapters.OrderByDescending(item => item.FeatureSet).First());

            // Build our "screen".
            _screen = new GorgonSwapChain(_graphics,
                                          this,
                                          new GorgonSwapChainInfo
            {
                Width  = ClientSize.Width,
                Height = ClientSize.Height,
                Format = BufferFormat.R8G8B8A8_UNorm
            });

            if (!Settings.Default.IsWindowed)
            {
                // Go full screen by using borderless windowed mode.
                _screen.EnterFullScreen();
            }

            // Build up our 2D renderer.
            _renderer = new Gorgon2D(_graphics);

            // Load in the logo texture from our resources.
            GorgonExample.LoadResources(_graphics);

            // Create fonts.
            _textFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo("GiGi", 24.0f, FontHeightMode.Points, "GiGi_24pt")
            {
                AntiAliasingMode = FontAntiAliasMode.AntiAlias,
                TextureWidth     = 512,
                TextureHeight    = 256
            });

            // Use the form font for this one.
            _helpFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo(Font.FontFamily.Name,
                                                                       Font.Size,
                                                                       Font.Unit == GraphicsUnit.Pixel ? FontHeightMode.Pixels : FontHeightMode.Points,
                                                                       "Form Font")
            {
                AntiAliasingMode = FontAntiAliasMode.AntiAlias,
                FontStyle        = FontStyle.Bold
            });

            // Create our file system and mount the resources.
            _fileSystem = new GorgonFileSystem(GorgonApplication.Log);
            _fileSystem.Mount(GorgonExample.GetResourcePath(@"FileSystems\FolderSystem").FullName);

            // In the previous versions of Gorgon, we used to load the image first, and then the sprites.
            // But in this version, we have an extension that will load the sprite textures for us.
            _sprites = new GorgonSprite[3];

            // The sprites are in the v2 format.
            IEnumerable <IGorgonSpriteCodec> v2Codec  = new[] { new GorgonV2SpriteCodec(_renderer) };
            IEnumerable <IGorgonImageCodec>  pngCodec = new[] { new GorgonCodecPng() };

            _sprites[0] = _fileSystem.LoadSpriteFromFileSystem(_renderer, "/Sprites/base.gorSprite", spriteCodecs: v2Codec, imageCodecs: pngCodec);
            _sprites[1] = _fileSystem.LoadSpriteFromFileSystem(_renderer, "/Sprites/Mother.gorSprite", spriteCodecs: v2Codec, imageCodecs: pngCodec);
            _sprites[2] = _fileSystem.LoadSpriteFromFileSystem(_renderer, "/Sprites/Mother2c.gorSprite", spriteCodecs: v2Codec, imageCodecs: pngCodec);

            // This is how you would get the sprites in v2 of Gorgon:

            /*_spriteImage = _graphics.Textures.FromMemory<GorgonTexture2D>("0_HardVacuum", LoadFile("/Images/0_HardVacuum.png"), new GorgonCodecPNG());
             *
             *      // Get the sprites.
             *      // The sprites in the file system are from version 1.0 of Gorgon.
             *      // This version is backwards compatible and can load any version
             *      // of the sprites produced by older versions of Gorgon.
             *      _sprites = new GorgonSprite[3];
             *      _sprites[0] = _renderer.Renderables.FromMemory<GorgonSprite>("Base", LoadFile("/Sprites/base.gorSprite"));
             *      _sprites[1] = _renderer.Renderables.FromMemory<GorgonSprite>("Mother", LoadFile("/Sprites/Mother.gorSprite"));
             *      _sprites[2] = _renderer.Renderables.FromMemory<GorgonSprite>("Mother2c", LoadFile("/Sprites/Mother2c.gorSprite"));
             */

            // Get poetry.
            _textPosition = new DX.Vector2(0, ClientSize.Height + _textFont.LineHeight);

            _poetry = new GorgonTextSprite(_textFont, Encoding.UTF8.GetString(LoadFile("/SomeText.txt")))
            {
                Position = _textPosition,
                Color    = Color.Black
            };

            // Set up help text.
            _helpText = new GorgonTextSprite(_helpFont, "F1 - Show/hide this help text.\nS - Show frame statistics.\nESC - Exit.")
            {
                Color    = Color.Blue,
                Position = new DX.Vector2(3, 3)
            };

            // Unlike the old example, we'll blend to render targets, ping-ponging back and forth, for a much better quality image and smoother transition.
            _blurEffect = new Gorgon2DGaussBlurEffect(_renderer, 3)
            {
                BlurRenderTargetsSize = new DX.Size2((int)_sprites[2].Size.Width * 2, (int)_sprites[2].Size.Height * 2),
                PreserveAlpha         = false
            };
            _blurEffect.Precache();

            _blurredTarget[0] = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo("Blurred RTV")
            {
                Width   = _blurEffect.BlurRenderTargetsSize.Width,
                Height  = _blurEffect.BlurRenderTargetsSize.Height,
                Binding = TextureBinding.ShaderResource,
                Format  = BufferFormat.R8G8B8A8_UNorm,
                Usage   = ResourceUsage.Default
            });
            _blurredTarget[1] = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, _blurredTarget[0]);
            _blurredImage[0]  = _blurredTarget[0].GetShaderResourceView();
            _blurredImage[1]  = _blurredTarget[1].GetShaderResourceView();

            GorgonApplication.IdleMethod = Idle;
        }
Exemple #4
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        private static async Task InitializeAsync(FormMain window)
        {
            try
            {
                GorgonExample.ResourceBaseDirectory   = new DirectoryInfo(Settings.Default.ResourceLocation);
                GorgonExample.PlugInLocationDirectory = new DirectoryInfo(Settings.Default.PlugInLocation);

                // Load our packed file system plug in.
                window.UpdateStatus("Loading plugins...");

                IGorgonPlugInService plugIns = await Task.Run(() =>
                {
                    _assemblyCache = new GorgonMefPlugInCache(GorgonApplication.Log);
                    _assemblyCache.LoadPlugInAssemblies(GorgonExample.GetPlugInPath().FullName, "Gorgon.FileSystem.GorPack.dll");
                    return(new GorgonMefPlugInService(_assemblyCache));
                });

                window.UpdateStatus("Initializing graphics...");

                // Retrieve the list of video adapters. We can do this on a background thread because there's no interaction between other threads and the
                // underlying D3D backend yet.
                IReadOnlyList <IGorgonVideoAdapterInfo> videoDevices = await Task.Run(() => GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log));

                if (videoDevices.Count == 0)
                {
                    throw new GorgonException(GorgonResult.CannotCreate,
                                              "Gorgon requires at least a Direct3D 11.4 capable video device.\nThere is no suitable device installed on the system.");
                }

                // Find the best video device.
                _graphics = new GorgonGraphics(videoDevices.OrderByDescending(item => item.FeatureSet).First());

                _screen = new GorgonSwapChain(_graphics,
                                              window,
                                              new GorgonSwapChainInfo("Gorgon2D Space Scene Example")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                // Create a secondary render target for our scene. We use 16 bit floating point for the effect fidelity.
                // We'll lock our resolution to 1920x1080 (pretty common resolution for most people).
                _mainRtv = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo("Main RTV")
                {
                    Width   = (int)_baseResolution.X,
                    Height  = (int)_baseResolution.Y,
                    Format  = BufferFormat.R16G16B16A16_Float,
                    Binding = TextureBinding.ShaderResource
                });
                _mainSrv       = _mainRtv.GetShaderResourceView();
                _mainRtvAspect = _mainRtv.Width < _mainRtv.Height ? new DX.Vector2(1, (float)_mainRtv.Height / _mainRtv.Width) : new DX.Vector2((float)_mainRtv.Width / _mainRtv.Height, 1);

                // Initialize the renderer so that we are able to draw stuff.
                _renderer = new Gorgon2D(_graphics);

                // Set up our raw input.
                _input           = new GorgonRawInput(window, GorgonApplication.Log);
                _keyboard        = new GorgonRawKeyboard();
                _keyboard.KeyUp += Keyboard_KeyUp;
                _input.RegisterDevice(_keyboard);

                GorgonExample.LoadResources(_graphics);

                // Now for the fun stuff, load our asset resources. We can load this data by mounting a directory (which I did while developing), or use a packed file.
                //
                // The resource manager will hold all the data we need for the scene. Including 3D meshes, post processing effects, etc...
                _resources = new ResourceManagement(_renderer, plugIns);
                _resources.Load(Path.Combine(GorgonExample.GetResourcePath(@"FileSystems").FullName, "SpaceScene.gorPack"));

                window.UpdateStatus("Loading resources...");
                await _resources.LoadResourcesAsync();

                SetupScene();

                // Build up a font to use for rendering any GUI text.
                _helpFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo("Segoe UI", 10.0f, FontHeightMode.Points, "Segoe UI 10pt")
                {
                    OutlineSize      = 2,
                    Characters       = (Resources.Instructions + "S:1234567890x").Distinct().ToArray(),
                    FontStyle        = FontStyle.Bold,
                    AntiAliasingMode = FontAntiAliasMode.AntiAlias,
                    OutlineColor1    = GorgonColor.Black,
                    OutlineColor2    = GorgonColor.Black
                });

                _textSprite = new GorgonTextSprite(_helpFont)
                {
                    Position = new DX.Vector2(0, 64),
                    DrawMode = TextDrawMode.OutlinedGlyphs,
                    Color    = GorgonColor.YellowPure
                };

                GorgonExample.ShowStatistics = true;

                // Set the idle here. We don't want to try and render until we're done loading.
                GorgonApplication.IdleMethod = Idle;
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Exemple #5
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Form.Load"></see> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                GorgonExample.PlugInLocationDirectory = new DirectoryInfo(Settings.Default.PlugInLocation);

                // Load the assembly.
                _assemblyCache = new GorgonMefPlugInCache(GorgonApplication.Log);

                // Create the plugin service.
                IGorgonPlugInService plugInService = new GorgonMefPlugInService(_assemblyCache);

                // Create the factory to retrieve gaming device drivers.
                var factory = new GorgonGamingDeviceDriverFactory(plugInService);

                // Create the raw input interface.
                _input = new GorgonRawInput(this, GorgonApplication.Log);

                // Get available gaming device driver plug ins.
                _assemblyCache.LoadPlugInAssemblies(GorgonExample.GetPlugInPath().FullName, "Gorgon.Input.DirectInput.dll");
                _assemblyCache.LoadPlugInAssemblies(GorgonExample.GetPlugInPath().FullName, "Gorgon.Input.XInput.dll");

                _drivers = factory.LoadAllDrivers();

                _joystickList = new List <IGorgonGamingDevice>();

                // Get all gaming devices from the drivers.
                foreach (IGorgonGamingDeviceDriver driver in _drivers)
                {
                    IReadOnlyList <IGorgonGamingDeviceInfo> infoList = driver.EnumerateGamingDevices(true);

                    foreach (IGorgonGamingDeviceInfo info in infoList)
                    {
                        IGorgonGamingDevice device = driver.CreateGamingDevice(info);

                        // Turn off dead zones for this example.
                        foreach (GorgonGamingDeviceAxis axis in device.Axis)
                        {
                            axis.DeadZone = GorgonRange.Empty;
                        }

                        _joystickList.Add(device);
                    }
                }

                // Create mouse.
                _mouse = new GorgonRawMouse();

                // Create the graphics interface.
                ClientSize = Settings.Default.Resolution;

                IReadOnlyList <IGorgonVideoAdapterInfo> adapters = GorgonGraphics.EnumerateAdapters();
                _graphics = new GorgonGraphics(adapters[0], log: GorgonApplication.Log);
                _screen   = new GorgonSwapChain(_graphics, this, new GorgonSwapChainInfo("INeedYourInput Swapchain")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });
                _graphics.SetRenderTarget(_screen.RenderTargetView);

                if (!Settings.Default.IsWindowed)
                {
                    _screen.EnterFullScreen();
                }

                // For the backup image. Used to make it as large as the monitor that we're on.
                var currentScreen = Screen.FromHandle(Handle);

                // Relocate the window to the center of the screen.
                Location = new Point(currentScreen.Bounds.Left + (currentScreen.WorkingArea.Width / 2) - (ClientSize.Width / 2),
                                     currentScreen.Bounds.Top + (currentScreen.WorkingArea.Height / 2) - (ClientSize.Height / 2));


                // Create the 2D renderer.
                _2D = new Gorgon2D(_graphics);

                // Create the text font.
                var fontFactory = new GorgonFontFactory(_graphics);
                _font = fontFactory.GetFont(new GorgonFontInfo("Arial", 9.0f, FontHeightMode.Points, "Arial 9pt")
                {
                    FontStyle        = FontStyle.Bold,
                    AntiAliasingMode = FontAntiAliasMode.AntiAlias
                });

                // Create text sprite.
                _messageSprite = new GorgonTextSprite(_font, "Using mouse and keyboard (Windows Forms).")
                {
                    Color = Color.Black
                };

                // Create a back buffer.
                _backBuffer = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo("Backbuffer storage")
                {
                    Width  = _screen.Width,
                    Height = _screen.Height,
                    Format = _screen.Format
                });
                _backBuffer.Clear(Color.White);
                _backBufferView = _backBuffer.GetShaderResourceView();

                // Clear our backup image to white to match our primary screen.
                using (IGorgonImage image = new GorgonImage(new GorgonImageInfo(ImageType.Image2D, _screen.Format)
                {
                    Width = _screen.Width,
                    Height = _screen.Height,
                    Format = _screen.Format
                }))
                {
                    image.Buffers[0].Fill(0xff);
                    _backupImage = image.ToTexture2D(_graphics,
                                                     new GorgonTexture2DLoadOptions
                    {
                        Binding = TextureBinding.None,
                        Usage   = ResourceUsage.Staging
                    });
                }

                // Set gorgon events.
                _screen.BeforeSwapChainResized += BeforeSwapChainResized;
                _screen.AfterSwapChainResized  += AfterSwapChainResized;

                // Enable the mouse.
                Cursor = Cursors.Cross;
                _mouse.MouseButtonDown += MouseInput;
                _mouse.MouseMove       += MouseInput;
                _mouse.MouseWheelMove  += (sender, args) =>
                {
                    _radius += args.WheelDelta.Sign();

                    if (_radius < 2.0f)
                    {
                        _radius = 2.0f;
                    }
                    if (_radius > 10.0f)
                    {
                        _radius = 10.0f;
                    }
                };

                // Set the mouse position.
                _mouse.Position = new Point(ClientSize.Width / 2, ClientSize.Height / 2);

                _noBlending = _blendBuilder.BlendState(GorgonBlendState.NoBlending)
                              .Build();
                _inverted = _blendBuilder.BlendState(GorgonBlendState.Inverted)
                            .Build();

                // Set up blending states for our pen.
                var blendStateBuilder = new GorgonBlendStateBuilder();
                _currentBlend = _drawModulatedBlend = _blendBuilder.BlendState(blendStateBuilder
                                                                               .ResetTo(GorgonBlendState.Default)
                                                                               .DestinationBlend(alpha: Blend.One)
                                                                               .Build())
                                                      .Build();

                _drawAdditiveBlend = _blendBuilder.BlendState(blendStateBuilder
                                                              .ResetTo(GorgonBlendState.Additive)
                                                              .DestinationBlend(alpha: Blend.One)
                                                              .Build())
                                     .Build();

                _drawNoBlend = _blendBuilder.BlendState(blendStateBuilder
                                                        .ResetTo(GorgonBlendState.NoBlending)
                                                        .DestinationBlend(alpha: Blend.One)
                                                        .Build())
                               .Build();

                GorgonApplication.IdleMethod = Gorgon_Idle;
            }
            catch (ReflectionTypeLoadException refEx)
            {
                string refErr = string.Join("\n", refEx.LoaderExceptions.Select(item => item.Message));
                GorgonDialogs.ErrorBox(this, refErr);
            }
            catch (Exception ex)
            {
                GorgonExample.HandleException(ex);
                GorgonApplication.Quit();
            }
        }
Exemple #6
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        private static void Initialize()
        {
            GorgonExample.ShowStatistics = false;
            _window = GorgonExample.Initialize(new DX.Size2(Settings.Default.Resolution.Width, Settings.Default.Resolution.Height), "Primitives");

            try
            {
                // Find out which devices we have installed in the system.
                IReadOnlyList <IGorgonVideoAdapterInfo> deviceList = GorgonGraphics.EnumerateAdapters();

                if (deviceList.Count == 0)
                {
                    throw new
                          NotSupportedException("There are no suitable video adapters available in the system. This example is unable to continue and will now exit.");
                }

                _graphics = new GorgonGraphics(deviceList[0]);
                _renderer = new SimpleRenderer(_graphics);

                _swapChain = new GorgonSwapChain(_graphics,
                                                 _window,
                                                 new GorgonSwapChainInfo("Swap")
                {
                    Width  = _window.ClientSize.Width,
                    Height = _window.ClientSize.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                BuildDepthBuffer(_swapChain.Width, _swapChain.Height);

                _graphics.SetRenderTarget(_swapChain.RenderTargetView, _depthBuffer);

                LoadShaders();

                LoadTextures();

                BuildLights();

                BuildMeshes();

                _renderer.Camera = _camera = new Camera
                {
                    Fov        = 75.0f,
                    ViewWidth  = _swapChain.Width,
                    ViewHeight = _swapChain.Height
                };

                _input    = new GI.GorgonRawInput(_window);
                _keyboard = new GI.GorgonRawKeyboard();

                _input.RegisterDevice(_keyboard);

                _keyboard.KeyDown  += Keyboard_KeyDown;
                _window.MouseDown  += Mouse_Down;
                _window.MouseWheel += Mouse_Wheel;

                _swapChain.BeforeSwapChainResized += (sender, args) =>
                {
                    _graphics.SetDepthStencil(null);
                };

                // When we resize, update the projection and viewport to match our client size.
                _swapChain.AfterSwapChainResized += (sender, args) =>
                {
                    _camera.ViewWidth  = args.Size.Width;
                    _camera.ViewHeight = args.Size.Height;

                    BuildDepthBuffer(args.Size.Width, args.Size.Height);

                    _graphics.SetDepthStencil(_depthBuffer);
                };

                _2DRenderer = new Gorgon2D(_graphics);

                GorgonExample.LoadResources(_graphics);

                // Create a font so we can render some text.
                _font = GorgonExample.Fonts.GetFont(new GorgonFontInfo("Segoe UI", 14.0f, FontHeightMode.Points, "Segoe UI 14pt")
                {
                    OutlineSize   = 2,
                    OutlineColor1 = GorgonColor.Black,
                    OutlineColor2 = GorgonColor.Black
                });

                _textSprite = new GorgonTextSprite(_font)
                {
                    DrawMode = TextDrawMode.OutlinedGlyphs
                };
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Exemple #7
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        private static void Initialize()
        {
            GorgonExample.ShowStatistics = false;

            _window = GorgonExample.Initialize(new DX.Size2(Settings.Default.ScreenWidth, Settings.Default.ScreenHeight), "Balls");

            try
            {
                // Create the graphics interface.
                IReadOnlyList <IGorgonVideoAdapterInfo> adapters = GorgonGraphics.EnumerateAdapters();

                if (adapters.Count == 0)
                {
                    throw new GorgonException(GorgonResult.CannotCreate,
                                              "Gorgon requires at least a Direct3D 11.4 capable video device.\nThere is no suitable device installed on the system.");
                }

                // Find the best video device.
                _graphics = new GorgonGraphics(adapters.OrderByDescending(item => item.FeatureSet).First());

                // Create the primary swap chain.
                _mainScreen = new GorgonSwapChain(_graphics,
                                                  _window,
                                                  new GorgonSwapChainInfo("Main Screen")
                {
                    Width  = Settings.Default.ScreenWidth,
                    Height = Settings.Default.ScreenHeight,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                // Center the display.
                if (_mainScreen.IsWindowed)
                {
                    _window.Location =
                        new Point((Screen.PrimaryScreen.Bounds.Width / 2) - (_window.Width / 2) + Screen.PrimaryScreen.Bounds.Left,
                                  (Screen.PrimaryScreen.Bounds.Height / 2) - (_window.Height / 2) + Screen.PrimaryScreen.Bounds.Top);
                }

                // Load the ball texture.
                _ballTexture = GorgonTexture2DView.FromFile(_graphics,
                                                            GetResourcePath(@"Textures\Balls\BallsTexture.dds"),
                                                            new GorgonCodecDds(),
                                                            new GorgonTexture2DLoadOptions
                {
                    Usage = ResourceUsage.Immutable,
                    Name  = "Ball Texture"
                });

                // Create the 2D interface.
                _2D = new Gorgon2D(_graphics);

                // Create the wall sprite.
                _wall = new GorgonSprite
                {
                    Size          = new DX.Size2F(63, 63),
                    Texture       = _ballTexture,
                    TextureRegion = new DX.RectangleF(0, 0, 0.5f, 0.5f)
                };

                // Create the ball sprite.
                _ball = new GorgonSprite
                {
                    Size          = new DX.Size2F(64, 64),
                    Texture       = _ballTexture,
                    TextureRegion = new DX.RectangleF(0, 0, 0.5f, 0.5f),
                    Anchor        = new DX.Vector2(0.5f, 0.5f)
                };

                // Create the ball render target.
                _ballTarget = GorgonRenderTarget2DView.CreateRenderTarget(_graphics,
                                                                          new GorgonTexture2DInfo("Ball Target")
                {
                    Width  = Settings.Default.ScreenWidth,
                    Height = Settings.Default.ScreenHeight,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });
                _ballTargetView = _ballTarget.GetShaderResourceView();

                // Create our blur effect.
                _blur = new Gorgon2DGaussBlurEffect(_2D, 15)
                {
                    BlurRenderTargetsSize = new DX.Size2(512, 512),
                    BlurRadius            = 0
                };

                _mainScreen.BeforeSwapChainResized += (sender, args) =>
                {
                    _ballTargetView.Dispose();
                    _ballTarget.Dispose();
                };

                // Ensure that our secondary camera gets updated.
                _mainScreen.AfterSwapChainResized += (sender, args) =>
                {
                    // Fix any objects caught outside of the main target.
                    for (int i = 0; i < _ballCount; i++)
                    {
                        _ballList[i].Position.X = _ballList[i].Position.X.Max(0).Min(args.Size.Width);
                        _ballList[i].Position.Y = _ballList[i].Position.Y.Max(0).Min(args.Size.Height);
                    }

                    _ballTarget = GorgonRenderTarget2DView.CreateRenderTarget(_graphics,
                                                                              new GorgonTexture2DInfo("Ball Target")
                    {
                        Width  = args.Size.Width,
                        Height = args.Size.Height,
                        Format = BufferFormat.R8G8B8A8_UNorm
                    });
                    _ballTargetView = _ballTarget.GetShaderResourceView();

                    DX.Size2 newTargetSize;
                    newTargetSize.Width =
                        (int)((512.0f * (args.Size.Width / (float)Settings.Default.ScreenWidth)).Min(512));
                    newTargetSize.Height =
                        (int)((512.0f * (args.Size.Height / (float)Settings.Default.ScreenHeight)).Min(512));

                    _blur.BlurRenderTargetsSize = newTargetSize;
                };

                // Generate the ball list.
                GenerateBalls(Settings.Default.BallCount);

                // Assign event handlers.
                _window.KeyDown += Form_KeyDown;

                var stateBuilder      = new Gorgon2DBatchStateBuilder();
                var blendStateBuilder = new GorgonBlendStateBuilder();

                _blurBlend = stateBuilder.BlendState(blendStateBuilder.ResetTo(GorgonBlendState.Default)
                                                     .SourceBlend(alpha: Blend.InverseDestinationAlpha)
                                                     .DestinationBlend(alpha: Blend.One)
                                                     .Build())
                             .Build();

                GorgonExample.LoadResources(_graphics);

                _ballFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo("Arial", 9.0f, FontHeightMode.Points, "Arial 9pt Bold")
                {
                    FontStyle     = FontStyle.Bold,
                    Characters    = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890()_.-+:\u2191\u2193",
                    OutlineSize   = 1,
                    OutlineColor1 = GorgonColor.Black,
                    OutlineColor2 = GorgonColor.Black
                });

                // Statistics text buffer.
                _fpsText = new StringBuilder(64);

                // Create statistics render target.
                _statsTexture = GorgonTexture2DView.CreateTexture(_graphics,
                                                                  new GorgonTexture2DInfo("Stats Render Target")
                {
                    Width = (int)_ballFont
                            .MeasureText(string.Format(Resources.FPSLine,
                                                       999999,
                                                       999999.999,
                                                       _ballCount,
                                                       9999),
                                         true).Width,
                    Height  = (int)((_ballFont.FontHeight * 4) + _ballFont.Descent),
                    Format  = BufferFormat.R8G8B8A8_UNorm,
                    Binding = TextureBinding.RenderTarget
                });

                using (GorgonRenderTarget2DView rtv = _statsTexture.Texture.GetRenderTargetView())
                {
                    // Draw our stats window frame.
                    rtv.Clear(new GorgonColor(0, 0, 0, 0.5f));
                    _graphics.SetRenderTarget(rtv);
                    _2D.Begin();
                    _2D.DrawRectangle(new DX.RectangleF(0, 0, rtv.Width, rtv.Height), new GorgonColor(0.86667f, 0.84314f, 0.7451f, 1.0f));
                    _2D.End();
                }

                _helpTextSprite = new GorgonTextSprite(_ballFont,
                                                       string.Format(Resources.HelpText,
                                                                     _graphics.VideoAdapter.Name,
                                                                     _graphics.VideoAdapter.FeatureSet,
                                                                     _graphics.VideoAdapter.Memory.Video.FormatMemory()))
                {
                    Color    = Color.Yellow,
                    Position = new DX.Vector2(3, (_statsTexture.Height + 8.0f).FastFloor()),
                    DrawMode = TextDrawMode.OutlinedGlyphs
                };

                // Set our main render target.
                _graphics.SetRenderTarget(_mainScreen.RenderTargetView);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }