diff --git a/RecrownedGTK/Graphics/UI/BookSystem/Book.cs b/RecrownedGTK/Graphics/UI/BookSystem/Book.cs deleted file mode 100644 index 51b8e67..0000000 --- a/RecrownedGTK/Graphics/UI/BookSystem/Book.cs +++ /dev/null @@ -1,211 +0,0 @@ -using RecrownedGTK.Input; -using RecrownedGTK.Assets; -using RecrownedGTK.Graphics.Render; -using RecrownedGTK.Graphics.UI.SkinSystem; -using System; -using System.Collections.Generic; -using System.Linq; -using RecrownedGTK.Types; -using OpenTK; - -namespace RecrownedGTK.Graphics.UI.BookSystem -{ - /// - /// Contains the pages. - /// - public class Book : IInputListener - { - readonly AssetManager assets; - readonly ISkin skin; - Page targetPage; - int width, height; - Dictionary pages = new Dictionary(); - List orderedPages = new List(); - - /// - /// The camera to use to change between pages. - /// - public Camera2D camera; - private BasicScissor basicScissor; - - /// - /// Creates a book. - /// - /// that holds the assets that are to be used in the pages for this book during initialization. - /// The skin that will be passed to pages during their initialization. - /// Camera to move to change pages. - public Book(AssetManager assets, ISkin skin, Camera2D camera) - { - this.assets = assets; - this.skin = skin; - - this.camera = camera ?? throw new ArgumentNullException("Camera can't be null since book needs a camera to move to change between the slides (pages)."); - this.basicScissor = new BasicScissor(); - } - - /// - /// Should be called whenever a valid camera and dimensions for the book exist. - /// Initializes book with given parameters. - /// Generally used with a and called in the function. - /// - /// Camera to move to change pages. - /// Dimensions of the book and the dimensions the pages will use. - public void Initiate(Camera2D camera, Rectangle dimensions) - { - this.camera = camera; - } - - /// - /// Applies the size if the book's pages. - /// - /// The width of one page. - /// The height of one page. - public void ApplySize(int width, int height) - { - if (this.width == width && this.height == height) return; - - this.width = width; - this.height = height; - for (int pageIndex = 0; pageIndex < pages.Count; pageIndex++) - { - Page page = orderedPages[pageIndex]; - if (page.Boundaries.Width != width || page.Boundaries.Height != height) - { - page.requiresSizeUpdate = true; - } - } - } - - /// - /// Draws the pages. - /// - /// Batch used to draw. - public void Draw(ConsistentSpriteBatch batch) - { - for (int pageIndex = 0; pageIndex < pages.Count; pageIndex++) - { - orderedPages[pageIndex].Draw(batch); - } - } - - /// - /// Updates the book. - /// - /// Snapshot of information of the game time. - public void Update(GameTime gameTime) - { - if (targetPage != null) - { - Vector2 position; - Rectangle targetBounds = targetPage.Boundaries; - position.X = targetBounds.X + (targetBounds.Width * 0.5f); - position.Y = targetBounds.Y + (targetBounds.Height * 0.5f); - camera.LinearInterpolationToPosition(0.4f, position, (float)gameTime.ElapsedGameTime.TotalSeconds); - if (camera.Position == position) - { - targetPage = null; - } - } - - for (int pageIndex = 0; pageIndex < pages.Count; pageIndex++) - { - Page page = pages.ElementAt(pageIndex).Value; - if (page.requiresSizeUpdate) page.ApplySize(width, height); - page.Update(gameTime); - } - } - - /// - /// Adds the page(s). - /// - /// The page(s) to add. - public void AddPages(params Page[] pages) - { - foreach (Page page in pages) - { - orderedPages.Add(page); - this.pages.Add(page.name, page); - page.Initialize(assets, skin, basicScissor); - } - } - - /// - /// Removes the page. - /// - /// Page to remove. - public void RemovePage(Page page) - { - RemovePage(page.name); - } - - /// - /// Removes the page. - /// - /// Name of page to remove. - public void RemovePage(string name) - { - orderedPages.Remove(pages[name]); - pages.Remove(name); - } - - - /// - /// Removes all pages. - /// - public void ClearPages() - { - orderedPages.Clear(); - pages.Clear(); - } - - /// - /// Perform a step of linear interpolation to the given page. - /// - /// The page to lerp to. - public void LerpToPage(Page page) - { - targetPage = page; - } - - /// - /// Goes to page instantly. - /// - /// Page to go to. - public void GoToPage(Page page) - { - Rectangle targetBounds = page.Boundaries; - camera.position.X = targetBounds.X + (targetBounds.Width * 0.5f); - camera.position.Y = targetBounds.Y + (targetBounds.Height * 0.5f); - } - - /// - /// Passes the new keyboard state down to each page in order of when it was added. - /// - /// - /// True if the state change should to trigger further input listeners. - public bool KeyboardStateChanged(KeyboardState state) - { - for (int pageIndex = 0; pageIndex < pages.Count; pageIndex++) - { - Page page = orderedPages[pageIndex]; - if (!page.KeyboardStateChanged(state)) return false; - } - return true; - } - - /// - /// Passes the new mouse state down to each page in order of when it was added. - /// - /// - /// True if the state change should to trigger further input listeners. - public bool MouseStateChanged(MouseState state) - { - for (int pageIndex = 0; pageIndex < pages.Count; pageIndex++) - { - Page page = orderedPages[pageIndex]; - if (!page.MouseStateChanged(state)) return false; - } - return true; - } - } -} diff --git a/RecrownedGTK/Graphics/UI/BookSystem/Page.cs b/RecrownedGTK/Graphics/UI/BookSystem/Page.cs deleted file mode 100644 index 0d771b8..0000000 --- a/RecrownedGTK/Graphics/UI/BookSystem/Page.cs +++ /dev/null @@ -1,57 +0,0 @@ -using RecrownedGTK.Assets; -using RecrownedGTK.Graphics.Render; -using RecrownedGTK.Graphics.UI.Modular; -using RecrownedGTK.Graphics.UI.SkinSystem; - -namespace RecrownedGTK.Graphics.UI.BookSystem -{ - /// - /// A page a part of a . - /// - public class Page : UIModuleGroup - { - private readonly int pageX, pageY; - /// - /// Whether or not this book needs to be refreshed with new dimensions. - /// - public bool requiresSizeUpdate; - - /// - /// Constructs a page. - /// - /// The X position in the book. - /// The Y position in the book. - public Page(int pageX, int pageY) : base() - { - this.pageX = pageX; - this.pageY = pageY; - requiresSizeUpdate = true; - name = ToString(); - } - - /// - /// Called when this page is flagged as needing a size update. - /// - /// New width. - /// New Height - public virtual void ApplySize(int width, int height) - { - X = pageX * width; - Y = pageY * height; - Width = width; - Height = height; - requiresSizeUpdate = false; - } - - /// - /// Called only once after a page is added to a . Generally used to instantiate the modules of the page. - /// - /// The assets to be used during initialization passed by the book this page belongs to. - /// The skin the book containing this page is given that can be used by this page. - /// The scissor box to use for cropping. - protected internal virtual void Initialize(AssetManager assets, ISkin skin, BasicScissor basicScissor) - { - this.basicScissor = basicScissor; - } - } -} diff --git a/RecrownedGTK/Graphics/UI/Modular/Modules/Image.cs b/RecrownedGTK/Graphics/UI/Modular/Modules/Image.cs deleted file mode 100644 index ddf295d..0000000 --- a/RecrownedGTK/Graphics/UI/Modular/Modules/Image.cs +++ /dev/null @@ -1,85 +0,0 @@ -using RecrownedGTK.Graphics.Render; -using RecrownedGTK.Types; -using OpenTK; -using OpenTK.Graphics; -using System; - -namespace RecrownedGTK.Graphics.UI.Modular.Modules -{ - /// - /// Represents a texture with more information. - /// - public class Image : UIModule, ISpecialDrawable - { - /// - /// The rotation of the image. - /// - public float rotation = 0f; - - /// - /// The texture to be rendered. - /// - public Texture2D texture; - - /// - /// Scale of of the X axis. - /// - public float ScaleX { get { return (float)Width / texture.Width; } set { Width = (int)(texture.Width * value); } } - - /// - /// Scale of the Y axis. - /// - public float ScaleY { get { return (float)Height / texture.Height; } set { Height = (int)(texture.Height * value); } } - - /// - /// Sets scale of X and Y. - /// - public float Scale { set { ScaleY = value; ScaleX = value; } } - - /// - /// Constructs an image given a texture. - /// - /// Texture to use. - public Image(Texture2D texture) - { - this.texture = texture ?? throw new ArgumentException("Image requires a texture."); - SetPositionAndDimensions(texture.Bounds); - } - - /// - /// Draws the image with default values. - /// - /// The batch to use. - public override void Draw(ConsistentSpriteBatch batch) - { - batch.Draw(texture, new Rectangle(X, Y, Width, Height), null, color, rotation, origin, SpriteEffects.None, 0f); - base.Draw(batch); - } - - /// - /// Draws the image with more options. - /// - /// Batch used. - /// Where to draw texture to. - /// The color tint to use. - /// Rotation of image. - /// Origin for the rotation. - public void Draw(ConsistentSpriteBatch spriteBatch, Rectangle destination, Color4 color, float rotation = 0, Vector2 origin = default(Vector2)) - { - this.color = color; - this.rotation = rotation; - this.origin = origin; - SetPositionAndDimensions(destination); - Draw(spriteBatch); - } - - /// - /// Center's the origin to the middle of the dimensions of the texture. - /// - public override void CenterOrigin() - { - origin.X = texture.Bounds.Width / 2f; - origin.Y = texture.Bounds.Height / 2f; - } - } -} diff --git a/RecrownedGTK/Graphics/UI/Modular/Modules/Interactive/Button.cs b/RecrownedGTK/Graphics/UI/Modular/Modules/Interactive/Button.cs deleted file mode 100644 index d0a424a..0000000 --- a/RecrownedGTK/Graphics/UI/Modular/Modules/Interactive/Button.cs +++ /dev/null @@ -1,155 +0,0 @@ -using RecrownedGTK.Types; -using RecrownedGTK.Input; -using RecrownedGTK.Graphics.UI.SkinSystem.Definitions; -using RecrownedGTK.Graphics.UI.SkinSystem; -using RecrownedGTK.Graphics.Render; - -namespace RecrownedGTK.Graphics.UI.Modular.Modules.Interactive -{ - /// - /// Function to be called when button is clicked. - /// - /// The button that was clicked. - public delegate void Clicked(Button button); - - /// - /// A very primitive button containing all the basic functions. - /// - public class Button : UIModule - { - private ButtonSkinDefinition skinDefinition; - private ISpecialDrawable downTexture, upTexture, highlightedTexture, disabledTexture; - /// - /// Click event listeners. - /// - public event Clicked Listeners; - private bool pressed; - /// - /// Whether or not this button should be currently disabled. - /// - public bool disabled = false; - - /// - /// Whether or not this button is currently being hovered on. - /// - public bool Highlighted { get; private set; } - - /// - /// Constructs this button using s for the different states it could be in. - /// - /// Button being pressed. - /// Button not being pressed. - /// Disabled button. - /// Button being highlighted. - public Button(ISpecialDrawable down, ISpecialDrawable up, ISpecialDrawable disabled = null, ISpecialDrawable selected = null) - { - this.downTexture = down; - this.upTexture = up; - this.disabledTexture = disabled; - this.highlightedTexture = selected; - } - - /// - /// Constructs this button using the skin system. - /// - /// The skin containing the information of the textures and design to follow. - /// The name of the definition in the skin. Can be null to select the default. - public Button(ISkin skin, string definitionName = null) - { - skinDefinition = skin.ObtainDefinition(definitionName); - downTexture = skin.GetTextureAtlasRegion(skinDefinition.downRegion, true); - upTexture = skin.GetTextureAtlasRegion(skinDefinition.upRegion, true); - disabledTexture = skin.GetTextureAtlasRegion(skinDefinition.disabledRegion); - highlightedTexture = skin.GetTextureAtlasRegion(skinDefinition.selectedRegion); - } - - /// - /// Instantiates a button using a definition. - /// - /// The skin the definition is defined in. - /// The definition itself. - public Button(ISkin skin, ButtonSkinDefinition skinDefinition) : - this(skin.GetTextureAtlasRegion(skinDefinition.downRegion, true), - skin.GetTextureAtlasRegion(skinDefinition.upRegion, true), - skin.GetTextureAtlasRegion(skinDefinition.disabledRegion), - skin.GetTextureAtlasRegion(skinDefinition.selectedRegion)) - { } - - /// - /// Draws the button. - /// - /// Batch used to draw the button. - public override void Draw(ConsistentSpriteBatch batch) - { - if (disabled) - { - disabledTexture?.Draw(batch, Boundaries, color); - } - else - { - if (pressed) - { - downTexture.Draw(batch, Boundaries, color); - } - else if (Highlighted) - { - highlightedTexture?.Draw(batch, Boundaries, color); - } - else - { - upTexture.Draw(batch, Boundaries, color); - } - } - - base.Draw(batch); - } - - /// - /// Called when the mouse changes state. - /// - /// The new state. - /// Whether or not to continue calling the next mouse change listener. - public sealed override bool MouseStateChanged(MouseState state) - { - if (InputUtilities.MouseWithinBoundries(Boundaries)) - { - if (state.LeftButton == ButtonState.Pressed) - { - pressed = true; - } - else - { - pressed = false; - } - if (InputUtilities.MouseClicked()) - { - OnClick(); - } - Highlighted = true; - } - else - { - Highlighted = false; - pressed = false; - } - - return base.MouseStateChanged(state); - } - - /// - /// Called when the state of the keyboard changes. - /// - /// The new state. - /// Whether or not the next keyboard change listener should be called. - public sealed override bool KeyboardStateChanged(KeyboardState state) - { - return base.KeyboardStateChanged(state); - } - - internal void OnClick() - { - Listeners?.Invoke(this); - } - - } -} diff --git a/RecrownedGTK/Graphics/UI/Modular/Modules/Interactive/TextButton.cs b/RecrownedGTK/Graphics/UI/Modular/Modules/Interactive/TextButton.cs deleted file mode 100644 index bc60bcf..0000000 --- a/RecrownedGTK/Graphics/UI/Modular/Modules/Interactive/TextButton.cs +++ /dev/null @@ -1,92 +0,0 @@ -using RecrownedGTK.Graphics.Render; -using OpenTK.Graphics; -using RecrownedGTK.Graphics.UI.SkinSystem; -using RecrownedGTK.Graphics.UI.SkinSystem.Definitions; - -namespace RecrownedGTK.Graphics.UI.Modular.Modules.Interactive -{ - /// - /// Button that holds a string. - /// - public class TextButton : Button - { - /// - /// The text that is used to display the string. - /// - public readonly Text text; - - /// - /// The color the font should be rendered in. - /// - public Color4 FontColor { get { return text.color; } set { text.color = value; } } - - /// - /// Constructs text button with the positions represented by - /// - /// The string representing the text to be displayed. - /// The font to be used to display the text. - /// What to draw as button is pushed down. - /// What to draw as button is not pushed. - /// What to draw as button is disabled. - /// What to draw as button is selected. - public TextButton(string text, SpriteFont font, ISpecialDrawable down, ISpecialDrawable up, ISpecialDrawable disabled = null, ISpecialDrawable selected = null) : base(down, up, disabled, selected) - { - this.text = new Text(font, text); - this.text.autoScale = true; - this.text.centered = true; - } - - /// - /// Constructs a text button using a skin and definition. - /// - /// The text to display. - /// The font to be used. - /// The skin to use. - /// Name of the definition for this type in the skin given. - public TextButton(string text, SpriteFont font, ISkin skin, string definitionName = null) : base(skin, skin.ObtainDefinition(definitionName)) - { - TextButtonSkinDefinition skinDefinition = skin.ObtainDefinition(definitionName); - this.text = new Text(font, text); - this.text.autoScale = true; - this.text.centered = true; - FontColor = skin.GetColor(skinDefinition.fontColor); - } - - /// - /// Creates a text button with a given definition. - /// - /// The text to be displayed on this button. - /// The font to use for this button. - /// The skin the definition is from. - /// The definition to use. - public TextButton(string text, SpriteFont font, ISkin skin, TextButtonSkinDefinition skinDefinition) : - this(text, - font, - skin.GetTextureAtlasRegion(skinDefinition.downRegion, true), - skin.GetTextureAtlasRegion(skinDefinition.upRegion, true), - skin.GetTextureAtlasRegion(skinDefinition.disabledRegion), - skin.GetTextureAtlasRegion(skinDefinition.selectedRegion)) - { } - - /// - /// Updates the text button. - /// - /// Snapshot of information about time for game. - public override void Update(GameTime gameTime) - { - text.SetPositionAndDimensions(Boundaries); - text.Update(gameTime); - base.Update(gameTime); - } - - /// - /// Called whenever game wants to render this button. - /// - /// Batch to use. Batch should already be started. - public override void Draw(ConsistentSpriteBatch batch) - { - base.Draw(batch); - text.Draw(batch); - } - } -} diff --git a/RecrownedGTK/Graphics/UI/Modular/Modules/Text.cs b/RecrownedGTK/Graphics/UI/Modular/Modules/Text.cs deleted file mode 100644 index 43b2b13..0000000 --- a/RecrownedGTK/Graphics/UI/Modular/Modules/Text.cs +++ /dev/null @@ -1,206 +0,0 @@ -using OpenTK; -using RecrownedGTK.Graphics.Render; -using System; -using System.Text; - -namespace RecrownedGTK.Graphics.UI.Modular.Modules -{ - /// - /// Represents text for the UI. - /// - public class Text : UIModule - { - private SpriteFont font; - private float scale = 1f; - private Vector2 position; - private string originalText; - private string displayedText; - private Vector2 modifiedTextSize; - - /// - /// Centers the text int bounds. - /// - public bool centered; - - /// - /// Whether or not to try and wrap text automatically. Meaning will check and attempt to wrap every update. - /// - public bool autoWrap; - - /// - /// Whether or not to automatically scale the text every update. Happens after auto wrap if enabled. - /// - public bool autoScale; - - /// - /// Should this use ellipses? Will perform this operation before auto wrapping or auto scalling. - /// - public bool useEllipses; - - /// - /// The text to use for the ellipsis. - /// - public string ellipsis = "..."; - private string ModifiedText { get { return displayedText; } set { displayedText = value; modifiedTextSize = font.MeasureString(value); } } - - /// - /// The string to be displayed. - /// - public string Content { get { return originalText; } set { originalText = value; if (value == null) value = ellipsis; modifiedTextSize = font.MeasureString(value); displayedText = value; } } - - /// - /// Creates a UI text object. - /// - /// The font to use. - /// The string for the text. - public Text(SpriteFont font, string content = null) - { - this.font = font ?? throw new ArgumentNullException("Font cannot be null."); - Content = content; - } - - /// - /// Updates the positioning and attempts to perform any operations that were marked automatic. - /// - /// The game time. - public override void Update(GameTime gameTime) - { - position.X = X; - position.Y = Y; - - if (useEllipses) AttemptToApplyEllipsis(); - if (autoWrap) AttemptToWrapText(); - if (autoScale) AttemptToScaleFont(); - if (centered) Center(); - - base.Update(gameTime); - } - - /// - /// Draws the text. - /// - /// Batch to use. - public override void Draw(ConsistentSpriteBatch batch) - { - batch.DrawString(font, Content, position, color, 0f, default(Vector2), scale, SpriteEffects.None, 0f); - base.Draw(batch); - } - - /// - /// Attempts to apply ellipsis. Checks of nessecary. - /// - public void AttemptToApplyEllipsis() - { - if (modifiedTextSize.X * scale > Width && ModifiedText.Length > ellipsis.Length + 1) - { - RemoveLineBreaks(); - StringBuilder stringBuilder = new StringBuilder(ModifiedText); - do - { - stringBuilder.Remove(stringBuilder.Length, ellipsis.Length - 1); - stringBuilder.Insert(stringBuilder.Length, ellipsis); - } - while (font.MeasureString(stringBuilder).X * scale > Width); - - ModifiedText = stringBuilder.ToString(); - } - } - - /// - /// Attempts to scale the font. Checks if nessecary. - /// - public void AttemptToScaleFont() - { - - if (Width < Height) - { - if (Math.Round(modifiedTextSize.X * scale ) != Width) - { - scale = Width / modifiedTextSize.X; - } - } - else - { - if (Math.Round(modifiedTextSize.Y * scale ) != Height) - { - scale = Height / (modifiedTextSize.Y); - } - } - } - - /// - /// Removes line breaks. - /// - public void RemoveLineBreaks() - { - ModifiedText = ModifiedText.Replace("\n", " "); - } - - /// - /// Resets to original text. - /// - public void ResetToOriginalText() - { - Content = originalText; - } - - /// - /// Attempts to wrap text. Checks if nessecary. - /// - /// If true, will first unwrap text, and the wrap again. This occurs before nessecity check. - public void AttemptToWrapText(bool unwrap = false) - { - if (unwrap) RemoveLineBreaks(); - if (modifiedTextSize.X * scale > Width) - { - ModifiedText = ModifiedText.Replace("\n", " "); - string[] words = ModifiedText.Split(' '); - StringBuilder stringBuilder = new StringBuilder(); - float currentScaledLineWidth = 0f; - - for (int w = 0; w < words.Length; w++) - { - string word = words[w]; - float scaledWidth = font.MeasureString(word).X * scale; - - if (currentScaledLineWidth + scaledWidth <= Width) - { - stringBuilder.Append(word); - currentScaledLineWidth += scaledWidth; - } - else - { - stringBuilder.AppendLine(); - currentScaledLineWidth = 0; - } - } - ModifiedText = stringBuilder.ToString(); - } - } - - private bool Center() - { - Vector2 textSize = new Vector2(modifiedTextSize.X * scale, modifiedTextSize.Y * scale); - - if (textSize.X <= Width) - { - position.X = X + (Width - textSize.X) / 2f; - } - else - { - return false; - } - - if (textSize.Y <= Height) - { - position.Y = Y + (Height - textSize.Y) / 2f; - } - else - { - return false; - } - - return true; - } - } -} diff --git a/RecrownedGTK/Graphics/UI/Modular/Modules/UIScrollable.cs b/RecrownedGTK/Graphics/UI/Modular/Modules/UIScrollable.cs deleted file mode 100644 index 413241b..0000000 --- a/RecrownedGTK/Graphics/UI/Modular/Modules/UIScrollable.cs +++ /dev/null @@ -1,451 +0,0 @@ -using RecrownedGTK.Input; -using RecrownedGTK.Graphics.Render; -using RecrownedGTK.Types; -using RecrownedGTK.Graphics.UI.SkinSystem; -using RecrownedGTK.Graphics.UI.SkinSystem.Definitions; -using OpenTK; -using OpenTK.Graphics; -using System; - -namespace RecrownedGTK.Graphics.UI.Modular.Modules -{ - public class UIScrollable : UIModule - { - BasicScissor basicScissor; - Rectangle viewport; - UIModuleGroup group; - - Color4 scrollBarColor = Color4.White; - float opacityOfBar = 1f; - bool showingBars; - private bool mouseWasPressed; - private bool horizontalSelected; - private Vector2 mouseRelativePosition; - float shiftX, shiftY; - - public float XScrollPosition - { - get - { - return (Width - horizontalScrollBarBounds.Width) * (-shiftX / (group.Width - viewport.Width)); - } - - set - { - if (value > Width - verticalScrollBarBounds.Height) - { - value = Width - verticalScrollBarBounds.Height; - } - if (value < 0) value = 0; - shiftX = -(group.Width - viewport.Width) * (value / (Width - horizontalScrollBarBounds.Width)); - WidthOrXChange(true); - } - } - public float YScrollPosition - { - get - { - return (Height - verticalScrollBarBounds.Height) * (-shiftY / (group.Height - viewport.Height)); - } - - set - { - if (value > Height - verticalScrollBarBounds.Height) - { - value = Height - verticalScrollBarBounds.Height; - } - if (value < 0) value = 0; - shiftY = -(group.Height - viewport.Height) * (value / (Height - verticalScrollBarBounds.Height)); - HeightOrYChange(true); - } - } - - UIModule furthestXModule, furthestYMod; - - bool horScrollAvailable, vertScrollAvailable; - - Rectangle horizontalScrollBarBounds, verticalScrollBarBounds; - /// - /// How fast the bars fade away in opacity (0 to 254) per second. - /// - public float barFadeSpeed = 250; - - ISpecialDrawable horizontalScrollBar, verticalScrollBar; - ISpecialDrawable background, horizontalBarTrack, verticalBarTrack; - - private int topPadding, bottomPadding, leftPadding, rightPadding; - - /// - /// - /// - public int PadTop { get { return topPadding; } set { topPadding = value; HeightOrYChange(); } } - public int PadBottom { get { return bottomPadding; } set { bottomPadding = value; HeightOrYChange(); } } - public int PadLeft { get { return leftPadding; } set { leftPadding = value; WidthOrXChange(); } } - public int PadRight { get { return rightPadding; } set { rightPadding = value; WidthOrXChange(); } } - - /// - /// The minimum bar length for the scroll bar. - /// - public int minimumBarLength = 16; - - public int HorizontalBarThickness { get { return horizontalScrollBarBounds.Height; } set { horizontalScrollBarBounds.Height = value; HeightOrYChange(); } } - public int VerticalBarThickness { get { return verticalScrollBarBounds.Width; } set { verticalScrollBarBounds.Width = value; WidthOrXChange(); } } - - bool hideScrollBars; - - /// - /// Whether or not to hide scroll bars. - /// - public bool HideScrollBars - { - get { return hideScrollBars; } - set - { - hideScrollBars = value; - WidthOrXChange(true); - HeightOrYChange(true); - if (!value) - { - opacityOfBar = 1f; - scrollBarColor = color.ReturnMultipliedByFloat(opacityOfBar); - } - } - } - - - /// - /// Set to true to change from the normal position to the new position. - /// - public bool verticalBarLeftPosition, horizontalBarTopPosition; - - - public override int Width - { - get - { - return base.Width; - } - set - { - base.Width = value; - WidthOrXChange(); - } - } - - public override int Height - { - get - { - return base.Height; - } - set - { - base.Height = value; - HeightOrYChange(); - } - } - - public override int X - { - get - { - return base.X; - } - set - { - WidthOrXChange(true); - base.X = value; - } - } - - public override int Y - { - get - { - return base.Y; - } - set - { - HeightOrYChange(true); - base.Y = value; - } - } - - public UIScrollable(ISpecialDrawable horizontalScrollBar, ISpecialDrawable verticalScrollBar, ISpecialDrawable horizontalBarTrack = null, ISpecialDrawable verticalBarTrack = null, ISpecialDrawable background = null) - { - this.horizontalScrollBar = horizontalScrollBar; - this.verticalScrollBar = verticalScrollBar; - this.horizontalBarTrack = horizontalBarTrack; - this.verticalBarTrack = verticalBarTrack; - this.background = background; - - basicScissor = new BasicScissor(); - group = new UIModuleGroup(); - HorizontalBarThickness = 12; - VerticalBarThickness = 12; - } - - public UIScrollable(ISkin skin, string definition = null) : - this(skin.GetTextureAtlasRegion(skin.ObtainDefinition().horizontalBar, true), - skin.GetTextureAtlasRegion(skin.ObtainDefinition().verticalBar, true), - skin.GetTextureAtlasRegion(skin.ObtainDefinition().horizontalBarTrack), - skin.GetTextureAtlasRegion(skin.ObtainDefinition().verticalBarTrack), - skin.GetTextureAtlasRegion(skin.ObtainDefinition().background)) - { - } - - public override void Update(GameTime gameTime) - { - if (hideScrollBars) - { - if (!showingBars && !mouseWasPressed) - { - if (opacityOfBar > 0f) - { - opacityOfBar -= (barFadeSpeed / 255f) * (float)gameTime.ElapsedGameTime.TotalSeconds; - } - } - else - { - opacityOfBar = 1f; - } - scrollBarColor = color.ReturnMultipliedByFloat(opacityOfBar); - } - - if (horScrollAvailable) - { - horizontalScrollBarBounds.X = (int)XScrollPosition; - } - - if (vertScrollAvailable) - { - verticalScrollBarBounds.Y = (int)YScrollPosition; - } - - - base.Update(gameTime); - } - - public override void Draw(ConsistentSpriteBatch spriteBatch) - { - background?.Draw(spriteBatch, Boundaries, color, origin: origin); - spriteBatch.End(); - basicScissor.Begin(viewport, spriteBatch); - group.Draw(spriteBatch); - basicScissor.End(); - spriteBatch.Begin(); - if (horScrollAvailable) - { - horizontalScrollBar.Draw(spriteBatch, horizontalScrollBarBounds, scrollBarColor); - } - if (vertScrollAvailable) - { - horizontalScrollBar.Draw(spriteBatch, verticalScrollBarBounds, scrollBarColor); - } - base.Draw(spriteBatch); - } - - public void AddModules(params UIModule[] addModules) - { - group.AddModules(addModules); - - for (int i = 0; i < addModules.Length; i++) - { - UIModule m = addModules[i]; - int mFurthestX = m.Boundaries.X + m.Boundaries.Width; - int mFurthestY = m.Boundaries.Y + m.Boundaries.Height; - if (mFurthestX > group.Width) - { - furthestXModule = m; - group.Width = mFurthestX; - } - if (mFurthestY > group.Height) - { - furthestYMod = m; - group.Height = mFurthestY; - } - } - - WidthOrXChange(); - HeightOrYChange(); - } - - public void RemoveModule(UIModule module) - { - group.RemoveModule(module); - - if (module == furthestXModule) - { - group.Width = 0; - UIModule[] modules = group.GetCopyOfModules(); - for (int i = 0; i < modules.Length; i++) - { - UIModule m = modules[i]; - int mFurthestX = m.Boundaries.X + m.Boundaries.Width; - if (mFurthestX > group.Width) - { - furthestXModule = m; - group.Width = mFurthestX; - } - } - } - - if (module == furthestYMod) - { - group.Height = 0; - UIModule[] modules = group.GetCopyOfModules(); - - for (int i = 0; i < modules.Length; i++) - { - UIModule m = modules[i]; - int mFurthestY = m.Boundaries.Y + m.Boundaries.Height; - if (mFurthestY > group.Height) - { - furthestYMod = m; - group.Height = mFurthestY; - } - } - } - } - - private void WidthOrXChange(bool onlyXChange = false) - { - group.X = X + leftPadding + (int)shiftX; - if (!onlyXChange) - { - viewport.X = X + leftPadding; - viewport.Width = Width - rightPadding - leftPadding; - if (Width < group.Width) - { - horScrollAvailable = true; - horizontalScrollBarBounds.Width = (int)(Width * ((float)Width / group.Width)); - horizontalScrollBarBounds.Width = Math.Max(horizontalScrollBarBounds.Width, minimumBarLength); - } - else { horScrollAvailable = false; } - - verticalScrollBarBounds.X = X; - if (!hideScrollBars) - { - viewport.Width -= VerticalBarThickness; - if (!verticalBarLeftPosition) - { - verticalScrollBarBounds.X += viewport.Width; - } - } - else - { - if (!verticalBarLeftPosition) - { - verticalScrollBarBounds.X += viewport.Width - verticalScrollBarBounds.Width; - } - } - } - } - - private void HeightOrYChange(bool onlyYChange = false) - { - group.Y = Y + bottomPadding + (int)shiftY; - if (!onlyYChange) - { - viewport.Y = Y + bottomPadding; - viewport.Height = Height - bottomPadding - topPadding; - if (Height < group.Height) - { - vertScrollAvailable = true; - verticalScrollBarBounds.Height = (int)(Height * ((float)Height / group.Height)); - verticalScrollBarBounds.Height = Math.Max(verticalScrollBarBounds.Height, minimumBarLength); - } - else { vertScrollAvailable = false; } - - horizontalScrollBarBounds.Y = Y; - if (!hideScrollBars) - { - viewport.Height -= HorizontalBarThickness; - if (!horizontalBarTopPosition) - { - horizontalScrollBarBounds.Y += viewport.Height; - } - else - { - viewport.Y += horizontalScrollBarBounds.Height; - } - } - else - { - if (!horizontalBarTopPosition) - { - horizontalScrollBarBounds.Y += viewport.Height - horizontalScrollBarBounds.Height; - } - } - } - } - - public override bool KeyboardStateChanged(KeyboardState state) - { - if (state.IsKeyDown(Keys.Right)) - { - XScrollPosition += 1; - } - - return base.KeyboardStateChanged(state); - } - - public override bool MouseStateChanged(MouseState state) - { - if (InputUtilities.MouseWithinBoundries(Boundaries)) - { - showingBars = true; - } - else - { - showingBars = false; - } - - if (InputUtilities.MouseWithinBoundries(horizontalScrollBarBounds)) - { - if (state.LeftButton == ButtonState.Pressed) - { - mouseWasPressed = true; - horizontalSelected = true; - } - if (!mouseWasPressed) - { - mouseRelativePosition.X = state.X - horizontalScrollBarBounds.X; - } - } - - if (InputUtilities.MouseWithinBoundries(verticalScrollBarBounds)) - { - if (state.LeftButton == ButtonState.Pressed) - { - mouseWasPressed = true; - horizontalSelected = false; - } - if (!mouseWasPressed) - { - mouseRelativePosition.Y = state.Y - verticalScrollBarBounds.Y; - } - } - - if (mouseWasPressed) - { - if (horizontalSelected) - { - float latestPosition = state.X - mouseRelativePosition.X - X; - XScrollPosition = latestPosition; - } - else - { - float latestPosition = state.Y - mouseRelativePosition.Y - Y; - YScrollPosition = latestPosition; - } - - if (state.LeftButton == ButtonState.Released) - { - mouseWasPressed = false; - } - } - return base.MouseStateChanged(state); - } - } -} diff --git a/RecrownedGTK/Graphics/UI/Modular/UIModule.cs b/RecrownedGTK/Graphics/UI/Modular/UIModule.cs deleted file mode 100644 index 0741361..0000000 --- a/RecrownedGTK/Graphics/UI/Modular/UIModule.cs +++ /dev/null @@ -1,190 +0,0 @@ -using RecrownedGTK.Types; -using OpenTK; -using OpenTK.Graphics; -using RecrownedGTK.Input; -using RecrownedGTK.Graphics.Render; -using System; - -namespace RecrownedGTK.Graphics.UI.Modular -{ - - /// - /// Module for UI layout. - /// - public abstract class UIModule : IInputListener - { - /// - /// The width of the module. - /// - public virtual int Width { get; set; } - - /// - /// The height of the module. - /// - public virtual int Height { get; set; } - - /// - /// The X position of the module. - /// - public virtual int X { get; set; } - - /// - /// The Y position of the module. - /// - public virtual int Y { get; set; } - - /// - /// Bounds of this module (after factoring in the origin). - /// - public Rectangle Boundaries - { - get - { - return new Rectangle((int)(X - origin.X), (int)(Y - origin.Y), Width, Height); - } - } - - /// - /// Origin of this module. - /// - public Vector2 origin; - - /// - /// The parent of this module. May be null. - /// - public UIModuleGroup parent; - - /// - /// Name of this module. For organizational/referencial purposes mostly. - /// - public string name; - - /// - /// The color tint of this module. - /// - public Color4 color = Color4.White; - - /// - /// Called every frame to update this module. Calculations and movement should go here. - /// - /// Game time information. - public virtual void Update(GameTime gameTime) - { - - } - - /// - /// Called every frame to draw this module. Anything that needs to be drawn should go here. - /// - /// Batch used to draw. - public virtual void Draw(ConsistentSpriteBatch batch) - { - } - - /// - /// Converts the given rectangle to the coordinates of the parent. - /// - /// Rectangle to convert. - /// - public Rectangle ConvertToParentCoordinates(Rectangle rectangle) - { - if (parent != null) - { - Rectangle parentHitbox = parent.ConvertToParentCoordinates(rectangle); - int tX = rectangle.X + parentHitbox.X; - int tY = rectangle.Y + parentHitbox.Y; - return new Rectangle(tX, tY, rectangle.Width, rectangle.Height); - } - else - { - return rectangle; - } - } - - /// - /// Removes this module from the parent. - /// - public void RemoveFromParent() - { - if (parent == null) throw new InvalidOperationException("Parent is null."); - parent.RemoveModule(this); - } - - /// - /// Called whenever the keyboard state is changed. - /// - /// The current keyboard state. - /// Returning whether or not to continue to call the next listener. - public virtual bool KeyboardStateChanged(KeyboardState state) - { - return true; - } - - /// - /// Called whenever the state of the mouse changes. This includes movement. - /// - /// The current state of the mouse. - /// Returning whether or not to continue to call the next listener. - public virtual bool MouseStateChanged(MouseState state) - { - return true; - } - - /// - /// Sets the origin to be the center using the and . - /// - public virtual void CenterOrigin() - { - origin.X = Width / 2f; - origin.Y = Height / 2f; - } - - /// - /// Centers this module's on the horizontal axis relative to the parent . - /// - /// True if possible and false if not. - public bool CenterHorizontally() - { - if (parent != null) - { - Rectangle rectangle = parent.Boundaries; - if (parent != null && rectangle.Width >= Boundaries.Width) - { - X = rectangle.Width / 2 + X; - return true; - } - } - return false; - } - - /// - /// Centers this module's origin on the vertical axis relative to the parent . - /// - /// True if possible. - public virtual bool CenterVertically() - { - if (parent != null) - { - Rectangle rectangle = parent.Boundaries; - if (rectangle.Height >= Boundaries.Height) - { - Y = rectangle.Height / 2 + Y; - return true; - } - } - return false; - } - - /// - /// Sets the position and dimension of this module. - /// - /// The rectangle that represents the position and dimensions of the module. - public virtual void SetPositionAndDimensions(Rectangle rectangle) - { - X = rectangle.X; - Y = rectangle.Y; - Width = rectangle.Width; - Height = rectangle.Height; - } - } -} diff --git a/RecrownedGTK/Graphics/UI/Modular/UIModuleGroup.cs b/RecrownedGTK/Graphics/UI/Modular/UIModuleGroup.cs deleted file mode 100644 index cca58e6..0000000 --- a/RecrownedGTK/Graphics/UI/Modular/UIModuleGroup.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System; -using System.Collections.Generic; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Input; -using RecrownedGTK.Graphics.Render; - -namespace RecrownedGTK.Graphics.UI.Modular -{ - - /// - /// Contains a group of modules and has its own relative coordinate system. - /// - public class UIModuleGroup : UIModule - { - List modules = new List(); - - /// - /// Set this to crop anything that flows out of the boundaries of this group. Will not crop if this is null. - /// - public BasicScissor basicScissor; - - /// - /// Instantiates the UI module group. - /// - /// Sets the field. - public UIModuleGroup(BasicScissor basicScissor = null) - { - this.basicScissor = basicScissor; - } - - /// - /// Draws this group of modules. If scissoring, will use the matrix and effect designated in the to begin the batch normally again. - /// - /// Batch used to draw the group. - public override void Draw(ConsistentSpriteBatch spriteBatch) - { - if (basicScissor != null) - { - spriteBatch.End(); - basicScissor.Begin(Boundaries, spriteBatch); - } - - foreach (UIModule module in modules) - { - int offsetX = module.X; - int offsetY = module.Y; - module.X = X + offsetX; - module.Y = Y + offsetY; - module.Draw(spriteBatch); - module.X = offsetX; - module.Y = offsetY; - } - - if (basicScissor != null) - { - basicScissor.End(); - spriteBatch.Begin(); - } - } - - /// - /// Updates the group of modules. - /// - /// Game time used. - public override void Update(GameTime gameTime) - { - foreach (UIModule module in modules) - { - module.Update(gameTime); - } - } - - /// - /// Adds module(s) to this group. - /// - /// The module(s) to add. - public virtual void AddModules(params UIModule[] addModules) - { - foreach (UIModule module in addModules) - { - if (modules.Contains(module)) - { - throw new InvalidOperationException(module.ToString() + " already exists in " + this.ToString()); - } - module.parent = this; - modules.Add(module); - } - } - - /// - /// Removes given module from group. - /// - /// module to remove. - public virtual void RemoveModule(UIModule module) - { - module.parent = null; - modules.Remove(module); - } - - /// - /// Obtains an array snapshot of all the modules. - /// - public UIModule[] GetCopyOfModules() - { - return modules.ToArray(); - } - - /// - /// Updates the keyboard state of the modules in this group. - /// - /// The new state. - /// Whether or not to continue updating the other listeners. - public override bool KeyboardStateChanged(KeyboardState state) - { - foreach (UIModule module in modules) - { - module.KeyboardStateChanged(state); - } - return base.KeyboardStateChanged(state); - } - - /// - /// Updates the moues state of the modules in this group. - /// - /// The new state. - /// Whether or not to continue updating other listeners. - public override bool MouseStateChanged(MouseState state) - { - foreach (UIModule module in modules) - { - module.MouseStateChanged(state); - } - return base.MouseStateChanged(state); - } - } -} diff --git a/RecrownedGTK/Graphics/UI/ScreenSystem/ITransition.cs b/RecrownedGTK/Graphics/UI/ScreenSystem/ITransition.cs deleted file mode 100644 index 3bdde32..0000000 --- a/RecrownedGTK/Graphics/UI/ScreenSystem/ITransition.cs +++ /dev/null @@ -1,46 +0,0 @@ -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using RecrownedGTK.Graphics.Render; - -namespace RecrownedGTK.Graphics.UI.ScreenSystem -{ - /// - /// Contracts a transition that the can use. - /// - public interface ITransition - { - /// - /// Called once when the transition is needed. - /// The dimensions of the screen. - /// - void InitiateTransition(Rectangle dimensions); - - /// - /// Called every frame if the state of the screen this transition is placed upon is in the enter transition phase. - /// - /// The time passed in seconds since the last frame. - /// Whether or not this transition is waiting on something. Usually the . - /// If this returns true, then it is considered that this transition is complete. - bool UpdateEnteringTransition(double delta, bool waiting); - - /// - /// Called every frame if the state of the screen this transition is placed upon is in the exit phase. - /// - /// The time passed in seconds since the last frame. - /// Whether or not this transition is waiting on something. Usually the . - /// If this returns true, then it is considered that this transition is complete. - bool UpdateExitingTransition(double delta, bool waiting); - - /// - /// Called once every frame while transition is active. Meant to draw transition. - /// - /// - void DrawTransition(ConsistentSpriteBatch spriteBatch); - - /// - /// Updates if the previous screen uses a render target for exit transition. - /// - /// The frame of the previous screen. - void UpdatePreviousScreenFrame(RenderTarget2D previousScreenFrame); - } -} diff --git a/RecrownedGTK/Graphics/UI/ScreenSystem/LoadingScreen.cs b/RecrownedGTK/Graphics/UI/ScreenSystem/LoadingScreen.cs deleted file mode 100644 index b786feb..0000000 --- a/RecrownedGTK/Graphics/UI/ScreenSystem/LoadingScreen.cs +++ /dev/null @@ -1,166 +0,0 @@ -using OpenTK.Graphics; -using OpenTK; -using RecrownedGTK.Graphics.Render; -using RecrownedGTK.Types; -using System; - -namespace RecrownedGTK.Graphics.UI.ScreenSystem -{ - /// - /// A screen specifically meant to fill in loading times. - /// - public class LoadingScreen : Screen, ITransition - { - private const float ENTER_TIME = 2f; - private const float EXIT_TIME = 1f; - Game game; - readonly Texture2D texture; - Color4 color; - Rectangle textureBounds; - readonly float proportion; - bool recorded; - float rR, rG, rB; - float progR, progG, progB; - float progC = 254; - float rotation; - readonly bool rotate; - Vector2 origin; - - /// - /// Constructs a loading screen. - /// - /// The game itself to adjust mouse settings and such. - /// - /// - /// - public LoadingScreen(Game game, Texture2D screenImage, float proportion, bool rotate = false) : base(true) - { - this.game = game; - this.texture = screenImage; - this.proportion = proportion; - this.rotate = rotate; - Transitions.Add(this); - } - - /// - public override void Show() - { - game.IsMouseVisible = false; - base.Show(); - } - - /// - public override void Hide() - { - game.IsMouseVisible = true; - base.Hide(); - } - - /// - /// Sets things to correct values for start of transition. - /// - /// The window dimensions. - public void InitiateTransition(Rectangle dimensions) - { - color = Color4.White; - textureBounds.Width = (int)(height * proportion); - textureBounds.Height = (int)(height * proportion); - textureBounds.X = (width) / 2; - textureBounds.Y = (height) / 2; - origin.X = texture.Width / 2f; - origin.Y = texture.Height / 2f; - } - - void DoRotate(float deltaf) - { - rotation += (2f / 3f) * (float)Math.PI * deltaf; - if (rotation >= 2 * Math.PI) - { - rotation = 0; - } - } - - /// - /// Draws the transition. - /// - /// Batch to use. - public void DrawTransition(ConsistentSpriteBatch spriteBatch) - { - spriteBatch.Draw(texture, textureBounds, null, color, rotation, origin, SpriteEffects.None, 0f); - } - - /// - /// Updates the entering transition. - /// - /// Time passed between frames. - /// Whether or not this transition should be waiting. - /// Whether or not transition is complete. - public bool UpdateEnteringTransition(double delta, bool waiting) - { - float deltaf = (float)delta; - if (rotate) - { - DoRotate(deltaf); - } - if (waiting) - { - if (progR < 254 || progG < 254 || progB < 254) - { - if (!recorded) - { - rR = (Color4.White.R - BackgroundColor.R) / ENTER_TIME; - rG = (Color4.White.G - BackgroundColor.G) / ENTER_TIME; - rB = (Color4.White.B - BackgroundColor.B) / ENTER_TIME; - recorded = true; - } - progR += rR * deltaf; - progR = Math.Min(progR, 254); - progG += rG * deltaf; - progG = Math.Min(progG, 254); - progB += rB * deltaf; - progB = Math.Min(progB, 254); - BackgroundColor.R = (byte)progR; - BackgroundColor.G = (byte)progG; - BackgroundColor.B = (byte)progB; - } - else - { - StartExitTransition(true); - return true; - } - } - return false; - } - - /// - /// Updates the exiting transition. - /// - /// Time passed between frames. - /// Whether or not this transition should be waiting. - /// Whether or not transition is complete. - public bool UpdateExitingTransition(double delta, bool waiting) - { - float deltaf = (float)delta; - if (rotate) - { - DoRotate(deltaf); - } - if (progC > 0) - { - float rate = deltaf * 255 / EXIT_TIME; - progC -= rate; - progC = Math.Max(progC, 0); - color.R = (byte)progC; - color.G = (byte)progC; - color.B = (byte)progC; - color.A = (byte)progC; - } - else - { - return true; - } - return false; - } - - } -} diff --git a/RecrownedGTK/Graphics/UI/ScreenSystem/Screen.cs b/RecrownedGTK/Graphics/UI/ScreenSystem/Screen.cs deleted file mode 100644 index 6688d97..0000000 --- a/RecrownedGTK/Graphics/UI/ScreenSystem/Screen.cs +++ /dev/null @@ -1,204 +0,0 @@ -using OpenTK.Graphics; -using RecrownedGTK.Graphics.Render; -using System.Collections.Generic; - -namespace RecrownedGTK.Graphics.UI.ScreenSystem -{ - /// - /// Represents one of the poosible states a screen can be in. - /// - public enum ScreenState { - /// - /// Screen is transitioning in. - /// - EnterTransition, - /// - /// Screen is transitioning out. - /// - ExitTransition, - /// - /// Screen is currently displayed normally without transition. - /// - Normal - } - - /// - /// A screen represents a virtual system of management that controls an system of items to be displayed. - /// - public class Screen - { - /// - /// Transitions to apply. - /// - public readonly List Transitions; - - /// - /// Whether or not to continue rendering this screen onto a buffer for the benefit of the next screen to use as a transition. - /// - public bool UseRenderTargetForExitTransition { get; private set; } - - /// - /// The background color to be used to clear the screen. - /// - public Color4 BackgroundColor; - - /// - /// The next screen to be displayed after exit transition finishes. May be null, leading to transition to previous screen or loading screen. - /// - public Screen NextScreen { get; set; } - - /// - /// The current window dimensions. - /// - public int width, height; - - /// - /// Current state of the screen. - /// - public ScreenState State { get; private set; } - - /// - /// Creates a new screen. - /// - /// True to start in entering transition state. - public Screen(bool useEnterTransition = false) - { - State = useEnterTransition ? ScreenState.EnterTransition : ScreenState.Normal; - Transitions = new List(); - } - - /// - /// Called when screen size is set. - /// - /// The width of the screen. - /// The height of the screen. - public virtual void ApplySize(int width, int height) - { - this.width = width; - this.height = height; - } - - /// - /// Called to update the screen. - /// - /// Game time information. - public virtual void Update(GameTime gameTime) - { - - } - - /// - /// Called to draw this screen. - /// - /// SpriteBatch to use. - public virtual void Draw(ConsistentSpriteBatch spriteBatch) - { - foreach (ITransition transition in Transitions) - { - transition.DrawTransition(spriteBatch); - } - } - - /// - /// Updates the transition based on the current state of the screen. - /// - /// Time passed since last frame in seconds. - /// If the this transition should wait. - /// Only returns true if exit transition is complete. Returns false otherwise. - public bool UpdateTransition(double delta, bool waiting) - { - switch (State) - { - case ScreenState.EnterTransition: - EnteringTransition(delta, waiting); - break; - case ScreenState.ExitTransition: - return ExitingTransition(delta, waiting); - } - - return false; - } - - private void EnteringTransition(double delta, bool waiting) - { - bool complete = true; - for (int transitionID = 0; transitionID < Transitions.Count; transitionID++) - { - ITransition transition = Transitions[transitionID]; - if (!transition.UpdateEnteringTransition(delta, waiting)) - { - complete = false; - } - } - if (complete && State != ScreenState.ExitTransition) - { - State = ScreenState.Normal; - } - } - - private bool ExitingTransition(double delta, bool waiting) - { - bool complete = true; - foreach (ITransition transition in Transitions) - { - if (!transition.UpdateExitingTransition(delta, waiting)) - { - complete = false; - } - - } - return complete; - } - - /// - /// Called when the screen is shown. - /// - public virtual void Show() - { - foreach (ITransition transition in Transitions) - { - transition.InitiateTransition(new Rectangle(0, 0, width, height)); - } - } - - /// - /// Called when this screen is no longer the displayed screen. - /// - public virtual void Hide() - { - - } - - /// - /// Called whenever the status of assets changes from being loaded to unloaded or unloaded to loaded. - /// - /// True for loaded, false for unloaded. - public virtual void AssetLoadStateChange(bool state) - { - - } - - - /// - /// Call this to begin exit transition. - /// - /// Whether or not to use a render target for the next screen to use. - public void StartExitTransition(bool UseRenderTargetForExitTransition = false) - { - this.UseRenderTargetForExitTransition = UseRenderTargetForExitTransition; - State = ScreenState.ExitTransition; - } - - /// - /// Called everytime the previous screen frame buffer updates. Used for transition purposes. - /// - /// The previous screen's render buffer. - public virtual void UpdatePreviousScreenFrame(RenderTarget2D previousScreenFrame) - { - foreach (ITransition transition in Transitions) - { - transition.UpdatePreviousScreenFrame(previousScreenFrame); - } - } - } -} diff --git a/RecrownedGTK/Graphics/UI/ScreenSystem/ScreenManager.cs b/RecrownedGTK/Graphics/UI/ScreenSystem/ScreenManager.cs deleted file mode 100644 index 9cd7aa6..0000000 --- a/RecrownedGTK/Graphics/UI/ScreenSystem/ScreenManager.cs +++ /dev/null @@ -1,213 +0,0 @@ -using OpenTK.Graphics; -using RecrownedGTK.Graphics.Render; -using System; -using System.Diagnostics; - -namespace RecrownedGTK.Graphics.UI.ScreenSystem -{ - /// - /// Called when the first screen is being shown. - /// - /// The screen to show after the loading screen. - public delegate void NeedNextScreen(Screen screen); - - /// - /// A manager for screens. Helps with transitions and updating screens as well as resizes. - /// - public class ScreenManager : IDisposable - { - bool disposed = false; - - /// - /// Called when the first loading screen is done, and needs to show the landing screen. - /// - public event NeedNextScreen NeedNextScreen; - - /// - /// The settings this manager will use to begin a sprite batch. - /// - private GraphicsDeviceManager graphics; - private Screen previousScreen; - private RenderTarget2D previousScreenRenderTarget; - private Screen currentScreen; - private bool firstScreenChangeComplete; - private bool resizing; - /// - /// Currently displayed screen. - /// - public Screen Screen - { - get - { - return currentScreen; - } - set - { - previousScreen = currentScreen; - currentScreen = value; - if (Screen.width != graphics.PreferredBackBufferWidth || Screen.height != graphics.PreferredBackBufferHeight) - { - Screen.ApplySize(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight); - } - if (previousScreen != null && previousScreenRenderTarget == null && previousScreen.UseRenderTargetForExitTransition) - { - previousScreenRenderTarget = new RenderTarget2D(graphics.GraphicsDevice, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight); - } - graphics.GraphicsDevice.SetRenderTarget(previousScreenRenderTarget); - graphics.GraphicsDevice.Clear(Color4.Black); - - Debug.WriteLine("Showing " + value.GetType().Name); - Screen.Show(); - previousScreen?.Hide(); - } - } - - /// - /// Creates a screen manager that helps update, draw, and manage multiple screens and their transitions. Uses its own . - /// - /// The graphics device manager to be used. - public ScreenManager(GraphicsDeviceManager graphicsDeviceManager) - { - graphics = graphicsDeviceManager ?? throw new ArgumentNullException("Graphics device manager argument cannot be null."); - } - - /// - /// Updates the screens. Should be called once every frame. - /// - /// Contains the time that has passed from the last frame. - /// Whether or not there is something a transition should be waiting for. Usually used to wait for assets to complete loading. - public void UpdateCurrentScreen(GameTime gameTime, bool waiting) - { - waiting = !waiting; - switch (Screen.State) - { - case ScreenState.EnterTransition: - if (previousScreen != null && previousScreen.UseRenderTargetForExitTransition) - { - previousScreen.UpdateTransition(gameTime.ElapsedGameTime.TotalSeconds, waiting); - } - Screen.UpdateTransition(gameTime.ElapsedGameTime.TotalSeconds, waiting); - break; - case ScreenState.ExitTransition: - if (Screen.UseRenderTargetForExitTransition || Screen.UpdateTransition(gameTime.ElapsedGameTime.TotalSeconds, waiting)) - { - if (!firstScreenChangeComplete) - { - firstScreenChangeComplete = true; - OnNeedNextScreen(Screen); - } - if (Screen.NextScreen != null) - { - Debug.WriteLine("Changing to the next given screen."); - Screen = Screen.NextScreen; - } - else if (previousScreen != null) - { - Debug.WriteLine("Changing to previous screen."); - Screen = previousScreen; - } - else - { - throw new InvalidOperationException("No next screen provided and no previous screen to return to."); - } - } - break; - } - Screen.Update(gameTime); - } - - /// - /// Renders screen into window. - /// Starts and ends the given . - /// - /// The consistent sprite batch to use. Needs to be consistent as changing render targets requires ending and beginning the sprite batch. - public void DrawScreen(ConsistentSpriteBatch consistentSpriteBatch) - { - if (consistentSpriteBatch == null) - { - throw new ArgumentNullException(nameof(consistentSpriteBatch)); - } - if (Screen == null) return; - - graphics.GraphicsDevice.Clear(Screen.BackgroundColor); - if (Screen.State == ScreenState.EnterTransition && previousScreen != null && previousScreen.UseRenderTargetForExitTransition) - { - graphics.GraphicsDevice.SetRenderTarget(previousScreenRenderTarget); - graphics.GraphicsDevice.Clear(previousScreen.BackgroundColor); - - consistentSpriteBatch.Begin(); - previousScreen.Draw(consistentSpriteBatch); - consistentSpriteBatch.End(); - - graphics.GraphicsDevice.SetRenderTarget(null); - Screen.UpdatePreviousScreenFrame(previousScreenRenderTarget); - } - - consistentSpriteBatch.Begin(); - Screen.Draw(consistentSpriteBatch); - consistentSpriteBatch.End(); - } - - /// - /// Should be called when resize is occurring to change to a loading screen. - /// This will notify the screen of the status of the assets, change the screen to a loading screen, and dispose of the previous screen buffer. - /// - /// The loading screen to change to. - public void Resize(LoadingScreen loadingScreen) - { - if (resizing) throw new InvalidOperationException("Already resizing."); - resizing = true; - if (Screen != null) { - Screen.AssetLoadStateChange(false); - Screen = loadingScreen; - previousScreenRenderTarget.Dispose(); - previousScreenRenderTarget = null; - } - } - - /// - /// Notifies all screen that assets have completed being loaded after a resize. - /// - public void PostResize() - { - if (!resizing) throw new InvalidOperationException("Was never resizing."); - Screen.AssetLoadStateChange(true); - } - - private void OnNeedNextScreen(Screen screen) - { - NeedNextScreen?.Invoke(screen); - } - - /// - /// Disposes this. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// An overridable dispose. - /// - /// True of user invoked dispose called. - public virtual void Dispose(bool disposing) - { - if (disposed) throw new ObjectDisposedException(GetType().Name); - if (disposing) - { - previousScreenRenderTarget?.Dispose(); - } - disposed = true; - } - - /// - /// Destructor. - /// - ~ScreenManager() - { - Dispose(false); - } - } -} diff --git a/RecrownedGTK/Graphics/UI/SkinSystem/Definitions/ButtonSkinDefinition.cs b/RecrownedGTK/Graphics/UI/SkinSystem/Definitions/ButtonSkinDefinition.cs deleted file mode 100644 index 7a56ce6..0000000 --- a/RecrownedGTK/Graphics/UI/SkinSystem/Definitions/ButtonSkinDefinition.cs +++ /dev/null @@ -1,28 +0,0 @@ -using RecrownedGTK.Graphics.UI.Modular.Modules.Interactive; - -namespace RecrownedGTK.Graphics.UI.SkinSystem.Definitions -{ - /// - /// Skin definition for a button. - /// - public class ButtonSkinDefinition : SkinDefinitionData - { - /// - /// Names for the regions in the texture atlas respectively. - /// - public string upRegion, downRegion, disabledRegion, selectedRegion; - - /// - /// Constructs the definition with minimum requirements. - /// - /// Name of region specifying the texture shown for when the button is pressed down. - /// Name of region specifying the texture shown for when the button is not pressed. - public ButtonSkinDefinition(string downRegion, string upRegion) - { - UIModuleType = typeof(Button); - this.downRegion = downRegion; - this.upRegion = upRegion; - } - - } -} diff --git a/RecrownedGTK/Graphics/UI/SkinSystem/Definitions/SkinDefinition.cs b/RecrownedGTK/Graphics/UI/SkinSystem/Definitions/SkinDefinition.cs deleted file mode 100644 index f25d9c7..0000000 --- a/RecrownedGTK/Graphics/UI/SkinSystem/Definitions/SkinDefinition.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; - -namespace RecrownedGTK.Graphics.UI.SkinSystem.Definitions -{ - /// - /// A definition containing the data for the skin system. Needs to follow data transfer object model. - /// - public abstract class SkinDefinitionData - { - /// - /// The full name of the UI module this definition defines. - /// - public string uiModuleTypeFullName; - - /// - /// Sets the module type by setting . - /// - public Type UIModuleType { set { uiModuleTypeFullName = value.FullName; } } - } -} diff --git a/RecrownedGTK/Graphics/UI/SkinSystem/Definitions/TextButtonSkinDefinition.cs b/RecrownedGTK/Graphics/UI/SkinSystem/Definitions/TextButtonSkinDefinition.cs deleted file mode 100644 index c55fb43..0000000 --- a/RecrownedGTK/Graphics/UI/SkinSystem/Definitions/TextButtonSkinDefinition.cs +++ /dev/null @@ -1,25 +0,0 @@ -using RecrownedGTK.Graphics.UI.Modular.Modules.Interactive; - -namespace RecrownedGTK.Graphics.UI.SkinSystem.Definitions -{ - /// - /// Definition for a text button for a skin theme. - /// - public class TextButtonSkinDefinition : ButtonSkinDefinition - { - /// - /// Name of color from the skin to use for the font. - /// - public string fontColor; - - /// - /// Creates this definition with the most minimal requirements. - /// - /// Texture region from skin that represents when the button is pressed down. - /// The texture region that represents when the button is not pressed. - public TextButtonSkinDefinition(string downRegion, string upRegion) : base(downRegion, upRegion) - { - UIModuleType = typeof(TextButton); - } - } -} diff --git a/RecrownedGTK/Graphics/UI/SkinSystem/Definitions/UIScrollableSkinDefinition.cs b/RecrownedGTK/Graphics/UI/SkinSystem/Definitions/UIScrollableSkinDefinition.cs deleted file mode 100644 index c9d4ba3..0000000 --- a/RecrownedGTK/Graphics/UI/SkinSystem/Definitions/UIScrollableSkinDefinition.cs +++ /dev/null @@ -1,32 +0,0 @@ -using RecrownedGTK.Graphics.UI.Modular.Modules; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace RecrownedGTK.Graphics.UI.SkinSystem.Definitions -{ - /// - /// Skin definition of a scroll module. - /// - public class UIScrollableSkinDefinition : SkinDefinitionData - { - /// - /// Name of the region that specifies the texture needed. - /// - public string horizontalBar, verticalBar, horizontalBarTrack, verticalBarTrack, background; - - /// - /// Instantiates the definition with the minimum requirements. - /// - /// Name of the region used by the skin that defines what the horizontal scroll bar looks like. - /// Name of the region used by the skin that defines what the vertical scroll bar looks like. - public UIScrollableSkinDefinition(string horizontalBar, string verticalBar) - { - this.horizontalBar = horizontalBar; - this.verticalBar = verticalBar; - UIModuleType = typeof(UIScrollable); - } - } -} diff --git a/RecrownedGTK/Graphics/UI/SkinSystem/ISkin.cs b/RecrownedGTK/Graphics/UI/SkinSystem/ISkin.cs deleted file mode 100644 index 8f4671d..0000000 --- a/RecrownedGTK/Graphics/UI/SkinSystem/ISkin.cs +++ /dev/null @@ -1,54 +0,0 @@ -using RecrownedGTK.Graphics.Render; -using RecrownedGTK.Types; -using RecrownedGTK.Graphics.UI.SkinSystem.Definitions; -using OpenTK.Graphics; -using OpenTK; - -namespace RecrownedGTK.Graphics.UI.SkinSystem -{ - /// - /// The output requirements of a skin. This allows for very customized skin systems if needed. - /// - public interface ISkin - { - /// - /// The texture for the cursor. - /// - Texture2D CursorTexture { get; } - - /// - /// Draws a region from the texture atlas. - /// - /// Region to draw. - /// The color to tint the region. - /// The batch to use. - /// The destination to draw to. - /// The rotation to use in radians. - /// The origin for the rotation. - void Draw(string regionName, string color, ConsistentSpriteBatch batch, Rectangle destination, float rotation = 0, Vector2 origin = default(Vector2)); - - /// - /// Returns a with given name of defined color; - /// Should use value "default" if is null. - /// - /// Name of defined color. - /// The defined color based on the name given. - Color4 GetColor(string name = null); - - /// - /// Returns a with given name of region. - /// - /// Name of region. - /// Whether or not the region is required. If true, it will throw an error if the region does not exist while if false, will return null if the region does not exist. - /// The region corresponding to the name and may return null depending on if the region exists, and is required. - TextureAtlas.Region GetTextureAtlasRegion(string name, bool required = false); - - /// - /// Returns the proper definition for the given parameters or throws exception in the case the requested definition does not exist. - /// - /// Convenience to cast to the needed definition type. - /// The name of the definition. Default is null and will be replaced with "default" for name. - /// The definition cast to T. - T ObtainDefinition(string definitionName = null) where T : SkinDefinitionData; - } -} \ No newline at end of file diff --git a/RecrownedGTK/Graphics/UI/SkinSystem/MergedSkin.cs b/RecrownedGTK/Graphics/UI/SkinSystem/MergedSkin.cs deleted file mode 100644 index 20d0b7d..0000000 --- a/RecrownedGTK/Graphics/UI/SkinSystem/MergedSkin.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System; -using System.Collections.Generic; -using RecrownedGTK.Graphics.Render; -using RecrownedGTK.Types; -using RecrownedGTK.Graphics.UI.SkinSystem.Definitions; -using OpenTK.Graphics; -using OpenTK; - -namespace RecrownedGTK.Graphics.UI.SkinSystem -{ - internal class MergedSkin : ISkin - { - /// - /// The skin to try to use first. - /// - public ISkin mainSkin; - - /// - /// The fallback skin. - /// - public ISkin alternateSkin; - - public Texture2D CursorTexture - { - get - { - if (mainSkin.CursorTexture != null) { - return mainSkin.CursorTexture; - } else { - return alternateSkin.CursorTexture; - } - } - } - - public void Draw(string regionName, string color, ConsistentSpriteBatch batch, Rectangle destination, float rotation = 0, Vector2 origin = default(Vector2)) - { - try - { - mainSkin.Draw(regionName, color, batch, destination, rotation, origin); - } catch (KeyNotFoundException) - { - alternateSkin.Draw(regionName, color, batch, destination, rotation, origin); - } catch (NullReferenceException) - { - alternateSkin.Draw(regionName, color, batch, destination, rotation, origin); - } - } - - public Color4 GetColor(string name) - { - try - { - return mainSkin.GetColor(name); - } catch (KeyNotFoundException) - { - return alternateSkin.GetColor(name); - } - catch (NullReferenceException) - { - return alternateSkin.GetColor(name); - } - } - - public TextureAtlas.Region GetTextureAtlasRegion(string name, bool required = false) - { - try - { - return mainSkin.GetTextureAtlasRegion(name); - } - catch (NullReferenceException) - { - return alternateSkin.GetTextureAtlasRegion(name, required); - } - } - - public T ObtainDefinition(string definitionName = null) where T : SkinDefinitionData - { - try - { - return mainSkin.ObtainDefinition(definitionName); - } - catch (NullReferenceException) - { - return alternateSkin.ObtainDefinition(definitionName); - } - } - } -} diff --git a/RecrownedGTK/Graphics/UI/SkinSystem/Skin.cs b/RecrownedGTK/Graphics/UI/SkinSystem/Skin.cs deleted file mode 100644 index 6f53514..0000000 --- a/RecrownedGTK/Graphics/UI/SkinSystem/Skin.cs +++ /dev/null @@ -1,183 +0,0 @@ -using RecrownedGTK.Graphics.Render; -using RecrownedGTK.Types; -using RecrownedGTK.Graphics.UI.SkinSystem.Definitions; -using System; -using System.Collections.Generic; -using OpenTK.Graphics; -using OpenTK; - -namespace RecrownedGTK.Graphics.UI.SkinSystem -{ - /// - /// A skin is used to group a theme which can then be applied to the UI via the use of modules. - /// - public class Skin : IDisposable, ISkin - { - /// - /// Whether or not this skin is completed being built and thus ready to use. - /// - public bool Laminated { get; private set; } - private bool disposed; - - private TextureAtlas textureAtlas; - - Dictionary colors; - readonly Dictionary definitionOfType; - readonly Dictionary> definitions; - - /// - /// The texture for the cursor. - /// - public virtual Texture2D CursorTexture { get; private set; } - - /// - /// Creates a basic unfilled skin. - /// - /// The texture atlas to use for this skin. - /// The texture the cursor will be. - public Skin(TextureAtlas textureAtlas, Texture2D cursorTexture) - { - this.textureAtlas = textureAtlas; - this.CursorTexture = cursorTexture; - colors = new Dictionary(); - definitionOfType = new Dictionary(); - definitions = new Dictionary>(); - } - - /// - /// Returns a with given name of region. Null values acceptable. Will return null if parameter is null. - /// - /// Name of region. - /// Whether or not this texture is mandatory for the module to work. If true, will throw error on failing to retrieve. - /// The region corresponding to the name or null if the requested region doesn't exist. - public TextureAtlas.Region GetTextureAtlasRegion(string name, bool required = false) - { - if (!required && (name == null || !textureAtlas.ContainsRegion(name))) - { - return null; - } else - { - return textureAtlas[name]; - } - } - - /// - /// Returns a with given name of defined color; - /// - /// Name of defined color. Will use "default" if null. Default value is null. - /// The defined color based on the name given. - public Color4 GetColor(string name = null) - { - if (name == null) name = "default"; - return colors[name]; - } - - /// - /// Draws a region from the texture atlas. - /// - /// Region to draw. - /// The color to tint the region. - /// The batch to use. - /// The destination to draw to. - /// The rotation to use in radians. - /// The origin for the rotation. - public void Draw(string regionName, string color, ConsistentSpriteBatch batch, Rectangle destination, float rotation = 0, Vector2 origin = default(Vector2)) - { - if (disposed) throw new ObjectDisposedException(GetType().Name); - textureAtlas.Draw(regionName, batch, destination, colors[color], rotation, origin); - } - - private SkinDefinitionData ObtainDefinition(string typeFullName, string definitionName) - { - if (disposed) throw new ObjectDisposedException(GetType().Name); - if (!Laminated) throw new InvalidOperationException("Skin has yet to be laminated yet."); - if (definitionName == null) definitionName = "default"; - if (!definitions.ContainsKey(typeFullName)) throw new KeyNotFoundException("Could not find any skin definition defining type \"" + typeFullName + "\""); - if (!definitions[typeFullName].ContainsKey(definitionName)) throw new KeyNotFoundException("Could not find skin definition defining type \"" + typeFullName + "\" with name \"" + definitionName + "\""); - return definitions[typeFullName][definitionName]; - } - - /// - /// Returns the proper definition for the given parameters or throws exception in the case the requested definition does not exist. - /// - /// Convenience to cast to the needed definition type. - /// The name of the definition. - /// The definition cast to T. - public T ObtainDefinition(string definitionName = null) where T : SkinDefinitionData - { - return (T)ObtainDefinition(definitionOfType[typeof(T).FullName], definitionName); - } - - /// - /// Adds the definition. - /// - /// The name of the definition. Default (if left blank) name is "default". - /// The definition itself. - public void AddDefinition(SkinDefinitionData skinDefinition, string definitionName = null) - { - if (disposed) throw new ObjectDisposedException(GetType().Name); - if (Laminated) throw new InvalidOperationException("This skin has been laminated and cannot be edited."); - if (definitionName == null) definitionName = "default"; - if (!definitions.ContainsKey(skinDefinition.uiModuleTypeFullName)) - { - definitionOfType.Add(skinDefinition.GetType().FullName, skinDefinition.uiModuleTypeFullName); - definitions.Add(skinDefinition.uiModuleTypeFullName, new Dictionary()); - } - else if (definitions[skinDefinition.uiModuleTypeFullName].ContainsKey(definitionName)) throw new ArgumentException("Type of definition with that name already exists!"); - - definitions[skinDefinition.uiModuleTypeFullName].Add(definitionName, skinDefinition); - } - - /// - /// Adds color to skin. - /// - /// - /// - public void AddColor(string name, Color4 color) - { - if (Laminated) throw new InvalidOperationException("This skin has been laminated and cannot be edited."); - colors.Add(name, color); - } - - /// - /// Laminates the skin. Making sure no more additions are done and sets the skin to be ready for use. - /// Needs to be called before any use of skin. Building skin needs to be done before lamination. - /// - public void Laminate() - { - Laminated = true; - } - - /// - /// Disposes and the holding the cursor texture. - /// - public void Dispose() - { - if (disposed) throw new ObjectDisposedException(GetType().Name); - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Overridable dispose function. - /// - /// true when it's a user call to dispose. - public virtual void Dispose(bool disposing) - { - disposed = true; - if (disposing && !disposed) - { - textureAtlas.Dispose(); - CursorTexture.Dispose(); - } - } - - /// - /// Destructor. Calls the dispose with false. - /// - ~Skin() - { - Dispose(false); - } - } -} diff --git a/RecrownedGTK/Graphics/UI/SkinSystem/SkinManager.cs b/RecrownedGTK/Graphics/UI/SkinSystem/SkinManager.cs deleted file mode 100644 index 858de36..0000000 --- a/RecrownedGTK/Graphics/UI/SkinSystem/SkinManager.cs +++ /dev/null @@ -1,239 +0,0 @@ -using OpenTK; -using OpenTK.Graphics; -using Newtonsoft.Json; -using RecrownedGTK.Data; -using RecrownedGTK.Types; -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; - -namespace RecrownedGTK.Graphics.UI.SkinSystem -{ - /// - /// Called when the skin manager has completed a async action. - /// - /// The completed action. - public delegate void AsyncComplete(SkinManager.Action actionCompleted); - - /// - /// Manages reference to default and loading of custom skins. - /// - public class SkinManager - { - private const string EXTENSION = ".rbskin"; - private readonly MergedSkin mergedSkin = new MergedSkin(); - private Thread thread; - private Action action; - private GraphicsDevice graphicsDevice; - private string selectedSkinPath; - private SkinData skinDataToUse; - - /// - /// Whether or not the skin manager is set up with a and . - /// - public bool MergingSkins { get { return (loadedSkin != null && SkinUseable); } } - - /// - /// Whether or not this manager has been set up with at least a base skin. - /// - public bool SkinUseable { get { return BaseSkin == null; } } - - /// - /// The list of paths for all found skins by . May be null. - /// - public volatile List skinPaths; - - /// - /// The event that is called when a state changes. - /// - public event AsyncComplete AsyncCompleteEvent; - - /// - /// The various possible states a skin manager could be in. - /// - public enum Action - { - /// - /// After a search has completed. - /// - SEARCH, - /// - /// Having the skin generated to be in a useable state. - /// - LOAD - } - - /// - /// the skin that favors the selected skin, but still has a fallback to the default skin in case anything is missing. - /// - public ISkin Skin { get { return mergedSkin; } } - - /// - /// The user loaded skin resulted from asynchronous . - /// - public ISkin loadedSkin { get { return mergedSkin.mainSkin; } private set { mergedSkin.mainSkin = value; } } - - /// - /// The default skin in case the selected skin doesn't cover a specific definition or color. - /// - public ISkin BaseSkin { get { return mergedSkin.alternateSkin; } set { mergedSkin.alternateSkin = value; } } - - /// - /// The directory that contains the skins. - /// - public string skinsDirectory; - - /// - /// Performs a recursive asynchronous search of the directory given in a path set by . - /// - public void SearchSkinDirectory() - { - action = Action.SEARCH; - AttemptAsync(); - } - - /// - /// Reads skin data if extension is valid. - /// - /// the path to load from. - /// A that holds all the information and some metadata for the loaded skin. - public SkinData ReadSkinData(string path) - { - if (path.ToLower().EndsWith(EXTENSION)) - { - return JsonConvert.DeserializeObject(File.ReadAllText(path)); - } - throw new ArgumentException("The path given does not point to a file with the required extension \"" + EXTENSION + "\" rather, has \"" + Path.GetExtension(path) + "\"."); - } - - /// - /// loads a skin asynchronously to the . - /// - /// The path pointing to the file with the extension "". - /// Graphics device to use for texture creation. - public void LoadSkin(string path, GraphicsDevice graphicsDevice) - { - action = Action.LOAD; - this.graphicsDevice = graphicsDevice ?? throw new ArgumentNullException("Requires graphics device to create textures."); - selectedSkinPath = path ?? throw new ArgumentNullException("Requires path to find textures."); - skinDataToUse = ReadSkinData(path); - - AttemptAsync(); - } - - private void AttemptAsync() - { - if (thread != null && thread.IsAlive) throw new InvalidOperationException("Already performing task: " + action); - thread = new Thread(ThreadStart); - } - - private void ThreadStart() - { - switch (action) - { - case Action.SEARCH: - SearchForSkins(); - OnAsyncComplete(action); - break; - case Action.LOAD: - loadedSkin = LoadSkinFromData(skinDataToUse, selectedSkinPath, graphicsDevice); - OnAsyncComplete(action); - break; - } - } - - private void SearchForSkins() - { - skinPaths.Clear(); - skinPaths = RecursiveSkinSearch(skinsDirectory); - } - - private Skin LoadSkinFromData(SkinData skinData, string path, GraphicsDevice graphicsDevice) - { - TextureAtlasDataReader textureAtlasDataReader = new TextureAtlasDataReader(); - FileInfo[] skinFiles = Directory.GetParent(path).GetFiles(); - Dictionary filePath = new Dictionary(); - for (int i = 0; i < skinFiles.Length; i++) - { - filePath.Add(skinFiles[i].Name, skinFiles[i].FullName); - } - TextureAtlasDataReader tatlasDataReader = new TextureAtlasDataReader(); - TextureAtlasData atlasData; - atlasData = JsonConvert.DeserializeObject(File.ReadAllText(filePath[skinData.nameOfTextureAtlas])); - Texture2D atlasTexture; - using (FileStream stream = new FileStream(filePath[atlasData.textureName], FileMode.Open)) - { - atlasTexture = Texture2D.FromStream(graphicsDevice, stream); - Vector4[] data = new Vector4[atlasTexture.Width * atlasTexture.Height]; - atlasTexture.GetData(data); - for (int i = 0; i < data.Length; i++) - { - Color4Ext.FromNonPremultiplied(ref data[i]); - } - atlasTexture.SetData(data); - } - TextureAtlas.Region[] regions = textureAtlasDataReader.GenerateAtlasRegionsFromData(atlasData, atlasTexture); - TextureAtlas textureAtlas = new TextureAtlas(atlasTexture, regions); - Texture2D cursorTexture; - if (Path.HasExtension(skinData.cursorTextureName) && filePath.ContainsKey(skinData.cursorTextureName)) - { - using (FileStream stream = new FileStream(filePath[skinData.cursorTextureName], FileMode.Open)) - { - cursorTexture = Texture2D.FromStream(graphicsDevice, stream); - Vector4[] data = new Vector4[cursorTexture.Width * cursorTexture.Height]; - atlasTexture.GetData(data); - for (int i = 0; i < data.Length; i++) - { - Color4Ext.FromNonPremultiplied(ref data[i]); - } - cursorTexture.SetData(data); - } - } - else - { - cursorTexture = textureAtlas[skinData.cursorTextureName].AsTexture2D(graphicsDevice); - } - Skin skin = new Skin(new TextureAtlas(atlasTexture, regions), cursorTexture); - - for (int i = 0; i < skinData.colors.Length; i++) - { - SkinData.ColorData colorData = skinData.colors[i]; - skin.AddColor(colorData.name, new Color4(colorData.r, colorData.g, colorData.b, colorData.a)); - } - - for (int i = 0; i < skinData.definitions.Length; i++) - { - SkinData.DefinitionData definitionData = skinData.definitions[i]; - skin.AddDefinition(definitionData.skin, definitionData.name); - } - - return skin; - } - - private List RecursiveSkinSearch(string path) - { - string[] files = Directory.GetFiles(path); - string[] folders = Directory.GetDirectories(path); - List skins = new List(); - for (int i = 0; i < files.Length; i++) - { - if (files[i].ToLower().EndsWith(EXTENSION)) - { - skins.Add(files[i]); - } - } - for (int i = 0; i < folders.Length; i++) - { - skins.AddRange(RecursiveSkinSearch(folders[i])); - } - - return skins; - } - - private void OnAsyncComplete(Action newState) - { - AsyncCompleteEvent?.Invoke(newState); - } - } -}