Compare commits

...

51 Commits

Author SHA1 Message Date
52279d6d60 Add a WrapText property to Label 2026-06-02 02:08:04 +02:00
7b6fb71e1e Add a ClipContents property to UIElement 2026-06-02 02:03:50 +02:00
e5f7e3aad4 Update TODO 2026-06-02 01:57:15 +02:00
96b2ad44ad TextLayout, match rendered text with measured text, implement word wrapping 2026-06-02 01:55:59 +02:00
8ba21166be Expose scissor mode, use it in UI 2026-06-02 00:59:29 +02:00
b29ab443fe New dirty flag system. Avoid calling updates in rendering (yuck!) 2026-06-02 00:54:36 +02:00
2576ea87bc Move element update out of Render in UISystem, fix Size property retriggering MarkDirty. 2026-06-01 22:45:05 +02:00
7bbfab8359 Use enums for ActionTypes in InputField, use ReadOnlySpan<char> for Font measurements, only measure placeholderSize if the input is empty. 2026-06-01 22:30:54 +02:00
828ff3561b Backspace and direction key echoing in InputField. 2026-05-31 23:01:50 +02:00
c7acc70dcd Input fields and refactors required to support them 2026-05-31 22:14:25 +02:00
b506b78c32 Fix explicit definition of nested styles, resolve parent style if the style for the variant is not present in the stylesheet. 2026-05-31 19:34:51 +02:00
11423d86e5 Document GridSet, fix resource hot reload on every frame. 2025-11-15 17:20:22 +01:00
828ec4973f Add docs to UIInputContext. 2025-07-04 19:13:52 +02:00
bef27762ee Prepare UIElement and Style for animated style implementation. 2025-06-30 18:34:04 +02:00
8a3ed42bb7 Make Merge a method of Style. 2025-06-30 18:04:29 +02:00
52bbf5a9e1 Update TODO 2025-06-30 18:01:16 +02:00
49aa3f071f Update TODO 2025-06-29 23:35:40 +02:00
6c0e6707ee Use font.Size for totalHeight, update default style in TestGame, add Pressed virtual method to Button. 2025-06-29 23:35:08 +02:00
c6e1bf7f41 Add parsing for Size. 2025-06-29 23:27:16 +02:00
5d3a2c2222 Update TODO 2025-06-29 22:27:14 +02:00
e1e965796b Add proper inheritance for TextColor. 2025-06-29 22:24:54 +02:00
207c8a20a4 We got CSS at home 2025-06-29 22:21:13 +02:00
681496d812 Update TODO 2025-06-29 19:39:02 +02:00
6f3a945f34 Update TODO 2025-06-29 19:38:10 +02:00
c18adaeede Element styling, rename IsMousePressed to IsMouseButtonPressed in InputSystem, Button widget. 2025-06-29 19:22:14 +02:00
e75dcb7753 Update TODO 2025-06-29 17:40:22 +02:00
09c24e7123 Don't update MarginContainer if it already matches its parent size, update TestGame. 2025-06-29 17:39:52 +02:00
87e0a69dcf WIP: button widget 2025-06-29 17:29:47 +02:00
b810e1b882 Update TODO 2025-06-29 16:52:48 +02:00
26cb66dbe0 Font fallbacks. 2025-06-29 16:51:06 +02:00
b3c1db3145 Show fallback glyph if its not present in the font, add Japanese font to TestGame. 2025-06-29 16:21:34 +02:00
9bc9810c8f WIP: use kerning for text measuring. 2025-06-29 15:53:29 +02:00
0ec4e45c38 WIP: measure text in Font. 2025-06-29 15:10:37 +02:00
6b108ba56c Make Rect a core type, move Color out of Utils. 2025-06-29 14:29:52 +02:00
e0e8d6e9ff Move some FreeType operations to Font itself, add lazy loading for Glyph data, remove IDisposable from base Resource. 2025-06-29 14:28:39 +02:00
552e05d498 WIP: use Unicode for charmaps inside a font, try read all unicode symbols. 2025-06-29 14:09:11 +02:00
17196c9437 WIP: load fonts with FreeType. 2025-06-25 23:20:46 +02:00
4b2aa31b63 Update TODO 2025-06-25 21:46:30 +02:00
90fe38b017 Remove resizing of FillContainer in TestGame. 2025-06-25 21:41:24 +02:00
8a1e359c22 WIP: GridSet, add Vector2.Snapped extension method. 2025-06-25 19:50:03 +02:00
64d3dba42d Add MarginContainer, mark parent elements dirty when child gets marked dirty too. 2025-06-25 00:35:35 +02:00
5bf052db96 Rename Frame to FillContainer. 2025-06-24 23:48:31 +02:00
389a73cf24 Don't reassign Size in Container if the new size is identical to current size in RecalculateSizes. 2025-06-24 23:44:38 +02:00
d44341974f Add dirty UI element visualization to UISystem, fix Frame being constantly updated. 2025-06-24 23:29:26 +02:00
b2f3e1c351 Remove readonly keyword from FromHexString in Color (whoops!), add docs to Color. 2025-06-24 23:11:12 +02:00
255dea138b Make all predefined colors in Color readonly. 2025-06-24 23:04:17 +02:00
9fa6b45cea Add more colors to Color. 2025-06-24 22:58:52 +02:00
5871e8966b Mark UIElement as dirty in SetParent. 2025-06-24 22:50:45 +02:00
ed9f17e6c4 Add documentation to IElement, Anchor and UIElement. 2025-06-24 22:46:35 +02:00
4362e88eab Add more methods to retrieve resources in ResourceRef, and document existing ones. 2025-06-24 22:25:26 +02:00
58efd449a8 Set window state for Raylib, make Frame occupy full size of parent UIElement or window. 2025-06-24 22:11:38 +02:00
49 changed files with 2947 additions and 559 deletions

26
TODO.md
View File

@@ -5,7 +5,7 @@
- ActionJustPressed and KeyboardKeyJustPressed don't detect inputs consistently.
- **Solution**: This is a problem related to custom frame pacing for fixed timestep. Raylib polls input in BeginFrame, which means certain functions related to JustPressed* may work incorrectly when polled in a separate timestep. This can be fixed if the entire input system will be moved to SDL or with a custom render + input backend altogether.
- ~~Fix any remaining bugs with anchor positioning system.~~
- ~~Containers don't position their chilren correctly when using anchors and adding/removing them.~~
- ~~Containers don't position their chilren correctly when using anchors and adding/removing them.~~
## Core
@@ -69,6 +69,18 @@
- Make action system use an InputMap resource instead.
- Gamepad support
## Diagnostics
- Implement Profiler class.
- Generate a Speedscope report.
- Collect reports for systems
- Game
- Render
- Audio
- ResourceManager
- UI
- Particles
## UI
- ~~Layout~~
@@ -80,8 +92,14 @@
- ~~Positioning (anchors)~~
- ~~Move layouting to Render instead of Update, use Update for input.~~
- Input propagation
- Basic input elements (button, text field, toggle).
- ~~Pass input to widgets.~~
- Add element focus logic, make them focusable with action inputs.
- Basic input elements (~~button~~, ~~text field~~, toggle).
- Styling
- Add style settings for UI panels (for buttons, labels, etc.).
- ~~Style sheet~~
- ~~Add style settings for UI panels (for buttons, labels, etc.).~~
- ~~Parse StyleSheet from TOML file.~~
- Animated styles
- (stretch goal) Style variables
- Find a way to reference external assets in the style (fonts, textures).
- Create a default style for widgets.
- Create a default style for widgets.

View File

@@ -0,0 +1,74 @@
[Button]
BackgroundColor = "#0f62fe"
CornerRadius = 16.0
TextColor = "#ffffff"
Padding = 16.0
[Button.Hovered]
BackgroundColor = "#0353e9"
[Button.Pressed]
BackgroundColor = "#002d9c"
[Button.Danger]
TextColor = "#ffffff"
[Button.Danger.Normal]
BackgroundColor = "#da1e28"
[Button.Danger.Hovered]
BackgroundColor = "#ba1b23"
[Button.Danger.Pressed]
BackgroundColor = "#750e13"
[Button.Outline]
BackgroundColor = [0, 0, 0, 0]
BorderSize = 1.0
BorderColor = "#0f62fe"
[Button.Outline.Normal]
TextColor = "#0353e9"
[Button.Outline.Hovered]
BackgroundColor = "#0353e9"
[Button.Outline.Pressed]
BackgroundColor = "#002d9c"
BorderColor = [0, 0, 0, 0]
[Button.Link]
BackgroundColor = [0, 0, 0, 0]
TextColor = "#0f62fe"
Padding = 0.0
[Button.Link.Normal]
[Button.Link.Hovered]
BorderColor = "#0043ce"
TextColor = "#0043ce"
BorderSize = [0, 0, 0, 1]
[Button.Link.Pressed]
TextColor = "#161616"
BorderSize = [0, 0, 0, 1]
BorderColor = "#161616"
# Default background color for all Container derived classes.
[Container]
BackgroundColor = "#e0e0e0"
[InputField]
TextColor = "#161616"
BorderColor = "#8d8d8d"
BorderSize = [0, 0, 0, 1]
Padding = [16, 16, 4, 8]
[InputField.Focused]
BorderColor = "#0f62fe"
BorderSize = 2.0
# [InputField.Hovered]BorderColor = "#0f62fe"
# BackgroundColor = "#f4f4f4"

Binary file not shown.

View File

@@ -0,0 +1,3 @@
[FontSet]
fonts = ["Inter-Regular.ttf", "NotoSansJP-Regular.ttf"]

View File

@@ -19,8 +19,10 @@ public class TestGame : Game
{
InitializeSystemsDefault();
_uiSystem = new UISystem(Input, ResourceRef<Style>.Empty());
_uiSystem.RenderDebugRects = true;
_uiSystem = new UISystem(Input);
_uiSystem.RenderDebugRects = false;
ResourceManager.EnableFileWatching();
_particleSystem = new ParticleSystem();
@@ -36,12 +38,18 @@ public class TestGame : Game
protected override void LoadResources()
{
ResourceManager.AddResourceLoaderAssociation(new ParticleEmitterSettingsResourceLoader());
ResourceManager.AddResourceLoaderAssociation(new StyleSheetLoader());
if (!ResourceManager.TryLoad("fonts/Inter-Regular.ttf", out _font))
{
}
if (!ResourceManager.TryLoad("fonts/NotoSansJP-Regular.ttf", out _jpFont))
{
}
ResourceManager.TryLoad("icon.png", out _icon);
ResourceManager.TryLoad("sounds/test_sound_mono.ogg", out _sound);
@@ -49,55 +57,86 @@ public class TestGame : Game
{
throw new Exception("Failed to load emitter settings!");
}
if (ResourceManager.TryLoad("default.style.toml", out _styleSheet))
{
}
_defaultFontSet = new([_font, _jpFont]);
}
protected override void Ready()
{
Input.AddInputMapping("reload", new IInputAction[] { new KeyInputAction(KeyboardKey.R) });
_emitterId = _particleSystem.CreateEmitter(Renderer.WindowSize / 2, _fireEffect);
// _emitterId = _particleSystem.CreateEmitter(Renderer.WindowSize / 2, _fireEffect);
_frame.AddChild(_container);
_uiSystem.SetStyleSheet(_styleSheet);
_uiSystem.AddElement(_frame);
var addButton = new Button("Default button", _defaultFontSet);
var removeButton = new Button("Danger button", _defaultFontSet);
removeButton.StyleVariant = "Danger";
var outlineButton = new Button("Outline button", _defaultFontSet);
outlineButton.StyleVariant = "Outline";
var linkButton = new Button("Link button", _defaultFontSet);
linkButton.StyleVariant = "Link";
var c = new HorizontalContainer()
{
StyleVariant = "Layer01",
ConfineToContents = true,
Anchor = Anchor.TopCenter,
};
var inputField = new InputField(string.Empty, _defaultFontSet)
{
PlaceholderText = "Hello, World!"
};
// c.AddChild(addButton);
// c.AddChild(removeButton);
// c.AddChild(outlineButton);
// c.AddChild(linkButton);
// c.AddChild(inputField);
_label = new Label("What the heck??? Word wrapping!!! That's crazy... Noooo wayyy Before GTA 6 too!!!\nnewline :)", _defaultFontSet)
{
Size = new Rect(256.0f, 128.0f),
ClipContents = false,
WrapText = true
};
// _rootFill.AddChild(_label);
_uiSystem.AddElement(_label);
}
protected override void Update(double deltaTime)
{
if (Input.IsActionPressed("reload"))
{
ResourceManager.Reload();
_particleSystem!.RestartEmitter(_emitterId);
}
_uiSystem.SetWindowSize(Renderer.WindowSize);
if (Input.IsActionPressed("accept"))
{
_container.AddChild(new RectangleWidget(new Rect(32.0f, 32.0f), MathUtils.RandomColor()));
}
if (Input.IsActionPressed("cancel") && _container.Children.Count != 0)
{
var lastChild = _container.Children.Last();
_container.RemoveChild(lastChild);
}
if (Input.IsMouseButtonDown(MouseButton.Left))
{
var mousePos = Input.GetMousePosition();
_frame.Size = new Rect(mousePos.X, mousePos.Y);
}
var mousePos = Input.GetMousePosition();
_label.Size = new Rect(mousePos.X, mousePos.Y);
}
protected override void Render(double deltaTime)
{
Renderer.ClearBackground(Color.Black);
foreach (var emitter in _particleSystem!.Emitters)
{
DrawEmitter(emitter);
}
Renderer.ClearBackground(Color.White);
// foreach (var emitter in _particleSystem!.Emitters)
// {
// DrawEmitter(emitter);
// }
Renderer.ResetTransform();
_uiSystem.Render(Renderer);
Renderer.SetTransform(_label.GlobalPosition, Vector2.Zero);
Renderer.DrawRectangleOutline(_label.Size, Color.Red, 2);
}
private void DrawEmitter(ParticleEmitter emitter)
@@ -124,25 +163,30 @@ public class TestGame : Game
private int _emitterId;
private ResourceRef<ParticleEmitterSettingsResource> _fireEffect;
private ResourceRef<Font> _font;
private ResourceRef<Font> _jpFont;
private ResourceRef<StyleSheet> _styleSheet;
private FontSet _defaultFontSet;
private ResourceRef<Sound> _sound;
private ResourceRef<Texture2d> _icon;
private FlexContainer _container = new(minimumSize: new Rect(64.0f, 64.0f), new())
private FlexContainer _container = new(minimumSize: new Rect(256.0f, 256.0f), new())
{
Anchor = Anchor.Center,
Size = new Rect(500, 300),
Direction = FlexDirection.Column,
Justify = JustifyContent.Start,
Align = AlignItems.Center,
Wrap = true,
Gap = 10f
Gap = 8.0f,
StyleVariant = "Layer02",
};
private Frame _frame = new();
// private VerticalContainer _container = new(new Rect(128.0f, 64.0f), new(), 16)
// {
// ConfineToContents = true,
// Anchor = Anchor.CenterLeft,
// AnchorOffset = new Vector2(0.5f, 0.0f)
// };
[NotNull] private Label _label;
private FillContainer _rootFill = new();
private HorizontalContainer _buttonContainer = new(16)
{
ConfineToContents = true,
};
}

46
Voile/GridSet.cs Normal file
View File

