/// <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 }); } }
/// <summary> /// Function to set up the renderer. /// </summary> /// <param name="renderer">Renderer to use.</param> public void SetupRenderer(Gorgon2D renderer) { if (DesignMode) { return; } try { Gorgon.ApplicationIdleLoopMethod = null; if (_renderer != renderer) { CleanUpRenderer(); } if (renderer == null) { return; } _renderer = renderer; _graphics = renderer.Graphics; if (_swapChain == null) { _swapChain = _graphics.Output.CreateSwapChain("ImageDisplay", new GorgonSwapChainSettings { Window = panelTextureDisplay, Format = BufferFormat.R8G8B8A8_UIntNormal }); } if (_lastState == null) { _lastState = renderer.Begin2D(); } if (_defaultTexture == null) { _defaultTexture = _graphics.Textures.CreateTexture <GorgonTexture2D>("DefaultPattern", Resources.Pattern); } if (_clipper == null) { InitializeClipper(null, RectangleF.Empty); } _region = new RectangleF(0, 0, 1, 1); _renderer.Target = _swapChain; Gorgon.ApplicationIdleLoopMethod = Idle; } finally { ValidateCommands(); } }
public void TestInitialize() { _form = new TestForm(); _graphics = new GorgonGraphics(); _renderer = _graphics.Output.Create2DRenderer(_form.panelDisplay); _screen = (GorgonSwapChain)_renderer.DefaultTarget; }
/// <summary> /// Function to return a leased out swap chain. /// </summary> /// <param name="swapChain">The swap chain to return.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="swapChain"/> parameter is <b>null</b>.</exception> public void ReturnSwapPresenter(ref GorgonSwapChain swapChain) { if (swapChain == null) { throw new ArgumentNullException(nameof(swapChain)); } // This swap chain does not exist. if (swapChain.Window.IsDisposed) { return; } // This swap chain is not cached here, so do nothing. if (!_swapChainLeases.TryGetValue(swapChain.Window.Name, out WeakReference <GorgonSwapChain> cachedSwap)) { return; } if (!cachedSwap.TryGetTarget(out swapChain)) { return; } _swapChainLeases.Remove(swapChain.Window.Name); swapChain.Dispose(); }
/// <summary> /// Function to initialize the application. /// </summary> private static void Initialize() { // Create our form and center on the primary monitor. _mainForm = new formMain { ClientSize = new Size(640, 480), }; _mainForm.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width / 2 - _mainForm.Width / 2, Screen.PrimaryScreen.WorkingArea.Height / 2 - _mainForm.Height / 2); // Create the main graphics interface for SM 4.0. // This is basically a Direct 3D 10 capable video device. This is here to illustrate how to // force a feature level. Graphics = new GorgonGraphics(DeviceFeatureLevel.SM4); // 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, and thus // this is here for illustration on how to determine if a format is OK for display purposes. if (!Graphics.VideoDevice.SupportsDisplayFormat(BufferFormat.R8G8B8A8_UIntNormal)) { GorgonDialogs.ErrorBox(_mainForm, "We should not see this error."); return; } // Create a swap chain as our graphics output to the window. _swap = Graphics.Output.CreateSwapChain("Main", new GorgonSwapChainSettings { Window = _mainForm, // Assign to our form. }); }
/// <summary> /// Function called when the content is being initialized. /// </summary> /// <returns> /// A control to place in the primary interface window. /// </returns> protected override ContentPanel OnInitialize() { _panel = new PanelSpriteEditor(this); _swap = Graphics.Output.CreateSwapChain("SpriteEditorSwap", new GorgonSwapChainSettings { Window = _panel.panelSprite, Format = BufferFormat.R8G8B8A8_UIntNormal }); Renderer = Graphics.Output.Create2DRenderer(_swap); BackgroundTexture = Graphics.Textures.CreateTexture <GorgonTexture2D>("BackgroundTexture", Resources.Pattern); if ((_settings == null) || (!_settings.CreateContent)) { return(_panel); } Sprite = Renderer.Renderables.CreateSprite(Name, _settings.Settings); var dependency = new Dependency(_settings.TextureDependency.EditorFile, TextureDependencyType); // Build the texture dependency. Dependencies.Add(dependency); Dependencies.CacheDependencyObject(dependency.EditorFile, dependency.Type, Sprite.Texture); InitSprite(); return(_panel); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); Visible = true; ClientSize = new Size(1280, 720); _graphics = new GorgonGraphics(); _swap = _graphics.Output.CreateSwapChain("Swap", new GorgonSwapChainSettings { BufferCount = 2, IsWindowed = true, Format = BufferFormat.R8G8B8A8_UIntNormal, Width = 1280, Height = 720, Window = this }); _font = _graphics.Fonts.CreateFont("FontTest", new GorgonFontSettings { FontFamilyName = "Segoe UI", FontHeightMode = FontHeightMode.Pixels, Size = 12.0f }); _2d = _graphics.Output.Create2DRenderer(_swap); _2d.Begin2D(); Gorgon.ApplicationIdleLoopMethod = Idle; }
/// <summary> /// Function to initialize the content editor. /// </summary> /// <returns> /// A control to place in the primary interface window. /// </returns> protected override ContentPanel OnInitialize() { _panel = new GorgonFontContentPanel(this, GetRawInput()); _swap = Graphics.Output.CreateSwapChain("FontEditor.SwapChain", new GorgonSwapChainSettings { Window = _panel.panelTextures, Format = BufferFormat.R8G8B8A8_UIntNormal }); Renderer = Graphics.Output.Create2DRenderer(_swap); _textDisplay = Graphics.Output.CreateSwapChain("FontEditor.TextDisplay", new GorgonSwapChainSettings { Window = _panel.panelText, Format = BufferFormat.R8G8B8A8_UIntNormal }); // If the font needs to be created, do so now. if (_createFont) { Font = Graphics.Fonts.CreateFont(Name, _settings); _settings = Font.Settings.Clone(); } _panel.CreateResources(); CurrentState = DrawState.DrawFontTextures; return(_panel); }
/// <summary> /// Function to clean up the renderer objects. /// </summary> private void CleanUpRenderer() { if (_renderer == null) { return; } if (_lastState != null) { _renderer.End2D(_lastState); _lastState = null; } if (_texture != null) { _texture.Dispose(); _texture = null; } if (_defaultTexture != null) { _defaultTexture.Dispose(); _defaultTexture = null; } if (_swapChain != null) { _swapChain.Dispose(); _swapChain = null; } _clipper = null; _graphics = null; }
/// <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); GorgonExample.ShowStatistics = false; Cursor.Current = Cursors.WaitCursor; try { Show(); Application.DoEvents(); // Initialize Gorgon // Set it up so that we won't be rendering in the background, but allow the screensaver to activate. IReadOnlyList <IGorgonVideoAdapterInfo> adapters = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log); if (adapters.Count == 0) { throw new GorgonException(GorgonResult.CannotCreate, "No suitable video adapter found in the system.\nGorgon requires a minimum of a Direct3D 11.4 capable video device."); } _graphics = new GorgonGraphics(adapters[0]); // Set the video mode. ClientSize = new Size(640, 400); _screen = new GorgonSwapChain(_graphics, this, new GorgonSwapChainInfo("FunWithShapes SwapChain") { Width = ClientSize.Width, Height = ClientSize.Height, Format = BufferFormat.R8G8B8A8_UNorm }); _screen.AfterSwapChainResized += Screen_AfterSwapChainResized; _graphics.SetRenderTarget(_screen.RenderTargetView); _halfSize = new DX.Size2F(_screen.Width / 2.0f, _screen.Height / 2.0f); // Create our 2D renderer so we can draw stuff. _renderer = new Gorgon2D(_graphics); LabelPleaseWait.Visible = false; GorgonExample.LoadResources(_graphics); // Draw the image. DrawAPrettyPicture(); } catch (Exception ex) { GorgonExample.HandleException(ex); GorgonApplication.Quit(); } finally { Cursor.Current = Cursors.Default; } }
/// <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(); } }
/// <summary>Initializes a new instance of the <see cref="T:Gorgon.Editor.SpriteEditor.SpriteContentRenderer"/> class.</summary> /// <param name="sprite">The sprite view model.</param> /// <param name="graphics">The graphics interface for the application.</param> /// <param name="swapChain">The swap chain for the render area.</param> /// <param name="renderer">The 2D renderer for the application.</param> /// <param name="rectClipper">The rectangle clipper used to clip out sprite data.</param> /// <param name="initialZoom">The initial zoom scale value.</param> public SpriteClipRenderer(ISpriteContent sprite, GorgonGraphics graphics, GorgonSwapChain swapChain, Gorgon2D renderer, IRectClipperService rectClipper, float initialZoom) : base(sprite, graphics, swapChain, renderer, initialZoom) { _clipper = rectClipper; _clipper.RectToClient = r => ToClient(r).Truncate(); _clipper.PointFromClient = p => FromClient(p).Truncate(); _clipper.KeyboardIconClicked += Clipper_KeyboardIconClicked; _clipper.RectChanged += Clipper_RectChanged; }
/// <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), "Polygonal Sprites"); 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); _texture = GorgonTexture2DView.FromFile(_graphics, GetResourcePath(@"Textures\PolySprites\Ship.png"), new GorgonCodecPng(), new GorgonTexture2DLoadOptions { Binding = TextureBinding.ShaderResource, Name = "Ship Texture", Usage = ResourceUsage.Immutable }); GorgonExample.LoadResources(_graphics); CreateSprites(); return(window); } finally { GorgonExample.EndInit(); } }
/// <summary>Initializes a new instance of the <see cref="T:Gorgon.Editor.SpriteEditor.SpriteContentRenderer"/> class.</summary> /// <param name="sprite">The sprite view model.</param> /// <param name="graphics">The graphics interface for the application.</param> /// <param name="swapChain">The swap chain for the render area.</param> /// <param name="renderer">The 2D renderer for the application.</param> /// <param name="pickClipper">The sprite picker used to automatically clip sprite data.</param> /// <param name="ants">The marching ants rectangle used to draw selection rectangles.</param> /// <param name="initialZoom">The initial zoom value.</param> public SpritePickRenderer(ISpriteContent sprite, GorgonGraphics graphics, GorgonSwapChain swapChain, Gorgon2D renderer, IPickClipperService pickClipper, IMarchingAnts ants, float initialZoom) : base(sprite, graphics, swapChain, renderer, initialZoom) { _marchAnts = ants; _picker = pickClipper; _picker.PointFromClient = p => { DX.Vector2 pos = FromClient(p); return(new DX.Vector2((int)pos.X, (int)pos.Y)); }; }
/// <summary>Function called during resource creation.</summary> /// <param name="context">The current application graphics context.</param> /// <param name="swapChain">The swap chain for presenting the rendered data.</param> protected override void OnCreateResources(IGraphicsContext context, GorgonSwapChain swapChain) { _axisFont = context.FontFactory.GetFont(new GorgonFontInfo("Segoe UI", 12, FontHeightMode.Points, "Segoe UI Bold 12pt - Axis Font") { OutlineColor1 = GorgonColor.Black, OutlineColor2 = GorgonColor.Black, OutlineSize = 3, FontStyle = FontStyle.Bold }); _selectionRect = new MarchingAnts(context.Renderer2D); }
/// <summary> /// Initializes a new instance of the <see cref="Gorgon2DTarget"/> struct. /// </summary> /// <param name="target">The target.</param> /// <param name="depthStencil">The depth/stencil view.</param> public Gorgon2DTarget(GorgonRenderTargetView target, GorgonDepthStencilView depthStencil) { Target = target; DepthStencil = null; SwapChain = null; Height = 1; switch (target.Resource.ResourceType) { case ResourceType.Buffer: var buffer = (GorgonBuffer)target.Resource; var info = GorgonBufferFormatInfo.GetInfo(buffer.Settings.DefaultShaderViewFormat); Width = buffer.SizeInBytes / info.SizeInBytes; Viewport = new GorgonViewport(0, 0, Width, Height, 0, 1.0f); break; case ResourceType.Texture1D: var target1D = (GorgonRenderTarget1D)target.Resource; Width = target1D.Settings.Width; Viewport = target1D.Viewport; DepthStencil = depthStencil ?? target1D.DepthStencilBuffer; break; case ResourceType.Texture2D: var target2D = (GorgonRenderTarget2D)target.Resource; Width = target2D.Settings.Width; Height = target2D.Settings.Height; Viewport = target2D.Viewport; if (target2D.IsSwapChain) { SwapChain = (GorgonSwapChain)target2D; } DepthStencil = depthStencil ?? target2D.DepthStencilBuffer; break; case ResourceType.Texture3D: var target3D = (GorgonRenderTarget3D)target.Resource; Width = target3D.Settings.Width; Height = target3D.Settings.Height; Viewport = target3D.Viewport; break; default: throw new GorgonException(GorgonResult.CannotBind, "Could not bind a render target. Resource type is unknown. Should not see this error."); } }
/// <summary> /// Raises the <see cref="E:System.Windows.Forms.Form.FormClosing"></see> event. /// </summary> /// <param name="e">A <see cref="T:System.Windows.Forms.FormClosingEventArgs"></see> that contains the event data.</param> protected override void OnFormClosing(FormClosingEventArgs e) { base.OnFormClosing(e); GorgonExample.UnloadResources(); // Perform clean up. Gorgon2D renderer = Interlocked.Exchange(ref _renderer, null); GorgonSwapChain screen = Interlocked.Exchange(ref _screen, null); GorgonGraphics graphics = Interlocked.Exchange(ref _graphics, null); renderer?.Dispose(); screen?.Dispose(); graphics?.Dispose(); }
/// <summary>Initializes a new instance of the <see cref="T:Gorgon.Editor.SpriteEditor.SpriteContentRenderer"/> class.</summary> /// <param name="sprite">The sprite view model.</param> /// <param name="graphics">The graphics interface for the application.</param> /// <param name="swapChain">The swap chain for the render area.</param> /// <param name="renderer">The 2D renderer for the application.</param> /// <param name="anchorEditor">The editor for the anchor position.</param> /// <param name="initialZoom">The initial zoom scale value.</param> public SpriteAnchorRenderer(ISpriteContent sprite, GorgonGraphics graphics, GorgonSwapChain swapChain, Gorgon2D renderer, IAnchorEditService anchorEditor, float initialZoom) : base(sprite, graphics, swapChain, renderer, initialZoom) { _anchorEdit = anchorEditor; _anchorEdit.PointToClient = r => ToClient(r); _anchorEdit.PointFromClient = p => { DX.Vector2 pos = FromClient(p); return(new DX.Vector2((int)pos.X, (int)pos.Y)); }; _anchorEdit.AnchorChanged += AnchorEdit_AnchorChanged; _anchorEdit.BoundsChanged += AnchorEdit_BoundsChanged; }
/// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (!_disposed) { if (disposing) { // Save our settings. GorgonFontEditorPlugIn.Settings.Save(); if (_badGlyphTexture != null) { _badGlyphTexture.Dispose(); } // Remove any externally linked dependencies. EditorFile = null; if (Font != null) { Font.Dispose(); } if (Renderer != null) { Renderer.Dispose(); } if (_textDisplay != null) { _textDisplay.Dispose(); } if (_swap != null) { _swap.Dispose(); } } _swap = null; Renderer = null; Font = null; _panel = null; _textDisplay = null; _disposed = true; } base.Dispose(disposing); }
/// <summary> /// Function to assign rendering to a win forms panel. /// </summary> /// <param name="panel">The panel to use.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="panel"/> parameter is <b>null</b>.</exception> public void SetPanel(Panel panel) { if (panel == null) { throw new ArgumentNullException(nameof(panel)); } _swapChain = new GorgonSwapChain(_graphics, panel, new GorgonSwapChainInfo("ExampleSwapChain") { Format = BufferFormat.R8G8B8A8_UNorm, Width = panel.ClientSize.Width, Height = panel.ClientSize.Height }); }
/// <summary>Initializes a new instance of the <see cref="T:Gorgon.Editor.SpriteEditor.DefaultSpriteRenderer"/> class.</summary> /// <param name="sprite">The sprite view model.</param> /// <param name="graphics">The graphics interface for the application.</param> /// <param name="swapChain">The swap chain for the render area.</param> /// <param name="renderer">The 2D renderer for the application.</param> /// <param name="ants">The marching ants rectangle used to draw selection rectangles.</param> /// <param name="initialScale">The initial scaling value to apply to the render.</param> public DefaultSpriteRenderer(ISpriteContent sprite, GorgonGraphics graphics, GorgonSwapChain swapChain, Gorgon2D renderer, IMarchingAnts ants, float initialScale) : base(sprite, graphics, swapChain, renderer, initialScale) { _marchAnts = ants; _workingSprite = new GorgonSprite { Texture = sprite.Texture, TextureRegion = sprite.TextureCoordinates, TextureArrayIndex = TextureArrayIndex, Size = sprite.Size, Scale = DX.Vector2.One, Anchor = DX.Vector2.Zero }; for (int i = 0; i < 4; ++i) { _workingSprite.CornerColors[i] = sprite.VertexColors[i]; _workingSprite.CornerOffsets[i] = sprite.VertexOffsets[i]; } UpdateWorkingSprite(); }
public void CleanUp() { if (_renderer != null) { _renderer.Dispose(); _renderer = null; } if (_screen != null) { _screen.Dispose(); _screen = null; } if (_graphics != null) { _graphics.Dispose(); _graphics = null; } if (_form != null) { _form.Dispose(); _form = null; } }
/// <summary>Function to allow user defined setup of the graphics context with this control.</summary> /// <param name="context">The context being assigned.</param> /// <param name="swapChain"> /// The swap chain assigned to the <span class="nolink">RenderControl<span class="languageSpecificText"><span class="cs">()</span><span class="cpp">()</span><span class="nu">()</span><span class="fs">()</span></span></span>. /// </param> protected override void OnSetupGraphics(IGraphicsContext context, GorgonSwapChain swapChain) { Debug.Assert(EditorCommonResources.CheckerBoardPatternImage != null, "Background texture was not loaded."); _ribbonForm.GraphicsContext = context; _background = GorgonTexture2DView.CreateTexture(context.Graphics, new GorgonTexture2DInfo("Editor_BG_Texture") { Format = EditorCommonResources.CheckerBoardPatternImage.Format, Width = EditorCommonResources.CheckerBoardPatternImage.Width, Height = EditorCommonResources.CheckerBoardPatternImage.Height, Binding = TextureBinding.ShaderResource, Usage = ResourceUsage.Immutable }, EditorCommonResources.CheckerBoardPatternImage); _viewers[ImageType.Image2D] = new Texture2DViewer(context, swapChain, ScrollHorizontal, ScrollVertical); _viewers[ImageType.Image2D].CreateResources(_background); _viewers[ImageType.ImageCube] = new TextureCubeViewer(context, swapChain, ScrollHorizontal, ScrollVertical); _viewers[ImageType.ImageCube].CreateResources(_background); _viewers[ImageType.Image3D] = new Texture3DViewer(context, swapChain, ScrollHorizontal, ScrollVertical); _viewers[ImageType.Image3D].CreateResources(_background); if (DataContext?.ImageType == null) { ValidateControls(); return; } _textureViewer = _viewers[DataContext.ImageType]; _textureViewer.UpdateTexture(DataContext); UpdateImageSizeDetails(DataContext); UpdateMipDetails(DataContext); UpdateArrayDetails(DataContext); UpdateDepthSliceDetails(DataContext); ValidateControls(); }
/// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (!_disposed) { if (disposing) { GorgonSpriteEditorPlugIn.Settings.Save(); // Clear any external dependencies. EditorFile = null; if (BackgroundTexture != null) { BackgroundTexture.Dispose(); } if (_swap != null) { _swap.Dispose(); } if (Renderer != null) { Renderer.Dispose(); } } } _disposed = true; Texture = null; BackgroundTexture = null; Renderer = null; _swap = null; base.Dispose(disposing); }
/// <summary> /// Function to initialize the example. /// </summary> private void Initialize() { GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation); 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]); _leftPanel = new GorgonSwapChain(_graphics, GroupControl1, new GorgonSwapChainInfo("Left Panel SwapChain") { Width = GroupControl1.ClientSize.Width, Height = GroupControl1.ClientSize.Height, Format = BufferFormat.R8G8B8A8_UNorm }); _rightPanel = new GorgonSwapChain(_graphics, GroupControl2, new GorgonSwapChainInfo(_leftPanel, "Right Panel SwapChain") { Width = GroupControl2.ClientSize.Width, Height = GroupControl2.ClientSize.Height }); _renderer = new Gorgon2D(_graphics); _fontFactory = new GorgonFontFactory(_graphics); _appFont = _fontFactory.GetFont(new GorgonFontInfo(Font.FontFamily.Name, Font.Size * 1.33333f, FontHeightMode.Points, "Form Font") { Characters = "SpdtoxDrag me!\u2190:1234567890.", TextureWidth = 128, TextureHeight = 128, OutlineSize = 2, FontStyle = FontStyle.Bold, OutlineColor1 = GorgonColor.Black, OutlineColor2 = GorgonColor.Black }); _torusTexture = GorgonTexture2DView.FromFile(_graphics, Path.Combine(GorgonExample.GetResourcePath(@"Textures\GiveMeSomeControl\").FullName, "Torus.png"), new GorgonCodecPng(), new GorgonTexture2DLoadOptions { Binding = TextureBinding.ShaderResource, Name = "Torus Animation Sheet", Usage = ResourceUsage.Immutable }); _torusLeft = new GorgonSprite { Anchor = new DX.Vector2(0.5f, 0.5f), Size = new DX.Size2F(64, 64), TextureSampler = GorgonSamplerState.PointFiltering }; _torusRight = new GorgonSprite { Anchor = new DX.Vector2(0.5f, 0.5f), Size = new DX.Size2F(64, 64), TextureSampler = GorgonSamplerState.PointFiltering }; BuildAnimation(); GorgonExample.LoadResources(_graphics); }
/// <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; }
/// <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), "Post Processing"); 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); GorgonExample.LoadResources(_graphics); // Load the Gorgon logo to show in the lower right corner. var ddsCodec = new GorgonCodecDds(); // Import the images we'll use in our post process chain. if (!LoadImageFiles(ddsCodec)) { return(window); } // Initialize the effects that we'll use for compositing, and the compositor itself. InitializeEffects(); // Set up our quick and dirty GUI. _buttons = new Button[_compositor.Passes.Count]; LayoutGUI(); // Select a random image to start _currentImage = GorgonRandom.RandomInt32(0, _images.Length - 1); window.KeyUp += Window_KeyUp; window.MouseUp += Window_MouseUp; window.MouseMove += Window_MouseMove; window.MouseDown += Window_MouseDown; window.IsLoaded = true; return(window); } finally { GorgonExample.EndInit(); } }
/// <summary>Initializes a new instance of the <see cref="Texture2DViewer"/> class.</summary> /// <param name="graphicsContext">The graphics context for the application.</param> /// <param name="swapChain">The swap chain for presenting the content.</param> /// <param name="hScroll">The horizontal scroll bar.</param> /// <param name="vScroll">The vertical scroll bar.</param> public Texture2DViewer(IGraphicsContext graphicsContext, GorgonSwapChain swapChain, ScrollBar hScroll, ScrollBar vScroll) : base(graphicsContext, swapChain, hScroll, vScroll) { }
/// <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 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(); } }