/// <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(); } }
/// <summary> /// Function to generate the Gorgon bitmap fonts. /// </summary> /// <param name="fontFamilies">The list of TrueType font families to use.</param> /// <param name="window">The window that contains the loading message.</param> private static void GenerateGorgonFonts(IReadOnlyList <Drawing.FontFamily> fontFamilies, FormMain window) { // Pick a font to use with outlines. int fontWithOutlineIndex = GorgonRandom.RandomInt32(1, 5); _glowIndex = GorgonRandom.RandomInt32(fontWithOutlineIndex + 1, fontWithOutlineIndex + 5); int fontWithGradient = GorgonRandom.RandomInt32(_glowIndex + 1, _glowIndex + 5); int fontWithTexture = GorgonRandom.RandomInt32(fontWithGradient + 1, fontWithGradient + 5).Min(_fontFamilies.Count - 1); var pngCodec = new GorgonCodecPng(); using (IGorgonImage texture = pngCodec.LoadFromFile(Path.Combine(GorgonExample.GetResourcePath(@"Textures\Fonts\").FullName, "Gradient.png"))) { for (int i = 0; i < _fontFamilies.Count; ++i) { string fontFamily = _fontFamilies[i]; // Use this to determine if the font is avaiable. if (fontFamilies.All(item => !string.Equals(item.Name, fontFamily, StringComparison.InvariantCultureIgnoreCase))) { // Can't locate this one, move on... continue; } bool isExternal = Drawing.FontFamily.Families.All(item => !string.Equals(item.Name, fontFamily, StringComparison.InvariantCultureIgnoreCase)); string fontName; int outlineSize = 0; GorgonColor outlineColor1 = GorgonColor.BlackTransparent; GorgonColor outlineColor2 = GorgonColor.BlackTransparent; GorgonGlyphBrush brush = null; if (i == fontWithOutlineIndex) { fontName = $"{fontFamily} 32px Outlined{(isExternal ? " External TTF" : string.Empty)}"; outlineColor1 = GorgonColor.Black; outlineColor2 = GorgonColor.Black; outlineSize = 3; } else if (i == _glowIndex) { fontName = $"{fontFamily} 32px Outline as Glow{(isExternal ? " External TTF" : string.Empty)}"; outlineColor1 = new GorgonColor(GorgonColor.YellowPure, 1.0f); outlineColor2 = new GorgonColor(GorgonColor.DarkRed, 0.0f); outlineSize = 16; } else if (i == fontWithGradient) { fontName = $"{fontFamily} 32px Gradient{(isExternal ? " External TTF" : string.Empty)}"; brush = new GorgonGlyphLinearGradientBrush { StartColor = GorgonColor.White, EndColor = GorgonColor.Black, Angle = 45.0f }; } else if (i == fontWithTexture) { fontName = $"{fontFamily} 32px Textured{(isExternal ? " External TTF" : string.Empty)}"; brush = new GorgonGlyphTextureBrush(texture); } else { fontName = $"{fontFamily} 32px{(isExternal ? " External TTF" : string.Empty)}"; } window.UpdateStatus($"Generating Font: {fontFamily}".Ellipses(50)); var fontInfo = new GorgonFontInfo(fontFamily, 30.25f, name: fontName) { AntiAliasingMode = FontAntiAliasMode.AntiAlias, OutlineSize = outlineSize, OutlineColor1 = outlineColor1, OutlineColor2 = outlineColor2, UsePremultipliedTextures = false, Brush = brush }; _font.Add(GorgonExample.Fonts.GetFont(fontInfo)); // Texture brushes have to be disposed when we're done with them. var disposableBrush = brush as IDisposable; disposableBrush?.Dispose(); } } }
/// <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), "Lights"); 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 }); _screen.BeforeSwapChainResized += Screen_BeforeSwapChainResized; _screen.AfterSwapChainResized += Screen_AfterSwapChainResized; // Tell the graphics API that we want to render to the "screen" swap chain. _graphics.SetRenderTarget(_screen.RenderTargetView); // Load in our texture for our logo background. _backgroundLogoTexture = GorgonTexture2DView.FromFile(_graphics, Path.Combine(GorgonExample.GetResourcePath(@"Textures\Lights\").FullName, "lights.dds"), new GorgonCodecDds(), new GorgonTexture2DLoadOptions { Usage = ResourceUsage.Immutable, Binding = TextureBinding.ShaderResource, Name = "Logo" }); _torchTexture = GorgonTexture2DView.FromFile(_graphics, Path.Combine(GorgonExample.GetResourcePath(@"Textures\Lights\").FullName, "Torch.png"), new GorgonCodecPng(), new GorgonTexture2DLoadOptions { Usage = ResourceUsage.Immutable, Binding = TextureBinding.ShaderResource, Name = "Torch" }); UpdateRenderTarget(); // Initialize the renderer so that we are able to draw stuff. _renderer = new Gorgon2D(_graphics); _logoSprite = new GorgonSprite { Texture = _backgroundLogoTexture, Bounds = new DX.RectangleF(0, 0, _backgroundLogoTexture.Width, _backgroundLogoTexture.Height), TextureRegion = new DX.RectangleF(0, 0, 1, 1), Anchor = new DX.Vector2(0.5f, 0.5f) }; _torchSprite = new GorgonSprite { Texture = _torchTexture, Bounds = new DX.RectangleF(0, 0, 55, _torchTexture.Height), TextureRegion = _torchTexture.Texture.ToTexel(new DX.Rectangle(0, 0, 55, _torchTexture.Height)), }; // Create the effect that will light up our sprite(s). _lightEffect = new Gorgon2DDeferredLightingEffect(_renderer); _lightEffect.Lights.Add(new Gorgon2DLight { Color = new GorgonColor(0.25f, 0.25f, 0.25f), Attenuation = 75, LightType = LightType.Point, SpecularEnabled = true, SpecularPower = 6.0f, Position = new DX.Vector3((_screen.Width / 2.0f) - 150.0f, (_screen.Height / 2.0f) - 150.0f, -50) }); _lightEffect.Lights.Add(new Gorgon2DLight { Color = GorgonColor.White, Intensity = 0.075f, LightType = LightType.Directional, SpecularEnabled = false, Position = new DX.Vector3(0, 0, -200), LightDirection = new DX.Vector3(0, 0, 1) }); GorgonExample.LoadResources(_graphics); window.MouseMove += Window_MouseMove; window.KeyDown += Window_KeyDown; _torchFrameTime = new GorgonTimerQpc(); return(window); } finally { GorgonExample.EndInit(); } }
/// <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), "Effects"); 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 }); _screen.BeforeSwapChainResized += Screen_BeforeSwapChainResized; _screen.AfterSwapChainResized += Screen_AfterSwapChainResized; // 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); // Create the displacement effect used for the "cloaking" effect. _displacement = new Gorgon2DDisplacementEffect(_renderer) { Strength = 0 }; // Create the old film effect for that old timey look. _oldFilm = new Gorgon2DOldFilmEffect(_renderer) { ScrollSpeed = 0.05f }; // Create the gaussian blur effect for that "soft" look. _gaussBlur = new Gorgon2DGaussBlurEffect(_renderer, 9) { BlurRenderTargetsSize = new DX.Size2(_screen.Width / 2, _screen.Height / 2), BlurRadius = 1 }; // The higher # of taps on the blur shader will introduce a stutter on first render, so precache its setup data. _gaussBlur.Precache(); // Load our texture with our space background in it. _background = GorgonTexture2DView.FromFile(_graphics, Path.Combine(GorgonExample.GetResourcePath(@"Textures\").FullName, "HotPocket.dds"), new GorgonCodecDds(), new GorgonTexture2DLoadOptions { Usage = ResourceUsage.Immutable, Binding = TextureBinding.ShaderResource }); // Load up our super space ship image. _spaceShipTexture = GorgonTexture2DView.FromFile(_graphics, Path.Combine(GorgonExample.GetResourcePath(@"Textures\Effects\").FullName, "ship.png"), new GorgonCodecPng(), new GorgonTexture2DLoadOptions { Usage = ResourceUsage.Immutable, Binding = TextureBinding.ShaderResource }); _shipSprite = new GorgonSprite { Texture = _spaceShipTexture, TextureRegion = new DX.RectangleF(0, 0, 1, 1), Anchor = new DX.Vector2(0.5f, 0.5f), Position = new DX.Vector2(_screen.Width / 2.0f, _screen.Height / 2.0f), Size = new DX.Size2F(_spaceShipTexture.Width, _spaceShipTexture.Height) }; BuildRenderTargets(); InitializeBackgroundTexturePositioning(); GorgonExample.LoadResources(_graphics); window.MouseMove += Window_MouseMove; window.MouseWheel += Window_MouseWheel; window.KeyUp += Window_KeyUp; return(window); } finally { GorgonExample.EndInit(); } }
/// <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); _fontFactory = new GorgonFontFactory(_graphics); _helpFont = _fontFactory.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 }); _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); return(window); } finally { GorgonExample.EndInit(); } }
/// <summary> /// Function to initialize the application. /// </summary> /// <returns>The main window.</returns> private static FormMain Initialize() { // Create our form and center on the primary monitor. FormMain window = GorgonExample.Initialize(new DX.Size2(1280, 800), "Gorgon MiniTri"); try { // First we create and enumerate the list of video devices installed in the computer. // We must do this in order to tell Gorgon which video device we intend to use. Note that this method may be quite slow (particularly when running DEBUG versions of // Direct 3D). To counter this, this object and its Enumerate method are thread safe so this can be run in the background while keeping the main UI responsive. // Find out which devices we have installed in the system. // If no suitable device was found (no Direct 3D 12.0 support) in the computer, this method will throw an exception. However, if it succeeds, then the devices object // will be populated with the IGorgonVideoDeviceInfo for each video device in the system. // // Using this method, we could also enumerate the software rasterizer. These devices are typically used to determine if there's a driver error, and can be terribly slow to render // It is recommended that these only be used in diagnostic scenarios only. 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."); } // Now we create the main graphics interface with the first applicable video device. _graphics = new GorgonGraphics(deviceList[0]); // Check to ensure that we can support the format required for our swap chain. // If a video device can't support this format, then the odds are good it won't render anything. Since we're asking for a very common display format, this will // succeed nearly 100% of the time (unless you've somehow gotten an ancient video device to work with Direct 3D 11.1). Regardless, it's good form to the check for a // working display format prior to setting up the swap chain. // // This method is also used to determine if a format can be used for other objects (e.g. a texture, render target, etc...) Like the swap chain format, this is also a // best practice to check if the object you're creating supports the desired format. if ((_graphics.FormatSupport[BufferFormat.R8G8B8A8_UNorm].FormatSupport & BufferFormatSupport.Display) != BufferFormatSupport.Display) { // We should never see this unless you've performed some form of black magic. GorgonDialogs.ErrorBox(window, "We should not see this error."); return(window); } // Finally, create a swap chain to display our output. // In this case we're setting up our swap chain to bind with our main window, and we use its client size to determine the width/height of the swap chain back buffers. // This width/height does not need to be the same size as the window, but, except for some scenarios, that would produce undesirable image quality. _swap = new GorgonSwapChain(_graphics, window, new GorgonSwapChainInfo("Main Swap Chain") { Format = BufferFormat.R8G8B8A8_UNorm, Width = window.ClientSize.Width, Height = window.ClientSize.Height }) { DoNotAutoResizeBackBuffer = true }; // Create the shaders used to render the triangle. // These shaders provide transformation and coloring for the output pixel data. CreateShaders(); // Set up our input layout. // // We'll be using this to describe to Direct 3D how the elements of a vertex is laid out in memory. // In order to provide synchronization between the layout on the CPU side and the GPU side, we have to pass the vertex shader because it will contain the vertex // layout to match with our C# input layout. _inputLayout = GorgonInputLayout.CreateUsingType <MiniTriVertex>(_graphics, _vertexShader); // Set up the triangle vertices. CreateVertexBuffer(); // Set up the constant buffer. // // This is used (but could be used for more) to transform the vertex data from 3D space into 2D space. CreateConstantBuffer(window); // This defines where to send the pixel data when rendering. For now, this goes to our swap chain. _graphics.SetRenderTarget(_swap.RenderTargetView); // Create our draw call. // // This will pass all the necessary information to the GPU to render the triangle // // Since draw calls are immutable objects, we use builders to create them (and any pipeline state). Once a draw // call is built, it cannot be changed (except for the vertex, and if applicable, index, and instance ranges). // // Builders work on a fluent interface. Much like LINQ and can be used to create multiple draw calls from the same // builder. var drawCallBuilder = new GorgonDrawCallBuilder(); var pipelineStateBuilder = new GorgonPipelineStateBuilder(_graphics); _drawCall = drawCallBuilder.VertexBuffer(_inputLayout, _vertexBuffer) .VertexRange(0, 3) .ConstantBuffer(ShaderType.Vertex, _constantBuffer) .PipelineState(pipelineStateBuilder .PixelShader(_pixelShader) .VertexShader(_vertexShader) .RasterState(GorgonRasterState.NoCulling)) .Build(); GorgonExample.LoadResources(_graphics); return(window); } finally { GorgonExample.EndInit(); } }
/// <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); }; // Create a font so we can render some text. _fontFactory = new GorgonFontFactory(_graphics); _font = _fontFactory.GetFont(new GorgonFontInfo("Segoe UI", 14.0f, FontHeightMode.Points, "Segoe UI 14pt") { OutlineSize = 2, OutlineColor1 = GorgonColor.Black, OutlineColor2 = GorgonColor.Black }); _2DRenderer = new Gorgon2D(_graphics); _textSprite = new GorgonTextSprite(_font) { DrawMode = TextDrawMode.OutlinedGlyphs }; GorgonExample.LoadResources(_graphics); } finally { GorgonExample.EndInit(); } }
/// <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); GorgonExample.PlugInLocationDirectory = new DirectoryInfo(Settings.Default.PlugInLocation); FormMain window = GorgonExample.Initialize(new DX.Size2(Settings.Default.Resolution.Width, Settings.Default.Resolution.Height), "Depth"); 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 Depth Buffer Example") { Width = Settings.Default.Resolution.Width, Height = Settings.Default.Resolution.Height, Format = BufferFormat.R8G8B8A8_UNorm }); _depthBuffer = GorgonDepthStencil2DView.CreateDepthStencil(_graphics, new GorgonTexture2DInfo(_screen.RenderTargetView) { Binding = TextureBinding.DepthStencil, Format = BufferFormat.D24_UNorm_S8_UInt }); // Tell the graphics API that we want to render to the "screen" swap chain. _graphics.SetRenderTarget(_screen.RenderTargetView, _depthBuffer); // Initialize the renderer so that we are able to draw stuff. _renderer = new Gorgon2D(_graphics); GorgonExample.LoadResources(_graphics); // Load our packed file system plug in. _assemblyCache = new GorgonMefPlugInCache(GorgonApplication.Log); _assemblyCache.LoadPlugInAssemblies(GorgonExample.GetPlugInPath().FullName, "Gorgon.FileSystem.GorPack.dll"); IGorgonPlugInService plugIns = new GorgonMefPlugInService(_assemblyCache); // Load the file system containing our application data (sprites, images, etc...) IGorgonFileSystemProviderFactory providerFactory = new GorgonFileSystemProviderFactory(plugIns, GorgonApplication.Log); IGorgonFileSystemProvider provider = providerFactory.CreateProvider("Gorgon.IO.GorPack.GorPackProvider"); IGorgonFileSystem fileSystem = new GorgonFileSystem(provider, GorgonApplication.Log); // We can load the editor file system directly. // This is handy for switching a production environment where your data may be stored // as a compressed file, and a development environment where your data consists of loose // files. // fileSystem.Mount(@"D:\unpak\scratch\DeepAsAPuddle.gorPack\fs\"); // For now though, we'll load the packed file. fileSystem.Mount(Path.Combine(GorgonExample.GetResourcePath(@"FileSystems").FullName, "Depth.gorPack")); // Get our sprites. These make up the frames of animation for our Guy. // If and when there's an animation editor, we'll only need to create a single sprite and load the animation. IGorgonVirtualFile[] spriteFiles = fileSystem.FindFiles("/Sprites/", "*", true).ToArray(); // Load our sprite data (any associated textures will be loaded as well). Dictionary <string, GorgonSprite> sprites = new Dictionary <string, GorgonSprite>(StringComparer.OrdinalIgnoreCase); for (int i = 0; i < spriteFiles.Length; i++) { IGorgonVirtualFile file = spriteFiles[i]; (GorgonSprite sprite, GorgonTexture2D texture) = fileSystem.LoadSprite(_renderer, file.FullPath); // The LoadSprite extension method will automatically find and load your associated texture if you're using // a Gorgon editor file system. So it's important that you leep track of your textures, disposing of just // the associated GorgonTexture2DView won't cut it here, so you'll need to dispose the actual texture resource // when you're done with it. if (!_textures.Contains(texture)) { _textures.Add(texture); } // At super duper resolution, the example graphics would be really hard to see, so we'll scale them up. sprite.Scale = new DX.Vector2((_screen.Width / (_screen.Height / 2)) * 2.0f); sprites[file.Name] = sprite; } _snowTile = sprites["Snow"]; _snowTile.Depth = 0.5f; _icicle = sprites["Icicle"]; _icicle.Depth = 0.2f; _guySprite = sprites["Guy_Up_0"]; _guySprite.Depth = 0.1f; _guyPosition = new DX.Vector2(_screen.Width / 2 + _guySprite.ScaledSize.Width * 1.25f, _screen.Height / 2 + _guySprite.ScaledSize.Height); BuildAnimations(sprites); } finally { GorgonExample.EndInit(); } return(window); }