@@ -0,0 +1,46 @@
using System.Collections;
using System.Collections.Generic;
using System.Numerics;
using Voile.Extensions;
namespace Voile;
public class GridSet<T>
{
/// <summary>
/// The size of a cell of this <see cref="GridSet"/>.
/// </summary>
public float CellSize { get; }
public GridSet(float cellSize = 32.0f)
{
CellSize = cellSize;
}
/// <summary>
/// Add an element to this <see cref="GridSet"/>.
/// </summary>
/// <param name="position">Position of the element in this <see cref="GridSet"/>.</param>
/// <param name="child">Element to add.</param>
public void Add(Vector2 position, T child)
{
var snap = Vector2.One * CellSize;
position = position.Snapped(snap);
if (_values.TryGetValue(position, out var list))
{
list.Add(child);
}
else
{
_values.Add(position, new List<T>());
}
}
/// <summary>
/// Removes an element from this <see cref="GridSet"/>.
/// </summary>
/// <param name="child">Element to remove.</param>
public void Remove(T child) => throw new NotImplementedException();
private Dictionary<Vector2, List<T>> _values = new();
}

302
Voile/Source/Color.cs Normal file
View File

@@ -0,0 +1,302 @@
namespace Voile
{
// Based on https://github.com/ppr-game/PPR/blob/engine/PER.Util/src/Color.cs
/// <summary>
/// A record struct representing a color.
/// </summary>
public record struct Color
{
public static readonly Color Transparent = new(1.0f, 1.0f, 1.0f, 0.0f);
public static readonly Color AliceBlue = new(0xF0F8FF);
public static readonly Color AntiqueWhite = new(0xFAEBD7);
public static readonly Color Aqua = new(0x00FFFF);
public static readonly Color Aquamarine = new(0x7FFFD4);
public static readonly Color Azure = new(0xF0FFFF);
public static readonly Color Beige = new(0xF5F5DC);
public static readonly Color Bisque = new(0xFFE4C4);
public static readonly Color Black = new(0x000000);
public static readonly Color BlanchedAlmond = new(0xFFEBCD);
public static readonly Color Blue = new(0x0000FF);
public static readonly Color BlueViolet = new(0x8A2BE2);
public static readonly Color Brown = new(0xA52A2A);
public static readonly Color BurlyWood = new(0xDEB887);
public static readonly Color CadetBlue = new(0x5F9EA0);
public static readonly Color Chartreuse = new(0x7FFF00);
public static readonly Color Chocolate = new(0xD2691E);
public static readonly Color Coral = new(0xFF7F50);
public static readonly Color CornflowerBlue = new(0x6495ED);
public static readonly Color Cornsilk = new(0xFFF8DC);
public static readonly Color Crimson = new(0xDC143C);
public static readonly Color Cyan = new(0x00FFFF);
public static readonly Color DarkBlue = new(0x00008B);
public static readonly Color DarkCyan = new(0x008B8B);
public static readonly Color White = new(0xFFFFFF);
public static readonly Color Green = new(0x00FF00);
public static readonly Color Red = new(0xFF0000);
public static readonly Color DarkGoldenRod = new(0xB8860B);
public static readonly Color DarkGray = new(0xA9A9A9);
public static readonly Color DarkGreen = new(0x006400);
public static readonly Color DarkKhaki = new(0xBDB76B);
public static readonly Color DarkMagenta = new(0x8B008B);
public static readonly Color DarkOliveGreen = new(0x556B2F);
public static readonly Color DarkOrange = new(0xFF8C00);
public static readonly Color DarkOrchid = new(0x9932CC);
public static readonly Color DarkRed = new(0x8B0000);
public static readonly Color DarkSalmon = new(0xE9967A);
public static readonly Color DarkSeaGreen = new(0x8FBC8F);
public static readonly Color DarkSlateBlue = new(0x483D8B);
public static readonly Color DarkSlateGray = new(0x2F4F4F);
public static readonly Color DarkTurquoise = new(0x00CED1);
public static readonly Color DarkViolet = new(0x9400D3);
public static readonly Color DeepPink = new(0xFF1493);
public static readonly Color DeepSkyBlue = new(0x00BFFF);
public static readonly Color DimGray = new(0x696969);
public static readonly Color DodgerBlue = new(0x1E90FF);
public static readonly Color FireBrick = new(0xB22222);
public static readonly Color FloralWhite = new(0xFFFAF0);
public static readonly Color ForestGreen = new(0x228B22);
public static readonly Color Gainsboro = new(0xDCDCDC);
public static readonly Color GhostWhite = new(0xF8F8FF);
public static readonly Color Gold = new(0xFFD700);
public static readonly Color GoldenRod = new(0xDAA520);
public static readonly Color Gray = new(0x808080);
public static readonly Color GreenYellow = new(0xADFF2F);
public static readonly Color HoneyDew = new(0xF0FFF0);
public static readonly Color HotPink = new(0xFF69B4);
public static readonly Color IndianRed = new(0xCD5C5C);
public static readonly Color Indigo = new(0x4B0082);
public static readonly Color Ivory = new(0xFFFFF0);
public static readonly Color Khaki = new(0xF0E68C);
public static readonly Color Lavender = new(0xE6E6FA);
public static readonly Color LavenderBlush = new(0xFFF0F5);
public static readonly Color LawnGreen = new(0x7CFC00);
public static readonly Color LemonChiffon = new(0xFFFACD);
public static readonly Color LightBlue = new(0xADD8E6);
public static readonly Color LightCoral = new(0xF08080);
public static readonly Color LightCyan = new(0xE0FFFF);
public static readonly Color LightGoldenRodYellow = new(0xFAFAD2);
public static readonly Color LightGray = new(0xD3D3D3);
public static readonly Color LightGreen = new(0x90EE90);
public static readonly Color LightPink = new(0xFFB6C1);
public static readonly Color LightSalmon = new(0xFFA07A);
public static readonly Color LightSeaGreen = new(0x20B2AA);
public static readonly Color LightSkyBlue = new(0x87CEFA);
public static readonly Color LightSlateGray = new(0x778899);
public static readonly Color LightSteelBlue = new(0xB0C4DE);
public static readonly Color LightYellow = new(0xFFFFE0);
public static readonly Color Lime = new(0x00FF00);
public static readonly Color LimeGreen = new(0x32CD32);
public static readonly Color Linen = new(0xFAF0E6);
public static readonly Color Magenta = new(0xFF00FF);
public static readonly Color Maroon = new(0x800000);
public static readonly Color MediumAquaMarine = new(0x66CDAA);
public static readonly Color MediumBlue = new(0x0000CD);
public static readonly Color MediumOrchid = new(0xBA55D3);
public static readonly Color MediumPurple = new(0x9370DB);
public static readonly Color MediumSeaGreen = new(0x3CB371);
public static readonly Color MediumSlateBlue = new(0x7B68EE);
public static readonly Color MediumSpringGreen = new(0x00FA9A);
public static readonly Color MediumTurquoise = new(0x48D1CC);
public static readonly Color MediumVioletRed = new(0xC71585);
public static readonly Color MidnightBlue = new(0x191970);
public static readonly Color MintCream = new(0xF5FFFA);
public static readonly Color MistyRose = new(0xFFE4E1);
public static readonly Color Moccasin = new(0xFFE4B5);
public static readonly Color NavajoWhite = new(0xFFDEAD);
public static readonly Color Navy = new(0x000080);
public static readonly Color OldLace = new(0xFDF5E6);
public static readonly Color Olive = new(0x808000);
public static readonly Color OliveDrab = new(0x6B8E23);
public static readonly Color Orange = new(0xFFA500);
public static readonly Color OrangeRed = new(0xFF4500);
public static readonly Color Orchid = new(0xDA70D6);
public static readonly Color PaleGoldenRod = new(0xEEE8AA);
public static readonly Color PaleGreen = new(0x98FB98);
public static readonly Color PaleTurquoise = new(0xAFEEEE);
public static readonly Color PaleVioletRed = new(0xDB7093);
public static readonly Color PapayaWhip = new(0xFFEFD5);
public static readonly Color PeachPuff = new(0xFFDAB9);
public static readonly Color Peru = new(0xCD853F);
public static readonly Color Pink = new(0xFFC0CB);
public static readonly Color Plum = new(0xDDA0DD);
public static readonly Color PowderBlue = new(0xB0E0E6);
public static readonly Color Purple = new(0x800080);
public static readonly Color RebeccaPurple = new(0x663399);
public static readonly Color RosyBrown = new(0xBC8F8F);
public static readonly Color RoyalBlue = new(0x4169E1);
public static readonly Color SaddleBrown = new(0x8B4513);
public static readonly Color Salmon = new(0xFA8072);
public static readonly Color SandyBrown = new(0xF4A460);
public static readonly Color SeaGreen = new(0x2E8B57);
public static readonly Color Seashell = new(0xFFF5EE);
public static readonly Color Sienna = new(0xA0522D);
public static readonly Color Silver = new(0xC0C0C0);
public static readonly Color SkyBlue = new(0x87CEEB);
public static readonly Color SlateBlue = new(0x6A5ACD);
public static readonly Color SlateGray = new(0x708090);
public static readonly Color Snow = new(0xFFFAFA);
public static readonly Color SpringGreen = new(0x00FF7F);
public static readonly Color SteelBlue = new(0x4682B4);
public static readonly Color Tan = new(0xD2B48C);
public static readonly Color Teal = new(0x008080);
public static readonly Color Thistle = new(0xD8BFD8);
public static readonly Color Tomato = new(0xFF6347);
public static readonly Color Turquoise = new(0x40E0D0);
public static readonly Color Violet = new(0xEE82EE);
public static readonly Color Wheat = new(0xF5DEB3);
public static readonly Color WhiteSmoke = new(0xF5F5F5);
public static readonly Color Yellow = new(0xFFFF00);
public static readonly Color YellowGreen = new(0x9ACD32);
/// <summary>
/// Red component of this <see cref="Color"/>.
/// </summary>
public byte R { get; set; }
/// <summary>
/// Green component of this <see cref="Color"/>.
/// </summary>
public byte G { get; set; }
/// <summary>
/// Blue component of this <see cref="Color"/>.
/// </summary>
public byte B { get; set; }
/// <summary>
/// Alpha component of this <see cref="Color"/>.
/// </summary>/// <summary>
/// Gets the color as a 32-bit ARGB integer in the format 0xAARRGGBB.
/// </summary>
public byte A { get; set; } = 255;
/// <summary>
/// Gets the color as a 32-bit ARGB integer in the format 0xAARRGGBB.
/// </summary>
public int Argb
{
get
{
int a = A << 24;
int r = R << 16;
int g = G << 8;
int b = B;
return a | r | g | b;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="Color"/> struct using float RGB(A) values between 0 and 1.
/// </summary>
/// <param name="r">The red component (0.0 to 1.0).</param>
/// <param name="g">The green component (0.0 to 1.0).</param>
/// <param name="b">The blue component (0.0 to 1.0).</param>
/// <param name="a">The alpha component (0.0 to 1.0), default is 1.0 (fully opaque).</param>
public Color(float r, float g, float b, float a = 1.0f)
{
R = (byte)Math.Clamp(r * 255, 0, 255);
G = (byte)Math.Clamp(g * 255, 0, 255);
B = (byte)Math.Clamp(b * 255, 0, 255);
A = (byte)Math.Clamp(a * 255, 0, 255);
}
/// <summary>
/// Initializes a new instance of the <see cref="Color"/> struct using byte RGB(A) values.
/// </summary>
/// <param name="r">The red component (0 to 255).</param>
/// <param name="g">The green component (0 to 255).</param>
/// <param name="b">The blue component (0 to 255).</param>
/// <param name="a">The alpha component (0 to 255), default is 255 (fully opaque).</param>
public Color(byte r, byte g, byte b, byte a = 255)
{
R = r;
G = g;
B = b;
A = a;
}
/// <summary>
/// Initializes a new instance of the <see cref="Color"/> struct using a hexadecimal value.
/// </summary>
/// <param name="hex">
/// A 24-bit (RRGGBB) or 32-bit (AARRGGBB) integer representing the color.
/// Alpha is assumed to be 255 if not included.
/// </param>
public Color(int hex)
{
A = 255; // Default alpha to 255 if not provided
B = (byte)(hex & 0xFF);
G = (byte)((hex >> 8) & 0xFF);
R = (byte)((hex >> 16) & 0xFF);
if (hex > 0xFFFFFF) // If the hex value includes alpha
{
A = (byte)((hex >> 24) & 0xFF);
}
}
/// <summary>
/// Parses a color from a hexadecimal string in the format "#RRGGBB" or "#AARRGGBB".
/// </summary>
/// <param name="hex">The hex string representing the color.</param>
/// <returns>A <see cref="Color"/> instance parsed from the string.</returns>
/// <exception cref="ArgumentException">Thrown if the format is invalid.</exception>
public static Color FromHexString(string hex)
{
if (hex.StartsWith("#"))
{
hex = hex[1..];
}
if (hex.Length == 6)
{
int rgb = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);
return new Color(rgb);
}
else if (hex.Length == 8)
{
int rgba = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);
return new Color(rgba);
}
else
{
throw new ArgumentException("Invalid hex color format. Use #RRGGBB or #RRGGBBAA.");
}
}
/// <summary>
/// Returns a lightened version of the color by interpolating toward white.
/// </summary>
/// <param name="amount">A value from 0.0 (no change) to 1.0 (fully white).</param>
/// <returns>A lighter <see cref="Color"/>.</returns>
public Color Lightened(float amount)
{
var result = this;
result.R = (byte)Math.Min(255, R + (255 - R) * amount);
result.G = (byte)Math.Min(255, G + (255 - G) * amount);
result.B = (byte)Math.Min(255, B + (255 - B) * amount);
return result;
}
/// <summary>
/// Returns a darkened version of the color by interpolating toward black.
/// </summary>
/// <param name="amount">A value from 0.0 (no change) to 1.0 (fully black).</param>
/// <returns>A darker <see cref="Color"/>.</returns>
public Color Darkened(float amount)
{
var result = this;
result.R = (byte)(R * (1.0f - amount));
result.G = (byte)(G * (1.0f - amount));
result.B = (byte)(B * (1.0f - amount));
return result;
}
/// <summary>
/// Converts this color to a <see cref="System.Drawing.Color"/>.
/// </summary>
/// <returns>A <see cref="System.Drawing.Color"/> with equivalent ARGB values.</returns>
public System.Drawing.Color ToSystemColor()
{
var result = System.Drawing.Color.FromArgb(Argb);
return result;
}
}
}

View File

@@ -8,5 +8,31 @@ namespace Voile.Extensions
{
return new Vector2((float)MathUtils.Lerp(a.X, b.X, t), (float)MathUtils.Lerp(a.Y, b.Y, t));
}
public static Vector2 Snapped(this Vector2 a, Vector2 snap)
{
var x = a.X % snap.X;
var y = a.Y % snap.Y;
if (x == 0)
{
x = a.X;
}
else
{
x = a.X - x;
}
if (y == 0)
{
y = a.Y;
}
else
{
y = a.Y - y;
}
return new Vector2(x, y);
}
}
}

View File

@@ -45,7 +45,7 @@ namespace Voile.Input
public bool IsPressed(InputSystem inputSystem)
{
return inputSystem.IsMousePressed(MouseButton);
return inputSystem.IsMouseButtonPressed(MouseButton);
}
public bool IsDown(InputSystem inputSystem)

