示例#1
0
 /// <summary>
 /// Function to assign the blend state to the batch state.
 /// </summary>
 /// <param name="blendState">The blend state to assign, or <b>null</b> for a default state.</param>
 /// <returns>The fluent builder interface.</returns>
 public Gorgon2DBatchStateBuilder BlendState(GorgonBlendStateBuilder blendState)
 {
     _worker.BlendState = blendState?.Build();
     return(this);
 }
示例#2
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();
            }
        }
示例#3
0
        /// <summary>
        /// Function to initialize the example.
        /// </summary>
        /// <returns>The main window for the application.</returns>
        private static FormMain Initialize()
        {
            GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation);
            GorgonExample.ShowStatistics        = false;

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

            try
            {
                // Create our primary graphics interface.
                IReadOnlyList <IGorgonVideoAdapterInfo> adapters = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log);

                if (adapters.Count == 0)
                {
                    throw new GorgonException(GorgonResult.CannotCreate, "This example requires a Direct3D 11.4 capable video card.\nThe application will now close.");
                }

                _graphics = new GorgonGraphics(adapters[0], log: GorgonApplication.Log);

                // Create our "screen".
                _screen = new GorgonSwapChain(_graphics, window, new GorgonSwapChainInfo("TheShadowGn0s Screen Swap chain")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                BuildRenderTargets(new DX.Size2(_screen.Width, _screen.Height));


                _backgroundTexture = GorgonTexture2DView.FromFile(_graphics,
                                                                  Path.Combine(GorgonExample.GetResourcePath(@"Textures\TheShadowGn0s\").FullName,
                                                                               "VBBack.jpg"),
                                                                  new GorgonCodecJpeg(),
                                                                  new GorgonTexture2DLoadOptions
                {
                    Name    = "Background Texture",
                    Binding = TextureBinding.ShaderResource,
                    Usage   = ResourceUsage.Immutable
                });

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

                _spriteTexture = GorgonTexture2DView.FromFile(_graphics,
                                                              Path.Combine(GorgonExample.GetResourcePath(@"Textures\TheShadowGn0s\").FullName,
                                                                           "0_HardVacuum.png"),
                                                              new GorgonCodecPng(),
                                                              new GorgonTexture2DLoadOptions
                {
                    Name    = "/Images/0_HardVacuum.png",
                    Binding = TextureBinding.ShaderResource,
                    Usage   = ResourceUsage.Immutable
                });

                var spriteCodec = new GorgonV2SpriteCodec(_renderer);
                _sprite1 = spriteCodec.FromFile(Path.Combine(GorgonExample.GetResourcePath(@"Sprites\TheShadowGn0s\").FullName, "Mother.gorSprite"));
                _sprite2 = spriteCodec.FromFile(Path.Combine(GorgonExample.GetResourcePath(@"Sprites\TheShadowGn0s\").FullName, "Mother2c.gorSprite"));

                _gaussBlur = new Gorgon2DGaussBlurEffect(_renderer, 9)
                {
                    BlurRenderTargetsSize = new DX.Size2(_screen.Width / 2, _screen.Height / 2)
                };

                var shadowBuilder = new ShadowBuilder(_renderer, _gaussBlur, _sprite1, _sprite2);
                (GorgonSprite[] shadowSprites, GorgonTexture2DView shadowTexture) = shadowBuilder.Build();
                _shadowSprites = shadowSprites;
                _shadowTexture = shadowTexture;

                var batchStateBuilder = new Gorgon2DBatchStateBuilder();
                var blendStateBuilder = new GorgonBlendStateBuilder();
                _rtvBlendState = batchStateBuilder
                                 .BlendState(blendStateBuilder
                                             .ResetTo(GorgonBlendState.Default)
                                             .DestinationBlend(alpha: Blend.InverseSourceAlpha))
                                 .Build();

                _sprite2.Position = new DX.Vector2((int)(_screen.Width / 2.0f), (int)(_screen.Height / 4.0f));
                _sprite1.Position = new DX.Vector2((int)(_screen.Width / 4.0f), (int)(_screen.Height / 5.0f));

                _bgSprite = _sprite2;
                _fgSprite = _sprite1;

                _screen.BeforeSwapChainResized += (sender, args) =>
                {
                    _blurTexture?.Dispose();
                    _blurTarget?.Dispose();
                    _layer1Texture?.Dispose();
                    _layer1Target?.Dispose();
                };

                window.MouseMove  += Window_MouseMove;
                window.MouseUp    += Window_MouseUp;
                window.MouseWheel += Window_MouseWheel;
                window.KeyUp      += Window_KeyUp;

                _screen.AfterSwapChainResized += (sender, args) => BuildRenderTargets(args.Size);

                GorgonExample.LoadResources(_graphics);

                _helpFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo("Segoe UI", 12.0f, FontHeightMode.Points, "Segoe UI 12pt Bold, Outlined")
                {
                    FontStyle     = FontStyle.Bold,
                    OutlineColor2 = GorgonColor.Black,
                    OutlineColor1 = GorgonColor.Black,
                    OutlineSize   = 2,
                    TextureWidth  = 512,
                    TextureHeight = 256
                });

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
示例#4
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), "Animation");

            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 Animation Example Swap Chain")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                _target = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo(_screen.RenderTargetView, "Video Target")
                {
                    Binding = TextureBinding.ShaderResource
                });
                _targetView = _target.GetShaderResourceView();
                _target.Clear(GorgonColor.CornFlowerBlue);

                // Load our textures.
                var gif = new GorgonCodecGif(decodingOptions: new GorgonGifDecodingOptions
                {
                    ReadAllFrames = true
                });

                // Find out how long to display each frame for.
                // We'll also convert it to milliseconds since GIF stores the delays as 1/100th of a second.
                _frameDelays = gif.GetFrameDelays(Path.Combine(GorgonExample.GetResourcePath(@"\Textures\Animation\").FullName, "metal.gif"))
                               .Select(item => item / 100.0f).ToArray();

                _metal = GorgonTexture2DView.FromFile(_graphics,
                                                      Path.Combine(GorgonExample.GetResourcePath(@"\Textures\Animation\").FullName, "metal.gif"),
                                                      gif,
                                                      new GorgonTexture2DLoadOptions
                {
                    Name    = @"Metal \m/",
                    Usage   = ResourceUsage.Immutable,
                    Binding = TextureBinding.ShaderResource
                });
                _trooper = GorgonTexture2DView.FromFile(_graphics,
                                                        Path.Combine(GorgonExample.GetResourcePath(@"\Textures\Animation\").FullName, "trooper.png"),
                                                        new GorgonCodecPng(),
                                                        new GorgonTexture2DLoadOptions
                {
                    Name    = "Trooper",
                    Usage   = ResourceUsage.Immutable,
                    Binding = TextureBinding.ShaderResource
                });

                GorgonExample.LoadResources(_graphics);

                _renderer       = new Gorgon2D(_graphics);
                _animatedSprite = new GorgonSprite
                {
                    Position = new DX.Vector2(_screen.Width / 2, _screen.Height / 2),
                    Size     = new DX.Size2F(_metal.Width, _metal.Height),
                    Anchor   = new DX.Vector2(0.5f, 0.5f)
                };

                MakeAn80sMusicVideo();

                // We need to set up a blend state so that the alpha in the render target doesn't get overwritten.
                var builder      = new Gorgon2DBatchStateBuilder();
                var blendBuilder = new GorgonBlendStateBuilder();
                _targetBatchState = builder.BlendState(blendBuilder
                                                       .ResetTo(GorgonBlendState.Default)
                                                       .DestinationBlend(alpha: Blend.DestinationAlpha)
                                                       .Build())
                                    .Build();

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
示例#5
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();
            }
        }