diff --git a/Ion.Examples/Ion.Examples.Breakout/Program.cs b/Ion.Examples/Ion.Examples.Breakout/Program.cs index b86e37f..1364599 100644 --- a/Ion.Examples/Ion.Examples.Breakout/Program.cs +++ b/Ion.Examples/Ion.Examples.Breakout/Program.cs @@ -65,7 +65,7 @@ public class BreakoutSystems(IWindow window, IInputState input, ISpriteBatch spr [Init] public void SetupBlocks(GameTime dt, GameLoopDelegate next) - { + { _blockTexture = assets.Load("Block1.png"); _ballTexture = assets.Load("Ball1.png"); _bonkSound = assets.Load("Bonk.wav"); diff --git a/Ion.Examples/Ion.Examples.Scenes/Program.cs b/Ion.Examples/Ion.Examples.Scenes/Program.cs index f397380..6b5a85a 100644 --- a/Ion.Examples/Ion.Examples.Scenes/Program.cs +++ b/Ion.Examples/Ion.Examples.Scenes/Program.cs @@ -87,8 +87,8 @@ IEnumerator CountDown(int from) game.UseUpdate((GameLoopDelegate next, IEventEmitter eventEmitter, IEventListener events) => { var flip = false; - var switchScene = Throttler.Wrap(TimeSpan.FromSeconds(1), (dt) => { - eventEmitter.Emit(new ChangeSceneEvent(flip ? (int)Scenes.MainMenu : (int)Scenes.Gameplay)); + var switchScene = Throttler.Wrap(TimeSpan.FromSeconds(3), (dt) => { + eventEmitter.EmitChangeScene(flip ? (int)Scenes.MainMenu : (int)Scenes.Gameplay); flip = !flip; }); @@ -117,28 +117,28 @@ IEnumerator CountDown(int from) game.UseScene((int)Scenes.MainMenu, scene => { - //scene.UseRender((GameLoopDelegate next, ISpriteBatch spriteBatch) => - //{ - // return dt => - // { - // spriteBatch.DrawRect(Color.ForestGreen, new RectangleF(10, 10, 90, 90)); - // next(dt); - // }; - //}); + scene.UseRender((GameLoopDelegate next, ISpriteBatch spriteBatch) => + { + return dt => + { + spriteBatch.DrawRect(Color.ForestGreen, new RectangleF(10, 10, 90, 90)); + next(dt); + }; + }); scene.UseSystem(); }); game.UseScene((int)Scenes.Gameplay, scene => { - //scene.UseRender((GameLoopDelegate next, ISpriteBatch spriteBatch) => - //{ - // return dt => - // { - // spriteBatch.DrawRect(Color.DarkRed, new RectangleF(10, 10, 90, 90)); - // next(dt); - // }; - //}); + scene.UseRender((GameLoopDelegate next, ISpriteBatch spriteBatch) => + { + return dt => + { + spriteBatch.DrawRect(Color.DarkRed, new RectangleF(10, 10, 90, 90)); + next(dt); + }; + }); }); game.UseRender(next => dt => Console.WriteLine("NEVER GETTING CALLED!")); diff --git a/Ion.Examples/Ion.Examples.SpriteRenderer/Ion.Examples.SpriteRenderer.csproj b/Ion.Examples/Ion.Examples.SpriteRenderer/Ion.Examples.SpriteRenderer.csproj deleted file mode 100644 index ecbd5e6..0000000 --- a/Ion.Examples/Ion.Examples.SpriteRenderer/Ion.Examples.SpriteRenderer.csproj +++ /dev/null @@ -1,26 +0,0 @@ - - - - Exe - net7.0 - enable - enable - Debug;Release;DebugGenerators - - - - - - - - - Always - - - - - - - - - diff --git a/Ion.Examples/Ion.Examples.SpriteRenderer/Program.cs b/Ion.Examples/Ion.Examples.SpriteRenderer/Program.cs deleted file mode 100644 index 843280f..0000000 --- a/Ion.Examples/Ion.Examples.SpriteRenderer/Program.cs +++ /dev/null @@ -1,27 +0,0 @@ -global using System.Numerics; -global using Microsoft.Extensions.Logging; -global using Ion; - -using Ion.Hosting; -using Ion.Examples.SpriteRenderer; - - -var gameHost = IonHost.CreateDefaultBuilder() - .ConfigureIon(static (game) => - { - game.Config.Title = "Ion SpriteRenderer Example"; - game.Config.WindowWidth = 1920; - game.Config.WindowHeight = 1080; - //game.Config.PreferredBackend = Veldrid.GraphicsBackend.Vulkan; - //game.Config.PreferredBackend = Veldrid.GraphicsBackend.OpenGL; - game.Config.VSync = false; - game.Config.MaxFPS = 120; - game.Config.ClearColor = Color.CornflowerBlue; - - //game.AddSystem() - // .AddSystem() - // .AddSystem(); - }) - .Build(); - -gameHost.StartAsync().Wait(); diff --git a/Ion.Examples/Ion.Examples.SpriteRenderer/Properties/launchSettings.json b/Ion.Examples/Ion.Examples.SpriteRenderer/Properties/launchSettings.json deleted file mode 100644 index 3905821..0000000 --- a/Ion.Examples/Ion.Examples.SpriteRenderer/Properties/launchSettings.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "profiles": { - "Ion.Examples.SpriteRenderer": { - "commandName": "Project", - "environmentVariables": { - "Logging__LogLevel__Ion": "Debug" - } - } - } -} \ No newline at end of file diff --git a/Ion.Examples/Ion.Examples.SpriteRenderer/RenderDoc.cap b/Ion.Examples/Ion.Examples.SpriteRenderer/RenderDoc.cap deleted file mode 100644 index 62ebb6e..0000000 --- a/Ion.Examples/Ion.Examples.SpriteRenderer/RenderDoc.cap +++ /dev/null @@ -1,27 +0,0 @@ -{ - "rdocCaptureSettings": 1, - "settings": { - "autoStart": false, - "commandLine": "", - "environment": [ - ], - "executable": "C:\\Projects\\Ion\\Ion.Examples\\Ion.Examples.SpriteRenderer\\bin\\Release\\net6.0\\Ion.Examples.SpriteRenderer.exe", - "inject": false, - "numQueuedFrames": 0, - "options": { - "allowFullscreen": false, - "allowVSync": true, - "apiValidation": true, - "captureAllCmdLists": false, - "captureCallstacks": true, - "captureCallstacksOnlyDraws": false, - "debugOutputMute": true, - "delayForDebugger": 0, - "hookIntoChildren": false, - "refAllResources": false, - "verifyBufferAccess": false - }, - "queuedFrameCap": 0, - "workingDir": "" - } -} diff --git a/Ion.Examples/Ion.Examples.SpriteRenderer/TestLoggerSystem.cs b/Ion.Examples/Ion.Examples.SpriteRenderer/TestLoggerSystem.cs deleted file mode 100644 index 2151429..0000000 --- a/Ion.Examples/Ion.Examples.SpriteRenderer/TestLoggerSystem.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System.Diagnostics; - -namespace Ion.Examples.SpriteRenderer; - -public class TestLoggerSystem : IInitializeSystem, IDestroySystem, IUpdateSystem -{ - private readonly ILogger _logger; - private readonly IInputState _input; - private readonly IEventListener _events; - - private bool _wasDown = false; - private double _totalDt = 0; - private int _frameCount = 0; - private readonly Stopwatch _stopwatch = new(); - - public bool IsEnabled { get; set; } = true; - - public TestLoggerSystem(ILogger logger, IInputState input, IEventListener events) - { - _logger = logger; - _input = input; - _events = events; - } - - public void Initialize() - { - _logger.LogInformation("Simple Example Started"); - } - - public void Update(GameTime dt) - { - _stopwatch.Restart(); - - if (_events.On()) _logger.LogInformation("Window Resized!"); - if (_events.On()) _logger.LogInformation("Window Focus Gained!"); - if (_events.On()) _logger.LogInformation("Window Focus Lost!"); - if (_events.On()) _logger.LogInformation("Window Closed!"); - - var spaceDown = _input.Down(Key.Space); - - if (_input.Pressed(Key.Space)) - { - _logger.LogInformation("SPACE PRESSED!"); - _wasDown = true; - } - if (spaceDown) - { - _logger.LogInformation("SPACE DOWN!"); - } - if (_input.Released(Key.Space)) - { - _wasDown = false; - _logger.LogInformation("SPACE UP!"); - } - - if (!spaceDown && _wasDown) - { - _logger.LogWarning($"MISSED DOWN!"); - } - - if (_input.Pressed(MouseButton.Left)) _logger.LogInformation("LEFT MOUSE DOWN!"); - if (_input.Released(MouseButton.Left)) _logger.LogInformation("LEFT MOUSE UP!"); - - - // next(); - - _stopwatch.Stop(); - var duration = _stopwatch.Elapsed.TotalSeconds; - _totalDt += duration; - _frameCount++; - - if (_totalDt > 0.5f) - { - _logger.LogInformation($"Frame Time: {1000 * _totalDt / _frameCount: 00.00}, FPS: {_frameCount / _totalDt:###.0}"); - _totalDt = 0f; - _frameCount = 0; - } - } - - public void Destroy() - { - _logger.LogInformation("Simple Example Stopped!"); - } -} diff --git a/Ion.Examples/Ion.Examples.SpriteRenderer/TestSpriteRendererSystem.cs b/Ion.Examples/Ion.Examples.SpriteRenderer/TestSpriteRendererSystem.cs deleted file mode 100644 index 8bf1d6b..0000000 --- a/Ion.Examples/Ion.Examples.SpriteRenderer/TestSpriteRendererSystem.cs +++ /dev/null @@ -1,170 +0,0 @@ -using Arch.Core; - -using Ion.Assets; -using Ion.Graphics; -using Ion.Utils; - -namespace Ion.Examples.SpriteRenderer; - -struct HueComponent -{ - public float Hue; - - public HueComponent(float hue) - { - Hue = hue; - } -} -record struct TestBlockComponent(bool Moving); - -public class TestSpriteRendererSystem : IInitializeSystem, IUpdateSystem, IRenderSystem -{ - private readonly Vector2 VECTOR2_HALF = Vector2.One / 2f; - - private readonly IWindow _window; - private readonly ISpriteBatch _spriteRenderer; - private readonly ILogger _logger; - private readonly IInputState _input; - private readonly IAssetManager _assetManager; - private readonly World _world; - private readonly Random _rand; - - private readonly int _bouncingSpriteCount; - private readonly QueryDescription _bouncingSpritesQuery; - - private const float _saturation = 0.5f; - private const float _value = 1f; - private Texture2D? _texture; - - private readonly int _depthBlockCount; - private readonly QueryDescription _spriteQuery; - - public bool IsEnabled { get; set; } = true; - - public TestSpriteRendererSystem( - IWindow window, ISpriteBatch spriteRenderer, ILogger logger, - IInputState input, IAssetManager assetManager, - World world) - { - _window = window; - _spriteRenderer = spriteRenderer; - _logger = logger; - _input = input; - _assetManager = assetManager; - _world = world; - _rand = new Random(); - - _bouncingSpriteCount = 50_000; - - _depthBlockCount = 8; - _spriteQuery = new QueryDescription().WithAll(); - } - - public void Initialize() - { - using var _ = MicroTimer.Start("TestSpriteRendererSystem::Initialize"); - - _texture = _assetManager.Load("Tile.png"); - - var depthBlockSize = 100; - var center = (_window.Size / 2) - new Vector2(depthBlockSize/2); - var radius = 50; - - for (var i = 0; i < _depthBlockCount; i++) - { - var x = center.X + (radius * MathF.Cos(i * MathHelper.TwoPi / _depthBlockCount)); - var y = center.Y + (radius * MathF.Sin(i * MathHelper.TwoPi / _depthBlockCount)); - var hue = i * 256 / _depthBlockCount; - - _world.Create( - new TextureComponent(_texture), - new Position2dComponent(new RectangleF(x, y, depthBlockSize, depthBlockSize), 10 + (float)(_rand.NextDouble() * 64)), - new ColorComponent(Color.FromHSV(hue, _saturation, _value)), - new HueComponent(hue), - new TestBlockComponent(false) - ); - } - - var baseHue = _rand.NextSingle() * 360; - for (var i = 0; i < _bouncingSpriteCount; i++) - { - var size = _rand.Next(80) + 20; - var hue = baseHue + (6f * i / _bouncingSpriteCount); - var angle = _rand.NextSingle() * MathHelper.TwoPi; - var speed = _rand.NextSingle() * 200 + 50; - - _world.Create( - new TextureComponent(_texture), - new Position2dComponent(new RectangleF(_rand.Next(_window.Width - size), _rand.Next(_window.Height - size), size, size), 10 + (float)(_rand.NextDouble() * 64)), - new ColorComponent(Color.FromHSV(hue, _saturation, _value)), - new HueComponent(hue), - new TestBlockComponent(true), - new Velocity2dComponent(new Vector2(MathF.Sin(angle), MathF.Cos(angle)) * speed) - ); - } - } - - public void Update(GameTime dt) - { - using var _ = MicroTimer.Start(name: "TestSpriteRenderSystem::Update"); - - var minX = 0; - var minY = 0; - var maxX = _window.Width; - var maxY = _window.Height; - - _world.Query(in _spriteQuery, (ref TestBlockComponent block, ref Position2dComponent pos, ref ColorComponent color, ref HueComponent hue, ref Velocity2dComponent vel) => - { - if (!block.Moving) return; - - pos.Position.X += (vel.Velocity.X * dt); - pos.Position.Y += (vel.Velocity.Y * dt); - - if (pos.Position.Left < minX) - { - pos.Position.X = minX; - vel.Velocity.X *= -1f; - hue.Hue += 6; - color.Color = Color.FromHSV(hue.Hue, _saturation, _value); - } - else if (pos.Position.Right > maxX) - { - pos.Position.X = maxX - pos.Position.Width; - vel.Velocity.X *= -1f; - hue.Hue += 6; - color.Color = Color.FromHSV(hue.Hue, _saturation, _value); - } - - if (pos.Position.Top < minY) - { - pos.Position.Y = minY; - vel.Velocity.Y *= -1f; - hue.Hue += 6; - color.Color = Color.FromHSV(hue.Hue, _saturation, _value); - } - else if (pos.Position.Bottom > maxY) - { - pos.Position.Y = maxY - pos.Position.Height; - vel.Velocity.Y *= -1f; - hue.Hue += 6; - color.Color = Color.FromHSV(hue.Hue, _saturation, _value); - } - }); - } - - public void Render(GameTime dt) - { - using var _ = MicroTimer.Start(name: "TestSpriteRenderSystem::Render"); - - var i = 0; - _world.Query(in _spriteQuery, (ref TextureComponent tex, ref Position2dComponent pos, ref Rotation2dComponent rot, ref ColorComponent color) => - { - //var texture = _assetManager.Get(tex.TextureId); - - if (i++ % 2 == 1) - _spriteRenderer.Draw(_texture!, pos.Position, color: color.Color, depth: pos.Depth, rotation: rot.Angle); - else - _spriteRenderer.DrawRect(color: color.Color, pos.Position, depth: pos.Depth, rotation: rot.Angle); - }); - } -} \ No newline at end of file diff --git a/Ion.Examples/Ion.Examples.SpriteRenderer/UserInputSystem.cs b/Ion.Examples/Ion.Examples.SpriteRenderer/UserInputSystem.cs deleted file mode 100644 index 596e1fb..0000000 --- a/Ion.Examples/Ion.Examples.SpriteRenderer/UserInputSystem.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace Ion.Examples.SpriteRenderer; - -public class UserInputSystem : IUpdateSystem -{ - private readonly IInputState _inputState; - private readonly IEventEmitter _eventEmitter; - - public bool IsEnabled { get; set; } = true; - - public UserInputSystem(IInputState inputState, IEventEmitter eventEmitter) - { - _inputState = inputState; - _eventEmitter = eventEmitter; - } - - public void Update(GameTime dt) - { - if (_inputState.Pressed(Key.Escape)) _eventEmitter.Emit(); - } -} diff --git a/Ion.Examples/Ion.Examples.SpriteRenderer/appsettings.json b/Ion.Examples/Ion.Examples.SpriteRenderer/appsettings.json deleted file mode 100644 index 3402d40..0000000 --- a/Ion.Examples/Ion.Examples.SpriteRenderer/appsettings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { // All providers, LogLevel applies to all the enabled providers. - "Default": "Debug", - "Ion": "Debug" - } - } -} \ No newline at end of file diff --git a/Ion/Ion.Core.Abstractions/Builder/MiddlewarePipelineBuilder.cs b/Ion/Ion.Core.Abstractions/Builder/MiddlewarePipelineBuilder.cs index 4b8bc4c..37e02bf 100644 --- a/Ion/Ion.Core.Abstractions/Builder/MiddlewarePipelineBuilder.cs +++ b/Ion/Ion.Core.Abstractions/Builder/MiddlewarePipelineBuilder.cs @@ -10,8 +10,8 @@ public interface IMiddlewarePipelineBuilder public class MiddlewarePipelineBuilder : IMiddlewarePipelineBuilder { - private readonly List> _systems = new(); - private readonly List _descriptions = new(); + private readonly List> _systems = []; + private readonly List _descriptions = []; public IMiddlewarePipelineBuilder Use(Func middleware) { @@ -22,26 +22,25 @@ public IMiddlewarePipelineBuilder Use(Func m public GameLoopDelegate Build() { - GameLoopDelegate app = (dt) => { }; + GameLoopDelegate gameLoop = (dt) => { }; - for (var s = _systems.Count - 1; s >= 0; s--) - { - app = _systems[s](app); - } + for (var s = _systems.Count - 1; s >= 0; s--) gameLoop = _systems[s](gameLoop); - return app; + return gameLoop; } - private string _createMiddlewareDescription(Func middleware) + private static string _createMiddlewareDescription(Func middleware) { - if (middleware.Target != null) + if (middleware.Target is not null) { if (middleware.Method.Name == "CreateMiddleware") { - return middleware.Target.ToString()!; + return middleware.Target?.ToString() ?? middleware.Method.Name.ToString(); ; + } + else + { + return middleware.Target.GetType().FullName + "." + middleware.Method.Name; } - - return middleware.Target.GetType().FullName + "." + middleware.Method.Name; } return middleware.Method.Name.ToString(); diff --git a/Ion/Ion.Core/Builder/IonApplication.cs b/Ion/Ion.Core/Builder/IonApplication.cs index 9d39147..8c17914 100644 --- a/Ion/Ion.Core/Builder/IonApplication.cs +++ b/Ion/Ion.Core/Builder/IonApplication.cs @@ -40,7 +40,7 @@ public static IonApplicationBuilder CreateBuilder(string[] args) public static IonApplicationBuilder CreateBuilder() { - return CreateBuilder(Array.Empty()); + return CreateBuilder([]); } public IIonApplication UseInit(Func middleware) diff --git a/Ion/Ion.Core/Events/EventSystem.cs b/Ion/Ion.Core/Events/EventSystem.cs index baf58b4..037e07a 100644 --- a/Ion/Ion.Core/Events/EventSystem.cs +++ b/Ion/Ion.Core/Events/EventSystem.cs @@ -2,22 +2,15 @@ namespace Ion; -internal class EventSystem +internal class EventSystem(IEventEmitter eventEmitter, ITraceTimer trace) { - private readonly EventEmitter _eventEmitter; - private readonly ITraceTimer _trace; - - public EventSystem(IEventEmitter eventEmitter, ITraceTimer trace) - { - _eventEmitter = (EventEmitter)eventEmitter; - _trace = trace; - } + private readonly EventEmitter _eventEmitter = (EventEmitter)eventEmitter; [Last] public void StepEvents(GameTime dt, GameLoopDelegate next) { next(dt); - var timer = _trace.Start("Step"); + var timer = trace.Start("Step"); _eventEmitter.Step(); timer.Stop(); } diff --git a/Ion/Ion.Core/GameLoop.cs b/Ion/Ion.Core/GameLoop.cs index 332e692..c41acb5 100644 --- a/Ion/Ion.Core/GameLoop.cs +++ b/Ion/Ion.Core/GameLoop.cs @@ -10,19 +10,16 @@ namespace Ion.Core; /// /// Top-level class representing the runnable game. /// -public class GameLoop +public class GameLoop(IOptionsMonitor gameConfig, IEventListener events, ITraceTimer trace) { private bool _shouldExit; private readonly float _maxFrameTime = 0.1f; // 100ms + private readonly ITraceTimer _trace = trace; - private readonly IOptionsMonitor _gameConfig; - private readonly IEventListener _events; - private readonly ITraceTimer _trace; + private float MaxFPS => gameConfig.CurrentValue.MaxFPS < 1 ? 120 : gameConfig.CurrentValue.MaxFPS; - private float MaxFPS => _gameConfig.CurrentValue.MaxFPS < 1 ? 120 : _gameConfig.CurrentValue.MaxFPS; - - public GameTime GameTime { get; } - public GameTime FixedGameTime { get; } + public GameTime GameTime { get; } = new(); + public GameTime FixedGameTime { get; private set; } = new(); public bool IsRunning { get; private set; } = false; @@ -34,7 +31,6 @@ public class GameLoop public GameLoopDelegate Last { get; set; } = (dt) => { }; public GameLoopDelegate Destroy { get; set; } = (dt) => { }; - public bool Rebuild { get; set; } = false; public MiddlewarePipelineBuilder InitBuilder { get; set; } = default!; @@ -45,19 +41,6 @@ public class GameLoop public MiddlewarePipelineBuilder LastBuilder { get; set; } = default!; public MiddlewarePipelineBuilder DestroyBuilder { get; set; } = default!; - public GameLoop(IOptionsMonitor gameConfig, IEventListener events, ITraceTimer trace) { - _gameConfig = gameConfig; - _events = events; - _trace = trace; - - GameTime = new(); - FixedGameTime = new() - { - Alpha = 1, - Delta = 1f / MaxFPS, - }; - } - public void Build() { Init = InitBuilder.Build(); @@ -72,6 +55,13 @@ public void Build() public void Run() { IsRunning = true; + + FixedGameTime = new() + { + Alpha = 1, + Delta = 1f / MaxFPS, + }; + Init(GameTime); var stopwatch = Stopwatch.StartNew(); @@ -106,7 +96,7 @@ public void Run() Render(GameTime); - if (_events.On()) _shouldExit = true; + if (events.On()) _shouldExit = true; Last(GameTime); diff --git a/Ion/Ion.Core/Storage/PersistentStorageProvider.cs b/Ion/Ion.Core/Storage/PersistentStorageProvider.cs index 0582c44..60fd9ba 100644 --- a/Ion/Ion.Core/Storage/PersistentStorageProvider.cs +++ b/Ion/Ion.Core/Storage/PersistentStorageProvider.cs @@ -1,13 +1,8 @@ namespace Ion; -internal class PersistentStorageProvider : IPersistentStorageProvider +internal class PersistentStorageProvider(params string[] rootPath) : IPersistentStorageProvider { - private readonly string _rootPath; - - public PersistentStorageProvider(params string[] rootPath) - { - _rootPath = Path.Combine(rootPath); - } + private readonly string _rootPath = Path.Combine(rootPath); public void Initialize() { diff --git a/Ion/Ion.Core/Utils/RingBuffer.cs b/Ion/Ion.Core/Utils/RingBuffer.cs index 2ee5618..61c219e 100644 --- a/Ion/Ion.Core/Utils/RingBuffer.cs +++ b/Ion/Ion.Core/Utils/RingBuffer.cs @@ -14,7 +14,7 @@ public class RingBuffer public T this[int index] { get { - if (index >= _size) throw new ArgumentOutOfRangeException(nameof(index)); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, _size); return _buffer[(_head + index) % _capacity]; } diff --git a/Ion/Ion.Core_old/Events/Event.cs b/Ion/Ion.Core_old/Events/Event.cs deleted file mode 100644 index d55c0c2..0000000 --- a/Ion/Ion.Core_old/Events/Event.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace Ion; - -public interface IEvent -{ - ulong Id { get; } - bool Handled { get; set; } -} - -public interface IEvent : IEvent -{ - T? Data { get; } -} - -internal record struct Event(ulong Id, T? Data, bool Handled) : IEvent -{ - public Event(ulong id) : this(id, default, false) { } - public Event(ulong id, T data) : this(id, data, false) { } -} \ No newline at end of file diff --git a/Ion/Ion.Core_old/Events/EventEmitter.cs b/Ion/Ion.Core_old/Events/EventEmitter.cs deleted file mode 100644 index 731cb42..0000000 --- a/Ion/Ion.Core_old/Events/EventEmitter.cs +++ /dev/null @@ -1,59 +0,0 @@ -namespace Ion; - -public interface IEventEmitter -{ - void Emit(); - void Emit(T data); -} - -internal class EventEmitter : IEventEmitter -{ - private readonly ConcurrentQueue _currFrame = new(); - private IEvent[] _prevFrame = Array.Empty(); - private readonly List _listeners = new(); - private ulong _nextId = 1; - - public void Step() - { - _prevFrame = _currFrame.Where(e => !e.Handled).ToArray(); - _currFrame.Clear(); - - foreach (var listener in _listeners) listener.UpdateKnownEvents(); - } - - public void Emit() - { - _currFrame.Enqueue(new Event(Interlocked.Increment(ref _nextId))); - } - - public void Emit(T data) - { - _currFrame.Enqueue(new Event(Interlocked.Increment(ref _nextId), data)); - } - - public void AttachListener(EventListener listener) - { - _listeners.Add(listener); - } - - public void DetachListener(EventListener listener) - { - _listeners.Remove(listener); - } - - public IEnumerable> GetEvents() - { - var type = typeof(T); - foreach (var e in _getEvents(_prevFrame, type)) yield return e; - foreach (var e in _getEvents(_currFrame, type)) yield return e; - } - - private IEnumerable> _getEvents(IEnumerable events, Type type) - { - foreach (var e in events) - { - if (e.Handled || e is not IEvent) continue; - yield return (IEvent)e; - } - } -} diff --git a/Ion/Ion.Core_old/Events/EventListener.cs b/Ion/Ion.Core_old/Events/EventListener.cs deleted file mode 100644 index 2f8b37c..0000000 --- a/Ion/Ion.Core_old/Events/EventListener.cs +++ /dev/null @@ -1,74 +0,0 @@ -namespace Ion; - -public interface IEventListener -{ - bool On(); - bool On([NotNullWhen(true)] out IEvent? data); - - bool OnLatest(); - bool OnLatest([NotNullWhen(true)] out IEvent? data); -} - -internal class EventListener : IEventListener, IDisposable -{ - public readonly EventEmitter _eventEmitter; - - private HashSet _currFrameSeenEvents = new(); - private HashSet _prevFrameKnownEvents = new(); - - public EventListener(IEventEmitter eventEmitter) - { - _eventEmitter = (EventEmitter)eventEmitter; - _eventEmitter.AttachListener(this); - } - - public bool On() - { - return On(out _); - } - - public bool On([NotNullWhen(true)]out IEvent? @event) - { - foreach(var e in _eventEmitter.GetEvents()) - { - if (_prevFrameKnownEvents.Contains(e.Id) || _currFrameSeenEvents.Contains(e.Id)) continue; - - @event = e; - _currFrameSeenEvents.Add(e.Id); - return true; - } - - @event = default; - return false; - } - - public bool OnLatest() - { - return OnLatest(out _); - } - - public bool OnLatest([NotNullWhen(true)] out IEvent? @event) - { - @event = default; - foreach (var e in _eventEmitter.GetEvents()) - { - if (_prevFrameKnownEvents.Contains(e.Id) || _currFrameSeenEvents.Contains(e.Id)) continue; - - @event = e; - _currFrameSeenEvents.Add(e.Id); - } - - return @event != default; - } - - public void UpdateKnownEvents() - { - _prevFrameKnownEvents = _currFrameSeenEvents; - _currFrameSeenEvents = new HashSet(); - } - - public void Dispose() - { - _eventEmitter.DetachListener(this); - } -} diff --git a/Ion/Ion.Core_old/GameTime.cs b/Ion/Ion.Core_old/GameTime.cs deleted file mode 100644 index 2727150..0000000 --- a/Ion/Ion.Core_old/GameTime.cs +++ /dev/null @@ -1,41 +0,0 @@ -namespace Ion; - -public class GameTime -{ - /// - /// The frame index, starting at zero and incrementing for each rendered frame. - /// - public uint Frame { get; internal set; } - - /// - /// The time in seconds since the last update. Typically a fixed timestep. - /// - public float Delta { get; internal set; } - - /// - /// The interpolation ratio of the remaining accumulated time over the fixed time. Ranges from 0 to 1 inclusive. Defaults to 1 for standard frames. - /// - public float Alpha { get; internal set; } - - /// - /// The total elapsed time. - /// - public TimeSpan Elapsed { get; internal set; } - - /// - /// Treats gametime as a float delta in seconds. - /// - /// - public static implicit operator float(GameTime time) => time.Delta; - - internal static GameTime FromDelta(float dt) - { - return new() - { - Frame = 0, - Delta = dt, - Alpha = 1f, - Elapsed = TimeSpan.Zero, - }; - } -} diff --git a/Ion/Ion.Core_old/Graphics/GraphicsOutput.cs b/Ion/Ion.Core_old/Graphics/GraphicsOutput.cs deleted file mode 100644 index a4d510a..0000000 --- a/Ion/Ion.Core_old/Graphics/GraphicsOutput.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace Ion.Graphics; - -public enum GraphicsOutput: byte -{ - /// - /// Indicates no graphical output should be generated. Useful for servers and unit tests. - /// - None = 0, - - /// - /// Indicates that graphics will be rendered to a file. Useful for simulations and automated tests. - /// - File, - - /// - /// Indicates that graphics will be rendered to a window. Default value for games. - /// - Window, -} - diff --git a/Ion/Ion.Core_old/Graphics/IGraphicsContext.cs b/Ion/Ion.Core_old/Graphics/IGraphicsContext.cs deleted file mode 100644 index 436cba7..0000000 --- a/Ion/Ion.Core_old/Graphics/IGraphicsContext.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Numerics; - -using Veldrid; - -namespace Ion.Graphics; - -public interface IGraphicsContext -{ - public GraphicsDevice? GraphicsDevice { get; } - public ResourceFactory Factory { get; } - Matrix4x4 ProjectionMatrix { get; } - bool NoRender { get; } - - void SubmitCommands(CommandList cl); - Matrix4x4 CreateOrthographic(float left, float right, float bottom, float top, float near, float far); - Matrix4x4 CreatePerspective(float fov, float aspectRatio, float near, float far); -} diff --git a/Ion/Ion.Core_old/IWindow.cs b/Ion/Ion.Core_old/IWindow.cs deleted file mode 100644 index c3409c4..0000000 --- a/Ion/Ion.Core_old/IWindow.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Numerics; - -namespace Ion; - -public record struct WindowResizeEvent(uint Width, uint Height); -public record struct WindowClosedEvent; -public record struct WindowFocusGainedEvent; -public record struct WindowFocusLostEvent; - -public interface IWindow -{ - int Width { get; set; } - int Height { get; set; } - - Vector2 Size { get; set; } - bool HasClosed { get; } - bool IsActive { get; } - - bool IsVisible { get; set; } - bool IsMaximized { get; set; } - bool IsMinimized { get; set; } - bool IsFullscreen { get; set; } - bool IsBorderlessFullscreen { get; set; } - - string Title { get; set; } - bool IsResizable { get; set; } - bool IsCursorVisible { get; set; } - bool IsBorderVisible { get; set; } - - void Close(); -} \ No newline at end of file diff --git a/Ion/Ion.Core_old/Input/IInputState.cs b/Ion/Ion.Core_old/Input/IInputState.cs deleted file mode 100644 index 117065e..0000000 --- a/Ion/Ion.Core_old/Input/IInputState.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Numerics; - -namespace Ion; - -public interface IInputState -{ - Vector2 MousePosition { get; } - float WheelDelta { get; } - - bool Down(Key key); - bool Down(MouseButton btn); - bool Pressed(Key key); - bool Pressed(Key key, ModifierKeys modifiers); - bool Pressed(MouseButton btn); - bool Released(Key key); - bool Released(Key key, ModifierKeys modifiers); - bool Released(MouseButton btn); - bool Up(Key key); - bool Up(MouseButton btn); - - void SetMousePosition(Vector2 position); - void SetMousePosition(int x, int y); -} \ No newline at end of file diff --git a/Ion/Ion.Core_old/Input/Key.cs b/Ion/Ion.Core_old/Input/Key.cs deleted file mode 100644 index 35e6631..0000000 --- a/Ion/Ion.Core_old/Input/Key.cs +++ /dev/null @@ -1,162 +0,0 @@ -namespace Ion; - -public enum Key -{ - Unknown = 0, - ShiftLeft = 1, - LShift = 1, - ShiftRight = 2, - RShift = 2, - ControlLeft = 3, - LControl = 3, - ControlRight = 4, - RControl = 4, - AltLeft = 5, - LAlt = 5, - AltRight = 6, - RAlt = 6, - WinLeft = 7, - LWin = 7, - WinRight = 8, - RWin = 8, - Menu = 9, - F1 = 10, - F2 = 11, - F3 = 12, - F4 = 13, - F5 = 14, - F6 = 0xF, - F7 = 0x10, - F8 = 17, - F9 = 18, - F10 = 19, - F11 = 20, - F12 = 21, - F13 = 22, - F14 = 23, - F15 = 24, - F16 = 25, - F17 = 26, - F18 = 27, - F19 = 28, - F20 = 29, - F21 = 30, - F22 = 0x1F, - F23 = 0x20, - F24 = 33, - F25 = 34, - F26 = 35, - F27 = 36, - F28 = 37, - F29 = 38, - F30 = 39, - F31 = 40, - F32 = 41, - F33 = 42, - F34 = 43, - F35 = 44, - Up = 45, - Down = 46, - Left = 47, - Right = 48, - Enter = 49, - Escape = 50, - Space = 51, - Tab = 52, - BackSpace = 53, - Back = 53, - Insert = 54, - Delete = 55, - PageUp = 56, - PageDown = 57, - Home = 58, - End = 59, - CapsLock = 60, - ScrollLock = 61, - PrintScreen = 62, - Pause = 0x3F, - NumLock = 0x40, - Clear = 65, - Sleep = 66, - Keypad0 = 67, - Keypad1 = 68, - Keypad2 = 69, - Keypad3 = 70, - Keypad4 = 71, - Keypad5 = 72, - Keypad6 = 73, - Keypad7 = 74, - Keypad8 = 75, - Keypad9 = 76, - KeypadDivide = 77, - KeypadMultiply = 78, - KeypadSubtract = 79, - KeypadMinus = 79, - KeypadAdd = 80, - KeypadPlus = 80, - KeypadDecimal = 81, - KeypadPeriod = 81, - KeypadEnter = 82, - A = 83, - B = 84, - C = 85, - D = 86, - E = 87, - F = 88, - G = 89, - H = 90, - I = 91, - J = 92, - K = 93, - L = 94, - M = 95, - N = 96, - O = 97, - P = 98, - Q = 99, - R = 100, - S = 101, - T = 102, - U = 103, - V = 104, - W = 105, - X = 106, - Y = 107, - Z = 108, - Number0 = 109, - Number1 = 110, - Number2 = 111, - Number3 = 112, - Number4 = 113, - Number5 = 114, - Number6 = 115, - Number7 = 116, - Number8 = 117, - Number9 = 118, - Tilde = 119, - Grave = 119, - Minus = 120, - Plus = 121, - BracketLeft = 122, - LBracket = 122, - BracketRight = 123, - RBracket = 123, - Semicolon = 124, - Quote = 125, - Comma = 126, - Period = 0x7F, - Slash = 0x80, - BackSlash = 129, - NonUSBackSlash = 130, - LastKey = 131 -} - -[Flags] -public enum ModifierKeys -{ - None = 0x0, - Alt = 0x1, - Control = 0x2, - Shift = 0x4, - Gui = 0x8 -} \ No newline at end of file diff --git a/Ion/Ion.Core_old/Input/MouseButton.cs b/Ion/Ion.Core_old/Input/MouseButton.cs deleted file mode 100644 index 2231bf9..0000000 --- a/Ion/Ion.Core_old/Input/MouseButton.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace Ion; - -public enum MouseButton -{ - Left, - Middle, - Right, - Button1, - Button2, - Button3, - Button4, - Button5, - Button6, - Button7, - Button8, - Button9, - LastButton -} diff --git a/Ion/Ion.Core_old/Ion.Core.csproj b/Ion/Ion.Core_old/Ion.Core.csproj deleted file mode 100644 index fa69ad3..0000000 --- a/Ion/Ion.Core_old/Ion.Core.csproj +++ /dev/null @@ -1,32 +0,0 @@ - - - - 0.2.0 - net7.0 - latest - enable - enable -Ion - Debug;Release;DebugGenerators - - - - - - - - - - - - - - - - - - - - - - diff --git a/Ion/Ion.Core_old/IonException.cs b/Ion/Ion.Core_old/IonException.cs deleted file mode 100644 index df53ba5..0000000 --- a/Ion/Ion.Core_old/IonException.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Ion; - -public class IonException : Exception -{ - /// - /// Constructs a new IonException with the given message. - /// - /// The exception message. - public IonException(string message) : base(message) { } - - /// - /// Constructs a new IonException with the given message and inner exception. - /// - /// The exception message. - /// The inner exception. - public IonException(string message, Exception innerException) : base(message, innerException) { } -} diff --git a/Ion/Ion.Core_old/Scenes/ISceneBuilder.cs b/Ion/Ion.Core_old/Scenes/ISceneBuilder.cs deleted file mode 100644 index fd1b466..0000000 --- a/Ion/Ion.Core_old/Scenes/ISceneBuilder.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Ion.Hosting.Scenes; - -public interface ISceneBuilder -{ - ISceneBuilder AddSystem() where T : class; -} \ No newline at end of file diff --git a/Ion/Ion.Core_old/Scenes/ISceneConfiguration.cs b/Ion/Ion.Core_old/Scenes/ISceneConfiguration.cs deleted file mode 100644 index 156679f..0000000 --- a/Ion/Ion.Core_old/Scenes/ISceneConfiguration.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Ion.Hosting.Scenes; - -public interface ISceneConfiguration -{ - void Configure(ISceneBuilder scene); -} diff --git a/Ion/Ion.Core_old/Scenes/ISceneManager.cs b/Ion/Ion.Core_old/Scenes/ISceneManager.cs deleted file mode 100644 index 62d6fdc..0000000 --- a/Ion/Ion.Core_old/Scenes/ISceneManager.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Ion.Hosting.Scenes; - -namespace Ion.Scenes; - -public interface ISceneManager -{ - string CurrentScene { get; } - string[] Scenes { get; } - - void LoadScene(string name); - //void LoadScene(float duration) where TScene : ISceneConfiguration where TTransition : Transition; - void LoadScene() where TScene : ISceneConfiguration; -} diff --git a/Ion/Ion.Core_old/Storage/IPersistentStorage.cs b/Ion/Ion.Core_old/Storage/IPersistentStorage.cs deleted file mode 100644 index f9878f8..0000000 --- a/Ion/Ion.Core_old/Storage/IPersistentStorage.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Ion.Storage; - -public interface IPersistentStorage -{ - IPersistentStorageProvider Game { get; } - IPersistentStorageProvider Assets { get; } - - IPersistentStorageProvider User { get; } - IPersistentStorageProvider Saves { get; } -} \ No newline at end of file diff --git a/Ion/Ion.Core_old/Storage/IPersistentStorageProvider.cs b/Ion/Ion.Core_old/Storage/IPersistentStorageProvider.cs deleted file mode 100644 index 1591e65..0000000 --- a/Ion/Ion.Core_old/Storage/IPersistentStorageProvider.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Ion.Storage; - -public interface IPersistentStorageProvider -{ - void CreateDirectory(params string[] path); - void Write(string text, params string[] path); - void Write(byte[] bytes, params string[] path); - BinaryWriter OpenWrite(params string[] path); - void Append(string text, params string[] path); - Stream Read(params string[] path); - IEnumerable List(params string[] path); - void DeleteFile(params string[] path); - void DeleteDirectory(params string[] path); -} diff --git a/Ion/Ion.Core_old/Systems/ISystem.cs b/Ion/Ion.Core_old/Systems/ISystem.cs deleted file mode 100644 index bdb3e32..0000000 --- a/Ion/Ion.Core_old/Systems/ISystem.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace Ion; - -public interface IBaseSystem -{ - bool IsEnabled { get; set; } -} - -public interface IInitializeSystem : IBaseSystem { void Initialize(); } - -public interface IFirstSystem : IBaseSystem { void First(GameTime time); } - -public interface IFixedUpdateSystem : IBaseSystem { void FixedUpdate(GameTime time); } - -public interface IUpdateSystem : IBaseSystem { void Update(GameTime time); } - -public interface IRenderSystem : IBaseSystem { void Render(GameTime time); } - -public interface ILastSystem : IBaseSystem { void Last(GameTime time); } - -public interface IDestroySystem : IBaseSystem { void Destroy(); } - - -public interface ISystem : IInitializeSystem, IFirstSystem, IUpdateSystem, IFixedUpdateSystem, IRenderSystem, ILastSystem, IDestroySystem { - //void IInitializeSystem.Initialize() { } - //void IFirstSystem.First(float dt) { } - //void IUpdateSystem.Update(float dt) { } - //void IRenderSystem.Render(float dt) { } - //void ILastSystem.Last(float dt) { } - //void IDestroySystem.Destroy() { } -} \ No newline at end of file diff --git a/Ion/Ion.Core_old/Systems/SystemGroup.cs b/Ion/Ion.Core_old/Systems/SystemGroup.cs deleted file mode 100644 index d51952b..0000000 --- a/Ion/Ion.Core_old/Systems/SystemGroup.cs +++ /dev/null @@ -1,157 +0,0 @@ -namespace Ion; - -public sealed class SystemGroup : ISystem -{ - private readonly IServiceProvider _serviceProvider; - private readonly HashSet _systems; - - private readonly List _initializeSystems = new(); - private readonly List _firstSystems = new(); - private readonly List _fixedUpdateSystems = new(); - private readonly List _updateSystems = new(); - private readonly List _renderSystems = new(); - private readonly List _lastSystems = new(); - private readonly List _destroySystems = new(); - - public bool IsEnabled { get; set; } = true; - - public SystemGroup(IServiceProvider serviceProvider, HashSet systemTypes) - { - _serviceProvider = serviceProvider; - _systems = systemTypes; - } - - public void Initialize() - { - _setupSystems(); - - foreach (var system in _initializeSystems) if (system.IsEnabled) system.Initialize(); - } - - public void First(GameTime dt) - { - foreach (var system in _firstSystems) if (system.IsEnabled) system.First(dt); - } - - public void FixedUpdate(GameTime dt) - { - foreach (var system in _fixedUpdateSystems) if (system.IsEnabled) system.FixedUpdate(dt); - } - - public void Update(GameTime dt) - { - foreach (var system in _updateSystems) if (system.IsEnabled) system.Update(dt); - } - - public void Render(GameTime dt) - { - foreach (var system in _renderSystems) if (system.IsEnabled) system.Render(dt); - } - - public void Last(GameTime dt) - { - foreach (var system in _lastSystems) if (system.IsEnabled) system.Last(dt); - } - - public void Destroy() - { - foreach (var system in _destroySystems) if (system.IsEnabled) system.Destroy(); - } - - public bool AddSystem() - { - var type = typeof(T); - if (_systems.Contains(type)) return false; - - var instance = _serviceProvider.GetService(type); - var added = _addSystem(instance); - - if (added) _systems.Add(type); - - return added; - } - - internal bool AddSystem(T instance) - { - var type = typeof(T); - if (_systems.Contains(type)) return false; - - var added = _addSystem(instance); - - if (added) _systems.Add(type); - - return added; - } - - private bool _addSystem(object? system) - { - if (system is null) return false; - - var added = false; - - if (system is IInitializeSystem startupSystem) - { - _initializeSystems.Add(startupSystem); - added = true; - } - - if (system is IFirstSystem firstSystem) - { - _firstSystems.Add(firstSystem); - added = true; - } - - if (system is IFixedUpdateSystem fixedUpdateSystem) - { - _fixedUpdateSystems.Add(fixedUpdateSystem); - added = true; - } - - if (system is IUpdateSystem updateSystem) - { - _updateSystems.Add(updateSystem); - added = true; - } - - if (system is IRenderSystem renderSystem) - { - _renderSystems.Add(renderSystem); - added = true; - } - - if (system is ILastSystem lastSystem) - { - _lastSystems.Add(lastSystem); - added = true; - } - - if (system is IDestroySystem shutdownSystem) - { - _destroySystems.Add(shutdownSystem); - added = true; - } - - return added; - } - - public void RemoveSystem() - { - _initializeSystems.RemoveAll(s => s is T); - _firstSystems.RemoveAll(s => s is T); - _fixedUpdateSystems.RemoveAll(s => s is T); - _updateSystems.RemoveAll(s => s is T); - _renderSystems.RemoveAll(s => s is T); - _destroySystems.RemoveAll(s => s is T); - - _systems.Remove(typeof(T)); - } - - private void _setupSystems() - { - foreach (var type in _systems) - { - var instance = _serviceProvider.GetService(type); - _addSystem(instance); - } - } -} diff --git a/Ion/Ion.Core_old/Systems/SystemGroupBuilder.cs b/Ion/Ion.Core_old/Systems/SystemGroupBuilder.cs deleted file mode 100644 index 25a51ec..0000000 --- a/Ion/Ion.Core_old/Systems/SystemGroupBuilder.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace Ion; - -internal class SystemGroupBuilder -{ - private readonly HashSet _systemTypes = new(); - private readonly Type[] _validSystemTypes = new[] { typeof(IInitializeSystem), typeof(IFirstSystem), typeof(IFixedUpdateSystem), typeof(IUpdateSystem), typeof(IRenderSystem), typeof(ILastSystem), typeof(IDestroySystem) }; - - public SystemGroupBuilder AddSystem() where T : class - { - var systemType = typeof(T); - - if (!_isValidSystem(systemType)) throw new Exception($"Invalid system provided ({systemType.FullName})!"); - - _systemTypes.Add(systemType); - - return this; - } - - private bool _isValidSystem(Type systemType) - { - foreach(var validSystemType in _validSystemTypes) - { - if (validSystemType.IsAssignableFrom(systemType)) return true; - } - - return false; - } - - public SystemGroup Build(IServiceProvider serviceProvider) - { - return new SystemGroup(serviceProvider, _systemTypes); - } -} \ No newline at end of file diff --git a/Ion/Ion.Core_old/Utils/MicroTimer.cs b/Ion/Ion.Core_old/Utils/MicroTimer.cs deleted file mode 100644 index 1a8ec4f..0000000 --- a/Ion/Ion.Core_old/Utils/MicroTimer.cs +++ /dev/null @@ -1,133 +0,0 @@ -using System.Diagnostics; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace Ion.Utils; - -public record struct MicroTiming(int Id, double Start, double Stop, int ThreadId) -{ - public double Duration => Stop - Start; -} - -public interface IMicroTimerInstance : IDisposable -{ - void Then(string name); -} - -public static class MicroTimer -{ - private static int _nextId = 0; - private static readonly double _toMicroSeconds; - - private static readonly ConcurrentDictionary _names = new(); - private static readonly ConcurrentBag _timings = new(); - - static MicroTimer() - { - _toMicroSeconds = 1000000D / Stopwatch.Frequency; - } - - public static IMicroTimerInstance Start(string name) - { - var id = Interlocked.Increment(ref _nextId); - _names.TryAdd(id, name); - return new MicroTimerInstance(id, Stopwatch.GetTimestamp() * _toMicroSeconds); - } - - public static void Clear() - { - _timings.Clear(); - _names.Clear(); - } - - public static void Export(string path) - { - var traceExport = new TraceExport() - { - TraceEvents = _timings.Select(t => _names.TryGetValue(t.Id, out var name) ? new TraceEvent(name, t) : null).Where(t => t != null).ToList() as List, - Metadata = new() - { - //{ "clock-offset-since-epoch", $"{_start}" }, - }, - }; - File.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(traceExport)); - } - - private static void _stop(int id, double start, int threadId) - { - var stop = Stopwatch.GetTimestamp() * _toMicroSeconds; - _timings.Add(new MicroTiming(id, start, stop, threadId)); - } - - private struct MicroTimerInstance : IMicroTimerInstance - { - private int _id; - private double _start; - private int _threadId; - - public MicroTimerInstance(int id, double start) - { - _id = id; - _start = start; - _threadId = Environment.CurrentManagedThreadId; - } - - public void Then(string name) - { - _stop(_id, _start, _threadId); - var newInstance = (MicroTimerInstance)Start(name); - _id = newInstance._id; - _start = newInstance._start; - _threadId = newInstance._threadId; - } - - public void Dispose() - { - _stop(_id, _start, _threadId); - } - } - - private class TraceEvent - { - [JsonPropertyName("name")] - public string Name { get; set; } - - [JsonPropertyName("tid")] - public long ThreadId { get; set; } - - [JsonPropertyName("ts")] - public double Timestamp { get; set; } - - [JsonPropertyName(name: "dur")] - public double Duration { get; set; } - - [JsonPropertyName("ph")] - public string Phase { get; set; } = "X"; - - //[JsonPropertyName("cat")] - //public string? Categories { get; set; } - - //[JsonPropertyName("args")] - //public Dictionary? Args { get; set; } = new(); - - public TraceEvent(string name, MicroTiming timing) - { - Name = name; - Timestamp = timing.Start; - Duration = timing.Duration; - ThreadId = timing.ThreadId; - } - } - - private class TraceExport - { - [JsonPropertyName("controllerTraceDataKey")] - public string ControllerTraceDataKey { get; set; } = "systraceController"; - - [JsonPropertyName("metadata")] - public Dictionary Metadata { get; set; } = new(); - - [JsonPropertyName("traceEvents")] - public List TraceEvents { get; set; } = new(); - } -} diff --git a/Ion/Ion.Extensions.Assets/AssetManager.cs b/Ion/Ion.Extensions.Assets/AssetManager.cs index 9fa7c9e..9d80cdd 100644 --- a/Ion/Ion.Extensions.Assets/AssetManager.cs +++ b/Ion/Ion.Extensions.Assets/AssetManager.cs @@ -5,7 +5,6 @@ namespace Ion.Extensions.Assets; internal class GlobalAssetManager(ILogger logger, IEnumerable loaders) : IBaseAssetManager { - private readonly ILogger _logger = logger; private readonly ImmutableDictionary _loaders = loaders.ToImmutableDictionary(l => l.AssetType); private readonly Dictionary _idCache = []; private readonly Dictionary _nameCache = []; diff --git a/Ion/Ion.Extensions.Audio/AudioManager.cs b/Ion/Ion.Extensions.Audio/AudioManager.cs index 6088d67..1fe7c23 100644 --- a/Ion/Ion.Extensions.Audio/AudioManager.cs +++ b/Ion/Ion.Extensions.Audio/AudioManager.cs @@ -8,10 +8,10 @@ namespace Ion.Extensions.Audio; public class AudioManager(ITraceTimer trace) : IAudioManager, IDisposable { - private readonly WaveOutEvent _outputDevice = new WaveOutEvent(); + private readonly WaveOutEvent _outputDevice = new(); private readonly MixingSampleProvider _mixer = new(WaveFormat.CreateIeeeFloatWaveFormat(48000, 2)) { ReadFully = true }; - public float MasterVolume { get; set; } = 1f; + public float MasterVolume { get; set; } = 10f; public void Initialize() { diff --git a/Ion/Ion.Extensions.Audio/AudioSystem.cs b/Ion/Ion.Extensions.Audio/AudioSystem.cs new file mode 100644 index 0000000..b04ce98 --- /dev/null +++ b/Ion/Ion.Extensions.Audio/AudioSystem.cs @@ -0,0 +1,12 @@ +namespace Ion.Extensions.Audio; + +public class AudioSystem(IAudioManager audioManager) +{ + private readonly AudioManager _audioManager = (AudioManager)audioManager; + + [Init] + public void Init() + { + _audioManager.Initialize(); + } +} diff --git a/Ion/Ion.Extensions.Audio/BuilderExtensions.cs b/Ion/Ion.Extensions.Audio/BuilderExtensions.cs index 9b704ca..25a3647 100644 --- a/Ion/Ion.Extensions.Audio/BuilderExtensions.cs +++ b/Ion/Ion.Extensions.Audio/BuilderExtensions.cs @@ -10,8 +10,15 @@ public static IServiceCollection AddAudio(this IServiceCollection services) { services .AddSingleton() - .AddSingleton(); + .AddSingleton() + .AddSingleton(); return services; } + + public static IIonApplication UseAudio(this IIonApplication app) + { + return app + .UseSystem(); + } } diff --git a/Ion/Ion.Extensions.Audio/SoundEffectSampleProvider.cs b/Ion/Ion.Extensions.Audio/SoundEffectSampleProvider.cs index b7e1892..d5e2015 100644 --- a/Ion/Ion.Extensions.Audio/SoundEffectSampleProvider.cs +++ b/Ion/Ion.Extensions.Audio/SoundEffectSampleProvider.cs @@ -2,18 +2,12 @@ namespace Ion.Extensions.Audio; -internal class SoundEffectSampleProvider : ISampleProvider +internal class SoundEffectSampleProvider(SoundEffect cachedSound) : ISampleProvider { - private readonly SoundEffect cachedSound; private long position; public WaveFormat WaveFormat => cachedSound.WaveFormat; - public SoundEffectSampleProvider(SoundEffect cachedSound) - { - this.cachedSound = cachedSound; - } - public int Read(float[] buffer, int offset, int count) { var availableSamples = cachedSound.AudioData.Length - position; diff --git a/Ion/Ion.Extensions.Coroutines.Abstractions/Ion.Extensions.Coroutines.Abstractions.csproj b/Ion/Ion.Extensions.Coroutines.Abstractions/Ion.Extensions.Coroutines.Abstractions.csproj index 509c906..5fda2cc 100644 --- a/Ion/Ion.Extensions.Coroutines.Abstractions/Ion.Extensions.Coroutines.Abstractions.csproj +++ b/Ion/Ion.Extensions.Coroutines.Abstractions/Ion.Extensions.Coroutines.Abstractions.csproj @@ -6,9 +6,11 @@ enable - + + + - + \ No newline at end of file diff --git a/Ion/Ion.Extensions.Coroutines.Abstractions/Wait.cs b/Ion/Ion.Extensions.Coroutines.Abstractions/Wait.cs index d91cf91..ea60c6c 100644 --- a/Ion/Ion.Extensions.Coroutines.Abstractions/Wait.cs +++ b/Ion/Ion.Extensions.Coroutines.Abstractions/Wait.cs @@ -18,14 +18,14 @@ public record struct WaitFor(float Delay) : IWait public record struct WaitUntil(Func Predicate) : IWait { - public bool IsReady => Predicate(); + public readonly bool IsReady => Predicate(); public void Update(GameTime dt, IEventListener eventListener) { } } public record struct WaitForEvent() : IWait where TEvent : unmanaged { private bool _isReady = false; - public bool IsReady => _isReady; + public readonly bool IsReady => _isReady; public void Update(GameTime dt, IEventListener eventListener) { if (eventListener.On()) _isReady = true; } diff --git a/Ion/Ion.Extensions.Coroutines/CoroutineRunner.cs b/Ion/Ion.Extensions.Coroutines/CoroutineRunner.cs index 02e805b..1c3ad5d 100644 --- a/Ion/Ion.Extensions.Coroutines/CoroutineRunner.cs +++ b/Ion/Ion.Extensions.Coroutines/CoroutineRunner.cs @@ -4,23 +4,17 @@ namespace Ion; -public class CoroutineRunner : ICoroutineRunner +public class CoroutineRunner(IServiceProvider services) : ICoroutineRunner { - private readonly List _routines = new(); - private readonly IServiceProvider _services; + private readonly List _routines = []; /// public int Count => _routines.Count; - public CoroutineRunner(IServiceProvider services) - { - _services = services; - } - /// public void Start(IEnumerator routine) { - _routines.Add(new CoroutineHandle(routine, _services.GetRequiredService())); + _routines.Add(new CoroutineHandle(routine, services.GetRequiredService())); } /// @@ -81,16 +75,10 @@ private bool _moveNext(IEnumerator routine, int index) return result; } - private class CoroutineHandle + private class CoroutineHandle(IEnumerator enumerator, IEventListener eventListener) { - public IEnumerator Enumerator { get; } - public IEventListener EventListener { get; } + public IEnumerator Enumerator { get; } = enumerator; + public IEventListener EventListener { get; } = eventListener; public IWait? Wait { get; set; } - - public CoroutineHandle(IEnumerator enumerator, IEventListener eventListener) - { - Enumerator = enumerator; - EventListener = eventListener; - } } } \ No newline at end of file diff --git a/Ion/Ion.Extensions.Graphics.Veldrid/Systems/GraphicsSystem.cs b/Ion/Ion.Extensions.Graphics.Veldrid/Systems/GraphicsSystem.cs index 4316ff4..9ccca29 100644 --- a/Ion/Ion.Extensions.Graphics.Veldrid/Systems/GraphicsSystem.cs +++ b/Ion/Ion.Extensions.Graphics.Veldrid/Systems/GraphicsSystem.cs @@ -3,21 +3,14 @@ namespace Ion.Extensions.Graphics; -public class GraphicsSystem +public class GraphicsSystem(IGraphicsContext graphics, ITraceTimer trace) { - private readonly GraphicsContext _graphics; - private readonly ITraceTimer _trace; - - public GraphicsSystem(IGraphicsContext graphics, ITraceTimer trace) - { - _graphics = (GraphicsContext)graphics; - _trace = trace; - } + private readonly GraphicsContext _graphics = (GraphicsContext)graphics; [Init] public void Init(GameTime dt, GameLoopDelegate next) { - var timer = _trace.Start("Init"); + var timer = trace.Start("Init"); _graphics.Initialize(); // ASSET MANAGER INIT timer.Stop(); @@ -28,11 +21,11 @@ public void Init(GameTime dt, GameLoopDelegate next) [Render] public void Render(GameTime dt, GameLoopDelegate next) { - var timer = _trace.Start("Render::Pre"); + var timer = trace.Start("Render::Pre"); _graphics.BeginFrame(dt); timer.Stop(); next(dt); - timer = _trace.Start("Render::Post"); + timer = trace.Start("Render::Post"); _graphics.EndFrame(dt); timer.Stop(); } diff --git a/Ion/Ion.Extensions.Graphics.Veldrid/Systems/InputSystem.cs b/Ion/Ion.Extensions.Graphics.Veldrid/Systems/InputSystem.cs index de980d6..904b2bc 100644 --- a/Ion/Ion.Extensions.Graphics.Veldrid/Systems/InputSystem.cs +++ b/Ion/Ion.Extensions.Graphics.Veldrid/Systems/InputSystem.cs @@ -3,21 +3,14 @@ namespace Ion.Extensions.Graphics; -public class InputSystem +public class InputSystem(IInputState input, ITraceTimer trace) { - private readonly InputState _input; - private readonly ITraceTimer _trace; - - public InputSystem(IInputState input, ITraceTimer trace) - { - _input = (InputState)input; - _trace = trace; - } + private readonly InputState _input = (InputState)input; [First] public void First(GameTime dt, GameLoopDelegate next) { - var timer = _trace.Start("First"); + var timer = trace.Start("First"); _input.Step(); timer.Stop(); next(dt); diff --git a/Ion/Ion.Extensions.Graphics.Veldrid/Systems/SpriteBatchSystem.cs b/Ion/Ion.Extensions.Graphics.Veldrid/Systems/SpriteBatchSystem.cs index 7e62475..df34ba3 100644 --- a/Ion/Ion.Extensions.Graphics.Veldrid/Systems/SpriteBatchSystem.cs +++ b/Ion/Ion.Extensions.Graphics.Veldrid/Systems/SpriteBatchSystem.cs @@ -2,21 +2,14 @@ namespace Ion.Extensions.Graphics; -public class SpriteBatchSystem +public class SpriteBatchSystem(ISpriteBatch spriteBatch, ITraceTimer trace) { - private readonly SpriteBatch _spriteBatch; - private readonly ITraceTimer _trace; - - public SpriteBatchSystem(ISpriteBatch spriteBatch, ITraceTimer trace) - { - _spriteBatch = (SpriteBatch)spriteBatch; - _trace = trace; - } + private readonly SpriteBatch _spriteBatch = (SpriteBatch)spriteBatch; [Init] public void Init(GameTime dt, GameLoopDelegate next) { - var timer = _trace.Start("Init"); + var timer = trace.Start("Init"); _spriteBatch.Initialize(); timer.Stop(); next(dt); @@ -25,11 +18,11 @@ public void Init(GameTime dt, GameLoopDelegate next) [Render] public void Render(GameTime dt, GameLoopDelegate next) { - var timer = _trace.Start("Render::Pre"); + var timer = trace.Start("Render::Pre"); _spriteBatch.Begin(dt); timer.Stop(); next(dt); - timer = _trace.Start("Render::Post"); + timer = trace.Start("Render::Post"); _spriteBatch.End(); timer.Stop(); } diff --git a/Ion/Ion.Extensions.Graphics.Veldrid/Systems/WindowSystem.cs b/Ion/Ion.Extensions.Graphics.Veldrid/Systems/WindowSystem.cs index d5fd82d..6fd2574 100644 --- a/Ion/Ion.Extensions.Graphics.Veldrid/Systems/WindowSystem.cs +++ b/Ion/Ion.Extensions.Graphics.Veldrid/Systems/WindowSystem.cs @@ -3,23 +3,14 @@ namespace Ion.Extensions.Graphics; -public class WindowSystem +public class WindowSystem(IWindow window, IEventListener events, ITraceTimer trace) { - private readonly Window _window; - private readonly IEventListener _events; - private readonly ITraceTimer _trace; - - public WindowSystem(IWindow window, IEventListener events, ITraceTimer trace) - { - _window = (Window)window; - _events = events; - _trace = trace; - } + private readonly Window _window = (Window)window; [Init] public void Init(GameTime dt, GameLoopDelegate next) { - var timer = _trace.Start("Init"); + var timer = trace.Start("Init"); _window.Initialize(); timer.Stop(); next(dt); @@ -28,7 +19,7 @@ public void Init(GameTime dt, GameLoopDelegate next) [First] public void First(GameTime dt, GameLoopDelegate next) { - var timer = _trace.Start("First"); + var timer = trace.Start("First"); _window.Step(); timer.Stop(); next(dt); @@ -38,8 +29,8 @@ public void First(GameTime dt, GameLoopDelegate next) public void Render(GameTime dt, GameLoopDelegate next) { next(dt); - var timer = _trace.Start("Render"); - if (_events.On()) _events.Emit(); + var timer = trace.Start("Render"); + if (events.On()) events.Emit(); timer.Stop(); } } diff --git a/Ion/Ion.Extensions.Scenes.Abstractions/SceneEvents.cs b/Ion/Ion.Extensions.Scenes.Abstractions/SceneEvents.cs index f020d24..3aa7bb5 100644 --- a/Ion/Ion.Extensions.Scenes.Abstractions/SceneEvents.cs +++ b/Ion/Ion.Extensions.Scenes.Abstractions/SceneEvents.cs @@ -1,3 +1,12 @@ namespace Ion.Extensions.Scenes; -public record struct ChangeSceneEvent(int NextScene); + +public record struct ChangeSceneEvent(int NextSceneId); + +public static class EventEmitterExtensions +{ + public static void EmitChangeScene(this IEventEmitter eventEmitter, int nextSceneId) + { + eventEmitter.Emit(new ChangeSceneEvent(nextSceneId)); + } +} diff --git a/Ion/Ion.Extensions.Scenes.Abstractions/Transition.cs b/Ion/Ion.Extensions.Scenes.Abstractions/Transition.cs new file mode 100644 index 0000000..1c540ab --- /dev/null +++ b/Ion/Ion.Extensions.Scenes.Abstractions/Transition.cs @@ -0,0 +1,105 @@ +namespace Ion.Extensions.Scenes; + +/// +/// A basic enum to indicate the transition direction. +/// +public enum TransitionState +{ + /// + /// Defaults to an unknown state. + /// + Unknown = 0, + + /// + /// Indicates a transition out. + /// + Out, + + /// + /// Indicates a transition in. + /// + In, +} + +/// +/// A base Transition used to animate the unload/load of scenes. +/// +public abstract class Transition : IDisposable +{ + private float _duration; + private float _halfDuration; + private float _currentSeconds; + + /// + /// The current state of the Transition. + /// + public TransitionState State { get; private set; } = TransitionState.Out; + + /// + /// The length of the Transition, in seconds. + /// + public float Duration + { + get => _duration; + internal set + { + _duration = value; + _halfDuration = _duration / 2f; + } + + } + + /// + /// The current relative value of the Transition (0f to 1f). + /// + public float Value => MathHelper.Clamp(_currentSeconds / _halfDuration, 0f, 1f); + + /// + /// Triggered when the transition is switching from Out to In. + /// + public event EventHandler? StateChanged; + + /// + /// Triggered when the transition is done. + /// + public event EventHandler? Completed; + + /// + public abstract void Dispose(); + + /// + /// Updates the timing of the transition. + /// + /// The elapsed time since the last call. + public void Update(float dt) + { + switch (State) + { + case TransitionState.Out: + _currentSeconds += dt; + + if (_currentSeconds >= _halfDuration) + { + State = TransitionState.In; + StateChanged?.Invoke(this, EventArgs.Empty); + } + break; + case TransitionState.In: + _currentSeconds -= dt; + + if (_currentSeconds <= 0.0f) + { + Completed?.Invoke(this, EventArgs.Empty); + } + break; + default: + throw new IndexOutOfRangeException($"Unknown transition state {State}"); + } + } + + /// + /// Renders the transition to the screen. + /// + /// The elapsed time since the last call. + public abstract void Render(float dt); +} diff --git a/Ion/Ion.Extensions.Scenes.Tests/SceneTests.cs b/Ion/Ion.Extensions.Scenes.Tests/SceneTests.cs index a4591f7..1f41c7d 100644 --- a/Ion/Ion.Extensions.Scenes.Tests/SceneTests.cs +++ b/Ion/Ion.Extensions.Scenes.Tests/SceneTests.cs @@ -30,12 +30,12 @@ public void SwitchingScenes() Assert.Equal(1, currentScene.SceneId); gameLoop.Step(dt); - eventEmitter.Emit(new ChangeSceneEvent(2)); + eventEmitter.EmitChangeScene(2); gameLoop.Step(dt); Assert.Equal(2, currentScene.SceneId); - eventEmitter.Emit(new ChangeSceneEvent(1)); + eventEmitter.EmitChangeScene(1); gameLoop.Step(dt); Assert.Equal(1, currentScene.SceneId); diff --git a/Ion/Ion.Extensions.Scenes/Systems/SceneSystem.cs b/Ion/Ion.Extensions.Scenes/Systems/SceneSystem.cs index ca28018..abddf8b 100644 --- a/Ion/Ion.Extensions.Scenes/Systems/SceneSystem.cs +++ b/Ion/Ion.Extensions.Scenes/Systems/SceneSystem.cs @@ -8,33 +8,27 @@ namespace Ion.Extensions.Scenes; internal delegate Scene SceneBuilderFactory(IConfiguration config, IServiceProvider services); -internal sealed class SceneSystem : IDisposable +/// +/// Creates a new SceneManager instance, keeping a reference to the service provider. +/// +/// The root service provider. +internal sealed class SceneSystem( + IServiceProvider serviceProvider, + ILogger logger, IConfiguration config, + IEventListener events, + ITraceTimer trace + ) : IDisposable { - private readonly IServiceProvider _serviceProvider; - private readonly ILogger _logger; - private readonly IConfiguration _config; - private readonly IEventListener _events; - private readonly ITraceTimer _trace; + private readonly ILogger _logger = logger; + private readonly ITraceTimer _trace = trace; private readonly Dictionary _scenesBuilders = new(); private Scene? _activeScene; + private Transition? _activeTransition; private IServiceScope? _activeScope; - private int _nextScene = 0; + private int _nextSceneId = 0; - public int CurrentScene => _activeScene?.Id ?? 0; - - /// - /// Creates a new SceneManager instance, keeping a reference to the service provider. - /// - /// The root service provider. - public SceneSystem(IServiceProvider serviceProvider, ILogger logger, IConfiguration config, IEventListener events, ITraceTimer trace) - { - _serviceProvider = serviceProvider; - _logger = logger; - _config = config; - _events = events; - _trace = trace; - } + public int CurrentSceneId => _activeScene?.Id ?? 0; public void Register(int sceneId, SceneBuilderFactory sceneBuilderFactory) { @@ -43,25 +37,25 @@ public void Register(int sceneId, SceneBuilderFactory sceneBuilderFactory) private void _loadNextScene(GameTime dt) { - if (_nextScene == CurrentScene) return; + if (_nextSceneId == CurrentSceneId) return; if (_activeScene != null) { - _logger.LogInformation("Unloading {CurrentScene} Scene.", CurrentScene); + _logger.LogInformation("Unloading {CurrentSceneId} Scene.", CurrentSceneId); _activeScene?.Destroy(dt); _activeScope?.Dispose(); - _logger.LogInformation("Unloaded {CurrentScene} Scene.", CurrentScene); + _logger.LogInformation("Unloaded {CurrentSceneId} Scene.", CurrentSceneId); _activeScene = null; } - _logger.LogInformation("Loading {NextScene} Scene.", _nextScene); - _activeScope = _serviceProvider.CreateScope(); + _logger.LogInformation("Loading {NextScene} Scene.", _nextSceneId); + _activeScope = serviceProvider.CreateScope(); var currScene = (CurrentScene)_activeScope.ServiceProvider.GetRequiredService(); - currScene.Set(_nextScene); + currScene.Set(_nextSceneId); - _activeScene = _scenesBuilders[_nextScene](_config, _activeScope.ServiceProvider); + _activeScene = _scenesBuilders[_nextSceneId](config, _activeScope.ServiceProvider); _activeScene.Init(dt); - _logger.LogInformation("Loaded {NextScene} Scene.", _nextScene); + _logger.LogInformation("Loaded {NextScene} Scene.", _nextSceneId); } /// @@ -72,7 +66,7 @@ public void Init(GameTime dt, GameLoopDelegate _) { var timer = _trace.Start("Init"); - _logger.LogDebug("Init ({CurrentScene}) {dt}", CurrentScene, dt); + _logger.LogDebug("Init ({CurrentSceneId}) {dt}", CurrentSceneId, dt); _handleChangeSceneEvents(); @@ -82,7 +76,7 @@ public void Init(GameTime dt, GameLoopDelegate _) } else { - _nextScene = _scenesBuilders.First().Key; + _nextSceneId = _scenesBuilders.First().Key; _loadNextScene(dt); } @@ -97,7 +91,7 @@ public void First(GameTime dt, GameLoopDelegate _) _handleChangeSceneEvents(); - if (_nextScene != CurrentScene) _loadNextScene(dt); + if (_nextSceneId != CurrentSceneId) _loadNextScene(dt); _activeScene?.First(dt); timer.Stop(); @@ -123,6 +117,7 @@ public void Update(GameTime dt, GameLoopDelegate _) var timer = _trace.Start("Update"); _activeScene?.Update(dt); + _activeTransition?.Update(dt); timer.Stop(); } @@ -137,6 +132,7 @@ public void Render(GameTime dt, GameLoopDelegate _) var timer = _trace.Start("Render"); _activeScene?.Render(dt); + _activeTransition?.Render(dt); timer.Stop(); } @@ -174,11 +170,11 @@ public void Dispose() private void _handleChangeSceneEvents() { - if (_events.OnLatest(out var e)) + if (events.OnLatest(out var e)) { - if (!_scenesBuilders.ContainsKey(e.Data.NextScene)) _logger.LogWarning("Tried to load unknown scene '{NextScene}'.", e.Data.NextScene); + if (!_scenesBuilders.ContainsKey(e.Data.NextSceneId)) _logger.LogWarning("Tried to load unknown scene '{NextSceneId}'.", e.Data.NextSceneId); - _nextScene = e.Data.NextScene; + _nextSceneId = e.Data.NextSceneId; e.Handled = true; } } diff --git a/Ion/Ion/BuilderExtensions.cs b/Ion/Ion/BuilderExtensions.cs index ec1a57e..fc2acfb 100644 --- a/Ion/Ion/BuilderExtensions.cs +++ b/Ion/Ion/BuilderExtensions.cs @@ -18,7 +18,6 @@ public static IServiceCollection AddIon(this IServiceCollection services, IConfi .AddDebugUtils(config) .AddAssets() .AddVeldridGraphics(config, configureOptions) - //.AddWGPUGraphics(config, configureOptions) .AddAudio() .AddScenes() .AddCoroutines(); @@ -29,7 +28,7 @@ public static IIonApplication UseIon(this IIonApplication app) return app .UseDebugUtils() .UseEvents() - //.UseWGPUGraphics(); - .UseVeldridGraphics(); + .UseVeldridGraphics() + .UseAudio(); } } diff --git a/Ion/Ion_old/Builder/GameApplication.cs b/Ion/Ion_old/Builder/GameApplication.cs deleted file mode 100644 index 6d98825..0000000 --- a/Ion/Ion_old/Builder/GameApplication.cs +++ /dev/null @@ -1,114 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; - -namespace Ion.Builder; - -public class GameApplication : IDisposable -{ - private readonly IHost _host; - - private readonly IGameLoopBuilder _init = new GameLoopBuilder(); - private readonly IGameLoopBuilder _first = new GameLoopBuilder(); - private readonly IGameLoopBuilder _fixedUpdate = new GameLoopBuilder(); - private readonly IGameLoopBuilder _update = new GameLoopBuilder(); - private readonly IGameLoopBuilder _render = new GameLoopBuilder(); - private readonly IGameLoopBuilder _last = new GameLoopBuilder(); - private readonly IGameLoopBuilder _destroy = new GameLoopBuilder(); - - /// - /// The application's configured services. - /// - public IServiceProvider Services => _host.Services; - - /// - /// The application's configured . - /// - public IConfiguration Configuration => _host.Services.GetRequiredService(); - - /// - /// Allows consumers to be notified of application lifetime events. - /// - public IHostApplicationLifetime Lifetime => _host.Services.GetRequiredService(); - - internal GameApplication(IHost host) - { - _host = host; - } - - public static GameApplicationBuilder CreateBuilder(string[] args) - { - return new GameApplicationBuilder(args); - } - - public GameApplication UseInit(Func middleware) - { - _init.Use(middleware); - return this; - } - - public GameApplication UseFirst(Func middleware) - { - _first.Use(middleware); - return this; - } - - public GameApplication UseFixedUpdate(Func middleware) - { - _fixedUpdate.Use(middleware); - return this; - } - - public GameApplication UseUpdate(Func middleware) - { - _update.Use(middleware); - return this; - } - - public GameApplication UseRender(Func middleware) - { - _update.Use(middleware); - return this; - } - - public GameApplication UseLast(Func middleware) - { - _last.Use(middleware); - return this; - } - - public GameApplication UseDestroy(Func middleware) - { - _destroy.Use(middleware); - return this; - } - - public void Run() - { - var gameLoop = _build(); - - gameLoop.Run(); - } - - public void Dispose() - { - _host.Dispose(); - } - - private GameLoop _build() - { - var gameConfig = Services.GetRequiredService(); - var gameLoop = new GameLoop(gameConfig) - { - Initialize = _init.Build(), - First = _first.Build(), - FixedUpdate = _fixedUpdate.Build(), - Update = _update.Build(), - Render = _render.Build(), - Last = _last.Build(), - Destroy = _destroy.Build() - }; - - return gameLoop; - } -} diff --git a/Ion/Ion_old/Builder/GameApplicationBuilder.cs b/Ion/Ion_old/Builder/GameApplicationBuilder.cs deleted file mode 100644 index 7d33176..0000000 --- a/Ion/Ion_old/Builder/GameApplicationBuilder.cs +++ /dev/null @@ -1,43 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.FileProviders; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Hosting.Internal; - -using System.Reflection; - -namespace Ion.Builder; - -public class GameApplicationBuilder -{ - private HostApplicationBuilder _hostBuilder; - - public ConfigurationManager Configuration => _hostBuilder.Configuration; - public IServiceCollection Services => _hostBuilder.Services; - - public GameApplicationBuilder(string[] args) - { - _hostBuilder = Host.CreateApplicationBuilder(args); - - Services.AddLogging(config => - { - config - .ClearProviders() - .AddSimpleConsole(options => - { - options.TimestampFormat = "[HH:mm:ss] "; - options.SingleLine = true; - }) - .AddDebug(); - }); - - Services.AddSingleton(); - } - - public GameApplication Build() - { - var host = _hostBuilder.Build(); - var builtGame = new GameApplication(host); - return builtGame; - } -} diff --git a/Ion/Ion_old/Builder/GameLoopBuilder.cs b/Ion/Ion_old/Builder/GameLoopBuilder.cs deleted file mode 100644 index 67c5c08..0000000 --- a/Ion/Ion_old/Builder/GameLoopBuilder.cs +++ /dev/null @@ -1,50 +0,0 @@ -namespace Ion.Builder; - - -public delegate void GameLoopDelegate(GameTime dt); - -public interface IGameLoopBuilder -{ - IGameLoopBuilder Use(Func middleware); - GameLoopDelegate Build(); -} - -internal class GameLoopBuilder : IGameLoopBuilder -{ - private readonly List> _systems = new(); - private readonly List _descriptions = new(); - - public IGameLoopBuilder Use(Func middleware) - { - _systems.Add(middleware); - _descriptions.Add(_createMiddlewareDescription(middleware)); - return this; - } - - public GameLoopDelegate Build() - { - GameLoopDelegate app = (dt) => { }; - - for (var s = _systems.Count - 1; s >= 0; s--) - { - app = _systems[s](app); - } - - return app; - } - - private string _createMiddlewareDescription(Func middleware) - { - if (middleware.Target != null) - { - if (middleware.Method.Name == "CreateMiddleware") - { - return middleware.Target.ToString()!; - } - - return middleware.Target.GetType().FullName + "." + middleware.Method.Name; - } - - return middleware.Method.Name.ToString(); - } -} \ No newline at end of file diff --git a/Ion/Ion_old/Builder/ServiceCollectionExtensions.cs b/Ion/Ion_old/Builder/ServiceCollectionExtensions.cs deleted file mode 100644 index 06a58f4..0000000 --- a/Ion/Ion_old/Builder/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; - -namespace Ion.Builder; - -public static class ServiceCollectionExtensions -{ - public static IServiceCollection AddGameConfig(this IServiceCollection services, Action config) - { - return services.AddSingleton(_ => - { - var gameConfig = new GameConfig(); - config(gameConfig); - return gameConfig; - }); - } -} diff --git a/Ion/Ion_old/Builder/UseMiddlewareExtensions.cs b/Ion/Ion_old/Builder/UseMiddlewareExtensions.cs deleted file mode 100644 index ccb5072..0000000 --- a/Ion/Ion_old/Builder/UseMiddlewareExtensions.cs +++ /dev/null @@ -1,94 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; - -using System.Reflection; - -namespace Ion.Builder; - -[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] -public class UpdateAttribute : Attribute { } - -public static class UseMiddlewareExtensions -{ - // We're going to keep all public constructors and public methods on middleware - private const DynamicallyAccessedMemberTypes MiddlewareAccessibility = DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods; - - /// - /// Adds a middleware type to the application's request pipeline. - /// - /// The middleware type. - /// The instance. - /// The arguments to pass to the middleware type instance's constructor. - /// The instance. - public static GameApplication UseUpdateMiddleware<[DynamicallyAccessedMembers(MiddlewareAccessibility)] TMiddleware>(this GameApplication app, params object?[] args) - { - return app.UseUpdateMiddleware(typeof(TMiddleware), args); - } - - /// - /// Adds a middleware type to the application's request pipeline. - /// - /// The instance. - /// The middleware type. - /// The arguments to pass to the middleware type instance's constructor. - /// The instance. - public static GameApplication UseUpdateMiddleware( - this GameApplication app, - [DynamicallyAccessedMembers(MiddlewareAccessibility)] Type middleware, - params object?[] args) - { - var methods = middleware.GetMethods(BindingFlags.Instance | BindingFlags.Public); - - foreach (var method in methods) - { - var updateAttr = method.GetCustomAttribute(); - if (updateAttr is null) continue; - - if (!typeof(void).IsAssignableTo(method.ReturnType)) continue; - - var parameters = method.GetParameters(); - if (parameters.Length == 0 || (parameters.Length == 1 && parameters[0].ParameterType == typeof(GameTime))) - { - var reflectionBinder = new ReflectionMiddlewareBinder(app, middleware, args, method, parameters); - app.UseUpdate(reflectionBinder.CreateMiddleware); - } - } - - return app; - } - - private sealed class ReflectionMiddlewareBinder - { - private readonly GameApplication _app; - [DynamicallyAccessedMembers(MiddlewareAccessibility)] private readonly Type _middleware; - private readonly object?[] _args; - private readonly MethodInfo _invokeMethod; - private readonly ParameterInfo[] _parameters; - - public ReflectionMiddlewareBinder( - GameApplication app, - [DynamicallyAccessedMembers(MiddlewareAccessibility)] Type middleware, - object?[] args, - MethodInfo invokeMethod, - ParameterInfo[] parameters) - { - _app = app; - _middleware = middleware; - _args = args; - _invokeMethod = invokeMethod; - _parameters = parameters; - } - - // The CreateMiddleware method name is used by ApplicationBuilder to resolve the middleware type. - public GameLoopDelegate CreateMiddleware(GameLoopDelegate next) - { - var ctorArgs = new object[_args.Length + 1]; - ctorArgs[0] = next; - Array.Copy(_args, 0, ctorArgs, 1, _args.Length); - var instance = ActivatorUtilities.CreateInstance(_app.Services, _middleware, ctorArgs); - - return (GameLoopDelegate)_invokeMethod.CreateDelegate(typeof(GameLoopDelegate), instance); - } - - public override string ToString() => _middleware.ToString(); - } -} diff --git a/Ion/Ion_old/Color.cs b/Ion/Ion_old/Color.cs deleted file mode 100644 index ef85756..0000000 --- a/Ion/Ion_old/Color.cs +++ /dev/null @@ -1,511 +0,0 @@ -using System.Runtime.Serialization; - -namespace Ion; - -/// -/// An RGBA color value backed by a Vector4 (16 bytes). -/// Based MonoGame's Color struct but modified to work with System.Numerics Vector4. -/// -[DataContract] -public struct Color : IEquatable -{ - // X-------Y-------Z-------W------- - // R G B A - private readonly Vector4 _channels; - - /// - /// 16 bytes. - /// - public static readonly uint SizeInBytes = 16; - - /// - /// The red channel. - /// - public float R => _channels.X; - - /// - /// The green channel. - /// - public float G => _channels.Y; - - /// - /// The blue channel. - /// - public float B => _channels.Z; - - /// - /// The alpha channel. - /// - public float A => _channels.W; - - /// - /// Gets or sets packed value of this . - /// - public uint PackedValue => ((uint)(R * 255) << 24) | ((uint)(G * 255) << 16) | ((uint)(B * 255) << 8) | (uint)(A * 255); - - /// - /// Constructs an RGBA color from a packed value. - /// The value is a 32-bit unsigned integer, with A in the least significant octet. - /// - /// The packed value. - public Color(uint packedValue) - { - float r, g, b, a; - unchecked - { - if ((packedValue & 0xff000000) != 0) - { - r = (byte)packedValue >> 24; - g = (byte)packedValue >> 16; - b = (byte)packedValue >> 8; - a = (byte)packedValue; - } else { - r = (byte)packedValue >> 16; - g = (byte)packedValue >> 8; - b = (byte)packedValue; - a = 0; - } - - } - - _channels = new Vector4(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f); - } - - /// - /// Constructs an RGBA color from the XYZW unit length components of a vector. - /// - /// A representing color. - public Color(Vector4 color) { - _channels = color; - } - - /// - /// Constructs an RGBA color from the XYZ unit length components of a vector. Alpha value will be opaque. - /// - /// A representing color. - public Color(Vector3 color) : this(color.X, color.Y, color.Z, 1f) { } - - /// - /// Constructs an RGBA color from a and an alpha value. - /// - /// A for RGB values of new instance. - /// The alpha component value from 0 to 255. - public Color(Color color, int alpha) : this(color.R, color.G, color.B, alpha / 255f) { } - - /// - /// Constructs an RGBA color from color and alpha value. - /// - /// A for RGB values of new instance. - /// Alpha component value from 0.0f to 1.0f. - public Color(Color color, float alpha) : this(color.R, color.G, color.B, alpha) { } - - /// - /// Constructs an RGBA color from scalars representing red, green and blue values. Alpha value will be opaque. - /// - /// Red component value from 0.0f to 1.0f. - /// Green component value from 0.0f to 1.0f. - /// Blue component value from 0.0f to 1.0f. - public Color(float r, float g, float b) : this(r,g, b, 1f) { } - - /// - /// Constructs an RGBA color from scalars representing red, green, blue and alpha values. - /// - /// Red component value from 0.0f to 1.0f. - /// Green component value from 0.0f to 1.0f. - /// Blue component value from 0.0f to 1.0f. - /// Alpha component value from 0.0f to 1.0f. - public Color(float r, float g, float b, float alpha) { - _channels = new Vector4(r, g, b, alpha); - } - - /// - /// Constructs an RGBA color from scalars representing red, green and blue values. Alpha value will be opaque. - /// - /// Red component value from 0 to 255. - /// Green component value from 0 to 255. - /// Blue component value from 0 to 255. - public Color(int r, int g, int b) : this(r / 255f, g / 255f, b / 255f, 1f) { } - - /// - /// Constructs an RGBA color from scalars representing red, green, blue and alpha values. - /// - /// Red component value from 0 to 255. - /// Green component value from 0 to 255. - /// Blue component value from 0 to 255. - /// Alpha component value from 0 to 255. - public Color(int r, int g, int b, int alpha) : this(r / 255f, g / 255f, b / 255f, alpha/255f) { } - - /// - /// Compares whether two instances are equal. - /// - /// instance on the left of the equal sign. - /// instance on the right of the equal sign. - /// true if the instances are equal; false otherwise. - public static bool operator ==(Color a, Color b) - { - return a._channels == b._channels; - } - - /// - /// Compares whether two instances are not equal. - /// - /// instance on the left of the not equal sign. - /// instance on the right of the not equal sign. - /// true if the instances are not equal; false otherwise. - public static bool operator !=(Color a, Color b) - { - return a._channels != b._channels; - } - - /// - /// Gets the hash code of this . - /// - /// Hash code of this . - public override int GetHashCode() - { - return _channels.GetHashCode(); - } - - /// - /// Compares whether current instance is equal to specified object. - /// - /// The to compare. - /// true if the instances are equal; false otherwise. - public override bool Equals(object? obj) - { - return (obj is Color color) && Equals(color); - } - - /// - /// Performs linear interpolation of . - /// - /// Source . - /// Destination . - /// Interpolation factor. - /// Interpolated . - public static Color Lerp(Color value1, Color value2, float amount) - { - amount = MathHelper.Clamp(amount, 0, 1); - return new Color( - MathHelper.Lerp(value1.R, value2.R, amount), - MathHelper.Lerp(value1.G, value2.G, amount), - MathHelper.Lerp(value1.B, value2.B, amount), - MathHelper.Lerp(value1.A, value2.A, amount)); - } - - /// - /// Multiply by value. - /// - /// Source . - /// Multiplicator. - /// Multiplication result. - public static Color Multiply(Color value, float scale) - { - return new Color(value.R * scale, value.G * scale, value.B * scale, value.A * scale); - } - - public static Color FromHSV(float hue, float saturation, float value) - { - int hi = Convert.ToInt32(MathF.Floor(hue / 60)) % 6; - double f = hue / 60 - MathF.Floor(hue / 60); - - value *= 255; - int v = Convert.ToInt32(value); - int p = Convert.ToInt32(value * (1 - saturation)); - int q = Convert.ToInt32(value * (1 - f * saturation)); - int t = Convert.ToInt32(value * (1 - (1 - f) * saturation)); - - if (hi == 0) - return new Color(v, t, p); - else if (hi == 1) - return new Color(q, v, p); - else if (hi == 2) - return new Color(p, v, t); - else if (hi == 3) - return new Color(p, q, v); - else if (hi == 4) - return new Color(t, p, v); - else - return new Color(v, p, q); - } - - /// - /// Multiply by value. - /// - /// Source . - /// Multiplicator. - /// Multiplication result. - public static Color operator *(Color value, float scale) - { - return new Color(value.R * scale, value.G * scale, value.B * scale, value.A * scale); - } - - public static Color operator *(float scale, Color value) - { - return new Color(value.R * scale, value.G * scale, value.B * scale, value.A * scale); - } - - /// - /// Gets a representation for this object. - /// - /// A representation for this object. - public Vector3 ToVector3() - { - return new Vector3(_channels.X, _channels.Y, _channels.Z); - } - - /// - /// Gets a representation for this object. - /// - /// A representation for this object. - public Vector4 ToVector4() - { - return _channels; - } - - /// - /// Converts Color to RgbaFloat. - /// - /// The color to convert. - public static implicit operator Veldrid.RgbaFloat(Color color) => new(color._channels); - - internal string DebugDisplayString - { - get - { - return string.Concat( - R.ToString(), " ", - G.ToString(), " ", - B.ToString(), " ", - A.ToString() - ); - } - } - - /// - /// Returns a representation of this in the format: - /// {R:[red] G:[green] B:[blue] A:[alpha]} - /// - /// representation of this . - public override string ToString() - { - return $"#{(uint)(R * 255):X2}{(uint)(G * 255):X2}{(uint)(B * 255):X2} {A:0.##}"; - } - - #region IEquatable Members - - /// - /// Compares whether current instance is equal to specified . - /// - /// The to compare. - /// true if the instances are equal; false otherwise. - public bool Equals(Color other) - { - return _channels == other._channels; - } - - #endregion - - /// - /// Deconstruction method for . - /// - /// Red component value from 0 to 255. - /// Green component value from 0 to 255. - /// Blue component value from 0 to 255. - public void Deconstruct(out byte r, out byte g, out byte b) - { - r = (byte)(R * 255); - g = (byte)(G * 255); - b = (byte)(B * 255); - } - - /// - /// Deconstruction method for with Alpha. - /// - /// Red component value from 0 to 255. - /// Green component value from 0 to 255. - /// Blue component value from 0 to 255. - /// Alpha component value from 0 to 255. - public void Deconstruct(out byte r, out byte g, out byte b, out byte a) - { - r = (byte)(R * 255); - g = (byte)(G * 255); - b = (byte)(B * 255); - a = (byte)(A * 255); - } - - /// - /// Deconstruction method for . - /// - /// Red component value from 0.0f to 1.0f. - /// Green component value from 0.0f to 1.0f. - /// Blue component value from 0.0f to 1.0f. - public void Deconstruct(out float r, out float g, out float b) - { - r = R; - g = G; - b = B; - } - - /// - /// Deconstruction method for with Alpha. - /// - /// Red component value from 0.0f to 1.0f. - /// Green component value from 0.0f to 1.0f. - /// Blue component value from 0.0f to 1.0f. - /// Alpha component value from 0.0f to 1.0f. - public void Deconstruct(out float r, out float g, out float b, out float a) - { - r = R / 255f; - g = G / 255f; - b = B / 255f; - a = A / 255f; - } - - #region Named Colors - - public static readonly Color Transparent = new(0x00, 0x00, 0x00, 0x00); - public static readonly Color AliceBlue = new(0xf0, 0xf8, 0xff, 0xff); - public static readonly Color AntiqueWhite = new(0xfa, 0xeb, 0xd7, 0xff); - public static readonly Color Aqua = new(0x00, 0xff, 0xff, 0xff); - public static readonly Color Aquamarine = new(0x7f, 0xff, 0xd4, 0xff); - public static readonly Color Azure = new(0xf0, 0xff, 0xff, 0xff); - public static readonly Color Beige = new(0xf5, 0xf5, 0xdc, 0xff); - public static readonly Color Bisque = new(0xff, 0xe4, 0xc4, 0xff); - public static readonly Color Black = new(0x00, 0x00, 0x00, 0xff); - public static readonly Color BlanchedAlmond = new(0xff, 0xeb, 0xcd, 0xff); - public static readonly Color Blue = new(0x00, 0x00, 0xff, 0xff); - public static readonly Color BlueViolet = new(0x8a, 0x2b, 0xe2, 0xff); - public static readonly Color Brown = new(0xa5, 0x2a, 0x2a, 0xff); - public static readonly Color BurlyWood = new(0xde, 0xb8, 0x87, 0xff); - public static readonly Color CadetBlue = new(0x5f, 0x9e, 0xa0, 0xff); - public static readonly Color Chartreuse = new(0x7f, 0xff, 0x00, 0xff); - public static readonly Color Chocolate = new(0xd2, 0x69, 0x1e, 0xff); - public static readonly Color Coral = new(0xff, 0x7f, 0x50, 0xff); - public static readonly Color CornflowerBlue = new(0x64, 0x95, 0xed, 0xff); - public static readonly Color Cornsilk = new(0xff, 0xf8, 0xdc, 0xff); - public static readonly Color Crimson = new(0xdc, 0x14, 0x3c, 0xff); - public static readonly Color Cyan = new(0x00, 0xff, 0xff, 0xff); - public static readonly Color DarkBlue = new(0x00, 0x00, 0x8b, 0xff); - public static readonly Color DarkCyan = new(0x00, 0x8b, 0x8b, 0xff); - public static readonly Color DarkGoldenrod = new(0xb8, 0x86, 0x0b, 0xff); - public static readonly Color DarkGray = new(0xa9, 0xa9, 0xa9, 0xff); - public static readonly Color DarkGreen = new(0x00, 0x64, 0x00, 0xff); - public static readonly Color DarkKhaki = new(0xbd, 0xb7, 0x6b, 0xff); - public static readonly Color DarkMagenta = new(0x8b, 0x00, 0x8b, 0xff); - public static readonly Color DarkOliveGreen = new(0x55, 0x6b, 0x2f, 0xff); - public static readonly Color DarkOrange = new(0xff, 0x8c, 0x00, 0xff); - public static readonly Color DarkOrchid = new(0x99, 0x32, 0xcc, 0xff); - public static readonly Color DarkRed = new(0x8b, 0x00, 0x00, 0xff); - public static readonly Color DarkSalmon = new(0xe9, 0x96, 0x7a, 0xff); - public static readonly Color DarkSeaGreen = new(0x8f, 0xbc, 0x8b, 0xff); - public static readonly Color DarkSlateBlue = new(0x48, 0x3d, 0x8b, 0xff); - public static readonly Color DarkSlateGray = new(0x2f, 0x4f, 0x4f, 0xff); - public static readonly Color DarkTurquoise = new(0x00, 0xce, 0xd1, 0xff); - public static readonly Color DarkViolet = new(0x94, 0x00, 0xd3, 0xff); - public static readonly Color DeepPink = new(0xff, 0x14, 0x93, 0xff); - public static readonly Color DeepSkyBlue = new(0x00, 0xbf, 0xff, 0xff); - public static readonly Color DimGray = new(0x69, 0x69, 0x69, 0xff); - public static readonly Color DodgerBlue = new(0x1e, 0x90, 0xff, 0xff); - public static readonly Color Firebrick = new(0xb2, 0x22, 0x22, 0xff); - public static readonly Color FloralWhite = new(0xff, 0xfa, 0xf0, 0xff); - public static readonly Color ForestGreen = new(0x22, 0x8b, 0x22, 0xff); - public static readonly Color Fuchsia = new(0xff, 0x00, 0xff, 0xff); - public static readonly Color Gainsboro = new(0xdc, 0xdc, 0xdc, 0xff); - public static readonly Color GhostWhite = new(0xf8, 0xf8, 0xff, 0xff); - public static readonly Color Gold = new(0xff, 0xd7, 0x00, 0xff); - public static readonly Color Goldenrod = new(0xda, 0xa5, 0x20, 0xff); - public static readonly Color Gray = new(0x80, 0x80, 0x80, 0xff); - public static readonly Color Green = new(0x00, 0x80, 0x00, 0xff); - public static readonly Color GreenYellow = new(0xad, 0xff, 0x2f, 0xff); - public static readonly Color Honeydew = new(0xf0, 0xff, 0xf0, 0xff); - public static readonly Color HotPink = new(0xff, 0x69, 0xb4, 0xff); - public static readonly Color IndianRed = new(0xcd, 0x5c, 0x5c, 0xff); - public static readonly Color Indigo = new(0x4b, 0x00, 0x82, 0xff); - public static readonly Color Ivory = new(0xff, 0xff, 0xf0, 0xff); - public static readonly Color Khaki = new(0xf0, 0xe6, 0x8c, 0xff); - public static readonly Color Lavender = new(0xe6, 0xe6, 0xfa, 0xff); - public static readonly Color LavenderBlush = new(0xff, 0xf0, 0xf5, 0xff); - public static readonly Color LawnGreen = new(0x7c, 0xfc, 0x00, 0xff); - public static readonly Color LemonChiffon = new(0xff, 0xfa, 0xcd, 0xff); - public static readonly Color LightBlue = new(0xad, 0xd8, 0xe6, 0xff); - public static readonly Color LightCoral = new(0xf0, 0x80, 0x80, 0xff); - public static readonly Color LightCyan = new(0xe0, 0xff, 0xff, 0xff); - public static readonly Color LightGoldenrodYellow = new(0xfa, 0xfa, 0xd2, 0xff); - public static readonly Color LightGray = new(0xd3, 0xd3, 0xd3, 0xff); - public static readonly Color LightGreen = new(0x90, 0xee, 0x90, 0xff); - public static readonly Color LightPink = new(0xff, 0xb6, 0xc1, 0xff); - public static readonly Color LightSalmon = new(0xff, 0xa0, 0x7a, 0xff); - public static readonly Color LightSeaGreen = new(0x20, 0xb2, 0xaa, 0xff); - public static readonly Color LightSkyBlue = new(0x87, 0xce, 0xfa, 0xff); - public static readonly Color LightSlateGray = new(0x77, 0x88, 0x99, 0xff); - public static readonly Color LightSteelBlue = new(0xb0, 0xc4, 0xde, 0xff); - public static readonly Color LightYellow = new(0xff, 0xff, 0xe0, 0xff); - public static readonly Color Lime = new(0x00, 0xff, 0x00, 0xff); - public static readonly Color LimeGreen = new(0x32, 0xcd, 0x32, 0xff); - public static readonly Color Linen = new(0xfa, 0xf0, 0xe6, 0xff); - public static readonly Color Magenta = new(0xff, 0x00, 0xff, 0xff); - public static readonly Color Maroon = new(0x80, 0x00, 0x00, 0xff); - public static readonly Color MediumAquamarine = new(0x66, 0xcd, 0xaa, 0xff); - public static readonly Color MediumBlue = new(0x00, 0x00, 0xcd, 0xff); - public static readonly Color MediumOrchid = new(0xba, 0x55, 0xd3, 0xff); - public static readonly Color MediumPurple = new(0x93, 0x70, 0xdb, 0xff); - public static readonly Color MediumSeaGreen = new(0x3c, 0xb3, 0x71, 0xff); - public static readonly Color MediumSlateBlue = new(0x7b, 0x68, 0xee, 0xff); - public static readonly Color MediumSpringGreen = new(0x00, 0xfa, 0x9a, 0xff); - public static readonly Color MediumTurquoise = new(0x48, 0xd1, 0xcc, 0xff); - public static readonly Color MediumVioletRed = new(0xc7, 0x15, 0x85, 0xff); - public static readonly Color MidnightBlue = new(0x19, 0x19, 0x70, 0xff); - public static readonly Color MintCream = new(0xf5, 0xff, 0xfa, 0xff); - public static readonly Color MistyRose = new(0xff, 0xe4, 0xe1, 0xff); - public static readonly Color Moccasin = new(0xff, 0xe4, 0xb5, 0xff); - public static readonly Color MonoGameOrange = new(0xe7, 0x3c, 0x00, 0xff); - public static readonly Color NavajoWhite = new(0xff, 0xde, 0xad, 0xff); - public static readonly Color Navy = new(0x00, 0x00, 0x80, 0xff); - public static readonly Color OldLace = new(0xfd, 0xf5, 0xe6, 0xff); - public static readonly Color Olive = new(0x80, 0x80, 0x00, 0xff); - public static readonly Color OliveDrab = new(0x6b, 0x8e, 0x23, 0xff); - public static readonly Color Orange = new(0xff, 0xa5, 0x00, 0xff); - public static readonly Color OrangeRed = new(0xff, 0x45, 0x00, 0xff); - public static readonly Color Orchid = new(0xda, 0x70, 0xd6, 0xff); - public static readonly Color PaleGoldenrod = new(0xee, 0xe8, 0xaa, 0xff); - public static readonly Color PaleGreen = new(0x98, 0xfb, 0x98, 0xff); - public static readonly Color PaleTurquoise = new(0xaf, 0xee, 0xee, 0xff); - public static readonly Color PaleVioletRed = new(0xdb, 0x70, 0x93, 0xff); - public static readonly Color PapayaWhip = new(0xff, 0xef, 0xd5, 0xff); - public static readonly Color PeachPuff = new(0xff, 0xda, 0xb9, 0xff); - public static readonly Color Peru = new(0xcd, 0x85, 0x3f, 0xff); - public static readonly Color Pink = new(0xff, 0xc0, 0xcb, 0xff); - public static readonly Color Plum = new(0xdd, 0xa0, 0xdd, 0xff); - public static readonly Color PowderBlue = new(0xb0, 0xe0, 0xe6, 0xff); - public static readonly Color Purple = new(0x80, 0x00, 0x80, 0xff); - public static readonly Color Red = new(0xff, 0x00, 0x00, 0xff); - public static readonly Color RosyBrown = new(0xbc, 0x8f, 0x8f, 0xff); - public static readonly Color RoyalBlue = new(0x41, 0x69, 0xe1, 0xff); - public static readonly Color SaddleBrown = new(0x8b, 0x45, 0x13, 0xff); - public static readonly Color Salmon = new(0xfa, 0x80, 0x72, 0xff); - public static readonly Color SandyBrown = new(0xf4, 0xa4, 0x60, 0xff); - public static readonly Color SeaGreen = new(0x2e, 0x8b, 0x57, 0xff); - public static readonly Color SeaShell = new(0xff, 0xf5, 0xee, 0xff); - public static readonly Color Sienna = new(0xa0, 0x52, 0x2d, 0xff); - public static readonly Color Silver = new(0xc0, 0xc0, 0xc0, 0xff); - public static readonly Color SkyBlue = new(0x87, 0xce, 0xeb, 0xff); - public static readonly Color SlateBlue = new(0x6a, 0x5a, 0xcd, 0xff); - public static readonly Color SlateGray = new(0x70, 0x80, 0x90, 0xff); - public static readonly Color Snow = new(0xff, 0xfa, 0xfa, 0xff); - public static readonly Color SpringGreen = new(0x00, 0xff, 0x7f, 0xff); - public static readonly Color SteelBlue = new(0x46, 0x82, 0xb4, 0xff); - public static readonly Color Tan = new(0xd2, 0xb4, 0x8c, 0xff); - public static readonly Color Teal = new(0x00, 0x80, 0x80, 0xff); - public static readonly Color Thistle = new(0xd8, 0xbf, 0xd8, 0xff); - public static readonly Color Tomato = new(0xff, 0x63, 0x47, 0xff); - public static readonly Color Turquoise = new(0x40, 0xe0, 0xd0, 0xff); - public static readonly Color Violet = new(0xee, 0x82, 0xee, 0xff); - public static readonly Color Wheat = new(0xf5, 0xde, 0xb3, 0xff); - public static readonly Color White = new(0xff, 0xff, 0xff, 0xff); - public static readonly Color WhiteSmoke = new(0xf5, 0xf5, 0xf5, 0xff); - public static readonly Color Yellow = new(0xff, 0xff, 0x00, 0xff); - public static readonly Color YellowGreen = new(0x9a, 0xcd, 0x32, 0xff); - - #endregion -} \ No newline at end of file diff --git a/Ion/Ion_old/GameConfig.cs b/Ion/Ion_old/GameConfig.cs deleted file mode 100644 index d4eee20..0000000 --- a/Ion/Ion_old/GameConfig.cs +++ /dev/null @@ -1,56 +0,0 @@ -using Veldrid; -using Ion.Graphics; -namespace Ion; - -public interface IGameConfig -{ - #region Window Options - - string Title { get; set; } - int? WindowHeight { get; set; } - int? WindowWidth { get; set; } - int? WindowX { get; set; } - int? WindowY { get; set; } - uint? ResolutionX { get; set; } - uint? ResolutionY { get; set; } - WindowState WindowState { get; set; } - - #endregion - - #region Graphics Options - - GraphicsBackend PreferredBackend { get; set; } - bool VSync { get; set; } - uint MaxFPS { get; set; } - GraphicsOutput Output { get; set; } - Color ClearColor { get; set; } - - #endregion -} - -internal class GameConfig : IGameConfig -{ - public string Title { get; set; } = "Ion"; - - public int? WindowHeight { get; set; } = 1080; - - public int? WindowWidth { get; set; } - - public int? WindowX { get; set; } = Veldrid.Sdl2.Sdl2Native.SDL_WINDOWPOS_CENTERED; - - public int? WindowY { get; set; } = Veldrid.Sdl2.Sdl2Native.SDL_WINDOWPOS_CENTERED; - - public uint? ResolutionX { get; set; } - public uint? ResolutionY { get; set; } - - public WindowState WindowState { get; set; } = WindowState.Normal; - - public GraphicsBackend PreferredBackend { get; set; } = Veldrid.StartupUtilities.VeldridStartup.GetPlatformDefaultBackend(); - - public bool VSync { get; set; } = false; - - public uint MaxFPS { get; set; } = 300; - public GraphicsOutput Output { get; set; } = GraphicsOutput.Window; - - public Color ClearColor { get; set; } = Color.Black; -} diff --git a/Ion/Ion_old/GameLoop.cs b/Ion/Ion_old/GameLoop.cs deleted file mode 100644 index bd865d8..0000000 --- a/Ion/Ion_old/GameLoop.cs +++ /dev/null @@ -1,141 +0,0 @@ -using Ion.Builder; -using Ion.Graphics; -using Ion.Utils; - -using System.Diagnostics; - -namespace Ion; - -public record struct GameExitEvent(); - -/// -/// Top-level class representing the runnable game. -/// -internal class GameLoop -{ - private bool _shouldExit; - private readonly float _maxFrameTime = 0.1f; // 100ms - - private readonly IGameConfig _gameConfig; - - public GameTime GameTime { get; } - public GameTime FixedGameTime { get; } - - public bool IsRunning { get; private set; } = false; - - public event EventHandler? Exiting; - - public GameLoopDelegate Initialize { get; set; } = (dt) => { }; - public GameLoopDelegate First { get; set; } = (dt) => { }; - public GameLoopDelegate Update { get; set; } = (dt) => { }; - public GameLoopDelegate FixedUpdate { get; set; } = (dt) => { }; - public GameLoopDelegate Render { get; set; } = (dt) => { }; - public GameLoopDelegate Last { get; set; } = (dt) => { }; - public GameLoopDelegate Destroy { get; set; } = (dt) => { }; - - public GameLoop( - IGameConfig gameConfig - ) { - _gameConfig = gameConfig; - - GameTime = new(); - FixedGameTime = new() - { - Alpha = 1, - Delta = _gameConfig.MaxFPS == 0 ? (1f / 60f) : (1f / _gameConfig.MaxFPS) - }; - } - - public void Run() - { - IsRunning = true; - Initialize(GameTime); - - var stopwatch = Stopwatch.StartNew(); - - var targetFrameTime = (int)(1000 / (_gameConfig.MaxFPS == 0 ? 60 : _gameConfig.MaxFPS)); - var currentTime = stopwatch.Elapsed.TotalSeconds; - float accumulator = 0; - - while (_shouldExit == false) - { - GameTime.Alpha = FixedGameTime.Alpha = 1; - GameTime.Elapsed = FixedGameTime.Elapsed = stopwatch.Elapsed; - var newTime = GameTime.Elapsed.TotalSeconds; - GameTime.Delta = (float)(newTime - currentTime); - - if (GameTime.Delta > _maxFrameTime) GameTime.Delta = _maxFrameTime; - currentTime = newTime; - - accumulator += GameTime.Delta; - - using var timer = MicroTimer.Start("First"); - - First(GameTime); - timer.Then("Update"); - - while (accumulator >= FixedGameTime.Delta) - { - FixedUpdate(FixedGameTime); - accumulator -= FixedGameTime.Delta; - } - - GameTime.Alpha = accumulator / FixedGameTime.Delta; - - Update(GameTime); - - if (_gameConfig.Output != GraphicsOutput.None) - { - timer.Then("Render"); - Render(GameTime); - } - - timer.Then("Last"); - Last(GameTime); - - var delayTime = targetFrameTime - (int)((stopwatch.Elapsed.TotalSeconds - currentTime) * 1000); - if (delayTime > 0) - { - timer.Then("(idle)"); - Thread.Sleep(delayTime); - } - - GameTime.Frame = FixedGameTime.Frame = (GameTime.Frame + 1); - } - - MicroTimer.Export("./trace.json"); - - Destroy(GameTime); - IsRunning = false; - - Exiting?.Invoke(this, EventArgs.Empty); - } - - public void Step(GameTime time) - { - using var timer = MicroTimer.Start("First"); - - First(time); - - timer.Then("Update"); - - FixedUpdate(time); - Update(time); - - if (_shouldExit) return; //if (_shouldExit || _window.HasClosed) return; - - if (_gameConfig.Output != GraphicsOutput.None) - { - timer.Then("Render"); - Render(time); - } - - timer.Then("Last"); - Last(time); - } - - public void Exit() - { - _shouldExit = true; - } -} diff --git a/Ion/Ion_old/Graphics/2D/SpriteBatch.cs b/Ion/Ion_old/Graphics/2D/SpriteBatch.cs deleted file mode 100644 index d21e4a8..0000000 --- a/Ion/Ion_old/Graphics/2D/SpriteBatch.cs +++ /dev/null @@ -1,412 +0,0 @@ -using Veldrid; -using Veldrid.SPIRV; - -using Ion.Assets; -using Ion.Utils; - -namespace Ion.Graphics; - -[Flags] -public enum SpriteEffect -{ - /// - /// Renders the sprite normally. - /// - None = 0, - - /// - /// Horizontally flip the sprite. - /// - FlipHorizontally, - - /// - /// Vertically flip the sprite. - /// - FlipVertically, -} - -public interface ISpriteBatch -{ - void DrawRect(Color color, RectangleF destinationRectangle, Vector2 origin = default, float rotation = 0, float depth = 0); - void DrawRect(Color color, Vector2 position, Vector2 size, Vector2 origin = default, float rotation = 0, float depth = 0); - - void DrawPoint(Color color, Vector2 position, float depth = 0); - void DrawPoint(Color color, Vector2 position, Vector2 size, float depth = 0); - - void DrawLine(Color color, Vector2 pointA, Vector2 pointB, float thickness = 1f, float depth = 0); - void DrawLine(Color color, Vector2 start, float length, float angle, float thickness = 1, float depth = 0); - - void Draw(Texture2D texture, RectangleF destinationRectangle, RectangleF sourceRectangle = default, Color color = default, Vector2 origin = default, float rotation = 0, float depth = 0, SpriteEffect options = SpriteEffect.None); - void Draw(Texture2D texture, Vector2 position, Vector2 scale, RectangleF sourceRectangle = default, Color color = default, Vector2 origin = default, float rotation = 0, float depth = 0, SpriteEffect options = SpriteEffect.None); -} - -internal class SpriteBatch : ISpriteBatch, IDisposable -{ - private static readonly RectangleF _defaultScissor = new(-(1 << 22), -(1 << 22), 1 << 23, 1 << 23); - private static readonly Vector2 VEC2_HALF = Vector2.One / 2f; - - private readonly IWindow _window; - private readonly IGraphicsContext _graphicsContext; - private readonly ILogger _logger; - private readonly IEventListener _events; - - private readonly SpriteBatchManager _batchManager; - private Assets.Texture? _whitePixel; - - private CommandList _commandList; - private DeviceBuffer? _vertexBuffer; - - private ResourceLayout? _instanceResourceLayout; - private ResourceLayout? _fragmentResourceLayout; - - private Shader[]? _shaders; - private Pipeline? _pipeline; - - private bool _beginCalled = false; - - private class BufferContainer - { - public DeviceBuffer Buffer { get; set; } - public ResourceSet InstanceSet { get; set; } - public ResourceSet TextureSet { get; set; } - - public BufferContainer(DeviceBuffer buffer, ResourceSet instanceSet, ResourceSet textureSet) - { - Buffer = buffer; - InstanceSet = instanceSet; - TextureSet = textureSet; - } - - public void Dispose() - { - Buffer.Dispose(); - InstanceSet.Dispose(); - TextureSet.Dispose(); // TODO: Check if this is needed... - } - } - - private readonly Dictionary _buffers; - - private const string VertexCode = @" -#version 450 - -layout (constant_id = 0) const bool InvertY = false; - -layout(location = 0) in vec2 Position; -layout(location = 0) out vec4 fsin_Color; -layout(location = 1) out vec2 tex_coord; -layout(location = 2) out vec4 bounds; -layout(location = 3) out vec2 pos; - -struct Instance -{ - vec4 UV; - vec4 Color; - vec2 Scale; - vec2 Origin; - vec4 Location; - vec4 Scissor; -}; - -layout(std430, binding = 0) readonly buffer Instances -{ - mat4 projection; - vec4 spacer; - Instance instances[]; -}; - -mat2 makeRotation(float angle) -{ - float c = cos(angle); - float s = sin(angle); - return mat2(c, -s, s, c); -} - -void main() -{ - Instance item = instances[gl_InstanceIndex]; - - pos = Position * item.Scale; - pos -= item.Origin; - pos *= makeRotation(item.Location.w); - pos += item.Location.xy; - - tex_coord = Position * item.UV.zw + item.UV.xy; - - // scissor bounds - vec2 start = item.Scissor.xy; - vec2 end = start + item.Scissor.zw; - bounds = vec4(start, end); - - gl_Position = projection * vec4(pos, item.Location.z, 1); - pos = gl_Position.xy; - - if(!InvertY) - gl_Position.y = -gl_Position.y; - - fsin_Color = item.Color; -}"; - - private const string FragmentCode = @" -#version 450 - -layout(location = 0) in vec4 fsin_Color; -layout(location = 1) in vec2 tex_coord; -layout(location = 2) in vec4 bounds; -layout(location = 3) in vec2 pos; -layout(location = 0) out vec4 fsout_Color; - -layout(set = 1, binding = 0) uniform texture2D Tex; -layout(set = 1, binding = 1) uniform sampler Sampler; - -void main() -{ - float left = bounds.x; - float top = bounds.y; - float right = bounds.z; - float bottom = bounds.w; - - if(!(left <= pos.x && right >= pos.x && - top <= pos.y && bottom >= pos.y)) - discard; - - fsout_Color = fsin_Color * texture(sampler2D(Tex, Sampler), tex_coord); -}"; - - public SpriteBatch(IWindow window, IGraphicsContext graphicsContext, ILogger logger, IEventListener events) - { - _window = window; - _graphicsContext = graphicsContext; - _logger = logger; - _events = events; - - _batchManager = new(); - _buffers = new(); - } - - public void Initialize() - { - if (_graphicsContext.NoRender) return; - if (_graphicsContext.GraphicsDevice == null) - { - _logger.LogWarning($"{nameof(SpriteBatch)} automically disabled due to GraphicsDevice not being set."); - return; - } - - using var _ = MicroTimer.Start("SpriteRenderer::Initialize"); - - var factory = _graphicsContext.Factory; - _commandList = factory.CreateCommandList(); - - TextureDescription desc = new(1, 1, 1, 1, 1, PixelFormat.B8_G8_R8_A8_UNorm, TextureUsage.Sampled, Veldrid.TextureType.Texture2D); - _whitePixel = factory.CreateTexture2D(desc, "white-pixel"); - _graphicsContext.GraphicsDevice.UpdateTexture(_whitePixel, new byte[] { 255, 255, 255, 255 }, 0, 0, 0, 1, 1, 1, 0, 0); - - VertexLayoutDescription vertexLayout = new(new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)); - - ShaderDescription vertexShaderDesc = new(ShaderStages.Vertex, System.Text.Encoding.UTF8.GetBytes(VertexCode), "main"); - ShaderDescription fragmentShaderDesc = new(ShaderStages.Fragment, System.Text.Encoding.UTF8.GetBytes(FragmentCode), "main"); - - _logger.LogInformation("Created shaders"); - _shaders = factory.CreateFromSpirv(vertexShaderDesc, fragmentShaderDesc); - - _logger.LogInformation("Created _vertexBuffer"); - _vertexBuffer = factory.CreateBuffer(new(4 * MemUtils.SizeOf(), BufferUsage.VertexBuffer)); - _logger.LogInformation("Updated _vertexBuffer"); - _graphicsContext.GraphicsDevice.UpdateBuffer(_vertexBuffer, 0, new Vector2[] { - new( 0, 0), - new( 1, 0), - new( 0, 1), - new( 1, 1), - }); - - _instanceResourceLayout = factory.CreateResourceLayout(new(new ResourceLayoutElementDescription[] { - new("Instances", ResourceKind.StructuredBufferReadOnly, ShaderStages.Vertex) - })); - - _fragmentResourceLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(new ResourceLayoutElementDescription[] { - new("Tex", ResourceKind.TextureReadOnly, ShaderStages.Fragment), - new("Sampler", ResourceKind.Sampler, ShaderStages.Fragment) - })); - - _pipeline = factory.CreateGraphicsPipeline(new() - { - BlendState = BlendStateDescription.SingleAlphaBlend, - DepthStencilState = new DepthStencilStateDescription(depthTestEnabled: true, depthWriteEnabled: true, comparisonKind: ComparisonKind.GreaterEqual), - RasterizerState = new RasterizerStateDescription(cullMode: FaceCullMode.Back, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false), - PrimitiveTopology = PrimitiveTopology.TriangleStrip, - ResourceLayouts = new ResourceLayout[] { _instanceResourceLayout, _fragmentResourceLayout }, - ShaderSet = new(vertexLayouts: new[] { vertexLayout }, shaders: _shaders, specializations: new[] { - new SpecializationConstant(0, _graphicsContext.GraphicsDevice.IsClipSpaceYInverted) - }), - Outputs = _graphicsContext.GraphicsDevice.MainSwapchain.Framebuffer.OutputDescription - }); - } - - public void Begin(GameTime dt) - { - if (_graphicsContext.NoRender) return; - if (_graphicsContext.GraphicsDevice == null) throw new InvalidOperationException("Begin cannot be called until the GraphicsDevice has been initialized."); - - if (_beginCalled) throw new InvalidOperationException("Begin cannot be called again until End has been successfully called."); - - using var _ = MicroTimer.Start("SpriteRenderer::Begin"); - - _batchManager.Clear(); - _beginCalled = true; - } - - public void DrawRect(Color color, RectangleF destinationRectangle, Vector2 origin = default, float rotation = 0, float depth = 0f) - { - if (!_beginCalled) throw new InvalidOperationException("Begin must be called before calling Draw."); - - _addSprite(_whitePixel!, color, new RectangleF(0, 0, 1, 1), destinationRectangle, origin, rotation, depth, _defaultScissor, SpriteEffect.None); - } - - public void DrawRect(Color color, Vector2 position, Vector2 size, Vector2 origin = default, float rotation = 0, float depth = 0f) - { - if (!_beginCalled) throw new InvalidOperationException("Begin must be called before calling Draw."); - - _addSprite(_whitePixel!, color, new RectangleF(0, 0, 1, 1), new RectangleF(position.X, position.Y, size.X, size.Y), origin, rotation, depth, _defaultScissor, SpriteEffect.None); - } - - public void DrawPoint(Color color, Vector2 position, Vector2 size, float depth = 0) - { - DrawRect(color, position, size, origin: VEC2_HALF, depth: depth); - } - - public void DrawPoint(Color color, Vector2 position, float depth = 0) - { - DrawRect(color, position, Vector2.One, origin: VEC2_HALF, depth: depth); - } - - public void DrawLine(Color color, Vector2 pointA, Vector2 pointB, float thickness = 1f, float depth = 0) - { - var diff = pointB - pointA; - var length = MathF.Sqrt(Vector2.Dot(diff, diff)); - var angle = MathF.Atan2(diff.Y, diff.X); - DrawLine(color, pointA, length: length, angle: angle, thickness: thickness, depth: depth); - } - - public void DrawLine(Color color, Vector2 start, float length, float angle, float thickness = 1, float depth = 0) - { - var rect = new RectangleF(start.X, start.Y, length, thickness); - DrawRect(color, rect, new Vector2(0, 0.5f), rotation: angle, depth: depth); - } - - public void Draw(Texture2D texture, RectangleF destinationRectangle, RectangleF sourceRectangle = default, Color color = default, Vector2 origin = default, float rotation = 0, float depth = 0, SpriteEffect options = SpriteEffect.None) - { - if (!_beginCalled) throw new InvalidOperationException("Begin must be called before calling Draw."); - - if (color == default) color = Color.White; - if (sourceRectangle.Size.LengthSquared() == 0) sourceRectangle = new RectangleF(0f, 0f, texture.Width, texture.Height); - - _addSprite(texture, color, sourceRectangle, destinationRectangle, origin, rotation, depth, _defaultScissor, options); - } - - public void Draw(Texture2D texture, Vector2 position, Vector2 scale, RectangleF sourceRectangle = default, Color color = default, Vector2 origin = default, float rotation = 0, float depth = 0, SpriteEffect options = SpriteEffect.None) - { - if (!_beginCalled) throw new InvalidOperationException("Begin must be called before calling Draw."); - - if (color == default) color = Color.White; - if (sourceRectangle.Size.LengthSquared() == 0) sourceRectangle = new RectangleF(0f, 0f, texture.Width, texture.Height); - - _addSprite(texture, color, sourceRectangle, new RectangleF(position.X, position.Y, scale.X * texture.Width, scale.Y * texture.Height), origin, rotation, depth, _defaultScissor, options); - } - - public unsafe void End() - { - if (_graphicsContext.NoRender) return; - if (!_beginCalled) throw new InvalidOperationException("Begin must be called before calling End."); - - using var _ = MicroTimer.Start("SpriteRenderer::End"); - - _beginCalled = false; - - if (_batchManager.IsEmpty || _graphicsContext.GraphicsDevice is null) return; - - _commandList.Begin(); - _commandList.SetFramebuffer(_graphicsContext.GraphicsDevice.MainSwapchain.Framebuffer); - //_commandList.SetFullViewports(); - //_commandList.ClearColorTarget(0, Color.Transparent); - //_commandList.ClearDepthStencil(_graphicsContext.GraphicsDevice.IsDepthRangeZeroToOne ? 0f : 1f); - _commandList.SetPipeline(_pipeline); - foreach (var (texture, group) in _batchManager) - { - var pair = _getBuffer(texture, group.Count + 1); - using var timer = MicroTimer.Start("SpriteRenderer::End::Texture::Map"); - - var mapped = _graphicsContext.GraphicsDevice.Map(pair.Buffer, MapMode.Write); - - timer.Then("SpriteRenderer::End::Texture::Copy"); - MemUtils.Set(mapped.Data, _graphicsContext.ProjectionMatrix, 1); - MemUtils.Copy(mapped.Data + SpriteBatchManager.INSTANCE_SIZE, group.GetSpan()); - - timer.Then("SpriteRenderer::End::Texture::Unmap"); - _graphicsContext.GraphicsDevice.Unmap(pair.Buffer); - timer.Then("SpriteRenderer::End::Texture::Commands"); - _commandList.SetVertexBuffer(0, _vertexBuffer); - _commandList.SetGraphicsResourceSet(0, pair.InstanceSet); - _commandList.SetGraphicsResourceSet(1, pair.TextureSet); - _commandList.Draw(4, (uint)group.Count, 0, 0); - } - - _commandList.End(); - _graphicsContext.SubmitCommands(_commandList); - } - - private BufferContainer _getBuffer(Assets.Texture texture, int count) - { - using var _ = MicroTimer.Start("SpriteRenderer::_getBuffer"); - - var size = SpriteBatchManager.GetBatchSize(count); - var bci = new BufferDescription(size, BufferUsage.StructuredBufferReadOnly | BufferUsage.Dynamic, SpriteBatchManager.Instance.SizeInBytes); - - if (!_buffers.TryGetValue(texture, out var pair)) - { - using var _nb = MicroTimer.Start("SpriteRenderer::_getBuffer::NewBuffer"); - var buffer = _graphicsContext.Factory.CreateBuffer(bci); - pair = new(buffer, - _graphicsContext.Factory.CreateResourceSet(new ResourceSetDescription(_instanceResourceLayout, buffer)), - _graphicsContext.Factory.CreateResourceSet(new ResourceSetDescription(_fragmentResourceLayout, (Veldrid.Texture)texture, _graphicsContext.GraphicsDevice!.LinearSampler)) - ); - - _buffers[texture] = pair; - } - else if (size > pair.Buffer.SizeInBytes) - { - using var _rb = MicroTimer.Start("SpriteRenderer::_getBuffer::ResizeBuffer"); - pair.Dispose(); - - pair.Buffer = _graphicsContext.Factory.CreateBuffer(bci); - pair.InstanceSet = _graphicsContext.Factory.CreateResourceSet(new ResourceSetDescription(_instanceResourceLayout, pair.Buffer)); - pair.TextureSet = _graphicsContext.Factory.CreateResourceSet(new ResourceSetDescription(_fragmentResourceLayout, (Veldrid.Texture)texture, _graphicsContext.GraphicsDevice!.LinearSampler)); - _buffers[texture] = pair; - } - - return pair; - } - - public void Dispose() - { - _pipeline?.Dispose(); - if (_shaders != null) foreach (var shader in _shaders) shader.Dispose(); - - _vertexBuffer?.Dispose(); - } - - private void _addSprite(Assets.Texture texture, Color color, RectangleF sourceRect, RectangleF destinationRect, Vector2 origin, float rotation, float depth, RectangleF scissor, SpriteEffect options) - { - ref var instance = ref _batchManager.Add(texture); - - instance.Update(texture.Size, destinationRect, sourceRect, color, rotation, origin, depth, _transformRectF(scissor, _graphicsContext.ProjectionMatrix), options); - } - - private static RectangleF _transformRectF(RectangleF rect, System.Numerics.Matrix4x4 matrix) - { - var pos = Vector4.Transform(new Vector4(rect.X, rect.Y, 0, 1), matrix); - var size = Vector4.Transform(new Vector4(rect.X + rect.Width, rect.Y + rect.Height, 0, 1), matrix); - return new(pos.X, pos.Y, size.X - pos.X, size.Y - pos.Y); - } -} - diff --git a/Ion/Ion_old/Graphics/2D/SpriteBatchManager.cs b/Ion/Ion_old/Graphics/2D/SpriteBatchManager.cs deleted file mode 100644 index 9c4e4b9..0000000 --- a/Ion/Ion_old/Graphics/2D/SpriteBatchManager.cs +++ /dev/null @@ -1,143 +0,0 @@ -namespace Ion.Graphics; - -internal class SpriteBatchManager -{ - public const int BATCH_STEP_SIZE = 64; - public const int BATCH_STEP_SIZE_MINUS_ONE = BATCH_STEP_SIZE - 1; - public const int BATCH_STEP_SIZE_BIT_COMP = ~BATCH_STEP_SIZE_MINUS_ONE; - - public static int INSTANCE_SIZE = (int)MemUtils.SizeOf(); - - private readonly Stack _batchPool; - private readonly Dictionary _batches; - - public bool IsEmpty => !_batches.Any(b => b.Value.Count > 0); - - public SpriteBatchManager() - { - _batches = new(); - _batchPool = new(); - } - - public ref Instance Add(Assets.Texture texture) - { - if (!_batches.TryGetValue(texture, out var group)) - { - group = _rentSpriteBatch(); - group.Clear(); - _batches[texture] = group; - } - - return ref group.Add(); - } - - public void Clear() - { - foreach (var group in this) _releaseSpriteBatch(group.Value); - _batches.Clear(); - } - - public Dictionary.Enumerator GetEnumerator() => _batches.GetEnumerator(); - - private SpriteBatch _rentSpriteBatch() - { - if (!_batchPool.TryPop(out var group)) group = new(); - return group; - } - - private void _releaseSpriteBatch(SpriteBatch group) => _batchPool.Push(group); - - public static uint GetBatchSize(int count) - { - return (uint)(((count + BATCH_STEP_SIZE_MINUS_ONE) & BATCH_STEP_SIZE_BIT_COMP) * Instance.SizeInBytes); - } - - public class SpriteBatch - { - internal Instance[] _items; - - public int Count { get; private set; } - - public SpriteBatch() - { - _items = new Instance[BATCH_STEP_SIZE]; - } - - public ref Instance Add() - { - if (Count >= _items.Length) - { - var lastSize = _items.Length; - var newSize = (lastSize + lastSize / 2 + 63) & (~63); - Array.Resize(ref _items, newSize); - } - - return ref _items[Count++]; - } - - public void Clear() - { - Count = 0; - } - - public ReadOnlySpan GetSpan() - { - //Array.Sort(_items, 0, Count); - return new(_items, 0, Count); - } - } - - public struct Instance : IComparable - { - public Vector4 UV; - public Color Color; - public Vector2 Scale; - public Vector2 Origin; - public Vector3 Location; - public float Rotation; - public RectangleF Scissor; - - public static uint SizeInBytes => MemUtils.SizeOf(); - - public void Update(Vector2 textureSize, RectangleF destinationRectangle, RectangleF sourceRectangle, Color color, float rotation, Vector2 origin, float layerDepth, RectangleF scissor, SpriteEffect options) - { - var sourceSize = new Vector2(sourceRectangle.Width, sourceRectangle.Height) / textureSize; - var pos = new Vector2(sourceRectangle.X, sourceRectangle.Y) / textureSize; - - UV = _createUV(options, sourceSize, pos); - Color = color; - Scale = destinationRectangle.Size; - Origin = origin * Scale; - Location = new(destinationRectangle.Location, layerDepth); - Rotation = rotation; - Scissor = scissor; - } - private static Vector4 _createUV(SpriteEffect options, Vector2 sourceSize, Vector2 sourceLocation) - { - if (options != SpriteEffect.None) - { - // flipX - if (options.HasFlag(SpriteEffect.FlipHorizontally)) - { - sourceLocation.X += sourceSize.X; - sourceSize.X *= -1; - } - - // flipY - if (options.HasFlag(SpriteEffect.FlipVertically)) - { - sourceLocation.Y += sourceSize.Y; - sourceSize.Y *= -1; - } - } - - return new(sourceLocation.X, sourceLocation.Y, sourceSize.X, sourceSize.Y); - } - - public int CompareTo(Instance other) - { - return (int)(other.Location.Z - this.Location.Z); - } - } -} - diff --git a/Ion/Ion_old/Graphics/GraphicsContext.cs b/Ion/Ion_old/Graphics/GraphicsContext.cs deleted file mode 100644 index a425b8e..0000000 --- a/Ion/Ion_old/Graphics/GraphicsContext.cs +++ /dev/null @@ -1,202 +0,0 @@ -using Ion.Utils; - -using Veldrid; - -namespace Ion.Graphics; - -internal class GraphicsContext : IGraphicsContext, IDisposable -{ - private readonly IGameConfig _config; - private readonly IEventListener _events; - private readonly ILogger _logger; - private readonly Window _window; - -#pragma warning disable CS8603 // Possible null reference return. - private CommandList? _commandList; - public GraphicsDevice? GraphicsDevice { get; private set; } - public ResourceFactory Factory => GraphicsDevice?.ResourceFactory; -#pragma warning restore CS8603 // Possible null reference return. - - public Matrix4x4 ProjectionMatrix { get; private set; } = Matrix4x4.Identity; - - public bool NoRender { get; } - - public GraphicsContext(IGameConfig config, IEventListener events, ILogger logger, IWindow window) - { - _config = config; - _events = events; - _logger = logger; - _window = (Window)window; - - NoRender = _config.Output == GraphicsOutput.None; - } - - public void Initialize() - { - if (NoRender) return; - - using var _ = MicroTimer.Start("GraphicsContext::Initialize"); - _logger.LogInformation("Creating graphics device..."); - - if (!GraphicsDevice.IsBackendSupported(_config.PreferredBackend)) - { - throw new IonException($"Unsupported backend! ({_config.PreferredBackend}"); - } - - GraphicsDevice = Veldrid.StartupUtilities.VeldridStartup.CreateGraphicsDevice(_window.Sdl2Window, new GraphicsDeviceOptions() - { -#if DEBUG - //Debug = true, -#endif - SwapchainDepthFormat = PixelFormat.D32_Float_S8_UInt, - ResourceBindingModel = ResourceBindingModel.Default, - PreferStandardClipSpaceYDirection = true, - PreferDepthRangeZeroToOne = true, - SyncToVerticalBlank = _config.VSync, - }, _config.PreferredBackend); - - _commandList = GraphicsDevice.ResourceFactory.CreateCommandList(); - - _logger.LogInformation($"Graphics device created ({GraphicsDevice.BackendType})!"); - - UpdateProjection((uint)_window.Width, (uint)_window.Height); - } - - public void First() - { - if (_events.OnLatest(out var e)) - { - _logger.LogInformation($"Updating projection {e.Data.Width}x{e.Data.Height}!"); - UpdateProjection(e.Data.Width, e.Data.Height); - } - } - - public void UpdateProjection(uint width, uint height) - { - ProjectionMatrix = CreateOrthographic(0, width, 0, height, 1000f, -100f); - } - - public void BeginFrame(GameTime dt) - { - if (NoRender || GraphicsDevice is null || _commandList is null) return; - - using var _ = MicroTimer.Start("GraphicsContext::BeginFrame"); - - _commandList.Begin(); - _commandList.SetFramebuffer(GraphicsDevice.MainSwapchain.Framebuffer); - _commandList.SetFullViewports(); - _commandList.ClearColorTarget(0, _config.ClearColor); - _commandList.ClearDepthStencil(GraphicsDevice.IsDepthRangeZeroToOne ? 0f : 1f); - _commandList.End(); - GraphicsDevice.SubmitCommands(_commandList); - } - - public void EndFrame(GameTime dt) - { - if (NoRender || GraphicsDevice is null || _commandList is null) return; - - using var timer = MicroTimer.Start("GraphicsContext::EndFrame::WaitForIdle"); - - GraphicsDevice.WaitForIdle(); - - timer.Then("GraphicsContext::EndFrame::SwapBuffers"); - - if (_window.HasClosed) return; - - GraphicsDevice.SwapBuffers(); - - timer.Then("GraphicsContext::EndFrame::HandleResize"); - - if (_events.OnLatest(out var e)) - { - GraphicsDevice.ResizeMainWindow(e.Data.Width, e.Data.Height); - } - } - - public void SubmitCommands(CommandList commandList) - { - using var _ = MicroTimer.Start("GraphicsContext::SubmitCommands"); - GraphicsDevice?.SubmitCommands(commandList); - } - - public Matrix4x4 CreateOrthographic(float left, float right, float bottom, float top, float near, float far) - { - Matrix4x4 ortho; - if (GraphicsDevice?.IsDepthRangeZeroToOne ?? false) ortho = Matrix4x4.CreateOrthographicOffCenter(left, right, bottom, top, far, near); - else ortho = Matrix4x4.CreateOrthographicOffCenter(left, right, bottom, top, near, far); - - if (GraphicsDevice?.IsClipSpaceYInverted ?? false) - { - ortho *= new Matrix4x4( - 1, 0, 0, 0, - 0, -1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1); - } - - return ortho; - } - - public Matrix4x4 CreatePerspective(float fov, float aspectRatio, float near, float far) - { - Matrix4x4 persp; - if (GraphicsDevice?.IsDepthRangeZeroToOne ?? false) - { - persp = _createPerspective(fov, aspectRatio, far, near); - } - else - { - persp = _createPerspective(fov, aspectRatio, near, far); - } - - if (GraphicsDevice?.IsClipSpaceYInverted ?? false) - { - persp *= new Matrix4x4( - 1, 0, 0, 0, - 0, -1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1); - } - - return persp; - } - - private static Matrix4x4 _createPerspective(float fov, float aspectRatio, float near, float far) - { - if (fov <= 0.0f || fov >= MathF.PI) - throw new ArgumentOutOfRangeException(nameof(fov)); - - if (near <= 0.0f) - throw new ArgumentOutOfRangeException(nameof(near)); - - if (far <= 0.0f) - throw new ArgumentOutOfRangeException(nameof(far)); - - float yScale = 1.0f / MathF.Tan(fov * 0.5f); - float xScale = yScale / aspectRatio; - - Matrix4x4 result; - - result.M11 = xScale; - result.M12 = result.M13 = result.M14 = 0.0f; - - result.M22 = yScale; - result.M21 = result.M23 = result.M24 = 0.0f; - - result.M31 = result.M32 = 0.0f; - var negFarRange = float.IsPositiveInfinity(far) ? -1.0f : far / (near - far); - result.M33 = negFarRange; - result.M34 = -1.0f; - - result.M41 = result.M42 = result.M44 = 0.0f; - result.M43 = near * negFarRange; - - return result; - } - - public void Dispose() - { - _commandList?.Dispose(); - GraphicsDevice?.Dispose(); - } -} diff --git a/Ion/Ion_old/Hosting/HostBuilderExtensions.cs b/Ion/Ion_old/Hosting/HostBuilderExtensions.cs deleted file mode 100644 index 5687914..0000000 --- a/Ion/Ion_old/Hosting/HostBuilderExtensions.cs +++ /dev/null @@ -1,46 +0,0 @@ -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.DependencyInjection; - -using Ion.Builder; - -namespace Ion.Hosting; - -public static class IonHostBuilderExtensions -{ - /// - /// Configures the services for Ion. - /// - /// The host builder instance. - /// Callback to configure the basic options for the game. - /// The host builder instance. - public static IHostBuilder ConfigureIon(this IHostBuilder hostBuilder, Action configure) - { - return hostBuilder.ConfigureServices((hostContext, services) => - { - //services.AddSingleton(); - //services.AddSingleton(); - //services.AddTransient(); - //services.AddSingleton(); - - //services.AddSingleton(); - //services.AddSingleton(); - //services.AddScoped(); - //services.AddSingleton(); - - //services.AddSingleton(); - - - - - //services.AddScoped(svcs => World.Create()); - - //var gameBuilder = new GameApplication(services); - //configure(gameBuilder); - - //services.AddSingleton(gameBuilder.Config); - //services.AddSingleton(services => gameBuilder.Build(services)); - - //services.AddHostedService(); - }); - } -} \ No newline at end of file diff --git a/Ion/Ion_old/Input/InputState.cs b/Ion/Ion_old/Input/InputState.cs deleted file mode 100644 index a3119c9..0000000 --- a/Ion/Ion_old/Input/InputState.cs +++ /dev/null @@ -1,71 +0,0 @@ -namespace Ion; - -internal class InputState : IInputState -{ - private readonly Window _window; - private readonly ILogger _logger; - - private readonly Dictionary _keyEvents = new(64); - private readonly Dictionary _mouseEvents = new(13); - private readonly HashSet _downKeys = new(8); - - private Veldrid.InputSnapshot? _inputSnapshot; - - public Vector2 MousePosition { get; private set; } = Vector2.Zero; - - public float WheelDelta { get; private set; } = 0; - - public InputState(IWindow window, ILogger logger) - { - _window = (Window)window; - _logger = logger; - } - - public void Step() - { - _inputSnapshot = _window.InputSnapshot; - - _keyEvents.Clear(); - _mouseEvents.Clear(); - - MousePosition = _inputSnapshot?.MousePosition ?? Vector2.Zero; - WheelDelta = _inputSnapshot?.WheelDelta ?? 0; - - if (_inputSnapshot == default) return; - - foreach (var k in _inputSnapshot.KeyEvents) - { - var key = k.Key; - _keyEvents[(Key)key] = k; - - if (!k.Down) _downKeys.Remove((Key)key); - else if (!k.Repeat) _downKeys.Add((Key)key); - } - - foreach (var m in _inputSnapshot.MouseEvents) _mouseEvents[(MouseButton)m.MouseButton] = m; - } - - public bool Pressed(MouseButton btn) => _mouseEvents.TryGetValue(btn, out var mouseEvent) && mouseEvent.Down; - public bool Released(MouseButton btn) => _mouseEvents.TryGetValue(btn, out var mouseEvent) && !mouseEvent.Down; - public bool Down(MouseButton btn) => _inputSnapshot?.IsMouseDown((Veldrid.MouseButton)btn) ?? false; - public bool Up(MouseButton btn) => !Down(btn); - - public bool Pressed(Key key) => _keyEvents.TryGetValue(key, out var keyEvent) && keyEvent.Down && !keyEvent.Repeat; - public bool Pressed(Key key, ModifierKeys modifiers) => _keyEvents.TryGetValue(key, out var keyEvent) && ((keyEvent.Modifiers & modifiers) != ModifierKeys.None) && keyEvent.Down && !keyEvent.Repeat; - - public bool Released(Key key) => _keyEvents.TryGetValue(key, out var keyEvent) && !keyEvent.Down; - public bool Released(Key key, ModifierKeys modifiers) => _keyEvents.TryGetValue(key, out var keyEvent) && ((keyEvent.Modifiers & modifiers) != ModifierKeys.None) && !keyEvent.Down; - - public bool Down(Key key) => _downKeys.Contains(key); - public bool Up(Key key) => !Down(key); - - public void SetMousePosition(Vector2 position) - { - _window.Sdl2Window?.SetMousePosition(position); - } - - public void SetMousePosition(int x, int y) - { - _window.Sdl2Window?.SetMousePosition(x, y); - } -} diff --git a/Ion/Ion_old/Input/KeyEvent.cs b/Ion/Ion_old/Input/KeyEvent.cs deleted file mode 100644 index 93ec17a..0000000 --- a/Ion/Ion_old/Input/KeyEvent.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace Ion; - -public partial struct KeyEvent { - public Key Key; - public bool Down; - public ModifierKeys Modifiers; - public bool Repeat; - - internal KeyEvent(Veldrid.KeyEvent keyEvent) - { - Key = (Key)keyEvent.Key; - Down = keyEvent.Down; - Modifiers = (ModifierKeys)keyEvent.Modifiers; - Repeat = keyEvent.Repeat; - } - - public static implicit operator KeyEvent(Veldrid.KeyEvent other) => new(other); - - public override string ToString() => $"{Key} {(Down ? "Down" : "Up")} [{Modifiers}] (repeat={Repeat})"; -} diff --git a/Ion/Ion_old/Input/MouseEvent.cs b/Ion/Ion_old/Input/MouseEvent.cs deleted file mode 100644 index 1cd86b2..0000000 --- a/Ion/Ion_old/Input/MouseEvent.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace Ion; - -public struct MouseEvent -{ - public MouseButton MouseButton { get; } - - public bool Down { get; } - - internal MouseEvent(Veldrid.MouseEvent me) - { - MouseButton = (MouseButton)me.MouseButton; - Down = me.Down; - } - - public static implicit operator MouseEvent(Veldrid.MouseEvent other) => new(other); -} \ No newline at end of file diff --git a/Ion/Ion_old/MathHelper.cs b/Ion/Ion_old/MathHelper.cs deleted file mode 100644 index c6771ef..0000000 --- a/Ion/Ion_old/MathHelper.cs +++ /dev/null @@ -1,319 +0,0 @@ -namespace Ion; - -/// -/// Contains commonly used precalculated values and mathematical operations. (Imported from XNA/MonoGame) -/// -public static class MathHelper -{ - /// - /// Represents the mathematical constant e(2.71828175). - /// - public const float E = MathF.E; - - /// - /// Represents the log base ten of e(0.4342945). - /// - public const float Log10E = 0.4342945f; - - /// - /// Represents the log base two of e(1.442695). - /// - public const float Log2E = 1.442695f; - - /// - /// Represents the value of pi(3.14159274). - /// - public const float Pi = MathF.PI; - - /// - /// Represents the value of pi divided by two(1.57079637). - /// - public const float PiOver2 = (float)(Math.PI / 2.0); - - /// - /// Represents the value of pi divided by four(0.7853982). - /// - public const float PiOver4 = (float)(Math.PI / 4.0); - - /// - /// Represents the value of pi times two(6.28318548). - /// - public const float TwoPi = (float)(Math.PI * 2.0); - - /// - /// Represents the value of pi times two(6.28318548). - /// This is an alias of TwoPi. - /// - public const float Tau = TwoPi; - - /// - /// Returns the Cartesian coordinate for one axis of a point that is defined by a given triangle and two normalized barycentric (areal) coordinates. - /// - /// The coordinate on one axis of vertex 1 of the defining triangle. - /// The coordinate on the same axis of vertex 2 of the defining triangle. - /// The coordinate on the same axis of vertex 3 of the defining triangle. - /// The normalized barycentric (areal) coordinate b2, equal to the weighting factor for vertex 2, the coordinate of which is specified in value2. - /// The normalized barycentric (areal) coordinate b3, equal to the weighting factor for vertex 3, the coordinate of which is specified in value3. - /// Cartesian coordinate of the specified point with respect to the axis being used. - public static float Barycentric(float value1, float value2, float value3, float amount1, float amount2) - { - return value1 + (value2 - value1) * amount1 + (value3 - value1) * amount2; - } - - /// - /// Performs a Catmull-Rom interpolation using the specified positions. - /// - /// The first position in the interpolation. - /// The second position in the interpolation. - /// The third position in the interpolation. - /// The fourth position in the interpolation. - /// Weighting factor. - /// A position that is the result of the Catmull-Rom interpolation. - public static float CatmullRom(float value1, float value2, float value3, float value4, float amount) - { - // Using formula from http://www.mvps.org/directx/articles/catmull/ - // Internally using doubles not to lose precission - double amountSquared = amount * amount; - double amountCubed = amountSquared * amount; - return (float)(0.5 * (2.0 * value2 + - (value3 - value1) * amount + - (2.0 * value1 - 5.0 * value2 + 4.0 * value3 - value4) * amountSquared + - (3.0 * value2 - value1 - 3.0 * value3 + value4) * amountCubed)); - } - - /// - /// Restricts a value to be within a specified range. - /// - /// The value to clamp. - /// The minimum value. If value is less than min, min will be returned. - /// The maximum value. If value is greater than max, max will be returned. - /// The clamped value. - public static float Clamp(float value, float min, float max) - { - // First we check to see if we're greater than the max - value = (value > max) ? max : value; - - // Then we check to see if we're less than the min. - value = (value < min) ? min : value; - - // There's no check to see if min > max. - return value; - } - - /// - /// Restricts a value to be within a specified range. - /// - /// The value to clamp. - /// The minimum value. If value is less than min, min will be returned. - /// The maximum value. If value is greater than max, max will be returned. - /// The clamped value. - public static int Clamp(int value, int min, int max) - { - value = (value > max) ? max : value; - value = (value < min) ? min : value; - return value; - } - - /// - /// Calculates the absolute value of the difference of two values. - /// - /// Source value. - /// Source value. - /// Distance between the two values. - public static float Distance(float value1, float value2) - { - return Math.Abs(value1 - value2); - } - - /// - /// Performs a Hermite spline interpolation. - /// - /// Source position. - /// Source tangent. - /// Source position. - /// Source tangent. - /// Weighting factor. - /// The result of the Hermite spline interpolation. - public static float Hermite(float value1, float tangent1, float value2, float tangent2, float amount) - { - // All transformed to double not to lose precission - // Otherwise, for high numbers of param:amount the result is NaN instead of Infinity - double v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount, result; - double sCubed = s * s * s; - double sSquared = s * s; - - if (amount == 0f) - result = value1; - else if (amount == 1f) - result = value2; - else - result = (2 * v1 - 2 * v2 + t2 + t1) * sCubed + - (3 * v2 - 3 * v1 - 2 * t1 - t2) * sSquared + - t1 * s + - v1; - return (float)result; - } - - - /// - /// Linearly interpolates between two values. - /// - /// Source value. - /// Destination value. - /// Value between 0 and 1 indicating the weight of value2. - /// Interpolated value. - /// This method performs the linear interpolation based on the following formula: - /// value1 + (value2 - value1) * amount. - /// Passing amount a value of 0 will cause value1 to be returned, a value of 1 will cause value2 to be returned. - /// See for a less efficient version with more precision around edge cases. - /// - public static float Lerp(float value1, float value2, float amount) - { - return value1 + (value2 - value1) * amount; - } - - - /// - /// Linearly interpolates between two values. - /// This method is a less efficient, more precise version of . - /// See remarks for more info. - /// - /// Source value. - /// Destination value. - /// Value between 0 and 1 indicating the weight of value2. - /// Interpolated value. - /// This method performs the linear interpolation based on the following formula: - /// ((1 - amount) * value1) + (value2 * amount). - /// Passing amount a value of 0 will cause value1 to be returned, a value of 1 will cause value2 to be returned. - /// This method does not have the floating point precision issue that has. - /// i.e. If there is a big gap between value1 and value2 in magnitude (e.g. value1=10000000000000000, value2=1), - /// right at the edge of the interpolation range (amount=1), will return 0 (whereas it should return 1). - /// This also holds for value1=10^17, value2=10; value1=10^18,value2=10^2... so on. - /// For an in depth explanation of the issue, see below references: - /// Relevant Wikipedia Article: https://en.wikipedia.org/wiki/Linear_interpolation#Programming_language_support - /// Relevant StackOverflow Answer: http://stackoverflow.com/questions/4353525/floating-point-linear-interpolation#answer-23716956 - /// - public static float LerpPrecise(float value1, float value2, float amount) - { - return ((1 - amount) * value1) + (value2 * amount); - } - - /// - /// Returns the greater of two values. - /// - /// Source value. - /// Source value. - /// The greater value. - public static float Max(float value1, float value2) - { - return value1 > value2 ? value1 : value2; - } - - /// - /// Returns the greater of two values. - /// - /// Source value. - /// Source value. - /// The greater value. - public static int Max(int value1, int value2) - { - return value1 > value2 ? value1 : value2; - } - - /// - /// Returns the lesser of two values. - /// - /// Source value. - /// Source value. - /// The lesser value. - public static float Min(float value1, float value2) - { - return value1 < value2 ? value1 : value2; - } - - /// - /// Returns the lesser of two values. - /// - /// Source value. - /// Source value. - /// The lesser value. - public static int Min(int value1, int value2) - { - return value1 < value2 ? value1 : value2; - } - - /// - /// Interpolates between two values using a cubic equation. - /// - /// Source value. - /// Source value. - /// Weighting value. - /// Interpolated value. - public static float SmoothStep(float value1, float value2, float amount) - { - // It is expected that 0 < amount < 1 - // If amount < 0, return value1 - // If amount > 1, return value2 - float result = Clamp(amount, 0f, 1f); - result = Hermite(value1, 0f, value2, 0f, result); - - return result; - } - - /// - /// Converts radians to degrees. - /// - /// The angle in radians. - /// The angle in degrees. - /// - /// This method uses double precission internally, - /// though it returns single float - /// Factor = 180 / pi - /// - public static float ToDegrees(float radians) - { - return (float)(radians * 57.295779513082320876798154814105); - } - - /// - /// Converts degrees to radians. - /// - /// The angle in degrees. - /// The angle in radians. - /// - /// This method uses double precission internally, - /// though it returns single float - /// Factor = pi / 180 - /// - public static float ToRadians(float degrees) - { - return (float)(degrees * 0.017453292519943295769236907684886); - } - - /// - /// Reduces a given angle to a value between π and -π. - /// - /// The angle to reduce, in radians. - /// The new angle, in radians. - public static float WrapAngle(float angle) - { - if ((angle > -Pi) && (angle <= Pi)) - return angle; - angle %= TwoPi; - if (angle <= -Pi) - return angle + TwoPi; - if (angle > Pi) - return angle - TwoPi; - return angle; - } - - /// - /// Determines if value is powered by two. - /// - /// A value. - /// true if value is powered by two; otherwise false. - public static bool IsPowerOfTwo(int value) - { - return (value > 0) && ((value & (value - 1)) == 0); - } -} \ No newline at end of file diff --git a/Ion/Ion_old/MemUtils.cs b/Ion/Ion_old/MemUtils.cs deleted file mode 100644 index 82213ac..0000000 --- a/Ion/Ion_old/MemUtils.cs +++ /dev/null @@ -1,431 +0,0 @@ -// Copyright (c) 2021 ezequias2d and the Ez contributors -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -//namespace Ez.Memory -namespace Ion; - -/// -/// A static class with useful methods for memory manipulation operations. -/// -public static class MemUtils -{ - static readonly int PlatformWordSize = IntPtr.Size; - static readonly int PlatformWordSizeBits = PlatformWordSize * 8; - - /// - /// Gets the size in bytes of an unmanaged type. - /// - /// The unmanaged type to measure. - /// Size in bytes of . - public static uint SizeOf() where T : unmanaged - { - unsafe - { - return (uint)sizeof(T); - } - } - - /// - /// Gets the size of a in bytes. - /// - /// The unmanaged type to measure. - /// The span to measure - /// Size in bytes of . - public static long SizeOf(ReadOnlySpan span) where T : unmanaged - { - unsafe - { - return (long)span.Length * sizeof(T); - } - } - - /// - /// Adds an offset to the value of a pointer. - /// - /// The pointer to add the offset to. - /// The offset to add. - /// A new pointer that reflects the addition of - /// to . - public static IntPtr Add(IntPtr ptr, long offset) => new(ptr.ToInt64() + offset); - - /// - /// Returns a value indicating whether an instance is anywhere in the array. - /// - /// The unmanaged type of element to check. - /// The value to compare. - /// The list of values to compare with . - /// if the parameter - /// is contained in the ; otherwise, - public static bool AnyEquals(T value, params T[] list) where T : unmanaged - { - unsafe - { - fixed (T* pList = list) - { - T* current = pList; - T* max = pList + list.Length; - - while (current < max) - { - if (Equals(current, &value, SizeOf())) return true; - current++; - } - } - } - - return false; - } - - /// - /// Returns a value indicating whether a is equal - /// to another . - /// - /// - /// The first to compare. - /// The second to compare. - /// if the span parameter - /// equals to span parameter; otherwise, - public static bool Equals(ReadOnlySpan a, ReadOnlySpan b) where T : unmanaged - { - unsafe - { - int count = a.Length; - - if (count != b.Length) return false; - - fixed (void* ptrA = a, ptrB = b) - { - return Equals(ptrA, ptrB, SizeOf(a)); - } - } - } - - /// - /// Returns a value indicating whether the content of one pointer is equal - /// to that of another pointer by a specified number of bytes. - /// - /// The first pointer to compare. - /// The second pointer to compare. - /// The number of bytes to compare. - /// if the contents of the pointer - /// are equal to contents of the pointer by bytes. - public static unsafe bool Equals(void* a, void* b, long byteCount) - { - var i1 = 0L; - var i2 = 0L; - var i4 = 0L; - var i8 = 0L; - - var c8 = (byteCount >> 3); - var c4 = (byteCount - (c8 << 3)) >> 2; - var c2 = (byteCount - (c4 << 2) - (c8 << 3)) >> 1; - var c1 = (byteCount - (c2 << 1) - (c4 << 2) - (c8 << 3)); - - byte* aPos = (byte*)a; - byte* bPos = (byte*)b; - - while (i8 < c8) - { - if (*(ulong*)aPos != *(ulong*)bPos) return false; - aPos += 8; - bPos += 8; - i8++; - } - - while (i4 < c4) - { - if (*(uint*)aPos != *(uint*)bPos) return false; - aPos += 4; - bPos += 4; - i4++; - } - - while (i2 < c2) - { - if (*(ushort*)aPos != *(ushort*)bPos) return false; - aPos += 2; - bPos += 2; - i2++; - } - - while (i1 < c1) - { - if (*aPos != *bPos) return false; - aPos++; - bPos++; - i1++; - } - - return true; - } - - /// - /// Sets all bytes of a to a specified value. - /// - /// The type of items in the . - /// The span to be set. - /// The byte value to set. - public static void Set(Span span, byte value) where T : unmanaged - { - unsafe - { - fixed (T* spanPtr = span) - { - Set(spanPtr, value, SizeOf(span)); - } - } - } - - /// - /// Turns a pointer into a ref . - /// - /// The type of the reference. - /// The pointer to referenced memory. - /// A T reference of . - public static unsafe ref T GetRef(IntPtr ptr) where T : unmanaged => ref *(T*)ptr.ToPointer(); - - /// - /// Sets all first bytes to the byte. - /// - /// The pointer to the first byte. - /// The byte value to set. - /// The number of bytes to set. - public static unsafe void Set(void* memoryPtr, byte value, long byteCount) - { - if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount)); - - if (byteCount <= uint.MaxValue) - Unsafe.InitBlockUnaligned(memoryPtr, value, (uint)byteCount); - else - { - uint bc; - byte* ptr = (byte*)memoryPtr; - while (byteCount > 0) - { - bc = (uint)Math.Min(uint.MaxValue, byteCount); - Unsafe.InitBlockUnaligned(ptr, value, bc); - byteCount -= bc; - ptr += bc; - } - } - } - - /// - /// Sets all first bytes to the byte. - /// - /// The pointer to the first byte. - /// The byte value to set. - /// The number of bytes to set. - public static void Set(IntPtr memoryPtr, byte value, long byteCount) - { - unsafe - { - Set((void*)memoryPtr, value, byteCount); - } - } - - /// - /// Sets all the first Ts to the . - /// - /// - /// The pointer to the first T to set. - /// The value to set. - /// The number of Ts to set. - public static unsafe void Set(IntPtr ptr, in T value, long count) where T : unmanaged - { - var pptr = (T*)ptr; - while (count > 0) - { - *pptr = value; - count--; - pptr++; - } - } - - /// - /// Copies all data from one to a . - /// - /// The type of items in the and . - /// The that receives the data. - /// The that contains the data to copy. - /// The number of bytes copied. - public static long Copy(Span destination, ReadOnlySpan source) where T : unmanaged => Copy(destination, source); - - /// - /// Copies all data from to . - /// - /// The type of items in . - /// The destination span. - /// The source address to copy from. - /// The number of bytes copied. - public static long Copy(Span destination, IntPtr source) where T : unmanaged => Copy(destination, GetSpan(source, destination.Length)); - - /// - /// Copies all data from one to a . - /// - /// The type of items in the . - /// The type of items in the . - /// The that receives the data. - /// The that contains the data to copy. - /// The number of bytes copied. - public static long Copy(Span destination, ReadOnlySpan source) - where TDestination : unmanaged - where TSource : unmanaged - { - unsafe - { - var srcSize = SizeOf(source); - if (srcSize > SizeOf(destination)) - throw new ArgumentOutOfRangeException($"The destination is too small to copy all data from the source. \nSource size: {srcSize} bytes.\nDestination size: {SizeOf(destination)} bytes."); - - fixed (void* dst = destination, src = source) - Copy(dst, src, srcSize); - - return srcSize; - } - } - - /// - /// Copies all data from a to a destination address. - /// - /// The type of items in the . - /// The destination address to copy to. - /// The that contains the data to copy. - /// The number of bytes copied. - public static unsafe long Copy(IntPtr dst, ReadOnlySpan src) where T : unmanaged => Copy(dst.ToPointer(), src); - - /// - /// Copies all data from a to a destination address. - /// - /// The type of items in the . - /// The destination address to copy to. - /// The that contains the data to copy. - /// The number of bytes copied. - public static unsafe long Copy(void* dst, ReadOnlySpan src) where T : unmanaged - { - fixed (void* srcPtr = src) - { - var size = SizeOf(src); - Copy(dst, srcPtr, size); - return size; - } - } - - /// - /// Copies all data from a T value to a destination address. - /// - /// The type of data to copy. - /// The destination address to copy to. - /// The value to copy. - /// The number of bytes copied. - public static long Copy(IntPtr dst, in T src) where T : unmanaged - { - unsafe - { - *(T*)dst.ToPointer() = src; - return SizeOf(); - } - } - - /// - /// Copies bytes from the source address to the destination address. - /// - /// The destination address to copy to. - /// The source address to copy from. - /// The number of bytes to copy. - public static unsafe void Copy(IntPtr destination, IntPtr source, long byteCount) => Copy((void*)destination, (void*)source, byteCount); - - /// - /// Copies bytes from the source address to the destination address. - /// - /// The destination address to copy to. - /// The source address to copy from. - /// The number of bytes to copy. - public static unsafe void Copy(void* destination, void* source, long byteCount) - { - if (byteCount <= uint.MaxValue) - Unsafe.CopyBlockUnaligned(destination, source, (uint)byteCount); - else - { - uint bc; - byte* dst = (byte*)destination; - byte* src = (byte*)source; - while (byteCount > 0) - { - bc = (uint)Math.Min(uint.MaxValue, byteCount); - Unsafe.CopyBlockUnaligned(dst, src, bc); - byteCount -= bc; - dst += bc; - src += bc; - } - } - } - - /// - /// Gets the theoretical limit for an allocation. - /// . - /// - public static readonly long MaxAllocSize = (long)IntPtr.MaxValue; - - /// - /// Allocates memory from unmanaged memory of process. - /// - /// The required number of bytes in memory. - /// A pointer to the newly allocated memory. This memory must be released using - /// the method. - public static unsafe IntPtr Alloc(long size) => Marshal.AllocHGlobal((IntPtr)size); - - /// - /// Frees memory previously allocated from the unmanaged memory of the process. - /// - /// The handle returned by the original matching call to . - public static unsafe void Free(IntPtr ptr) => Marshal.FreeHGlobal(ptr); - - /// - /// Gets a from a pointer and length. - /// - /// The type of items in . - /// A pointer to the starting address. - /// The number of elements in - /// The span of and params. - public unsafe static Span GetSpan(IntPtr ptr, int length) where T : unmanaged => new Span((T*)ptr, length); - - ///// - ///// Gets a from a pointer and length. - ///// - ///// The type of items in . - ///// A pointer to the starting address. - ///// The number of elements in - ///// The span of and params. - //public unsafe static Memory GetMemory(IntPtr ptr, int length) where T : unmanaged => new UnmanagedMemoryManager(ptr, length).Memory; - - /// - /// Gets a null-terminated UTF-8 string from a pointer. - /// - /// The pointer of memory to read from. - /// A string with the characters read from . - public static string? GetUtf8String(IntPtr ptr) => Marshal.PtrToStringUTF8(ptr); - - /// - /// Casts a span of one primitive type to a span of another primitive type. - /// - /// The type of source . - /// The type of target span. - /// The source slice to convert. - /// The converted span. - public unsafe static Span Cast(Span span) where TTo : unmanaged where TFrom : unmanaged => MemoryMarshal.Cast(span); - - /// - /// Casts a read-only span of one primitive type to a span of another primitive type. - /// - /// The type of source . - /// The type of target span. - /// The source slice to convert. - /// The converted read-only span. - public unsafe static ReadOnlySpan Cast(ReadOnlySpan span) where TTo : unmanaged where TFrom : unmanaged => MemoryMarshal.Cast(span); -} \ No newline at end of file diff --git a/Ion/Ion_old/Point.cs b/Ion/Ion_old/Point.cs deleted file mode 100644 index 25c9573..0000000 --- a/Ion/Ion_old/Point.cs +++ /dev/null @@ -1,205 +0,0 @@ -using System.Diagnostics; -using System.Runtime.CompilerServices; - -namespace Ion; - -/// -/// Describes a 2D-point. -/// -[DebuggerDisplay("{DebugDisplayString,nq}")] -public readonly struct Point : IEquatable -{ - #region Private Fields - - private static readonly Point zeroPoint = new Point(); - - #endregion - - #region Public Fields - - /// - /// The x coordinate of this . - /// - public readonly int X; - - /// - /// The y coordinate of this . - /// - public readonly int Y; - - #endregion - - #region Properties - - /// - /// Returns a with coordinates 0, 0. - /// - public static Point Zero - { - get { return zeroPoint; } - } - - #endregion - - #region Internal Properties - - internal string DebugDisplayString => $"{X}, {Y}"; - - #endregion - - #region Constructors - - /// - /// Constructs a point with X and Y from two values. - /// - /// The x coordinate in 2d-space. - /// The y coordinate in 2d-space. - public Point(int x, int y) - { - X = x; - Y = y; - } - - /// - /// Constructs a point with X and Y set to the same value. - /// - /// The x and y coordinates in 2d-space. - public Point(int value) - { - X = value; - Y = value; - } - - #endregion - - #region Operators - - /// - /// Adds two points. - /// - /// Source on the left of the add sign. - /// Source on the right of the add sign. - /// Sum of the points. - public static Point operator +(Point value1, Point value2) - { - return new Point(value1.X + value2.X, value1.Y + value2.Y); - } - - /// - /// Subtracts a from a . - /// - /// Source on the left of the sub sign. - /// Source on the right of the sub sign. - /// Result of the subtraction. - public static Point operator -(Point value1, Point value2) - { - return new Point(value1.X - value2.X, value1.Y - value2.Y); - } - - /// - /// Multiplies the components of two points by each other. - /// - /// Source on the left of the mul sign. - /// Source on the right of the mul sign. - /// Result of the multiplication. - public static Point operator *(Point value1, Point value2) - { - return new Point(value1.X * value2.X, value1.Y * value2.Y); - } - - /// - /// Divides the components of a by the components of another . - /// - /// Source on the left of the div sign. - /// Divisor on the right of the div sign. - /// The result of dividing the points. - public static Point operator /(Point source, Point divisor) - { - return new Point(source.X / divisor.X, source.Y / divisor.Y); - } - - /// - /// Compares whether two instances are equal. - /// - /// instance on the left of the equal sign. - /// instance on the right of the equal sign. - /// true if the instances are equal; false otherwise. - public static bool operator ==(Point a, Point b) - { - return a.Equals(b); - } - - /// - /// Compares whether two instances are not equal. - /// - /// instance on the left of the not equal sign. - /// instance on the right of the not equal sign. - /// true if the instances are not equal; false otherwise. - public static bool operator !=(Point a, Point b) - { - return !a.Equals(b); - } - - #endregion - - #region Public methods - - /// - /// Compares whether current instance is equal to specified . - /// - /// The to compare. - /// true if the instances are equal; false otherwise. - public override bool Equals(object? obj) - { - return (obj is Point point) && Equals(point); - } - - /// - /// Compares whether current instance is equal to specified . - /// - /// The to compare. - /// true if the instances are equal; false otherwise. - public bool Equals(Point other) - { - return ((X == other.X) && (Y == other.Y)); - } - - /// - /// Gets the hash code of this . - /// - /// Hash code of this . - public override int GetHashCode() - { - return HashCode.Combine(X, Y); - } - - /// - /// Returns a representation of this in the format: - /// {X:[] Y:[]} - /// - /// representation of this . - public override string ToString() => $"{{X:{X} Y:{Y}}}"; - - /// - /// Gets a representation for this object. - /// - /// A representation for this object. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Vector2 ToVector2() - { - return new Vector2(X, Y); - } - - /// - /// Deconstruction method for . - /// - /// - /// - public void Deconstruct(out int x, out int y) - { - x = X; - y = Y; - } - - #endregion -} diff --git a/Ion/Ion_old/Rectangle.cs b/Ion/Ion_old/Rectangle.cs deleted file mode 100644 index 899e494..0000000 --- a/Ion/Ion_old/Rectangle.cs +++ /dev/null @@ -1,460 +0,0 @@ -using System.Diagnostics; - -namespace Ion; - -[DebuggerDisplay("{DebugDisplayString,nq}")] -public struct Rectangle : IEquatable -{ - #region Private Fields - - private static Rectangle emptyRectangle = new(); - - #endregion - - #region Public Fields - - /// - /// The x coordinate of the top-left corner of this . - /// - public int X; - - /// - /// The y coordinate of the top-left corner of this . - /// - public int Y; - - /// - /// The width of this . - /// - public int Width; - - /// - /// The height of this . - /// - public int Height; - - #endregion - - #region Public Properties - - /// - /// Returns a with X=0, Y=0, Width=0, Height=0. - /// - public static Rectangle Empty => emptyRectangle; - - /// - /// Returns the x coordinate of the left edge of this . - /// - public int Left => X; - - /// - /// Returns the x coordinate of the right edge of this . - /// - public int Right => X + Width; - - /// - /// Returns the y coordinate of the top edge of this . - /// - public int Top => Y; - - /// - /// Returns the y coordinate of the bottom edge of this . - /// - public int Bottom => Y + Height; - - /// - /// Whether or not this has a and - /// of 0, and a of (0, 0). - /// - public bool IsEmpty => Width == 0 && Height == 0 && X == 0 && Y == 0; - - /// - /// The top-left coordinates of this . - /// - public Point Location - { - get => new(X, Y); - set - { - X = value.X; - Y = value.Y; - } - } - - /// - /// The width-height coordinates of this . - /// - public Point Size => new(Width, Height); - - /// - /// A located in the center of this . - /// - /// - /// If or is an odd number, - /// the center point will be rounded down. - /// - public Point Center => new(X + (Width / 2), Y + (Height / 2)); - - #endregion - - #region Internal Properties - - internal string DebugDisplayString => ToString(); - - #endregion - - #region Constructors - - /// - /// Creates a new instance of struct, with the specified - /// position, width, and height. - /// - /// The x coordinate of the top-left corner of the created . - /// The y coordinate of the top-left corner of the created . - /// The width of the created . - /// The height of the created . - public Rectangle(int x, int y, int width, int height) - { - X = x; - Y = y; - Width = width; - Height = height; - } - - /// - /// Creates a new instance of struct, with the specified - /// location and size. - /// - /// The x and y coordinates of the top-left corner of the created . - /// The width and height of the created . - public Rectangle(Point location, Point size) - { - X = location.X; - Y = location.Y; - Width = size.X; - Height = size.Y; - } - - #endregion - - #region Operators - - /// - /// Compares whether two instances are equal. - /// - /// instance on the left of the equal sign. - /// instance on the right of the equal sign. - /// true if the instances are equal; false otherwise. - public static bool operator ==(Rectangle a, Rectangle b) - { - return (a.X == b.X) && (a.Y == b.Y) && (a.Width == b.Width) && (a.Height == b.Height); - } - - /// - /// Compares whether two instances are not equal. - /// - /// instance on the left of the not equal sign. - /// instance on the right of the not equal sign. - /// true if the instances are not equal; false otherwise. - public static bool operator !=(Rectangle a, Rectangle b) - { - return !(a == b); - } - - #endregion - - #region Public Methods - - /// - /// Gets whether or not the provided coordinates lie within the bounds of this . - /// - /// The x coordinate of the point to check for containment. - /// The y coordinate of the point to check for containment. - /// true if the provided coordinates lie inside this ; false otherwise. - public bool Contains(int x, int y) - { - return (X <= x) && (x < (X + Width)) && (Y <= y) && (y < (Y + Height)); - } - - /// - /// Gets whether or not the provided coordinates lie within the bounds of this . - /// - /// The x coordinate of the point to check for containment. - /// The y coordinate of the point to check for containment. - /// true if the provided coordinates lie inside this ; false otherwise. - public bool Contains(float x, float y) - { - return (X <= x) && (x < (X + Width)) && (Y <= y) && (y < (Y + Height)); - } - - /// - /// Gets whether or not the provided lies within the bounds of this . - /// - /// The coordinates to check for inclusion in this . - /// true if the provided lies inside this ; false otherwise. - public bool Contains(Point value) - { - return (X <= value.X) && (value.X < (X + Width)) && (Y <= value.Y) && (value.Y < (Y + Height)); - } - - /// - /// Gets whether or not the provided lies within the bounds of this . - /// - /// The coordinates to check for inclusion in this . - /// true if the provided lies inside this ; false otherwise. As an output parameter. - public void Contains(ref Point value, out bool result) - { - result = (X <= value.X) && (value.X < (X + Width)) && (Y <= value.Y) && (value.Y < (Y + Height)); - } - - /// - /// Gets whether or not the provided lies within the bounds of this . - /// - /// The coordinates to check for inclusion in this . - /// true if the provided lies inside this ; false otherwise. - public bool Contains(Vector2 value) - { - return (X <= value.X) && (value.X < (X + Width)) && (Y <= value.Y) && (value.Y < (Y + Height)); - } - - /// - /// Gets whether or not the provided lies within the bounds of this . - /// - /// The coordinates to check for inclusion in this . - /// true if the provided lies inside this ; false otherwise. As an output parameter. - public void Contains(ref Vector2 value, out bool result) - { - result = (X <= value.X) && (value.X < (X + Width)) && (Y <= value.Y) && (value.Y < (Y + Height)); - } - - /// - /// Gets whether or not the provided lies within the bounds of this . - /// - /// The to check for inclusion in this . - /// true if the provided 's bounds lie entirely inside this ; false otherwise. - public bool Contains(Rectangle value) - { - return (X <= value.X) && ((value.X + value.Width) <= (X + Width)) && (Y <= value.Y) && ((value.Y + value.Height) <= (Y + Height)); - } - - /// - /// Gets whether or not the provided lies within the bounds of this . - /// - /// The to check for inclusion in this . - /// true if the provided 's bounds lie entirely inside this ; false otherwise. As an output parameter. - public void Contains(ref Rectangle value, out bool result) - { - result = (X <= value.X) && ((value.X + value.Width) <= (X + Width)) && (Y <= value.Y) && ((value.Y + value.Height) <= (Y + Height)); - } - - /// - /// Compares whether current instance is equal to specified . - /// - /// The to compare. - /// true if the instances are equal; false otherwise. - public override bool Equals(object? obj) - { - return (obj is Rectangle rect) && this == rect; - } - - /// - /// Compares whether current instance is equal to specified . - /// - /// The to compare. - /// true if the instances are equal; false otherwise. - public bool Equals(Rectangle other) - { - return this == other; - } - - /// - /// Gets the hash code of this . - /// - /// Hash code of this . - public override int GetHashCode() - { - return HashCode.Combine(X, Y, Width, Height); - } - - /// - /// Adjusts the edges of this by specified horizontal and vertical amounts. - /// - /// Value to adjust the left and right edges. - /// Value to adjust the top and bottom edges. - public void Inflate(int horizontalAmount, int verticalAmount) - { - X -= horizontalAmount; - Y -= verticalAmount; - Width += horizontalAmount * 2; - Height += verticalAmount * 2; - } - - /// - /// Adjusts the edges of this by specified horizontal and vertical amounts. - /// - /// Value to adjust the left and right edges. - /// Value to adjust the top and bottom edges. - public void Inflate(float horizontalAmount, float verticalAmount) - { - X -= (int)horizontalAmount; - Y -= (int)verticalAmount; - Width += (int)horizontalAmount * 2; - Height += (int)verticalAmount * 2; - } - - /// - /// Gets whether or not the other intersects with this rectangle. - /// - /// The other rectangle for testing. - /// true if other intersects with this rectangle; false otherwise. - public bool Intersects(Rectangle value) - { - return value.Left < Right && - Left < value.Right && - value.Top < Bottom && - Top < value.Bottom; - } - - - /// - /// Gets whether or not the other intersects with this rectangle. - /// - /// The other rectangle for testing. - /// true if other intersects with this rectangle; false otherwise. As an output parameter. - public void Intersects(ref Rectangle value, out bool result) - { - result = value.Left < Right && - Left < value.Right && - value.Top < Bottom && - Top < value.Bottom; - } - - /// - /// Creates a new that contains overlapping region of two other rectangles. - /// - /// The first . - /// The second . - /// Overlapping region of the two rectangles. - public static Rectangle Intersect(Rectangle value1, Rectangle value2) - { - Intersect(ref value1, ref value2, out Rectangle rectangle); - return rectangle; - } - - /// - /// Creates a new that contains overlapping region of two other rectangles. - /// - /// The first . - /// The second . - /// Overlapping region of the two rectangles as an output parameter. - public static void Intersect(ref Rectangle value1, ref Rectangle value2, out Rectangle result) - { - if (value1.Intersects(value2)) - { - int right_side = Math.Min(value1.X + value1.Width, value2.X + value2.Width); - int left_side = Math.Max(value1.X, value2.X); - int top_side = Math.Max(value1.Y, value2.Y); - int bottom_side = Math.Min(value1.Y + value1.Height, value2.Y + value2.Height); - result = new Rectangle(left_side, top_side, right_side - left_side, bottom_side - top_side); - } - else - { - result = new Rectangle(0, 0, 0, 0); - } - } - - /// - /// Changes the of this . - /// - /// The x coordinate to add to this . - /// The y coordinate to add to this . - public void Offset(int offsetX, int offsetY) - { - X += offsetX; - Y += offsetY; - } - - /// - /// Changes the of this . - /// - /// The x coordinate to add to this . - /// The y coordinate to add to this . - public void Offset(float offsetX, float offsetY) - { - X += (int)offsetX; - Y += (int)offsetY; - } - - /// - /// Changes the of this . - /// - /// The x and y components to add to this . - public void Offset(Point amount) - { - X += amount.X; - Y += amount.Y; - } - - /// - /// Changes the of this . - /// - /// The x and y components to add to this . - public void Offset(Vector2 amount) - { - X += (int)amount.X; - Y += (int)amount.Y; - } - - /// - /// Returns a representation of this in the format: - /// {X:[] Y:[] Width:[] Height:[]} - /// - /// representation of this . - public override string ToString() => $"{{X: {X} Y: {Y} W: {Width} H: {Height}}}"; - - /// - /// Creates a new that completely contains two other rectangles. - /// - /// The first . - /// The second . - /// The union of the two rectangles. - public static Rectangle Union(Rectangle value1, Rectangle value2) - { - int x = Math.Min(value1.X, value2.X); - int y = Math.Min(value1.Y, value2.Y); - return new Rectangle(x, y, - Math.Max(value1.Right, value2.Right) - x, - Math.Max(value1.Bottom, value2.Bottom) - y); - } - - /// - /// Creates a new that completely contains two other rectangles. - /// - /// The first . - /// The second . - /// The union of the two rectangles as an output parameter. - public static void Union(ref Rectangle value1, ref Rectangle value2, out Rectangle result) - { - result.X = Math.Min(value1.X, value2.X); - result.Y = Math.Min(value1.Y, value2.Y); - result.Width = Math.Max(value1.Right, value2.Right) - result.X; - result.Height = Math.Max(value1.Bottom, value2.Bottom) - result.Y; - } - - /// - /// Deconstruction method for . - /// - /// - /// - /// - /// - public void Deconstruct(out int x, out int y, out int width, out int height) - { - x = X; - y = Y; - width = Width; - height = Height; - } - - #endregion -} diff --git a/Ion/Ion_old/RectangleF.cs b/Ion/Ion_old/RectangleF.cs deleted file mode 100644 index 05f6719..0000000 --- a/Ion/Ion_old/RectangleF.cs +++ /dev/null @@ -1,480 +0,0 @@ -using System.Diagnostics; - -namespace Ion; - -[DebuggerDisplay("{DebugDisplayString,nq}")] -public struct RectangleF : IEquatable -{ - #region Private Fields - - private static RectangleF emptyRectangle = new(); - - #endregion - - #region Public Fields - - /// - /// The x coordinate of the top-left corner of this . - /// - public float X; - - /// - /// The y coordinate of the top-left corner of this . - /// - public float Y; - - /// - /// The width of this . - /// - public float Width; - - /// - /// The height of this . - /// - public float Height; - - #endregion - - #region Public Properties - - /// - /// Returns a with X=0, Y=0, Width=0, Height=0. - /// - public static RectangleF Empty => emptyRectangle; - - /// - /// Returns the x coordinate of the left edge of this . - /// - public float Left => X; - - /// - /// Returns the x coordinate of the right edge of this . - /// - public float Right => X + Width; - - /// - /// Returns the y coordinate of the top edge of this . - /// - public float Top => Y; - - /// - /// Returns the y coordinate of the bottom edge of this . - /// - public float Bottom => Y + Height; - - /// - /// Whether or not this has a and - /// of 0, and a of (0, 0). - /// - public bool IsEmpty => Width == 0 && Height == 0 && X == 0 && Y == 0; - - /// - /// The top-left coordinates of this . - /// - public Vector2 Location - { - get => new(X, Y); - set - { - X = value.X; - Y = value.Y; - } - } - - /// - /// The width-height coordinates of this . - /// - public Vector2 Size => new(Width, Height); - - /// - /// A located in the center of this . - /// - /// - /// If or is an odd number, - /// the center point will be rounded down. - /// - public Vector2 Center => new(X + (Width / 2f), Y + (Height / 2f)); - - #endregion - - #region Internal Properties - - internal string DebugDisplayString => ToString(); - - #endregion - - #region Constructors - - /// - /// Creates a new instance of struct, with the specified - /// position, width, and height. - /// - /// The x coordinate of the top-left corner of the created . - /// The y coordinate of the top-left corner of the created . - /// The width of the created . - /// The height of the created . - public RectangleF(float x, float y, float width, float height) - { - X = x; - Y = y; - Width = width; - Height = height; - } - - /// - /// Creates a new instance of struct, with the specified - /// location and size. - /// - /// The x and y coordinates of the top-left corner of the created . - /// The width and height of the created . - public RectangleF(Vector2 location, Vector2 size) - { - X = location.X; - Y = location.Y; - Width = size.X; - Height = size.Y; - } - - #endregion - - #region Operators - - /// - /// Compares whether two instances are equal. - /// - /// instance on the left of the equal sign. - /// instance on the right of the equal sign. - /// true if the instances are equal; false otherwise. - public static bool operator ==(RectangleF a, RectangleF b) - { - return (a.X == b.X) && (a.Y == b.Y) && (a.Width == b.Width) && (a.Height == b.Height); - } - - /// - /// Compares whether two instances are not equal. - /// - /// instance on the left of the not equal sign. - /// instance on the right of the not equal sign. - /// true if the instances are not equal; false otherwise. - public static bool operator !=(RectangleF a, RectangleF b) - { - return !(a == b); - } - - #endregion - - #region Public Methods - - /// - /// Gets whether or not the provided coordinates lie within the bounds of this . - /// - /// The x coordinate of the point to check for containment. - /// The y coordinate of the point to check for containment. - /// true if the provided coordinates lie inside this ; false otherwise. - public bool Contains(int x, int y) - { - return (X <= x) && (x < (X + Width)) && (Y <= y) && (y < (Y + Height)); - } - - /// - /// Gets whether or not the provided coordinates lie within the bounds of this . - /// - /// The x coordinate of the point to check for containment. - /// The y coordinate of the point to check for containment. - /// true if the provided coordinates lie inside this ; false otherwise. - public bool Contains(float x, float y) - { - return (X <= x) && (x < (X + Width)) && (Y <= y) && (y < (Y + Height)); - } - - /// - /// Gets whether or not the provided lies within the bounds of this . - /// - /// The coordinates to check for inclusion in this . - /// true if the provided lies inside this ; false otherwise. - public bool Contains(Point value) - { - return (X <= value.X) && (value.X < (X + Width)) && (Y <= value.Y) && (value.Y < (Y + Height)); - } - - /// - /// Gets whether or not the provided lies within the bounds of this . - /// - /// The coordinates to check for inclusion in this . - /// true if the provided lies inside this ; false otherwise. As an output parameter. - public void Contains(ref Point value, out bool result) - { - result = (X <= value.X) && (value.X < (X + Width)) && (Y <= value.Y) && (value.Y < (Y + Height)); - } - - /// - /// Gets whether or not the provided lies within the bounds of this . - /// - /// The coordinates to check for inclusion in this . - /// true if the provided lies inside this ; false otherwise. - public bool Contains(Vector2 value) - { - return (X <= value.X) && (value.X < (X + Width)) && (Y <= value.Y) && (value.Y < (Y + Height)); - } - - /// - /// Gets whether or not the provided lies within the bounds of this . - /// - /// The coordinates to check for inclusion in this . - /// true if the provided lies inside this ; false otherwise. As an output parameter. - public void Contains(ref Vector2 value, out bool result) - { - result = (X <= value.X) && (value.X < (X + Width)) && (Y <= value.Y) && (value.Y < (Y + Height)); - } - - /// - /// Gets whether or not the provided lies within the bounds of this . - /// - /// The to check for inclusion in this . - /// true if the provided 's bounds lie entirely inside this ; false otherwise. - public bool Contains(Rectangle value) - { - return (X <= value.X) && ((value.X + value.Width) <= (X + Width)) && (Y <= value.Y) && ((value.Y + value.Height) <= (Y + Height)); - } - - /// - /// Gets whether or not the provided lies within the bounds of this . - /// - /// The to check for inclusion in this . - /// true if the provided 's bounds lie entirely inside this ; false otherwise. As an output parameter. - public void Contains(ref Rectangle value, out bool result) - { - result = (X <= value.X) && ((value.X + value.Width) <= (X + Width)) && (Y <= value.Y) && ((value.Y + value.Height) <= (Y + Height)); - } - - /// - /// Gets whether or not the provided lies within the bounds of this . - /// - /// The to check for inclusion in this . - /// true if the provided 's bounds lie entirely inside this ; false otherwise. - public bool Contains(RectangleF value) - { - return (X <= value.X) && ((value.X + value.Width) <= (X + Width)) && (Y <= value.Y) && ((value.Y + value.Height) <= (Y + Height)); - } - - /// - /// Gets whether or not the provided lies within the bounds of this . - /// - /// The to check for inclusion in this . - /// true if the provided 's bounds lie entirely inside this ; false otherwise. As an output parameter. - public void Contains(ref RectangleF value, out bool result) - { - result = (X <= value.X) && ((value.X + value.Width) <= (X + Width)) && (Y <= value.Y) && ((value.Y + value.Height) <= (Y + Height)); - } - - /// - /// Compares whether current instance is equal to specified . - /// - /// The to compare. - /// true if the instances are equal; false otherwise. - public override bool Equals(object? obj) - { - return (obj is RectangleF rect) && this == rect; - } - - /// - /// Compares whether current instance is equal to specified . - /// - /// The to compare. - /// true if the instances are equal; false otherwise. - public bool Equals(RectangleF other) - { - return this == other; - } - - /// - /// Gets the hash code of this . - /// - /// Hash code of this . - public override int GetHashCode() - { - return HashCode.Combine(X, Y, Width, Height); - } - - /// - /// Adjusts the edges of this by specified horizontal and vertical amounts. - /// - /// Value to adjust the left and right edges. - /// Value to adjust the top and bottom edges. - public void Inflate(int horizontalAmount, int verticalAmount) - { - X -= horizontalAmount; - Y -= verticalAmount; - Width += horizontalAmount * 2; - Height += verticalAmount * 2; - } - - /// - /// Adjusts the edges of this by specified horizontal and vertical amounts. - /// - /// Value to adjust the left and right edges. - /// Value to adjust the top and bottom edges. - public void Inflate(float horizontalAmount, float verticalAmount) - { - X -= (int)horizontalAmount; - Y -= (int)verticalAmount; - Width += (int)horizontalAmount * 2; - Height += (int)verticalAmount * 2; - } - - /// - /// Gets whether or not the other intersects with this rectangle. - /// - /// The other rectangle for testing. - /// true if other intersects with this rectangle; false otherwise. - public bool Intersects(RectangleF value) - { - return value.Left < Right && - Left < value.Right && - value.Top < Bottom && - Top < value.Bottom; - } - - - /// - /// Gets whether or not the other intersects with this rectangle. - /// - /// The other rectangle for testing. - /// true if other intersects with this rectangle; false otherwise. As an output parameter. - public void Intersects(ref RectangleF value, out bool result) - { - result = value.Left < Right && - Left < value.Right && - value.Top < Bottom && - Top < value.Bottom; - } - - /// - /// Creates a new that contains overlapping region of two other rectangles. - /// - /// The first . - /// The second . - /// Overlapping region of the two rectangles. - public static RectangleF Intersect(RectangleF value1, RectangleF value2) - { - Intersect(ref value1, ref value2, out RectangleF rectangle); - return rectangle; - } - - /// - /// Creates a new that contains overlapping region of two other rectangles. - /// - /// The first . - /// The second . - /// Overlapping region of the two rectangles as an output parameter. - public static void Intersect(ref RectangleF value1, ref RectangleF value2, out RectangleF result) - { - if (value1.Intersects(value2)) - { - float right_side = Math.Min(value1.X + value1.Width, value2.X + value2.Width); - float left_side = Math.Max(value1.X, value2.X); - float top_side = Math.Max(value1.Y, value2.Y); - float bottom_side = Math.Min(value1.Y + value1.Height, value2.Y + value2.Height); - result = new RectangleF(left_side, top_side, right_side - left_side, bottom_side - top_side); - } - else - { - result = new RectangleF(0, 0, 0, 0); - } - } - - /// - /// Changes the of this . - /// - /// The x coordinate to add to this . - /// The y coordinate to add to this . - public void Offset(int offsetX, int offsetY) - { - X += offsetX; - Y += offsetY; - } - - /// - /// Changes the of this . - /// - /// The x coordinate to add to this . - /// The y coordinate to add to this . - public void Offset(float offsetX, float offsetY) - { - X += (int)offsetX; - Y += (int)offsetY; - } - - /// - /// Changes the of this . - /// - /// The x and y components to add to this . - public void Offset(Point amount) - { - X += amount.X; - Y += amount.Y; - } - - /// - /// Changes the of this . - /// - /// The x and y components to add to this . - public void Offset(Vector2 amount) - { - X += (int)amount.X; - Y += (int)amount.Y; - } - - /// - /// Returns a representation of this in the format: - /// {X:[] Y:[] Width:[] Height:[]} - /// - /// representation of this . - public override string ToString() => $"{{X: {X} Y: {Y} W: {Width} H: {Height}}}"; - - /// - /// Creates a new that completely contains two other rectangles. - /// - /// The first . - /// The second . - /// The union of the two rectangles. - public static RectangleF Union(RectangleF value1, RectangleF value2) - { - float x = Math.Min(value1.X, value2.X); - float y = Math.Min(value1.Y, value2.Y); - return new RectangleF(x, y, - Math.Max(value1.Right, value2.Right) - x, - Math.Max(value1.Bottom, value2.Bottom) - y); - } - - /// - /// Creates a new that completely contains two other rectangles. - /// - /// The first . - /// The second . - /// The union of the two rectangles as an output parameter. - public static void Union(ref RectangleF value1, ref RectangleF value2, out RectangleF result) - { - result.X = Math.Min(value1.X, value2.X); - result.Y = Math.Min(value1.Y, value2.Y); - result.Width = Math.Max(value1.Right, value2.Right) - result.X; - result.Height = Math.Max(value1.Bottom, value2.Bottom) - result.Y; - } - - /// - /// Deconstruction method for . - /// - /// - /// - /// - /// - public void Deconstruct(out float x, out float y, out float width, out float height) - { - x = X; - y = Y; - width = Width; - height = Height; - } - - #endregion -} diff --git a/Ion/Ion_old/Scenes/CurrentScene.cs b/Ion/Ion_old/Scenes/CurrentScene.cs deleted file mode 100644 index 1e6d746..0000000 --- a/Ion/Ion_old/Scenes/CurrentScene.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace Ion.Scenes; - -public interface ICurrentScene -{ - bool IsRoot { get; } - string Name { get; } -} - -public sealed class CurrentScene : ICurrentScene -{ - public static readonly string Root = ""; - - public string Name { get; private set; } - public bool IsRoot { get; private set; } - - public CurrentScene() - { - Name = Root; - IsRoot = true; - } - - internal void Set(string name) - { - Name = name; - IsRoot = Name == Root; - } - - public override string ToString() - { - return Name ?? Root; - } -} diff --git a/Ion/Ion_old/Scenes/Scene.cs b/Ion/Ion_old/Scenes/Scene.cs deleted file mode 100644 index 57818fb..0000000 --- a/Ion/Ion_old/Scenes/Scene.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace Ion.Scenes; - -public sealed class Scene : IInitializeSystem, IUpdateSystem, IFixedUpdateSystem, IRenderSystem, IDestroySystem -{ - public bool IsEnabled { get; set; } = true; - public string Name { get; } - private readonly SystemGroup _systems; - - internal Scene(string name, SystemGroup systems) - { - Name = name; - _systems = systems; - } - - public void Initialize() => _systems.Initialize(); - - public void FixedUpdate(GameTime dt) => _systems.FixedUpdate(dt); - public void Update(GameTime dt) => _systems.Update(dt); - - public void Render(GameTime dt) => _systems.Render(dt); - - public void Destroy() => _systems.Destroy(); -} diff --git a/Ion/Ion_old/Scenes/SceneBuilder.cs b/Ion/Ion_old/Scenes/SceneBuilder.cs deleted file mode 100644 index 0139a59..0000000 --- a/Ion/Ion_old/Scenes/SceneBuilder.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; - -using Ion.Scenes; - -namespace Ion.Hosting.Scenes; - -internal class SceneBuilder : ISceneBuilder -{ - public string Name { get; } - protected readonly IServiceCollection _services; - protected readonly SystemGroupBuilder _systems = new(); - - public SceneBuilder(string name, IServiceCollection services) - { - Name = name; - _services = services; - } - - public ISceneBuilder AddSystem() where T : class - { - _systems.AddSystem(); - _services.TryAddScoped(); - return this; - } - - internal Scene Build(IServiceProvider serviceProvider) - { - var aggSys = _systems.Build(serviceProvider); - - return new Scene(Name, aggSys); - } -} \ No newline at end of file diff --git a/Ion/Ion_old/Storage/PersistentStorage.cs b/Ion/Ion_old/Storage/PersistentStorage.cs deleted file mode 100644 index a58bb15..0000000 --- a/Ion/Ion_old/Storage/PersistentStorage.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace Ion.Storage; - -internal class PersistentStorage : IPersistentStorage -{ - private readonly PersistentStorageProvider _game; - private readonly PersistentStorageProvider _assets; - private readonly PersistentStorageProvider _user; - private readonly PersistentStorageProvider _saves; - - public IPersistentStorageProvider Game => _game; - public IPersistentStorageProvider Assets => _assets; - - public IPersistentStorageProvider User => _user; - public IPersistentStorageProvider Saves => _saves; - - public PersistentStorage(IGameConfig config) - { - _game = new PersistentStorageProvider(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), config.Title); - _assets = _game.Subpath("Assets"); - - _user = new PersistentStorageProvider(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), config.Title); - _saves = _user.Subpath("Saves"); - } - - public void Initialize() - { - _game.Initialize(); - _assets.Initialize(); - _user.Initialize(); - _saves.Initialize(); - } -} diff --git a/Ion/Ion_old/Storage/PersistentStorageProvider.cs b/Ion/Ion_old/Storage/PersistentStorageProvider.cs deleted file mode 100644 index e8f1981..0000000 --- a/Ion/Ion_old/Storage/PersistentStorageProvider.cs +++ /dev/null @@ -1,73 +0,0 @@ -namespace Ion.Storage; - -internal class PersistentStorageProvider : IPersistentStorageProvider -{ - private readonly string _rootPath; - - public PersistentStorageProvider(params string[] rootPath) - { - _rootPath = Path.Combine(rootPath); - } - - public void Initialize() - { - // TODO: Determine if we really want to do this. - //Directory.CreateDirectory(_rootPath); - } - - public PersistentStorageProvider Subpath(params string[] path) - { - return new PersistentStorageProvider(_rootPath, Path.Combine(path)); - } - - public void CreateDirectory(params string[] path) - { - Directory.CreateDirectory(_getPath(path)); - } - - public void Write(string text, params string[] path) - { - File.WriteAllText(_getPath(path), text); - } - - public void Write(byte[] bytes, params string[] path) - { - File.WriteAllBytes(_getPath(path), bytes); - } - - public BinaryWriter OpenWrite(params string[] path) - { - var stream = File.OpenWrite(_getPath(path)); - return new BinaryWriter(stream); - } - - public void Append(string text, params string[] path) - { - File.AppendAllText(_getPath(path), text); - } - - public Stream Read(params string[] path) - { - return File.OpenRead(_getPath(path)); - } - - public IEnumerable List(params string[] path) - { - return Directory.EnumerateFileSystemEntries(_getPath(path)); - } - - public void DeleteFile(params string[] path) - { - File.Delete(_getPath(path)); - } - - public void DeleteDirectory(params string[] path) - { - Directory.Delete(_getPath(path)); - } - - private string _getPath(params string[] path) - { - return Path.Combine(_rootPath, Path.Combine(path)); - } -} diff --git a/Ion/Ion_old/Window.cs b/Ion/Ion_old/Window.cs deleted file mode 100644 index f14b4f6..0000000 --- a/Ion/Ion_old/Window.cs +++ /dev/null @@ -1,218 +0,0 @@ -using Veldrid; -using Veldrid.Sdl2; - -using Ion.Graphics; - -namespace Ion; - -internal class Window : IWindow -{ - private readonly IGameConfig _config; - private readonly ILogger _logger; - private readonly EventEmitter _eventEmitter; - private readonly IEventListener _events; - - public InputSnapshot? InputSnapshot { get; private set; } - - private Veldrid.StartupUtilities.WindowCreateInfo _windowCreateInfo; - internal Sdl2Window? Sdl2Window { get; private set; } - - private (int, int) _prevSize = (0, 0); - private bool _closeHandled = false; - - public int Width - { - get => Sdl2Window?.Width ?? 0; - set { - if (Sdl2Window != null) - { - Sdl2Window.Width = value; - _size = _size with { X = value }; - } - } - } - - public int Height - { - get => Sdl2Window?.Height ?? 0; - set - { - if (Sdl2Window != null) - { - Sdl2Window.Height = value; - _size = _size with { Y = value }; - } - } - } - - private Vector2 _size = default; - public Vector2 Size - { - get => _size; - set { - if (Sdl2Window != null) - { - _size = value; - Sdl2Window.Width = (int)value.X; - Sdl2Window.Height = (int)value.Y; - } - - } - } - - public bool HasClosed { get; private set; } - public bool IsActive => (Sdl2Window?.Focused ?? false); - - public bool IsVisible - { - get => Sdl2Window?.Visible ?? false; - set { if (Sdl2Window != null) Sdl2Window.Visible = value; } - } - - public bool IsMaximized - { - get => (Sdl2Window?.WindowState ?? WindowState.Hidden) == WindowState.Maximized; - set { if (Sdl2Window != null) Sdl2Window.WindowState = value ? WindowState.Maximized : WindowState.Normal; } - } - public bool IsMinimized - { - get => (Sdl2Window?.WindowState ?? WindowState.Hidden) == WindowState.Minimized; - set { if (Sdl2Window != null) Sdl2Window.WindowState = value ? WindowState.Minimized : WindowState.Normal; } - } - public bool IsFullscreen - { - get => (Sdl2Window?.WindowState ?? WindowState.Hidden) == WindowState.FullScreen; - set { if (Sdl2Window != null) Sdl2Window.WindowState = value ? WindowState.FullScreen : WindowState.Normal; } - } - public bool IsBorderlessFullscreen - { - get => (Sdl2Window?.WindowState ?? WindowState.Hidden) == WindowState.BorderlessFullScreen; - set { if (Sdl2Window != null) Sdl2Window.WindowState = value ? WindowState.BorderlessFullScreen : WindowState.Normal; } - } - - private string _title; - public string Title - { - get => Sdl2Window?.Title ?? _title; - set { - _title = value; - if (Sdl2Window != null) Sdl2Window.Title = _title; - } - } - public bool IsResizable - { - get => Sdl2Window?.Resizable ?? false; - set { if (Sdl2Window != null) Sdl2Window.Resizable = value; } - } - public bool IsCursorVisible - { - get => Sdl2Window?.CursorVisible ?? false; - set { if (Sdl2Window != null) Sdl2Window.CursorVisible = value; } - } - public bool IsBorderVisible - { - get => Sdl2Window?.BorderVisible ?? false; - set { if (Sdl2Window != null) Sdl2Window.BorderVisible = value; } - } - - public Window(IGameConfig config, ILogger logger, IEventEmitter eventEmitter, IEventListener events) - { - _config = config; - _logger = logger; - _eventEmitter = (EventEmitter)eventEmitter; - _events = events; - - _windowCreateInfo = new() - { - X = _config.WindowX ?? 100, - Y = _config.WindowY ?? 100, - WindowWidth = _config.WindowWidth ?? 960, - WindowHeight = _config.WindowHeight ?? 540, - WindowInitialState = _config.WindowState, - WindowTitle = _title = _config.Title ?? "Ion" - }; - } - - public void Initialize() - { - if (_config.Output != GraphicsOutput.Window) return; - - _logger.LogInformation("Creating window..."); - Sdl2Window = _createWindow(_windowCreateInfo); - Sdl2Window.SetCloseRequestedHandler(() => _closeHandled); - Sdl2Window.Closed += _onClosed; - Sdl2Window.FocusLost += _onFocusLost; - Sdl2Window.Resized += _onResize; - Sdl2Window.FocusGained += _onFocusGained; - _size = new(Sdl2Window.Width, Sdl2Window.Height); - - //_onResize(); - _logger.LogInformation($"Window created! ({Sdl2Window.Width}x{Sdl2Window.Height})"); - } - - private static Sdl2Window _createWindow(Veldrid.StartupUtilities.WindowCreateInfo windowCreateInfo) - { - SDL_WindowFlags sDL_WindowFlags = SDL_WindowFlags.OpenGL | SDL_WindowFlags.Resizable | GetWindowFlags(windowCreateInfo.WindowInitialState); - if (windowCreateInfo.WindowInitialState != WindowState.Hidden) - { - sDL_WindowFlags |= SDL_WindowFlags.Shown; - } - return new Sdl2Window(windowCreateInfo.WindowTitle, windowCreateInfo.X, windowCreateInfo.Y, windowCreateInfo.WindowWidth, windowCreateInfo.WindowHeight, sDL_WindowFlags, threadedProcessing: true); - } - - private static SDL_WindowFlags GetWindowFlags(WindowState state) - { - return state switch - { - WindowState.Normal => (SDL_WindowFlags)0u, - WindowState.FullScreen => SDL_WindowFlags.Fullscreen, - WindowState.Maximized => SDL_WindowFlags.Maximized, - WindowState.Minimized => SDL_WindowFlags.Minimized, - WindowState.BorderlessFullScreen => SDL_WindowFlags.FullScreenDesktop, - WindowState.Hidden => SDL_WindowFlags.Hidden, - _ => throw new VeldridException("Invalid WindowState: " + state), - }; - } - - public void Step() - { - if (_config.Output != GraphicsOutput.Window || Sdl2Window == null) - { - InputSnapshot = default; - return; - } - - if (_events.OnLatest()) _closeHandled = true; - - InputSnapshot = Sdl2Window.PumpEvents(); - } - - public void Close() - { - _logger.LogDebug("Closing..."); - - if (_config.Output == GraphicsOutput.Window) Sdl2Window?.Close(); - else _onClosed(); - } - - private void _onResize() - { - if (Sdl2Window == null) return; - if (_prevSize == (Sdl2Window.Width, Sdl2Window.Height)) return; - - _size = new(Sdl2Window.Width, Sdl2Window.Height); - _prevSize = (Sdl2Window.Width, Sdl2Window.Height); - _eventEmitter.Emit(new WindowResizeEvent((uint)Sdl2Window.Width, (uint)Sdl2Window.Height)); - } - - private void _onFocusGained() => _eventEmitter.Emit(); - - private void _onFocusLost() => _eventEmitter.Emit(); - - private void _onClosed() - { - HasClosed = true; - _logger.LogDebug("Window closed!"); - _eventEmitter.Emit(); - } -}