View File

@@ -25,11 +25,8 @@ namespace Voile.Input
/// Some backends require inputs to be polled once per specific interval. Override this method to implement this behavior.
/// </summary>
public virtual void Poll() { }
public void Shutdown() => Dispose();
public void Dispose() => GC.SuppressFinalize(this);
public bool Handled { get => _handled; set => _handled = value; }
public bool IsActionDown(string action)
@@ -108,7 +105,7 @@ namespace Voile.Input
public abstract int GetCharPressed();
public abstract bool IsMousePressed(MouseButton button);
public abstract bool IsMouseButtonPressed(MouseButton button);
public abstract bool IsMouseButtonDown(MouseButton button);
public abstract bool IsMouseButtonReleased(MouseButton button);
public abstract float GetMouseWheelMovement();
@@ -137,18 +134,20 @@ namespace Voile.Input
new KeyInputAction(KeyboardKey.Down),
]);
AddInputMapping("left", [
new KeyInputAction(KeyboardKey.A),
new KeyInputAction(KeyboardKey.Left),
]);
AddInputMapping("right", [
new KeyInputAction(KeyboardKey.D),
new KeyInputAction(KeyboardKey.Right),
]);
AddInputMapping("accept", [
new KeyInputAction(KeyboardKey.Enter),
]);
AddInputMapping("cancel", [
new KeyInputAction(KeyboardKey.Backspace),
new KeyInputAction(KeyboardKey.Escape),
]);
AddInputMapping("backspace", [
new KeyInputAction(KeyboardKey.Backspace)
]);
}

View File

@@ -50,7 +50,7 @@ namespace Voile.Input
public override bool KeyboardKeyJustPressed(KeyboardKey key) => _justPressedKeys.Contains(key);
public override bool KeyboardKeyJustReleased(KeyboardKey key) => _justReleasedKeys.Contains(key);
public override bool IsMousePressed(MouseButton button) => _pressedMouseButtons.Contains(button);
public override bool IsMouseButtonPressed(MouseButton button) => _pressedMouseButtons.Contains(button);
public override bool IsMouseButtonReleased(MouseButton button) => _releasedMouseButtons.Contains(button);
public override bool IsMouseButtonDown(MouseButton button) => _downMouseButtons.Contains(button);

119
Voile/Source/Rect.cs Normal file
View File

@@ -0,0 +1,119 @@
namespace Voile;
/// <summary>
/// Represents a rectangle. Used to determine widget confines for UI layout.
/// </summary>
public class Rect(float width = 0.0f, float height = 0.0f)
{
public float Width { get; set; } = width;
public float Height { get; set; } = height;
public static Rect Zero => new Rect(0.0f, 0.0f);
public float Area => Width * Height;
public int CompareTo(Rect other) => Area.CompareTo(other.Area);
public static bool operator >(Rect left, Rect right) => left.CompareTo(right) > 0;
public static bool operator <(Rect left, Rect right) => left.CompareTo(right) < 0;
public static bool operator >=(Rect left, Rect right) => left.CompareTo(right) >= 0;
public static bool operator <=(Rect left, Rect right) => left.CompareTo(right) <= 0;
/// <summary>
/// Returns the rectangle with the smallest width.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static Rect MinWidth(Rect a, Rect b)
{
if (a < b)
{
return a;
}
else if (a > b)
{
return b;
}
return a;
}
public static Rect MaxWidth(Rect a, Rect b)
{
if (a > b)
{
return a;
}
if (a < b)
{
return b;
}
return a;
}
public static Rect operator +(Rect left, Rect right)
{
var width = left.Width + right.Width;
var height = left.Height + right.Height;
return new(width, height);
}
}
/// <summary>
/// Represents the size offsets applied around a rectangle.
/// </summary>
public struct Size : IEquatable<Size>
{
public float Left;
public float Right;
public float Top;
public float Bottom;
public static Size Zero => new Size(0.0f);
public Size(float uniform)
{
Left = Right = Top = Bottom = uniform;
}
public Size(float horizontal, float vertical)
{
Left = Right = horizontal;
Top = Bottom = vertical;
}
public Size(float left, float right, float top, float bottom)
{
Left = left;
Right = right;
Top = top;
Bottom = bottom;
}
public static Rect operator +(Size margin, Rect rect) =>
new Rect(rect.Width + margin.Left + margin.Right,
rect.Height + margin.Top + margin.Bottom);
public static Rect operator +(Rect rect, Size margin) =>
margin + rect;
public static bool operator ==(Size a, Size b) =>
a.Equals(b);
public static bool operator !=(Size a, Size b) =>
!a.Equals(b);
public bool Equals(Size other) =>
Left == other.Left &&
Right == other.Right &&
Top == other.Top &&
Bottom == other.Bottom;
public override bool Equals(object? obj) =>
obj is Size other && Equals(other);
public override int GetHashCode() =>
HashCode.Combine(Left, Right, Top, Bottom);
}

View File

@@ -81,7 +81,7 @@ namespace Voile.Rendering
Raylib.InitWindow((int)_windowSize.X, (int)_windowSize.Y, windowSettings.Title);
}
// Raylib.SetWindowState(windowFlags);
Raylib.SetWindowState(windowFlags);
}
// TODO
@@ -139,6 +139,13 @@ namespace Voile.Rendering
Raylib.EndBlendMode();
}
public override void BeginScissored(Vector2 position, Rect rect)
{
Raylib.BeginScissorMode((int)position.X, (int)position.Y, (int)rect.Width, (int)rect.Height);
}
public override void EndScissored() => Raylib.EndScissorMode();
public override void BeginCamera2d(Vector2 offset, Vector2 target, float rotation, float zoom)
{
var camera = new Camera2D(offset, target, rotation, zoom);
@@ -240,13 +247,67 @@ namespace Voile.Rendering
var font = fontResource.Value;
if (font.Handle == -1)
LoadFont(font);
if (font.Dirty && font.Handle != -1)
{
UnloadFont(font);
LoadFont(font);
}
var rayFont = _fontPool[font.Handle];
Raylib.DrawTextPro(rayFont, text, transformPosition, transformPivot, transformRotation, font.Size, 0.0f, VoileColorToRaylibColor(color));
var layout = font.Layout(text, transformPosition);
foreach (var line in layout.Lines)
{
foreach (var run in line.Runs)
{
Raylib.DrawTextCodepoint(
rayFont,
run.Character,
run.Position,
font.Size,
VoileColorToRaylibColor(color)
);
}
}
}
/// <summary>
/// Draws the text using a pre-computed text layout.
/// </summary>
/// <param name="font">Rasterized font.</param>
/// <param name="layout"><see cref="TextLayout"/> to draw.</param>
/// <param name="color">Color of the text.</param>
public void DrawText(ResourceRef<Font> fontResource, TextLayout layout, Color color)
{
var font = fontResource.Value;
if (font.Handle == -1)
LoadFont(font);
if (font.Dirty && font.Handle != -1)
{
UnloadFont(font);
LoadFont(font);
}
var rayFont = _fontPool[font.Handle];
foreach (var line in layout.Lines)
{
foreach (var run in line.Runs)
{
Raylib.DrawTextCodepoint(
rayFont,
run.Character,
run.Position,
font.Size,
VoileColorToRaylibColor(color)
);
}
}
}
protected override int GetMonitorWidth(int monitorId)
@@ -268,10 +329,10 @@ namespace Voile.Rendering
{
Raylib_cs.Font fontRay;
string ext = ".ttf"; // TODO: don't use a hardcoded extension.
int fontChars = 250; // TODO: control this dynamically to not load the entire font.
string ext = ".ttf";
int fontChars = font.Codepoints.Count;
fontRay = Raylib.LoadFontFromMemory(ext, font.Buffer, font.Size, null, fontChars);
fontRay = Raylib.LoadFontFromMemory(ext, font.Buffer, font.Size, font.Codepoints.ToArray(), fontChars);
Raylib.GenTextureMipmaps(ref fontRay.Texture);
Raylib.SetTextureFilter(fontRay.Texture, TextureFilter.Bilinear);
@@ -281,6 +342,14 @@ namespace Voile.Rendering
font.Handle = _fontPool.Count - 1;
}
private void UnloadFont(Font font)
{
var fontRay = _fontPool[font.Handle];
Raylib.UnloadFont(fontRay);
_fontPool.RemoveAt(font.Handle);
}
private void LoadTexture(Texture2d texture)
{
Image image = new();

View File

@@ -125,6 +125,9 @@ namespace Voile.Rendering
public abstract void BeginBlended(BlendMode blendMode);
public abstract void EndBlended();
public abstract void BeginScissored(Vector2 position, Rect rect);
public abstract void EndScissored();
/// <summary>
/// Begins drawing using a 2D camera.
/// </summary>
@@ -181,8 +184,12 @@ namespace Voile.Rendering
/// <param name="color">Fill color.</param>
public abstract void DrawRectangle(Vector2 size, Color color);
public void DrawRectangle(Rect rect, Color color) => DrawRectangle(new Vector2(rect.Width, rect.Height), color);
public abstract void DrawRectangleOutline(Vector2 size, Color color, float outlineWidth = 1.0f);
public void DrawRectangleOutline(Rect rect, Color color, float outlineWidth = 1.0f) => DrawRectangleOutline(new Vector2(rect.Width, rect.Height), color, outlineWidth);
/// <summary>
/// Draws a debug text with a default font.
/// </summary>
@@ -256,7 +263,7 @@ namespace Voile.Rendering
{
public string Title;
public Vector2 Size = new Vector2(1280, 720);
public bool Resizable { get; set; }
public bool Resizable { get; set; } = true;
public WindowSettings(string title, Vector2 size)
{

View File

@@ -404,6 +404,16 @@ namespace Voile.Rendering
throw new NotImplementedException();
}
public override void BeginScissored(Vector2 position, Rect rect)
{
throw new NotImplementedException();
}
public override void EndScissored()
{
throw new NotImplementedException();
}
private Vector2 _windowSize = Vector2.Zero;
private IWindow? _window;

View File

@@ -65,6 +65,9 @@ namespace Voile.Resources.DataReaders
/// <param name="defaultValue">Default value in case this getter fails to get data.</param>
/// <returns></returns>
double GetDouble(string key, double defaultValue = 0.0);
string GetString(string key, string defaultValue);
/// <summary>
/// Get a Voile.Color from this data getter.
/// </summary>
@@ -79,5 +82,15 @@ namespace Voile.Resources.DataReaders
/// <param name="defaultValue">Default value in case this getter fails to get data.</param>
/// <returns></returns>
Vector2 GetVector2(string key, Vector2 defaultValue);
/// <summary>
/// Get a <see cref="Size"/> from this data getter.
/// </summary>
/// <param name="key">Key of the value.</param>
/// <param name="defaultValue">Default value in case this getter fails to get data.</param>
/// <returns></returns>
Size GetSize(string key, Size defaultValue);
T[] GetArray<T>(string key, T[] defaultValue);
}
}

View File

@@ -9,163 +9,129 @@ namespace Voile.Resources.DataReaders;
/// </summary>
public class TomlDataReader : IStreamDataReader, IDataValidator, IStreamKeyValueGetter
{
public string ExpectedHeader { get; private set; } = string.Empty;
public TomlDataReader(string expectedHeader)
{
ExpectedHeader = expectedHeader;
}
public TomlDataReader() { }
public void Read(Stream data)
{
using (var reader = new StreamReader(data))
using var reader = new StreamReader(data);
_table = TOML.Parse(reader);
_valid = _table != null;
}
public bool Valid() => _valid;
public bool HasKey(string key)
{
return _table != null &&
_table.HasKey(key);
}
public IEnumerable<string> GetSubKeys()
{
if (_table == null)
return Enumerable.Empty<string>();
return _table.Keys
.Where(k => _table[k].IsTable)
.ToList();
}
public IEnumerable<string> GetSubKeysRecursive(string prefix = "")
{
if (_table == null)
yield break;
foreach (var key in _table.Keys)
{
_table = TOML.Parse(reader);
_valid = _table.HasKey(ExpectedHeader);
var fullKey = string.IsNullOrEmpty(prefix) ? key : $"{prefix}.{key}";
if (_table[key].IsTable)
{
var subReader = GetSubReader(key);
if (subReader != null)
{
foreach (var subKey in subReader.GetSubKeysRecursive(fullKey))
yield return subKey;
yield return fullKey;
}
}
}
}
public IEnumerable<string> GetSubKeys(string subPath)
{
var subReader = GetSubReader(subPath);
if (subReader?._table == null)
return Enumerable.Empty<string>();
return subReader._table.Keys
.Where(k => subReader._table[k].IsTable)
.ToList();
}
public TomlDataReader? GetSubReader(string path)
{
var current = _table;
foreach (var part in path.Split('.'))
{
if (current == null || !current.HasKey(part) || !current[part].IsTable)
return null;
current = current[part].AsTable;
}
return new TomlDataReader { _table = current, _valid = true };
}
public bool GetBool(string key, bool defaultValue = false)
{
if (_table is null)
{
return defaultValue;
}
var dataTable = _table[ExpectedHeader];
if (!dataTable.HasKey(key))
{
return defaultValue;
}
var tableValue = dataTable[key];
if (!tableValue.IsBoolean)
{
return defaultValue;
}
return tableValue.AsBoolean;
}
=> TryGetNode(key, out var node) && node.IsBoolean ? node.AsBoolean : defaultValue;
public int GetInt(string key, int defaultValue = 0)
{
if (_table is null)
{
return defaultValue;
}
var dataTable = _table[ExpectedHeader];
if (!dataTable.HasKey(key))
{
return defaultValue;
}
var tableValue = dataTable[key];
if (!tableValue.IsInteger)
{
return defaultValue;
}
return tableValue.AsInteger;
}
=> TryGetNode(key, out var node) && node.IsInteger ? node.AsInteger : defaultValue;
public long GetLong(string key, long defaultValue = 0)
{
if (_table is null)
{
return defaultValue;
}
var dataTable = _table[ExpectedHeader];
if (!dataTable.HasKey(key))
{
return defaultValue;
}
var tableValue = dataTable[key];
if (!tableValue.IsInteger)
{
return defaultValue;
}
return tableValue.AsInteger.Value;
}
=> TryGetNode(key, out var node) && node.IsInteger ? node.AsInteger.Value : defaultValue;
public float GetFloat(string key, float defaultValue = 0)
{
if (_table is null)
{
if (!TryGetNode(key, out var node))
return defaultValue;
}
var dataTable = _table[ExpectedHeader];
if (!dataTable.HasKey(key))
{
return defaultValue;
}
var tableValue = dataTable[key];
if (!tableValue.IsFloat)
{
if (tableValue.IsInteger) return (float)tableValue.AsInteger.Value;
return defaultValue;
}
return tableValue.AsFloat;
if (node.IsFloat) return node.AsFloat;
if (node.IsInteger) return node.AsInteger;
return defaultValue;
}
public double GetDouble(string key, double defaultValue = 0)
=> TryGetNode(key, out var node) && node.IsFloat ? node.AsFloat : defaultValue;
public string GetString(string key, string defaultValue)
{
if (_table is null)
if (!TryGetNode(key, out var node))
{
return defaultValue;
}
var dataTable = _table[ExpectedHeader];
if (!dataTable.HasKey(key))
if (node.IsString)
{
return defaultValue;
return node.AsString;
}
if (!dataTable.IsFloat)
{
return defaultValue;
}
return dataTable.AsFloat.Value;
return defaultValue;
}
public Color GetColor(string key, Color defaultValue)
{
if (_table is null)
{
if (!TryGetNode(key, out var node))
return defaultValue;
}
var dataTable = _table[ExpectedHeader];
if (!dataTable.HasKey(key))
if (node.IsInteger)
{
return defaultValue;
return new Color(node.AsInteger);
}
var colorNode = dataTable[key];
if (colorNode.IsInteger)
else if (node.IsArray)
{
return new Color(colorNode.AsInteger);
}
else if (colorNode.IsArray)
{
var colorArray = colorNode.AsArray;
var colorArray = node.AsArray;
var rNode = colorArray[0];
var gNode = colorArray[1];
@@ -185,45 +151,102 @@ public class TomlDataReader : IStreamDataReader, IDataValidator, IStreamKeyValue
return new Color((byte)r, (byte)g, (byte)b, (byte)a);
}
else if (colorNode.IsString)
else if (node.IsString)
{
var colorHexString = colorNode.AsString.Value;
var colorHexString = node.AsString.Value;
return Color.FromHexString(colorHexString);
}
else
{
throw new ArgumentException("Color can only be represented as an array of integers in the range of 0-255, array of floats (0-1), hexadecimal, or hex string.");
return defaultValue;
}
}
public Vector2 GetVector2(string key, Vector2 defaultValue)
{
if (_table is null)
{
if (!TryGetNode(key, out var node) || !node.IsArray || node.AsArray.RawArray.Count != 2)
return defaultValue;
}
var dataTable = _table[ExpectedHeader];
if (!dataTable.HasKey(key))
{
return defaultValue;
}
var vector2Node = dataTable[key];
if (!vector2Node.IsArray)
{
return defaultValue;
}
var vector2Array = vector2Node.AsArray;
return new Vector2(vector2Array[0], vector2Array[1]);
var arr = node.AsArray;
return new Vector2(arr[0], arr[1]);
}
public bool Valid() => _valid;
public Size GetSize(string key, Size defaultValue)
{
if (!TryGetNode(key, out var node))
return defaultValue;
if (node.IsInteger)
{
return new Size(node.AsInteger);
}
else if (node.IsFloat)
{
return new Size(node.AsFloat);
}
else if (node.IsArray)
{
var sizeArray = node.AsArray;
var lNode = sizeArray[0];
var rNode = sizeArray[1];
var tNode = sizeArray[2];
var bNode = sizeArray[3];
var l = lNode.IsInteger ? lNode.AsInteger : 0;
var t = tNode.IsInteger ? tNode.AsInteger : 0;
var r = rNode.IsInteger ? rNode.AsInteger : 0;
var b = bNode.IsInteger ? bNode.AsInteger : 0;
return new Size(l, r, t, b);
}
return defaultValue;
}
public T[] GetArray<T>(string key, T[] defaultValue)
{
throw new NotImplementedException("Generic array reading not implemented yet.");
}
private bool TryGetNode(string key, out TomlNode node)
{
node = null!;
if (_table == null)
return false;
var current = _table;
var parts = key.Split('.');
for (int i = 0; i < parts.Length; i++)
{
if (!current.HasKey(parts[i]))
return false;
var child = current[parts[i]];
if (i == parts.Length - 1)
{
node = child;
return true;
}
if (!child.IsTable)
return false;
current = child.AsTable;
}
return false;
}
private TomlTable? _table;
private bool _valid;
// Internal use for subreaders
private TomlDataReader(TomlTable table)
{
_table = table;
_valid = true;
}
}

View File

@@ -1,21 +1,326 @@
using System.Numerics;
using FreeTypeSharp;
using static FreeTypeSharp.FT;
using static FreeTypeSharp.FT_LOAD;
namespace Voile;
public struct Glyph
{
public int TextureId { get; set; } = -1;
public Vector2 Offset;
public float Width { get; set; }
public float Height { get; set; }
public Vector2 Bearing { get; set; }
/// <summary>
/// Glyph's advance in pixels.
/// </summary>
public int Advance { get; set; }
public Glyph() { }
}
public struct GlyphRun
{
public char Character;
public Vector2 Position;
public GlyphRun(char character, Vector2 position)
{
Character = character;
Position = position;
}
}
public struct TextLine
{
public List<GlyphRun> Runs;
public float Width;
public float Height;
public float Ascent;
public float Descent;
public TextLine(List<GlyphRun> runs)
{
Runs = runs;
Width = 0;
Height = 0;
Ascent = 0;
Descent = 0;
}
}
public class TextLayout
{
public List<TextLine> Lines = new();
public Rect Size = Rect.Zero;
}
/// <summary>
/// Represents font data.
/// </summary>
public class Font : Resource
public class Font : Resource, IUpdatableResource, IDisposable
{
/// <summary>
/// Internal handle for the font. If it got successfully loaded into the GPU, the value will be other than -1.
/// </summary>
internal int Handle { get; set; } = -1;
public int Size { get; set; } = 16;
public int Size { get; set; } = 24;
public float LetterSpacing { get; set; } = 0f;
public float SpacingScale { get; set; } = 0.8f; // TODO: this is a super temporary fix for character spacing. Should be fixed once custom font rendering will be implemented.
public byte[]? Buffer { get; private set; }
public long BufferSize { get; set; }
public bool Dirty => _dirty;
internal float UnitsPerEm;
internal nint FacePtr;
internal nint LibraryPtr;
internal List<int> Codepoints => _glyphs.Keys.ToList();
public Font(string path, byte[] buffer) : base(path)
{
Buffer = buffer;
}
public void Dispose()
{
unsafe
{
if (FacePtr != IntPtr.Zero)
FT_Done_Face((FT_FaceRec_*)FacePtr);
if (LibraryPtr != IntPtr.Zero)
FT_Done_FreeType((FT_LibraryRec_*)LibraryPtr);
}
}
/// <summary>
/// Loads a basic ASCII charset for this font.
/// </summary>
public void LoadAsciiData()
{
for (char c = ' '; c < 127; c++)
{
GetGlyph(c);
}
}
public TextLayout Layout(string text, Vector2 origin) => Layout(text.AsSpan(), origin);
public TextLayout Layout(ReadOnlySpan<char> chars, Vector2 origin, float maxWidth = float.MaxValue)
{
var layout = new TextLayout();
float startX = origin.X;
float x = startX;
float y = origin.Y;
float lineHeight = Size;
var currentLine = new List<GlyphRun>();
float lineAscent = 0;
float lineDescent = 0;
float lineWidth = 0;
char prev = '\0';
void BreakLine()
{
layout.Lines.Add(new TextLine(currentLine)
{
Width = lineWidth,
Height = lineHeight,
Ascent = lineAscent,
Descent = lineDescent
});
layout.Size.Width = Math.Max(layout.Size.Width, lineWidth);
currentLine = new List<GlyphRun>();
x = startX;
y += lineHeight;
lineWidth = 0;
lineAscent = 0;
lineDescent = 0;
prev = '\0';
}
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
if (c == '\n')
{
BreakLine();
continue;
}
var glyph = GetGlyph(c);
float advance = 0;
if (prev != '\0')
advance += GetKerning(prev, c);
advance += glyph.Advance * SpacingScale + LetterSpacing;
if (maxWidth > 0 && lineWidth + advance > maxWidth)
{
BreakLine();
}
if (prev != '\0')
{
float kerning = GetKerning(prev, c);
x += kerning;
}
var pos = new Vector2(x, y);
currentLine.Add(new GlyphRun(c, pos));
x += glyph.Advance * SpacingScale + LetterSpacing;
lineWidth += advance;
lineAscent = Math.Max(lineAscent, glyph.Bearing.Y);
lineDescent = Math.Max(lineDescent, glyph.Height - glyph.Bearing.Y);
prev = c;
}
if (currentLine.Count > 0)
BreakLine();
layout.Size.Height = layout.Lines.Count * lineHeight;
return layout;
}
/// <summary>
/// Measures a given string using the font metrics.
/// </summary>
/// <param name="text">Text to measure.</param>
/// <returns>A <see cref="Rect"/> with the sizes of a given text using this font.</returns>
public Rect Measure(string text)
{
return Measure(text.AsSpan());
}
public Rect Measure(ReadOnlySpan<char> chars)
{
var layout = Layout(chars, Vector2.Zero);
return layout.Size;
}
public int GetKerning(char left, char right)
{
unsafe
{
var face = (FT_FaceRec_*)FacePtr;
if (face == null)
return 0;
uint leftIndex = FT_Get_Char_Index(face, left);
uint rightIndex = FT_Get_Char_Index(face, right);
if (leftIndex == 0 || rightIndex == 0)
return 0;
FT_Vector_ kerning;
if (FT_Get_Kerning(face, leftIndex, rightIndex, FT_Kerning_Mode_.FT_KERNING_DEFAULT, &kerning) != 0)
return 0;
return (int)(kerning.x >> 6);
}
}
public Glyph GetGlyph(char character)
{
if (!HasGlyph(character))
{
_glyphs.TryGetValue('?', out var defGlyph);
return defGlyph;
}
if (_glyphs.TryGetValue(character, out var glyph))
return glyph;
var loaded = LoadGlyph(character);
_glyphs[character] = loaded;
_dirty = true;
return loaded;
}
public bool HasGlyph(char character)
{
unsafe
{
var face = (FT_FaceRec_*)FacePtr;
if (FacePtr == IntPtr.Zero)
return false;
return FT_Get_Char_Index(face, character) != 0;
}
}
internal unsafe void InitializeFontSize()
{
var face = (FT_FaceRec_*)FacePtr;
if (face == null)
throw new Exception("Font face not initialized.");
FT_Set_Pixel_Sizes(face, 0, (uint)Size);
}
private unsafe Glyph LoadGlyph(char character)
{
var face = (FT_FaceRec_*)FacePtr;
var error = FT_Load_Char(face, character, FT_LOAD_RENDER);
if (error != 0)
throw new Exception($"Failed to load glyph for '{character}'");
var g = face->glyph;
var bitmap = g->bitmap;
var metrics = g->metrics;
return new Glyph
{
Width = bitmap.width,
Height = bitmap.rows,
Bearing = new Vector2(
metrics.horiBearingX >> 6,
metrics.horiBearingY >> 6
),
Advance = (int)(g->advance.x >> 6)
};
}
public void MarkUpdated()
{
_dirty = false;
}
private bool _dirty;
private Dictionary<int, Glyph> _glyphs = new();
}

View File

@@ -0,0 +1,45 @@
using System.Diagnostics.CodeAnalysis;
namespace Voile.Resources;
/// <summary>
/// Contains a set of multiple fonts. Used to fetch fonts based on availability of glyphs.
/// </summary>
public class FontSet
{
public FontSet() { }
public FontSet(IEnumerable<ResourceRef<Font>> fonts)
{
_fonts = fonts.ToList();
}
public void AddFont(ResourceRef<Font> font) => _fonts.Add(font);
/// <summary>
/// Tries to get a suitable font that has a given character.
/// </summary>
/// <param name="c">Character to get a suitable font for.</param>
/// <param name="result">Font that contains this character.</param>
/// <returns><c>true</c> if a font that contains this character exists, <c>false</c> otherwise.</returns>
public bool TryGetFontFor(char c, [NotNullWhen(true)] out ResourceRef<Font>? result)
{
result = ResourceRef<Font>.Empty();
foreach (var fontRef in _fonts)
{
if (!fontRef.TryGetValue(out var font))
{
return false;
}
if (font.HasGlyph(c))
{
result = fontRef;
return true;
}
}
return false;
}
private List<ResourceRef<Font>> _fonts = new();
}

View File

@@ -1,6 +1,11 @@
using System.Numerics;
using FreeTypeSharp;
using Voile.VFS;
using static FreeTypeSharp.FT;
using static FreeTypeSharp.FT_LOAD;
namespace Voile.Resources;
public class FontLoader : ResourceLoader<Font>
@@ -10,17 +15,43 @@ public class FontLoader : ResourceLoader<Font>
".ttf"
};
protected override Font LoadResource(string path)
{
using Stream stream = VirtualFileSystem.Read(path);
byte[] fileBuffer = new byte[stream.Length];
int bytesRead = stream.Read(fileBuffer, 0, fileBuffer.Length);
var result = new Font(path, fileBuffer);
var result = new Font(path, fileBuffer);
result.BufferSize = bytesRead;
LoadFaceData(result);
result.InitializeFontSize();
result.LoadAsciiData();
return result;
}
private unsafe void LoadFaceData(Font font)
{
FT_LibraryRec_* lib;
FT_Error error = FT_Init_FreeType(&lib);
if (error != 0)
throw new Exception("Failed to init FreeType");
font.LibraryPtr = (nint)lib;
fixed (byte* data = font.Buffer)
{
FT_FaceRec_* face;
error = FT_New_Memory_Face(lib, data, (nint)font.BufferSize, 0, &face);
if (error != 0)
throw new Exception("Failed to load font face");
font.UnitsPerEm = face->units_per_EM;
font.FacePtr = (nint)face;
}
}
}

View File

@@ -65,7 +65,12 @@ namespace Voile.Resources
var resource = ResourceManager.LoadedResources[resourceGuid];
ResourceManager.RemoveResource(resourceGuid);
resource.Dispose();
if (resource is IDisposable disposable)
{
disposable.Dispose();
}
return true;
}

View File

@@ -1,17 +0,0 @@
using Voile.UI;
namespace Voile.Resources;
public class StyleLoader : ResourceLoader<Style>
{
public override IEnumerable<string> SupportedExtensions =>
[
".toml"
];
protected override Style LoadResource(string path)
{
// TODO: implement loading styles.
return new Style(string.Empty);
}
}

View File

@@ -1,3 +1,4 @@
using System.Diagnostics.CodeAnalysis;
using Voile.Resources;
namespace Voile
@@ -13,11 +14,35 @@ namespace Voile
/// </summary>
public readonly Guid Guid = Guid.Empty;
public bool HasValue => Guid != Guid.Empty;
/// <summary>
/// Retrieve a reference.
/// </summary>
public T Value => ResourceManager.GetResource<T>(Guid);
/// <summary>
/// Retrieves a <see cref="Resource"/>.<br />
/// This will throw an <see cref="InvalidOperationException"/> if the resource wasn't loaded or is invalid. <br />
/// You can check if resource was loaded with <see cref="HasValue"/>, or consider using <see cref="TryGetValue"/>.
/// </summary>
public T Value => ResourceManager.GetResource<T>(Guid)
?? throw new InvalidOperationException($"Resource with GUID {Guid} is not loaded or invalid.");
/// <summary>
/// Retrieves a resource or <c>null</c> if the resource wasn't loaded or is invalid.
/// </summary>
public T? ValueOrNull => ResourceManager.GetResource<T>(Guid);
/// <summary>
/// Tries to retrieve a <see cref="Resource"/>.
/// </summary>
/// <param name="value">An instance of a retrieved <see cref="Resource"/>.</param>
/// <returns><c>true</c> if the resource was successfully retrieved, otherwise <c>false</c>.</returns>
public bool TryGetValue([NotNullWhen(true)] out T? value)
{
value = ResourceManager.GetResource<T>(Guid);
return value != null;
}
/// <summary>
/// Create an empty <see cref="ResourceRef"/>.
/// </summary>
/// <returns></returns>
public static ResourceRef<T> Empty()
{
return new ResourceRef<T>(Guid.Empty);
@@ -27,12 +52,34 @@ namespace Voile
{
Guid = guid;
}
public override bool Equals(object? obj)
{
return obj is ResourceRef<T> other && Guid.Equals(other.Guid);
}
public override int GetHashCode()
{
return Guid.GetHashCode();
}
public static bool operator ==(ResourceRef<T>? left, ResourceRef<T>? right)
{
if (ReferenceEquals(left, right)) return true;
if (left is null || right is null) return false;
return left.Guid == right.Guid;
}
public static bool operator !=(ResourceRef<T>? left, ResourceRef<T>? right)
{
return !(left == right);
}
}
/// <summary>
/// Represents data usable by Voile.
/// </summary>
public abstract class Resource : IDisposable
public abstract class Resource
{
/// <summary>
/// Path to this resource.
@@ -43,9 +90,21 @@ namespace Voile
{
Path = path;
}
}
public void Dispose()
{
}
/// <summary>
/// Represents a Resource that requires systems to react to its changes.
/// </summary>
public interface IUpdatableResource
{
/// <summary>
/// Gets a value indicating whether this resource's state has changed and needs to be reloaded.
/// </summary>
bool Dirty { get; }
/// <summary>
/// Marks this resource as updated.
/// </summary>
void MarkUpdated();
}
}

View File

@@ -231,7 +231,7 @@ namespace Voile.Resources
/// </summary>
/// <param name="path">Path to the resource.</param>
/// <returns>True if a resource at the specified path is loaded, otherwise false.</returns>
public bool IsResourceLoaded(string path) => _resourcePathMap.ContainsKey(path);
public static bool IsResourceLoaded(string path) => _resourcePathMap.ContainsKey(path);
/// <summary>
/// Adds a resource loader associated with a resource type.
@@ -269,7 +269,6 @@ namespace Voile.Resources
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size;
@@ -351,7 +350,6 @@ namespace Voile.Resources
{ typeof(Sound), new SoundLoader()},
{typeof(Texture2d), new Texture2dLoader()},
{typeof(Font), new FontLoader()},
{ typeof(Style), new StyleLoader()}
};
private static readonly Dictionary<Type, object> _resourceSaverAssociations = new()

View File

@@ -62,7 +62,7 @@ public class ParticleEmitterSettingsResourceLoader : ResourceLoader<ParticleEmit
{
var settings = new ParticleEmitterSettings();
var reader = new TomlDataReader("ParticleEmitterSettings");
var reader = new TomlDataReader();
reader.Read(VirtualFileSystem.Read(path));
settings.Local = reader.GetBool("Local", true);

View File

@@ -2,23 +2,76 @@ using System.Numerics;
namespace Voile.UI;
/// <summary>
/// Specifies predefined anchor points used to position UI elements relative to their parent container.
/// </summary>
public enum Anchor
{
/// <summary>
/// Anchors the element to the top-left corner of the parent.
/// </summary>
TopLeft,
/// <summary>
/// Anchors the element to the top-center of the parent.
/// </summary>
TopCenter,
/// <summary>
/// Anchors the element to the top-right corner of the parent.
/// </summary>
TopRight,
/// <summary>
/// Anchors the element to the center-left edge of the parent.
/// </summary>
CenterLeft,
/// <summary>
/// Anchors the element to the exact center of the parent.
/// </summary>
Center,
/// <summary>
/// Anchors the element to the center-right edge of the parent.
/// </summary>
CenterRight,
/// <summary>
/// Anchors the element to the bottom-left corner of the parent.
/// </summary>
BottomLeft,
/// <summary>
/// Anchors the element to the bottom-center of the parent.
/// </summary>
BottomCenter,
/// <summary>
/// Anchors the element to the bottom-right corner of the parent.
/// </summary>
BottomRight,
Fill
}
/// <summary>
/// Provides extension methods for calculating anchored positions of UI elements.
/// </summary>
public static class AnchorExtensions
{
/// <summary>
/// Calculates the offset position for an element based on the specified <see cref="Anchor"/>.
/// </summary>
/// <param name="anchor">The anchor mode to use.</param>
/// <param name="parentPosition">The absolute position of the parent container (top-left corner).</param>
/// <param name="parentRect">The bounding rectangle of the parent container.</param>
/// <param name="elementRect">The size of the element being anchored.</param>
/// <returns>
/// A <see cref="Vector2"/> representing the local offset position where the element should be placed inside the parent.
/// </returns>
/// <remarks>
/// The result is the relative offset from the parent's origin, not a global position.
/// </remarks>
public static Vector2 Calculate(this Anchor anchor, Vector2 parentPosition, Rect parentRect, Rect elementRect)
{
var size = new Vector2(elementRect.Width, elementRect.Height);

View File

@@ -3,7 +3,6 @@ using Voile.Rendering;
namespace Voile.UI.Containers;
// TODO: make Container extend Widget, it already implements similar behaviors.
/// <summary>
/// A base class for all UI containers, used to position and rendering child <see cref="IElement">s.
/// </summary>
@@ -17,6 +16,8 @@ public abstract class Container : UIElement, IParentableElement
/// </summary>
public bool ConfineToContents { get; set; } = false;
public override string? StyleElementName => nameof(Container);
public override Rect MinimumSize => _minimumSize;
public Container()
@@ -39,19 +40,20 @@ public abstract class Container : UIElement, IParentableElement
MarkDirty();
}
protected override void OnUpdate()
protected override void OnUpdate(LayoutContext layoutContext)
{
foreach (var child in _children)
for (int i = 0; i < _children.Count; i++)
{
if (child is not IUpdatableElement updatable) continue;
var child = _children[i];
updatable.MarkDirty();
updatable.Update();
if (!child.Visible)
continue;
if (child is IUpdatableElement updatable)
updatable.Update(layoutContext);
if (child is IAnchorableElement anchorable)
{
anchorable.ApplyAnchor(GlobalPosition, Size);
}
}
Arrange();
@@ -62,6 +64,18 @@ public abstract class Container : UIElement, IParentableElement
}
}
public override void MarkDirty(DirtyFlags flags = DirtyFlags.Layout)
{
base.MarkDirty(flags);
foreach (var child in _children)
{
if (child is not IUpdatableElement updatable) continue;
updatable.MarkDirty(flags);
}
}
/// <summary>
/// Called when this <see cref="Container"/> has to rearrange its children.
/// </summary>
@@ -73,6 +87,9 @@ public abstract class Container : UIElement, IParentableElement
/// </summary>
public void RecalculateSizes()
{
if (_children.Count == 0)
return;
float minX = float.MaxValue;
float minY = float.MaxValue;
float maxX = float.MinValue;
@@ -97,38 +114,68 @@ public abstract class Container : UIElement, IParentableElement
float finalWidth = MathF.Max(occupiedWidth, _minimumSize.Width);
float finalHeight = MathF.Max(occupiedHeight, _minimumSize.Height);
Size = new Rect(finalWidth, finalHeight);
var finalSize = new Rect(finalWidth, finalHeight);
if (finalSize != Size)
{
LayoutSize = finalSize;
}
if (_minimumSize > Size)
{
Size = _minimumSize;
LayoutSize = _minimumSize;
}
}
/// <summary>
/// Adds an <see cref="UIElement"/> to the list of children.
/// </summary>
/// <param name="child">Child <see cref="UIElement"/> to add.</param>
/// <exception cref="InvalidOperationException"></exception>
public void AddChild(UIElement child)
{
// child.StyleSheetOverride = StyleSheet;
if (child.Parent != null)
throw new InvalidOperationException("This UIElement already contains a parent.");
_children.Add(child);
child.SetParent(this);
MarkDirty();
Update();
}
/// <summary>
/// Removes an <see cref="UIElement"/> from the list of children.
/// </summary>
/// <param name="child">Child <see cref="UIElement"/> to remove.</param>
/// <exception cref="InvalidOperationException"></exception>
public void RemoveChild(UIElement child)
{
if (child.Parent != this)
throw new InvalidOperationException("This UIElement is not a child of this Container.");
_children.Remove(child);
MarkDirty();
Update();
}
public override void Render(RenderSystem renderer, Style style)
protected override void OnRender(RenderSystem renderer, Style style)
{
renderer.BeginScissored(GlobalPosition, LayoutSize);
foreach (var child in Children)
{
if (child is not IRenderableElement renderable) continue;
renderable.Render(renderer, style);
if (!child.TryGetStyle(StyleSheet.Value, out var childStyle))
{
childStyle = new Style();
}
renderable.Render(renderer, childStyle);
}
renderer.EndScissored();
}
private List<UIElement> _children = new();

View File

@@ -0,0 +1,23 @@
namespace Voile.UI.Containers;
/// <summary>
/// A special container that occupies the entire available size of the parent. <br />
/// Usually used as a root element for the UI system.
/// </summary>
public class FillContainer : Container
{
public override void Arrange()
{
// FillContainer does not position children.
// Children handle their own layout or are absolute.
}
protected override void OnUpdate(LayoutContext layout)
{
Size = Parent != null
? Parent.Size
: new Rect(layout.WindowSize.X, layout.WindowSize.Y);
base.OnUpdate(layout);
}
}

View File

@@ -124,7 +124,7 @@ public class FlexContainer : Container
float justifyOffset = GetJustifyOffset(containerMainSize, lineMainLength, line.Count);
float currentMain = mainPos + justifyOffset;
float maxLineCross = line.Select(child => GetCrossSize(GetChildSize(child))).Max();
float maxLineCross = line.Max(child => GetCrossSize(GetChildSize(child)));
foreach (var child in line)
{

View File

@@ -1,19 +0,0 @@
namespace Voile.UI.Containers;
public class Frame : Container
{
public Frame()
{
}
public Frame(Rect minimumSize) : base(minimumSize)
{
}
public override void Arrange()
{
}
}

View File

@@ -0,0 +1,50 @@
using System.Numerics;
namespace Voile.UI.Containers;
public class MarginContainer : Container
{
/// <summary>
/// The margin to apply around the contents of this container.
/// </summary>
public Size Margin { get; set; }
/// <summary>
/// Specifies if this <see cref="MarginContainer"/> will fill to parent size.
/// </summary>
public bool Fill { get; set; } = true;
public MarginContainer() : this(new Size()) { }
public MarginContainer(Size margin)
{
Margin = margin;
}
protected override void OnUpdate(LayoutContext layoutContext)
{
base.OnUpdate(layoutContext);
if (Parent == null) return;
if (Size != Parent.Size)
{
Size = Parent.Size;
}
}
public override void Arrange()
{
foreach (var child in Children)
{
var newPosition = new Vector2(Margin.Left, Margin.Top);
var newSize = new Rect(
Size.Width - Margin.Left - Margin.Right,
Size.Height - Margin.Top - Margin.Bottom
);
child.Size = newSize;
child.LocalPosition = newPosition;
}
}
}

View File

@@ -0,0 +1,10 @@
namespace Voile.UI;
[Flags]
public enum DirtyFlags
{
None = 0,
Layout = 1 << 0,
Content = 1 << 1,
Style = 1 << 2,
}

View File

@@ -4,6 +4,9 @@ using Voile.Rendering;
namespace Voile.UI;
/// <summary>
/// Represents a basic UI element with position and size information.
/// </summary>
public interface IElement
{
/// <summary>
@@ -16,6 +19,22 @@ public interface IElement
public Rect Size { get; set; }
}
/// <summary>
/// Represents a UI element that requires a frame-independent update tick loop.
/// </summary>
public interface ITickableElement
{
/// <summary>
/// Executes unconditionally on every frame engine loop step.
/// </summary>
/// <param name="dt">Elapsed delta frame time in seconds.</param>
/// <param name="input">InputSystem that this tickable element should use to poll input events.</param>
void Tick(float dt, InputSystem input);
}
/// <summary>
/// Represents a UI element that can contain child elements.
/// </summary>
public interface IParentableElement
{
/// <summary>
@@ -34,6 +53,10 @@ public interface IParentableElement
public void RemoveChild(UIElement child);
}
/// <summary>
/// Represents a UI element that can provide a minimum size constraint.<br />
/// Implement this interface if your UI element is expected to be resizeable.
/// </summary>
public interface IResizeableElement
{
/// <summary>
@@ -42,22 +65,29 @@ public interface IResizeableElement
public abstract Rect MinimumSize { get; }
}
/// <summary>
/// Represents a UI element that supports updates when its state changes.
/// </summary>
public interface IUpdatableElement
{
/// <summary>
/// Specifies if this element's properties have changed, making it necessary to update it.
/// Gets a value indicating whether the element's state has changed and needs to be updated.
/// </summary>
public bool Dirty { get; }
/// <summary>
/// Update this element.
/// </summary>
void Update();
void Update(LayoutContext layoutContext);
/// <summary>
/// Marks this element as changed, requiring an update.
/// Marks this element as dirty (i.e. requiring an update).
/// </summary>
void MarkDirty();
/// <param name="flags">The parts that were updated, as flags.</param>
void MarkDirty(DirtyFlags flags = DirtyFlags.Layout);
}
/// <summary>
/// Represents a UI element that can be rendered to the screen.
/// </summary>
public interface IRenderableElement
{
/// <summary>
@@ -77,6 +107,9 @@ public interface IRenderableElement
public void DrawSize(RenderSystem renderer);
}
/// <summary>
/// Represents a UI element that can receive and process user input.
/// </summary>
public interface IInputElement
{
/// <summary>
@@ -90,9 +123,23 @@ public interface IInputElement
void Input(UIInputContext action);
}
/// <summary>
/// Represents a UI element that supports positional anchoring within a parent.
/// </summary>
public interface IAnchorableElement
{
/// <summary>
/// Gets or sets the anchor point relative to the parent container.
/// </summary>
public Anchor Anchor { get; set; }
/// <summary>
/// Gets or sets an additional offset to apply after anchoring, in pixels.
/// </summary>
public Vector2 AnchorOffset { get; set; }
/// <summary>
/// Applies the current anchor settings based on the parent's position and size.
/// </summary>
/// <param name="parentPosition">The parent's top-left global position.</param>
/// <param name="parentRect">The bounding rectangle of the parent container.</param>
public void ApplyAnchor(Vector2 parentPosition, Rect parentRect);
}

View File

@@ -0,0 +1,13 @@
using System.Numerics;
namespace Voile.UI;
public readonly struct LayoutContext
{
public Vector2 WindowSize { get; }
public LayoutContext(Vector2 windowSize)
{
WindowSize = windowSize;
}
}

View File

@@ -1,23 +0,0 @@
namespace Voile.UI;
/// <summary>
/// Represents a rectangle. Used to determine widget confines for UI layout.
/// </summary>
public record Rect(float Width = 0.0f, float Height = 0.0f)
{
public float Width { get; set; } = Width;
public float Height { get; set; } = Height;
public static Rect Zero => new Rect(0.0f, 0.0f);
public float Area => Width * Height;
public int CompareTo(Rect? other)
{
if (other is null) return 1;
return Area.CompareTo(other.Area);
}
public static bool operator >(Rect left, Rect right) => left.CompareTo(right) > 0;
public static bool operator <(Rect left, Rect right) => left.CompareTo(right) < 0;
public static bool operator >=(Rect left, Rect right) => left.CompareTo(right) >= 0;
public static bool operator <=(Rect left, Rect right) => left.CompareTo(right) <= 0;
}

View File

@@ -1,13 +1,280 @@
using System.Diagnostics.CodeAnalysis;
using Voile.Resources;
using Voile.Resources.DataReaders;
using Voile.UI.Containers;
using Voile.VFS;
namespace Voile.UI;
/// <summary>
/// A resource containing UI style settings.
/// UI style settings.
/// </summary>
public class Style : TextDataResource
public class Style
{
public Style(string path) : base(path)
public enum TransitionType
{
Linear,
EaseIn,
EaseOut,
EaseInOut
}
public float TransitionDuration = 0f;
public TransitionType Transition = TransitionType.Linear;
public Style() { }
public Size? Padding { get; set; }
public Color? BackgroundColor { get; set; }
public Size? BorderSize { get; set; }
public Color? BorderColor { get; set; }
public float CornerRadius { get; set; }
public Color? TextColor { get; set; }
/// <summary>
/// Merges this <see cref="Style"/> with a different one.<br />
/// Properties that are not set for this <see cref="Style"/> will be inherited from <paramref name="overrideStyle"/>.
/// </summary>
/// <param name="other"></param>
/// <returns>A merged <see cref="Style"/>.</returns>
public Style Merge(Style other)
{
return new Style
{
Padding =
other.Padding ?? Padding,
BackgroundColor =
other.BackgroundColor ?? BackgroundColor,
BorderSize =
other.BorderSize ?? BorderSize,
BorderColor =
other.BorderColor ?? BorderColor,
TextColor =
other.TextColor ?? TextColor,
CornerRadius =
other.CornerRadius != default
? other.CornerRadius
: CornerRadius,
TransitionDuration =
other.TransitionDuration != default
? other.TransitionDuration
: TransitionDuration,
Transition =
other.Transition
};
}
}
public class StyleSheetLoader : ResourceLoader<StyleSheet>
{
public override IEnumerable<string> SupportedExtensions => [".toml"];
protected override StyleSheet LoadResource(string path)
{
var result = new StyleSheet(path);
var allStyles = new Dictionary<string, Style>();
using var stream = VirtualFileSystem.Read(path);
_reader.Read(stream);
foreach (var styleKey in _reader.GetSubKeysRecursive())
{
var subReader = _reader.GetSubReader(styleKey);
if (subReader == null || !subReader.Valid())
continue;
var style = ParseStyle(subReader, styleKey);
if (style != null)
{
allStyles[styleKey] = style;
}
}
foreach (var kvp in allStyles)
{
var finalStyle = GetMergedStyle(kvp.Key, allStyles);
result.Add(kvp.Key, finalStyle);
}
return result;
}
private Style ParseStyle(TomlDataReader reader, string input)
{
var style = new Style();
string transitionName = reader.GetString("TransitionType", "Linear");
if (!Enum.TryParse<Style.TransitionType>(transitionName, true, out var transition))
throw new ArgumentException($"\"{transitionName}\" is not a valid TransitionType.");
style.Transition = transition;
if (reader.HasKey("BackgroundColor"))
style.BackgroundColor = reader.GetColor("BackgroundColor", Color.Transparent);
if (reader.HasKey("TextColor"))
style.TextColor = reader.GetColor("TextColor", Color.Black);
if (reader.HasKey("Padding"))
style.Padding = reader.GetSize("Padding", Size.Zero);
if (reader.HasKey("BorderSize"))
style.BorderSize = reader.GetSize("BorderSize", Size.Zero);
if (reader.HasKey("BorderColor"))
style.BorderColor = reader.GetColor("BorderColor", Color.Transparent);
return style;
}
private Style GetMergedStyle(string fullKey, Dictionary<string, Style> allStyles)
{
var parts = fullKey.Split('.');
var merged = new Style();
for (int i = 1; i <= parts.Length; i++)
{
var subKey = string.Join('.', parts.Take(i));
if (allStyles.TryGetValue(subKey, out var parentStyle))
{
merged = merged.Merge(parentStyle);
}
}
return merged;
}
private readonly TomlDataReader _reader = new();
}
public class StyleSheet : Resource
{
public StyleSheet(string path) : base(path)
{
}
public StyleSheet(Dictionary<string, Style> styles) : base(string.Empty)
{
_styles = styles;
}
public void Add(string key, Style style) => _styles.Add(key, style);
public bool TryGet(
string styleName,
[NotNullWhen(true)] out Style? style)
{
style = Resolve(styleName);
return style != null;
}
public static StyleSheet Default => new(new Dictionary<string, Style>()
{
{"Label", new Style()
{
TextColor = Color.FromHexString("#161616"),
BackgroundColor = Color.DarkRed,
BorderSize = new Size(2.0f),
BorderColor = Color.Red
}},
{ "Button", new Style()
{
Padding = new Size(8.0f),
BackgroundColor = Color.FromHexString("#0f62fe"),
TextColor = Color.FromHexString("#ffffff"),
}},
{"Button.Normal", new Style()
{
Padding = new Size(8.0f),
BackgroundColor = Color.FromHexString("#0f62fe"),
TextColor = Color.FromHexString("#ffffff"),
}},
{"Button.Hovered", new Style()
{
Padding = new Size(8.0f),
BackgroundColor = Color.FromHexString("#0353e9"),
TextColor = Color.FromHexString("#ffffff"),
}},
{"Button.Pressed", new Style()
{
Padding = new Size(8.0f),
BackgroundColor = Color.FromHexString("#002d9c"),
TextColor = Color.FromHexString("#ffffff"),
}},
{"Button.Danger", new Style()
{
Padding = new Size(8.0f),
BackgroundColor = Color.FromHexString("#da1e28"),
TextColor = Color.FromHexString("#ffffff"),
}},
{"Button.Danger.Normal", new Style()
{
Padding = new Size(8.0f),
BackgroundColor = Color.FromHexString("#da1e28"),
TextColor = Color.FromHexString("#ffffff"),
}},
{"Button.Danger.Hovered", new Style()
{
Padding = new Size(8.0f),
BackgroundColor = Color.FromHexString("#ba1b23"),
TextColor = Color.FromHexString("#ffffff"),
}},
{"Button.Danger.Pressed", new Style()
{
Padding = new Size(8.0f),
BackgroundColor = Color.FromHexString("#750e13"),
TextColor = Color.FromHexString("#ffffff"),
}},
{"Container", new Style()
{
BackgroundColor = Color.FromHexString("#ffffff"),
TextColor = Color.FromHexString("#ffffff"),
}},
{"Container.Layer01", new Style()
{
BackgroundColor = Color.FromHexString("#f4f4f4"),
TextColor = Color.FromHexString("#ffffff"),
}},
{"Container.Layer02", new Style()
{
BackgroundColor = Color.FromHexString("#e8e8e8"),
TextColor = Color.FromHexString("#ffffff"),
}},
});
private Style? Resolve(string fullKey)
{
var parts = fullKey.Split('.');
Style? merged = null;
for (int i = 1; i <= parts.Length; i++)
{
var subKey = string.Join('.',
parts.Take(i));
if (_styles.TryGetValue(
subKey,
out var style))
{
merged ??= new Style();
merged = merged.Merge(style);
}
}
return merged;
}
private Dictionary<string, Style> _styles = new();
}

View File

@@ -0,0 +1,56 @@
namespace Voile.UI;
public class StyleAnimator
{
public bool IsComplete => _elapsed >= _duration;
public StyleAnimator(Style from, Style to, float duration)
{
_from = from;
_to = to;
_duration = duration;
_elapsed = 0f;
}
public static float Ease(float t, Style.TransitionType type)
{
return type switch
{
Style.TransitionType.Linear => t,
Style.TransitionType.EaseIn => t * t,
Style.TransitionType.EaseOut => t * (2 - t),
Style.TransitionType.EaseInOut => t < 0.5f
? 2 * t * t
: -1 + (4 - 2 * t) * t,
_ => t
};
}
public Style Update(float deltaTime)
{
_elapsed = MathF.Min(_elapsed + deltaTime, _duration);
float t = _duration == 0 ? 1 : _elapsed / _duration;
float easedT = Ease(t, _to.Transition);
return LerpStyle(_from, _to, easedT);
}
private static Style LerpStyle(Style from, Style to, float t)
{
var result = new Style()
{
BackgroundColor = MathUtils.LerpColor(from.BackgroundColor ?? Color.Transparent, to.BackgroundColor ?? Color.Transparent, t),
TextColor = MathUtils.LerpColor(from.TextColor ?? Color.Black, to.TextColor ?? Color.Black, t),
Padding = MathUtils.LerpSize(from.Padding ?? Size.Zero, to.Padding ?? Size.Zero, t),
BorderColor = MathUtils.LerpColor(from.BorderColor ?? Color.Transparent, to.BorderColor ?? Color.Transparent, t),
BorderSize = MathUtils.LerpSize(from.BorderSize ?? Size.Zero, to.BorderSize ?? Size.Zero, t),
Transition = to.Transition
};
return result;
}
private Style _from, _to;
private float _duration, _elapsed;
}

View File

@@ -1,8 +1,13 @@
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using System.Text;
using Voile.Rendering;
namespace Voile.UI;
/// <summary>
/// Base class for all UI elements.
/// </summary>
public abstract class UIElement : IElement, IRenderableElement, IResizeableElement, IUpdatableElement, IAnchorableElement
{
public bool Visible { get; set; } = true;
@@ -10,58 +15,116 @@ public abstract class UIElement : IElement, IRenderableElement, IResizeableEleme
public Vector2 LocalPosition { get; set; } = Vector2.Zero;
public Vector2 GlobalPosition => _parent?.GlobalPosition + LocalPosition ?? LocalPosition;
public string StyleName => $"{StyleElementName ?? "UIElement"}{GetStyleVariantString()}{ConstructStyleModifiers(StyleModifiers)}";
/// <summary>
/// An element name for style.
/// </summary>
public virtual string? StyleElementName { get; }
public string StyleVariant { get; set; } = string.Empty;
/// <summary>
/// List of style modifiers for this <see cref="UIElement"/>.
/// </summary>
public virtual string[]? StyleModifiers { get; }
public ResourceRef<StyleSheet> StyleSheet => Parent?.StyleSheet ?? StyleSheetOverride;
public ResourceRef<StyleSheet> StyleSheetOverride { get; set; } = ResourceRef<StyleSheet>.Empty();
/// <summary>
/// Parent <see cref="UIElement"/> of this element.
/// </summary>
public UIElement? Parent => _parent;
public Rect Size
{
get => _size;
set
{
_size = value;
float width = Math.Max(value.Width, MinimumSize.Width);
float height = Math.Max(value.Height, MinimumSize.Height);
if (value.Width < MinimumSize.Width)
{
_size.Width = MinimumSize.Width;
}
bool changed =
_size.Width != width ||
_size.Height != height;
if (value.Height < MinimumSize.Height)
{
_size.Height = MinimumSize.Height;
}
if (!changed)
return;
MarkDirty();
_size.Width = width;
_size.Height = height;
MarkDirty(DirtyFlags.Layout);
}
}
public Vector2 AnchorOffset { get; set; } = Vector2.Zero;
public Anchor Anchor { get; set; } = Anchor.TopLeft;
public abstract Rect MinimumSize { get; }
public bool Dirty => _dirty;
public bool Dirty => _dirty != DirtyFlags.None || _pendingDirty != DirtyFlags.None;
public virtual void MarkDirty() => _dirty = true;
public bool ClipContents { get; set; } = true;
public bool TryGetStyle(StyleSheet styleSheet, [NotNullWhen(true)] out Style? style)
{
return styleSheet.TryGet(StyleName, out style);
}
public virtual void MarkDirty(DirtyFlags flags = DirtyFlags.Layout) => _pendingDirty |= flags;
/// <summary>
/// Sets a parent element for this <see cref="UIElement"/>.
/// </summary>
/// <param name="parent">Element to parent this <see cref="UIElement"/> to.</param>
public void SetParent(UIElement parent)
{
_parent = parent;
MarkDirty(DirtyFlags.Layout);
}
public void Update()
public void Update(LayoutContext layoutContext)
{
if (!_dirty) return;
_dirty = false;
_dirty |= _pendingDirty;
_pendingDirty = DirtyFlags.None;
if (Size == Rect.Zero)
Size = MinimumSize;
if (_dirty == DirtyFlags.None)
return;
OnUpdate();
if (HasDirty(DirtyFlags.Layout))
OnLayoutUpdate();
if (_parent is not null && _parent.Size != Rect.Zero)
if (HasDirty(DirtyFlags.Content))
OnContentUpdate();
if (HasDirty(DirtyFlags.Style))
OnStyleUpdate();
_dirty = DirtyFlags.None;
OnUpdate(layoutContext);
}
public void Render(RenderSystem renderer, Style style)
{
RenderStyleBox(renderer, style);
if (ClipContents)
{
ApplyAnchor(_parent.GlobalPosition, _parent.Size);
renderer.BeginScissored(GlobalPosition, LayoutSize);
}
OnRender(renderer, style);
if (ClipContents)
{
renderer.EndScissored();
}
}
public abstract void Render(RenderSystem renderer, Style style);
protected abstract void OnUpdate();
public void DrawSize(RenderSystem renderer)
{
renderer.SetTransform(GlobalPosition, Vector2.Zero);
@@ -88,7 +151,124 @@ public abstract class UIElement : IElement, IRenderableElement, IResizeableEleme
LocalPosition = Anchor.Calculate(parentPosition, parentRect, Size) + new Vector2(AnchorOffset.X, AnchorOffset.Y);
}
private bool _dirty = true;
/// <summary>
/// Helper method for determining if this <see cref="UIElement"/> has a specific dirty flag.
/// </summary>
/// <param name="flags"></param>
/// <returns></returns>
public bool HasDirty(DirtyFlags flags) =>
(_dirty & flags) != 0 || (_pendingDirty & flags) != 0;
/// <summary>
/// The layout-computed size of this UI element that doesn't trigger
/// dirty state propagation.
/// </summary>
/// <remarks>
/// This property is intended to be used exclusively by the layout system
/// (e.g. containers during <c>RecalculateSizes</c>).
///
/// Unlike the <see cref="Size"/> property setter, this property does not call
/// <c>MarkDirty</c>, and therefore will not trigger layout invalidation or
/// parent propagation.
/// </remarks>
protected Rect LayoutSize
{
get => _size; set => _size = value;
}
protected abstract void OnRender(RenderSystem renderer, Style style);
protected virtual void OnLayoutUpdate() { }
protected virtual void OnContentUpdate() { }
protected virtual void OnStyleUpdate() { }
protected abstract void OnUpdate(LayoutContext layoutContext);
/// <summary>
/// Renders a stylebox from a given style.
/// </summary>
/// <param name="renderer"></param>
/// <param name="style"></param>
protected void RenderStyleBox(RenderSystem renderer, Style style)
{
var backgroundColor = style.BackgroundColor ?? Color.Transparent;
var borderColor = style.BorderColor ?? Color.Transparent;
var borderSize = style.BorderSize;
var borderLeft = borderSize?.Left ?? 0;
var borderRight = borderSize?.Right ?? 0;
var borderTop = borderSize?.Top ?? 0;
var borderBottom = borderSize?.Bottom ?? 0;
renderer.SetTransform(GlobalPosition, Vector2.Zero);
renderer.DrawRectangle(new Vector2(Size.Width, Size.Height), backgroundColor);
if (borderLeft > 0)
{
renderer.SetTransform(GlobalPosition, Vector2.Zero);
renderer.DrawRectangle(
new Vector2(borderLeft, Size.Height),
borderColor
);
}
if (borderTop > 0)
{
renderer.SetTransform(GlobalPosition, Vector2.Zero);
renderer.DrawRectangle(
new Vector2(Size.Width, borderTop),
borderColor
);
}
if (borderRight > 0)
{
var rightX = GlobalPosition.X + Size.Width - borderRight;
renderer.SetTransform(new Vector2(rightX, GlobalPosition.Y), Vector2.Zero);
renderer.DrawRectangle(
new Vector2(borderRight, Size.Height),
borderColor
);
}
if (borderBottom > 0)
{
var bottomY = GlobalPosition.Y + Size.Height - borderBottom;
renderer.SetTransform(new Vector2(GlobalPosition.X, bottomY), Vector2.Zero);
renderer.DrawRectangle(
new Vector2(Size.Width, borderBottom),
borderColor
);
}
}
private string ConstructStyleModifiers(string[]? modifiers)
{
if (modifiers == null)
{
return string.Empty;
}
var sb = new StringBuilder();
foreach (var modifier in modifiers)
{
if (string.IsNullOrEmpty(modifier)) continue;
sb.Append($".{modifier}");
}
return sb.ToString();
}
private string GetStyleVariantString()
{
if (string.IsNullOrEmpty(StyleVariant))
return string.Empty;
return $".{StyleVariant}";
}
private DirtyFlags _dirty = DirtyFlags.Layout;
private DirtyFlags _pendingDirty = DirtyFlags.None;
private Rect _size = Rect.Zero;
private UIElement? _parent;

View File

@@ -3,19 +3,73 @@ using Voile.Input;
namespace Voile.UI;
/// <summary>
/// Input information for UI elements.
/// </summary>
public class UIInputContext
{
/// <summary>
/// Current action handled by this <see cref="UIElement"/>.
/// </summary>
public IInputAction Action { get; }
/// <summary>
/// Current mouse position.
/// </summary>
public Vector2 MousePosition { get; }
/// <summary>
/// Determines if a left mouse button was pressed.
/// </summary>
public bool MousePressed { get; set; }
/// <summary>
/// Determines if a left mouse button was released.
/// </summary>
public bool MouseReleased { get; set; }
/// <summary>
/// Determines if a left mouse button is currently held.
/// </summary>
public bool MouseDown { get; set; }
/// <summary>
/// Name of the current <see cref="IInputAction"/>.
/// </summary>
public string ActionName { get; }
/// <summary>
/// Keycode of a currently pressed character.
/// </summary>
public int CharPressed { get; }
/// <summary>
/// Determines if the current input action corresponds to a cancel operation (ESC on the keyboard, B on the Xbox controller, etc.)
/// </summary>
public bool IsCancel => ActionName == "cancel";
/// <summary>
/// Determines if the current input action corresponds to a backspace operation. Used for text inputs.
/// </summary>
public bool IsBackspace => ActionName == "backspace";
/// <summary>
/// Determines if the current input action corresponds to an accept/submit operation (ENTER on the keyboard, A on the Xbox controller, etc.)
/// </summary>
public bool IsAccept => ActionName == "accept";
public bool IsLeft => ActionName == "left";
public bool IsRight => ActionName == "right";
public bool IsUp => ActionName == "up";
public bool IsDown => ActionName == "down";
public float DeltaTime { get; init; }
/// <summary>
/// Determines if control key is pressed.
/// </summary>
public bool Control { get; set; }
/// <summary>
/// Determines if this <see cref="UIInputContext"/> registered any character input from keyboard.
/// </summary>
public bool HasCharInput => CharPressed != 0;
/// <summary>
/// Determines if this context's input was already handled and no longer needs to be processed.
/// </summary>
public bool Handled => _handled;
/// <summary>

View File

@@ -4,115 +4,201 @@ using Voile.Rendering;
namespace Voile.UI;
public class UISystem : IUpdatableSystem, IRenderableSystem
public class UISystem : IUpdatableSystem, IRenderableSystem, IReloadableSystem
{
public IReadOnlyList<IElement> Elements => _elements;
public bool RenderDebugRects { get; set; }
public Color DebugSizeRectColor { get; set; } = Color.Red;
public Color DebugDirtyRectColor { get; set; } = new Color(1.0f, 1.0f, 0.0f, 0.5f);
public UISystem(InputSystem inputSystem)
{
_style = ResourceRef<Style>.Empty();
_input = inputSystem;
}
public UISystem(InputSystem inputSystem, ResourceRef<Style> style)
public UISystem(InputSystem inputSystem, List<UIElement> elements)
{
_input = inputSystem;
_style = style;
}
public UISystem(InputSystem inputSystem, ResourceRef<Style> style, List<UIElement> elements)
{
_input = inputSystem;
_style = style;
_elements = elements;
}
public void AddElement(UIElement element) => _elements.Add(element);
public void SetStyleSheet(ResourceRef<StyleSheet> styleSheet)
{
_styleSheet = styleSheet;
}
public void AddElement(UIElement element)
{
element.StyleSheetOverride = _styleSheet;
_elements.Add(element);
}
public void RemoveElement(UIElement element) => _elements.Remove(element);
public void SetWindowSize(Vector2 size)
{
if (_windowSize == size)
return;
_windowSize = size;
foreach (var element in _elements)
element.MarkDirty(DirtyFlags.Layout);
}
public void Update(double deltaTime)
{
HandleInput();
float dt = (float)deltaTime;
PropagateTick(_elements, dt);
HandleInput((float)deltaTime);
foreach (var element in _elements)
{
if (element is not IUpdatableElement updatable) continue;
if (!updatable.Dirty)
continue;
updatable.Update(new LayoutContext(_windowSize));
}
}
public void Render(RenderSystem renderer)
{
// Update elements each time UI system is rendered.
foreach (var element in _elements)
{
if (element is not IUpdatableElement updatable) continue;
updatable.Update();
}
foreach (var element in _elements)
{
if (element is IRenderableElement renderable)
{
renderable.Render(renderer, _style.Value);
var styleSheet = _styleSheet.Value;
if (!RenderDebugRects) return;
renderable.DrawSize(renderer);
}
if (element is IParentableElement parentable)
{
foreach (var child in parentable.Children)
if (!styleSheet.TryGet(element.StyleName, out var style))
{
if (child is not IRenderableElement renderableChild) continue;
if (!RenderDebugRects) return;
renderableChild.DrawSize(renderer);
style = new Style();
}
renderable.Render(renderer, style);
}
}
if (!RenderDebugRects) return;
foreach (var element in _elements)
{
if (element is not UIElement uiElement) continue;
DrawDebugForElement(renderer, uiElement);
}
}
public void Reload()
{
throw new NotImplementedException();
}
private void DrawDebugForElement(RenderSystem renderer, UIElement element)
{
var size = new Vector2(element.Size.Width, element.Size.Height);
renderer.SetTransform(element.GlobalPosition, Vector2.Zero);
renderer.DrawRectangleOutline(size, DebugSizeRectColor);
if (element.Dirty)
{
renderer.DrawRectangle(size, DebugDirtyRectColor);
}
if (element is IParentableElement parentableElement)
{
foreach (var child in parentableElement.Children)
{
if (child is not UIElement childElement) continue;
DrawDebugForElement(renderer, childElement);
}
}
}
private void HandleInput()
private void HandleInput(float deltaTime)
{
int charPressed = _input.GetCharPressed();
Vector2 mousePos = _input.GetMousePosition();
Vector2 currentMousePosition = _input.GetMousePosition();
bool inputHandled = false;
// Process Actions (Pressed or Held)
foreach (var (actionName, mappings) in InputSystem.InputMappings)
{
foreach (var action in mappings)
{
if (action.IsPressed(_input))
bool isPressed = action.IsPressed(_input);
bool isDown = action.IsDown(_input);
if (isPressed)
{
// TODO: specify which mouse button is used in the context.
var context = new UIInputContext(action, mousePos, actionName, charPressed)
{
MouseDown = _input.IsMouseButtonDown(MouseButton.Left),
MouseReleased = _input.IsMouseButtonReleased(MouseButton.Left),
MousePressed = _input.IsMouseButtonReleased(MouseButton.Left),
MousePressed = _input.IsMouseButtonPressed(MouseButton.Left),
DeltaTime = deltaTime
};
if (PropagateInput(_elements, context))
return;
{
inputHandled = true;
break;
}
}
}
if (inputHandled) break;
}
if (inputHandled)
{
_lastMousePosition = currentMousePosition;
return;
}
if (charPressed != 0)
{
var context = new UIInputContext(new KeyInputAction(KeyboardKey.Null), mousePos, "", charPressed);
PropagateInput(_elements, context);
var context = new UIInputContext(new KeyInputAction(KeyboardKey.Null), mousePos, "", charPressed)
{
DeltaTime = deltaTime
};
if (PropagateInput(_elements, context))
{
_lastMousePosition = currentMousePosition;
return;
}
}
if (currentMousePosition != _lastMousePosition)
var frameContext = new UIInputContext(new MouseInputAction(MouseButton.Left), mousePos, "", charPressed)
{
// TODO: specify which mouse button is used in the context.
var context = new UIInputContext(new MouseInputAction(MouseButton.Left), mousePos, "", charPressed)
MouseDown = _input.IsMouseButtonDown(MouseButton.Left),
MouseReleased = _input.IsMouseButtonReleased(MouseButton.Left),
MousePressed = _input.IsMouseButtonPressed(MouseButton.Left),
DeltaTime = deltaTime
};
PropagateInput(_elements, frameContext);
_lastMousePosition = currentMousePosition;
}
private void PropagateTick(List<UIElement> elements, float dt)
{
for (int i = 0; i < elements.Count; i++)
{
var element = elements[i];
if (!element.Visible) continue;
if (element is ITickableElement tickable)
{
MouseDown = _input.IsMouseButtonDown(MouseButton.Left),
MouseReleased = _input.IsMouseButtonReleased(MouseButton.Left),
MousePressed = _input.IsMouseButtonReleased(MouseButton.Left),
};
PropagateInput(_elements, context);
tickable.Tick(dt, _input);
}
if (element is IParentableElement parentable)
{
PropagateTick(parentable.Children.ToList(), dt);
}
}
}
@@ -122,24 +208,26 @@ public class UISystem : IUpdatableSystem, IRenderableSystem
{
var element = elements[i];
if (element is IInputElement inputElement && !inputElement.IgnoreInput)
{
inputElement.Input(context);
_input.SetAsHandled();
// return true;
}
if (element is IParentableElement parent)
{
if (PropagateInput(parent.Children.ToList(), context))
return true;
}
if (element is IInputElement input && !input.IgnoreInput)
{
input.Input(context);
if (context.Handled)
return true;
}
}
return false;
}
private ResourceRef<Style> _style;
private Vector2 _windowSize;
private ResourceRef<StyleSheet> _styleSheet;
private List<UIElement> _elements = new();
private InputSystem _input;

View File

@@ -1,47 +1,190 @@
using System.Numerics;
using Voile.Input;
using Voile.Rendering;
using Voile.Resources;
namespace Voile.UI.Widgets;
public enum ButtonState
{
Disabled,
Hovered,
Pressed,
Normal
}
/// <summary>
/// A clickable button with a label.
/// </summary>
public class Button : Widget
{
public string Label { get; set; } = "Button";
public override Rect MinimumSize => new Rect(Width: 128.0f, Height: 64.0f);
public Button(string label, Action pressedAction)
public enum ButtonState
{
Label = label;
Disabled,
Hovered,
Pressed,
Focused,
Normal
}
public string Text
{
get => _text; set
{
_text = value;
MarkDirty(DirtyFlags.Content);
}
}
public ButtonState CurrentState { get; private set; } = ButtonState.Normal;
public override Rect MinimumSize => Padding + _textSize;
/// <summary>
/// <see cref="FontSet"/> to use with this button.
/// </summary>
public FontSet FontSet { get; set; } = new();
public Size Padding
{
get => _padding; set
{
_padding = value;
}
}
public override string? StyleElementName => nameof(Button);
public override string[]? StyleModifiers =>
[
CurrentState.ToString()
];
public Button(string text, ResourceRef<Font> fontOverride, Action pressedAction)
{
_text = text;
_pressedAction = pressedAction;
FontSet.AddFont(fontOverride);
MarkDirty();
}
public override void Render(RenderSystem renderer, Style style)
public Button(string text, FontSet fontSet)
{
// TODO: use a button color from style.
renderer.SetTransform(GlobalPosition, Vector2.Zero);
renderer.DrawRectangle(new Vector2(MinimumSize.Width, MinimumSize.Height), new Color(0.25f, 0.25f, 0.25f));
_text = text;
FontSet = fontSet;
MarkDirty();
}
public Button(string text, FontSet fontSet, Action pressedAction)
{
_text = text;
_pressedAction = pressedAction;
FontSet = fontSet;
MarkDirty();
}
protected override void OnRender(RenderSystem renderer, Style style)
{
_padding = style.Padding ?? Voile.Size.Zero;
var color = style.TextColor ?? Color.Black;
var pos = new Vector2(
GlobalPosition.X + _padding.Left,
GlobalPosition.Y + _padding.Top);
renderer.SetTransform(pos, Vector2.Zero);
if (_font.HasValue)
{
renderer.DrawText(_font, _text, color);
}
}
protected virtual void Pressed() { }
protected override void OnInput(UIInputContext action)
{
bool isHovering = ContainsPoint(action.MousePosition);
if (action.MousePressed && isHovering)
{
_isHeldDown = true;
CurrentState = ButtonState.Pressed;
}
else if (action.MouseReleased)
{
if (_isHeldDown && isHovering)
{
_pressedAction?.Invoke();
Pressed();
}
_isHeldDown = false;
CurrentState = isHovering ? ButtonState.Hovered : ButtonState.Normal;
}
else
{
if (_isHeldDown)
{
CurrentState = ButtonState.Pressed; // keep showing as pressed
}
else if (isHovering)
{
CurrentState = ButtonState.Hovered;
}
else
{
CurrentState = ButtonState.Normal;
}
}
}
protected override void OnUpdate()
protected override void OnUpdate(LayoutContext layoutContext)
{
throw new NotImplementedException();
ResolveFont();
if (!_font.HasValue)
return;
var font = _font.Value;
var newSize = font.Measure(_text);
_textSize = newSize;
var final = _textSize + _padding;
if (_cachedSize.Width == final.Width &&
_cachedSize.Height == final.Height)
return;
_cachedSize = final;
Size = final;
MarkDirty(DirtyFlags.Layout);
}
private Action _pressedAction;
private void ResolveFont()
{
if (_font.HasValue)
return;
var text = _text;
for (int i = 0; i < text.Length; i++)
{
if (FontSet.TryGetFontFor(text[i], out var f))
{
_font = f;
break;
}
}
}
private Action? _pressedAction;
private Rect _cachedSize = Rect.Zero;
private string _text = "Hello, World!";
private Rect _textSize = Rect.Zero;
private ResourceRef<Font> _font = ResourceRef<Font>.Empty();
private Size _padding;
private bool _isHeldDown;
}

View File

@@ -0,0 +1,289 @@
using System.Numerics;
using Voile.Input;
using Voile.Rendering;
using Voile.Resources;
namespace Voile.UI.Widgets;
public class InputField : Widget, ITickableElement
{
enum ActionType { None, Backspace, Left, Right }
public override Rect MinimumSize => _placeholderSize + _padding;
public override string? StyleElementName => nameof(InputField);
public override string[]? StyleModifiers =>
[
_isFocused ? "Focused" : string.Empty
];
/// <summary>
/// Current text value of this input field.
/// </summary>
public string Value
{
get => _input;
set
{
_input = value ?? string.Empty;
_cursor = Math.Clamp(_cursor, 0, _input.Length);
MarkDirty(DirtyFlags.Content);
}
}
public string PlaceholderText { get; set; } = string.Empty;
public bool IsFocused => _isFocused;
public FontSet FontSet { get; set; } = new();
public InputField(string initialText, FontSet fontSet)
{
_input = initialText ?? string.Empty;
FontSet = fontSet;
MarkDirty();
}
public void Tick(float dt, InputSystem input)
{
if (!_isFocused)
return;
HandleRepeatingActions(dt, input);
}
protected override void OnInput(UIInputContext context)
{
HandleFocus(context);
if (!_isFocused)
{
_lastActiveAction = ActionType.None;
_repeatTimer = 0.0f;
return;
}
HandleTextInput(context);
ClampCursor();
}
private void HandleFocus(UIInputContext context)
{
if (!context.MousePressed)
return;
bool isInside = ContainsPoint(context.MousePosition);
_isFocused = isInside;
if (isInside)
context.SetHandled();
}
private void HandleTextInput(UIInputContext context)
{
if (!context.HasCharInput)
return;
char c = (char)context.CharPressed;
if (!char.IsControl(c))
{
_input = _input.Insert(_cursor, c.ToString());
_cursor++;
MarkDirty(DirtyFlags.Content);
}
context.SetHandled();
}
private void HandleRepeatingActions(float dt, InputSystem input)
{
ActionType currentAction = ActionType.None;
if (input.IsKeyboardKeyDown(KeyboardKey.Backspace)) currentAction = ActionType.Backspace;
else if (input.IsKeyboardKeyDown(KeyboardKey.Left)) currentAction = ActionType.Left;
else if (input.IsKeyboardKeyDown(KeyboardKey.Right)) currentAction = ActionType.Right;
if (currentAction == ActionType.None)
{
_lastActiveAction = ActionType.None;
_repeatTimer = 0.0f;
return;
}
bool shouldExecute = false;
if (_lastActiveAction != currentAction)
{
shouldExecute = true;
_repeatTimer = 0.0f;
_lastActiveAction = currentAction;
}
else
{
_repeatTimer += dt;
if (_repeatTimer >= INITIAL_DELAY)
{
shouldExecute = true;
_repeatTimer = INITIAL_DELAY - REPEAT_RATE;
}
}
if (shouldExecute)
{
ExecuteAction(currentAction);
}
}
private void ExecuteAction(ActionType action)
{
switch (action)
{
case ActionType.Backspace:
if (_cursor > 0 && _input.Length > 0)
{
_input = _input.Remove(_cursor - 1, 1);
_cursor--;
MarkDirty(DirtyFlags.Content);
}
break;
case ActionType.Left:
if (_cursor > 0)
{
_cursor--;
MarkDirty(DirtyFlags.Content);
}
break;
case ActionType.Right:
if (_cursor < _input.Length)
{
_cursor++;
MarkDirty(DirtyFlags.Content);
}
break;
}
}
private void ClampCursor()
{
_cursor = Math.Clamp(_cursor, 0, _input.Length);
}
protected override void OnRender(RenderSystem renderer, Style style)
{
_padding = style.Padding ?? Voile.Size.Zero;
var textColor = style.TextColor ?? Color.Black;
var caretColor = style.BorderColor ?? Color.Black;
var pos = new Vector2(GlobalPosition.X + _padding.Left,
GlobalPosition.Y + _padding.Top);
renderer.SetTransform(pos, Vector2.Zero);
string text = string.IsNullOrEmpty(_input)
? PlaceholderText
: _input;
// TODO: use a placeholder color from the style instead of making it lighter than the original text color.
var placeholderColor = textColor.Lightened(0.5f);
var color = string.IsNullOrEmpty(_input)
? placeholderColor
: textColor;
if (_font.HasValue)
renderer.DrawText(_font, text, color);
if (_isFocused && _blink)
{
float caretX = GetCaretX(_cursor);
renderer.SetTransform(
new Vector2(GlobalPosition.X + _padding.Left + caretX,
GlobalPosition.Y + _padding.Top),
Vector2.Zero);
float h = Math.Max(_textSize.Height, _placeholderSize.Height);
renderer.DrawRectangle(new Vector2(1, h), caretColor);
}
}
protected override void OnUpdate(LayoutContext layoutContext)
{
if (!_font.HasValue)
ResolveFont();
if (!_font.HasValue)
return;
var font = _font.Value;
_textSize = font.Measure(_input);
if (_input.Length == 0)
_placeholderSize = font.Measure(PlaceholderText);
var content = Rect.MaxWidth(_textSize, _placeholderSize);
float width = content.Width + _padding.Left + _padding.Right;
float height = content.Height + _padding.Top + _padding.Bottom;
if (LayoutSize.Width == width && LayoutSize.Height == height)
return;
LayoutSize = new Rect(width, height);
MarkDirty(DirtyFlags.Layout);
}
private float GetCaretX(int index)
{
var span = _input.AsSpan(0, index);
if (!_font.HasValue)
return 0.0f;
return _font.Value.Measure(span).Width;
}
private void ResolveFont()
{
if (_font.HasValue)
return;
var text = string.IsNullOrEmpty(_input) ? PlaceholderText : _input;
foreach (var c in text)
{
if (FontSet.TryGetFontFor(c, out var f))
_font = f;
}
}
private float _repeatTimer = 0.0f;
private ActionType _lastActiveAction = ActionType.None;
private const float INITIAL_DELAY = 0.5f;
private const float REPEAT_RATE = 0.05f;
private string _input = string.Empty;
private bool _isFocused;
private int _cursor;
private bool _blink = true;
private ResourceRef<Font> _font = ResourceRef<Font>.Empty();
private Size _padding = Voile.Size.Zero;
private Rect _textSize = Rect.Zero;
private Rect _placeholderSize = Rect.Zero;
}

View File

@@ -1,43 +1,96 @@
using System.Numerics;
using Voile.Input;
using Voile.Rendering;
using Voile.Resources;
namespace Voile.UI.Widgets;
public class Label : Widget
{
public override Rect MinimumSize => throw new NotImplementedException();
public override Rect MinimumSize => Rect.Zero;
public string Text { get; set; } = "Hello World!";
public bool WrapText { get; set; } = false;
public Label(string text)
public string Text
{
Text = text;
get => _text; set
{
_text = value;
MarkDirty();
}
}
public override string? StyleElementName => nameof(Label);
/// <summary>
/// <see cref="FontSet"/> to use with this label.
/// </summary>
public FontSet FontSet { get; set; } = new();
public Label(string text, ResourceRef<Font> fontOverride)
{
Text = text;
_fontOverride = fontOverride;
_text = text;
FontSet.AddFont(fontOverride);
MarkDirty();
}
public Label(string text, FontSet fontSet)
{
_text = text;
FontSet = fontSet;
MarkDirty();
}
protected override void OnInput(UIInputContext action)
{
throw new NotImplementedException();
}
public override void Render(RenderSystem renderer, Style style)
protected override void OnRender(RenderSystem renderer, Style style)
{
// TODO: use style here.
if (!_fontOverride.HasValue) return;
if (!_font.HasValue)
return;
if (renderer is not RaylibRenderSystem rayRenderer) return; // TODO: Do NOT rely on RaylibRenderSystem check here. Very bad.
renderer.SetTransform(GlobalPosition, Vector2.Zero);
renderer.DrawText(_fontOverride, Text, Color.White);
rayRenderer.DrawText(_font, _layout, style.TextColor ?? Color.Black);
}
protected override void OnUpdate()
protected override void OnUpdate(LayoutContext layoutContext)
{
throw new NotImplementedException();
ResolveFont();
if (!_font.HasValue)
return;
var width = WrapText ? Size.Width : float.MaxValue;
_layout = _font.Value.Layout(_text, Vector2.Zero, width);
}
private ResourceRef<Font> _fontOverride = ResourceRef<Font>.Empty();
private void ResolveFont()
{
if (_font.HasValue)
return;
var text = _text;
for (int i = 0; i < text.Length; i++)
{
if (FontSet.TryGetFontFor(text[i], out var f))
{
_font = f;
break;
}
}
}
private ResourceRef<Font> _font = ResourceRef<Font>.Empty();
private string _text = "Hello, World!";
private TextLayout _layout = new();
}

View File

@@ -20,7 +20,7 @@ public class RectangleWidget : Widget
_hoverColor = color.Lightened(0.25f);
}
public override void Render(RenderSystem renderer, Style style)
protected override void OnRender(RenderSystem renderer, Style style)
{
renderer.SetTransform(GlobalPosition, Vector2.Zero);
renderer.DrawRectangle(new Vector2(Size.Width, Size.Height), Color);
@@ -65,7 +65,7 @@ public class RectangleWidget : Widget
}
}
protected override void OnUpdate()
protected override void OnUpdate(LayoutContext layoutContext)
{
}

View File

@@ -29,10 +29,7 @@ public abstract class Widget : UIElement, IInputElement
public void Input(UIInputContext context)
{
if (context.Handled || IgnoreInput) return;
if (ContainsPoint(context.MousePosition))
{
OnInput(context);
}
OnInput(context);
}
/// <summary>

View File

@@ -1,130 +0,0 @@
namespace Voile
{
// Based on https://github.com/ppr-game/PPR/blob/engine/PER.Util/src/Color.cs
/// <summary>
/// A record struct representing a color.
/// </summary>
public record struct Color
{
// TODO: add more HTML colors.
public static Color AliceBlue = new(0xF0F8FF);
public static Color AntiqueWhite = new(0xFAEBD7);
public static Color Aqua = new(0x00FFFF);
public static Color Aquamarine = new(0x7FFFD4);
public static Color Azure = new(0xF0FFFF);
public static Color Beige = new(0xF5F5DC);
public static Color Bisque = new(0xFFE4C4);
public static Color Black = new(0x000000);
public static Color BlanchedAlmond = new(0xFFEBCD);
public static Color Blue = new(0x0000FF);
public static Color BlueViolet = new(0x8A2BE2);
public static Color Brown = new(0xA52A2A);
public static Color BurlyWood = new(0xDEB887);
public static Color CadetBlue = new(0x5F9EA0);
public static Color Chartreuse = new(0x7FFF00);
public static Color Chocolate = new(0xD2691E);
public static Color Coral = new(0xFF7F50);
public static Color CornflowerBlue = new(0x6495ED);
public static Color Cornsilk = new(0xFFF8DC);
public static Color Crimson = new(0xDC143C);
public static Color Cyan = new(0x00FFFF);
public static Color DarkBlue = new(0x00008B);
public static Color DarkCyan = new(0x008B8B);
public static Color White = new(0xFFFFFF);
public static Color Green = new(0x00FF00);
public static Color Red = new(0xFF0000);
public byte R { get; set; }
public byte G { get; set; }
public byte B { get; set; }
public byte A { get; set; } = 255;
public int Argb
{
get
{
int a = A << 24;
int r = R << 16;
int g = G << 8;
int b = B;
return a | r | g | b;
}
}
public Color(float r, float g, float b, float a = 1.0f)
{
R = (byte)Math.Clamp(r * 255, 0, 255);
G = (byte)Math.Clamp(g * 255, 0, 255);
B = (byte)Math.Clamp(b * 255, 0, 255);
A = (byte)Math.Clamp(a * 255, 0, 255);
}
public Color(byte r, byte g, byte b, byte a = 255)
{
R = r;
G = g;
B = b;
A = a;
}
public Color(int hex)
{
A = 255; // Default alpha to 255 if not provided
B = (byte)(hex & 0xFF);
G = (byte)((hex >> 8) & 0xFF);
R = (byte)((hex >> 16) & 0xFF);
if (hex > 0xFFFFFF) // If the hex value includes alpha
{
A = (byte)((hex >> 24) & 0xFF);
}
}
public static Color FromHexString(string hex)
{
if (hex.StartsWith("#"))
{
hex = hex[1..];
}
if (hex.Length == 6)
{
int rgb = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);
return new Color(rgb);
}
else if (hex.Length == 8)
{
int rgba = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);
return new Color(rgba);
}
else
{
throw new ArgumentException("Invalid hex color format. Use #RRGGBB or #RRGGBBAA.");
}
}
public Color Lightened(float amount)
{
var result = this;
result.R = (byte)Math.Min(255, R + (255 - R) * amount);
result.G = (byte)Math.Min(255, G + (255 - G) * amount);
result.B = (byte)Math.Min(255, B + (255 - B) * amount);
return result;
}
public Color Darkened(float amount)
{
var result = this;
result.R = (byte)(R * (1.0f - amount));
result.G = (byte)(G * (1.0f - amount));
result.B = (byte)(B * (1.0f - amount));
return result;
}
public System.Drawing.Color ToSystemColor()
{
var result = System.Drawing.Color.FromArgb(Argb);
return result;
}
}
}

View File

@@ -15,6 +15,18 @@ namespace Voile
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static float Lerp(float a, float b, float t) => t <= 0f ? a : t >= 1f ? b : LerpUnclamped(a, b, t);
public static Size LerpSize(Size a, Size b, float t)
{
t = Math.Clamp(t, 0f, 1f);
float left = Lerp(a.Left, b.Left, t);
float right = Lerp(a.Right, b.Right, t);
float top = Lerp(a.Top, b.Top, t);
float bottom = Lerp(a.Bottom, b.Bottom, t);
return new Size(left, right, top, bottom);
}
public static Color LerpColor(Color colorA, Color colorB, float t)
{
t = Math.Clamp(t, 0f, 1f);

View File

@@ -14,7 +14,7 @@ public class FileSystemFile : VirtualFile
public override Stream GetStream()
{
return new FileStream(_fsPath, FileMode.Open, FileAccess.Read);
return new FileStream(_fsPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
}
private string _fsPath;

View File

@@ -9,6 +9,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FreeTypeSharp" Version="3.0.0" />
<PackageReference Include="Silk.NET.WebGPU" Version="2.20.0" />
<PackageReference Include="Silk.NET.WebGPU.Native.WGPU" Version="2.20.0" />
<PackageReference Include="Silk.NET.Windowing" Version="2.20.0" />
@@ -16,8 +17,6 @@
<PackageReference Include="Tommy" Version="3.1.2" />
<PackageReference Include="ImGui.NET" Version="1.89.4" />
<PackageReference Include="Raylib-cs" Version="7.0.1" />
<PackageReference Include="SharpFont" Version="4.0.1" />
<PackageReference Include="SixLabors.Fonts" Version="1.0.0-beta19" />
<PackageReference Include="StbImageSharp" Version="2.27.13" />
<PackageReference Include="StbVorbisSharp" Version="1.22.4" />
</ItemGroup>